局部加权线性回归代码
时间: 2023-12-20 20:30:54 浏览: 154
以下是Python实现局部加权线性回归的代码:
```python
import numpy as np
def kernel(point, xmat, k):
m, n = np.shape(xmat)
weights = np.mat(np.eye(m))
for j in range(m):
diff = point - X[j]
weights[j, j] = np.exp(diff * diff.T / (-2.0 * k ** 2))
return weights
def localWeight(point, xmat, ymat, k):
wei = kernel(point, xmat, k)
W = (X.T * (wei * X)).I * (X.T * wei * ymat.T)
return W
def localWeightRegression(xmat, ymat, k):
m, n = np.shape(xmat)
ypred = np.zeros(m)
for i in range(m):
ypred[i] = xmat[i] * localWeight(xmat[i], xmat, ymat, k)
return ypred
```
其中,`kernel()`函数用于计算权重矩阵,`localWeight()`函数用于计算回归系数,`localWeightRegression()`函数用于进行预测。
阅读全文