Skip to content

Commit 6b833f0

Browse files
Create local_weight_regression.py
1 parent 3b7f155 commit 6b833f0

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# coding:UTF-8
2+
3+
import numpy as np
4+
from linear_regression_train import load_data
5+
6+
def lwlr(feature, label, k):
7+
'''局部加权线性回归
8+
input: feature(mat):特征
9+
label(mat):标签
10+
k(int):核函数的系数
11+
output: predict(mat):最终的结果
12+
'''
13+
m = np.shape(feature)[0]
14+
predict = np.zeros(m)
15+
weights = np.mat(np.eye(m))
16+
for i in xrange(m):
17+
for j in xrange(m):
18+
diff = feature[i, ] - feature[j, ]
19+
weights[j,j] = np.exp(diff * diff.T / (-2.0 * k ** 2))
20+
xTx = feature.T * (weights * feature)
21+
ws = xTx.I * (feature.T * (weights * label))
22+
predict[i] = feature[i, ] * ws
23+
return predict
24+
25+
if __name__ == "__main__":
26+
# 1、导入数据集
27+
feature, label = load_data("data.txt")
28+
predict = lwlr(feature, label, 0.002)
29+
m = np.shape(predict)[0]
30+
for i in xrange(m):
31+
print feature[i, 1], predict[i]

0 commit comments

Comments
 (0)