Repository navigation
Expand file tree
/
Copy pathLinearRegression.py
More file actions
86 lines (66 loc) · 3.1 KB
/
Copy pathLinearRegression.py
File metadata and controls
86 lines (66 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#-*- coding: utf-8 -*-
import numpy as np
from helpers import *
def linearRegression(alpha=0.01,num_iters=10):
print("加载数据...\n")
data = loadtxtAndcsv_data("data.txt",",",np.float64) #读取数据
X = data[:,0:-1] # X对应0到倒数第2列 ,切片操作返回的是view,不占用额外的内存,但也不是numpy.ndarray类型
y = data[:,-1] # y对应最后一列
num_samples = len(y) # 总的数据条数
num_col = data.shape[1] # data的列数
print("归一化特征...\n")
X,mu,sigma = featureNormaliza(X) # 归一化
plot_X1_X2(X) # 画图看一下归一化效果
X = np.hstack((np.ones((num_samples,1)),X)) # 在X前加一列1,为了和w^ = [w b] 相匹配
theta = np.zeros((num_col,1))
y = y.reshape(-1,1) #将行向量转化为列
print("执行梯度下降算法....\n")
theta,J_history = gradientDescent(X, y, theta, alpha, num_iters)
plotJ(J_history, num_iters)
return mu,sigma,theta #返回均值mu,标准差sigma,和学习的结果theta
# 标准化数值
def featureNormaliza(X):
X_norm = np.array(X) # 避免篡改原始数据
# 计算每个特征的平均值和方差
mu = np.zeros((1,X.shape[1]))
sigma = np.zeros((1,X.shape[1]))
mu = np.mean(X_norm,0) # 求每一列的平均值(0指定为列,1代表行)
sigma = np.std(X_norm,0) # 求每一列的标准差
for i in range(X.shape[1]): # 遍历列
X_norm[:,i] = (X_norm[:,i]-mu[i])/sigma[i] # 标准化,区别于归一化
return X_norm,mu,sigma
# 梯度下降算法
def gradientDescent(X,y,theta,alpha,num_iters):
# m = len(y)
n = len(theta)
temp = np.matrix(np.zeros((n,num_iters))) # 暂存每次迭代计算的theta,转化为矩阵形式
J_history = np.zeros((num_iters,1)) # 记录每次迭代计算的代价值
for i in range(num_iters): # 遍历迭代次数
h = np.dot(X,theta) # 计算内积,matrix可以直接乘
temp[:,i] = theta - ((alpha)*(np.dot(np.transpose(X),h-y))) # 梯度的计算,取决于损失函数
theta = temp[:,i]
J_history[i] = computerCost(X,y,theta) #调用计算代价函数
print('.', end=' ')
return theta,J_history
# 计算代价函数
def computerCost(X,y,theta):
# m = len(y)
J = 0
J = (np.transpose(X@theta-y))@(X@theta-y)/2 # 平方误差和作为loss函数
return J
# 测试学习效果(预测)
def predict(mu,sigma,theta):
result = 0
# 注意归一化
predict = np.array([852,2])
norm_predict = (predict-mu)/sigma
final_predict = np.hstack((np.ones((1)),norm_predict))
result = np.dot(final_predict,theta) # 预测结果
return result
# 测试linearRegression函数
def testLinearRegression():
mu,sigma,theta = linearRegression(0.001,100)
print(f"\n计算的theta值为:{theta}\n")
print(f"\n预测结果为:{predict(mu, sigma, theta)}\n")
if __name__ == "__main__":
testLinearRegression()