|
| 1 | +#-*- coding: utf-8 -*- |
1 | 2 | import numpy as np |
2 | 3 | from matplotlib import pyplot as plt |
| 4 | +from matplotlib.font_manager import FontProperties |
| 5 | +font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) # 解决windows环境下画图汉字乱码问题 |
3 | 6 |
|
4 | 7 |
|
5 | 8 | def linearRegression(alpha=0.01,num_iters=400): |
6 | | - print "加载数据...\n" |
| 9 | + print u"加载数据...\n" |
7 | 10 |
|
8 | | - data = loadtxtAndcsv_data("data.txt",",",np.float64) #读取数据 |
9 | | - X = data[:,0:-1] # X对应0到倒数第2列 |
10 | | - y = data[:,-1] # y对应最后一列 |
11 | | - m = len(y) # 总的数据条数 |
12 | | - col = data.shape[1] # data的列数 |
| 11 | + data = loadtxtAndcsv_data("data.txt",",",np.float64) #读取数据 |
| 12 | + X = data[:,0:-1] # X对应0到倒数第2列 |
| 13 | + y = data[:,-1] # y对应最后一列 |
| 14 | + m = len(y) # 总的数据条数 |
| 15 | + col = data.shape[1] # data的列数 |
13 | 16 |
|
14 | | - X,mu,sigma = featureNormaliza(X) # 归一化 |
15 | | - plot_X1_X2(X) # 画图看一下归一化效果 |
| 17 | + X,mu,sigma = featureNormaliza(X) # 归一化 |
| 18 | + plot_X1_X2(X) # 画图看一下归一化效果 |
16 | 19 |
|
17 | | - X = np.hstack((np.ones((m,1)),X)) # 在X前加一列1 |
| 20 | + X = np.hstack((np.ones((m,1)),X)) # 在X前加一列1 |
18 | 21 |
|
19 | | - print "\n执行梯度下降算法....\n" |
| 22 | + print u"\n执行梯度下降算法....\n" |
20 | 23 |
|
21 | 24 | theta = np.zeros((col,1)) |
22 | | - y = y.reshape(-1,1) #将行向量转化为列 |
| 25 | + y = y.reshape(-1,1) #将行向量转化为列 |
23 | 26 | theta,J_history = gradientDescent(X, y, theta, alpha, num_iters) |
24 | 27 |
|
25 | 28 | plotJ(J_history, num_iters) |
26 | 29 |
|
27 | | - return mu,sigma,theta #返回均值mu,标准差sigma,和学习的结果theta |
| 30 | + return mu,sigma,theta #返回均值mu,标准差sigma,和学习的结果theta |
28 | 31 |
|
29 | 32 |
|
30 | | -# 加载txt和csv文件 |
| 33 | +# 加载txt和csv文件 |
31 | 34 | def loadtxtAndcsv_data(fileName,split,dataType): |
32 | 35 | return np.loadtxt(fileName,delimiter=split,dtype=dataType) |
33 | 36 |
|
34 | | -# 加载npy文件 |
| 37 | +# 加载npy文件 |
35 | 38 | def loadnpy_data(fileName): |
36 | 39 | return np.load(fileName) |
37 | 40 |
|
38 | | -# 归一化feature |
| 41 | +# 归一化feature |
39 | 42 | def featureNormaliza(X): |
40 | | - X_norm = np.array(X) #将X转化为numpy数组对象,才可以进行矩阵的运算 |
41 | | - #定义所需变量 |
| 43 | + X_norm = np.array(X) #将X转化为numpy数组对象,才可以进行矩阵的运算 |
| 44 | + #定义所需变量 |
42 | 45 | mu = np.zeros((1,X.shape[1])) |
43 | 46 | sigma = np.zeros((1,X.shape[1])) |
44 | 47 |
|
45 | | - mu = np.mean(X_norm,0) # 求每一列的平均值(0指定为列,1代表行) |
46 | | - sigma = np.std(X_norm,0) # 求每一列的标准差 |
47 | | - for i in range(X.shape[1]): # 遍历列 |
48 | | - X_norm[:,i] = (X_norm[:,i]-mu[i])/sigma[i] # 归一化 |
| 48 | + mu = np.mean(X_norm,0) # 求每一列的平均值(0指定为列,1代表行) |
| 49 | + sigma = np.std(X_norm,0) # 求每一列的标准差 |
| 50 | + for i in range(X.shape[1]): # 遍历列 |
| 51 | + X_norm[:,i] = (X_norm[:,i]-mu[i])/sigma[i] # 归一化 |
49 | 52 |
|
50 | 53 | return X_norm,mu,sigma |
51 | 54 |
|
52 | | -# 画二维图 |
| 55 | +# 画二维图 |
53 | 56 | def plot_X1_X2(X): |
54 | 57 | plt.scatter(X[:,0],X[:,1]) |
55 | 58 | plt.show() |
56 | 59 |
|
57 | 60 |
|
58 | | -# 梯度下降算法 |
| 61 | +# 梯度下降算法 |
59 | 62 | def gradientDescent(X,y,theta,alpha,num_iters): |
60 | 63 | m = len(y) |
61 | 64 | n = len(theta) |
62 | 65 |
|
63 | | - temp = np.matrix(np.zeros((n,num_iters))) # 暂存每次迭代计算的theta,转化为矩阵形式 |
| 66 | + temp = np.matrix(np.zeros((n,num_iters))) # 暂存每次迭代计算的theta,转化为矩阵形式 |
64 | 67 |
|
65 | 68 |
|
66 | | - J_history = np.zeros((num_iters,1)) #记录每次迭代计算的代价值 |
| 69 | + J_history = np.zeros((num_iters,1)) #记录每次迭代计算的代价值 |
67 | 70 |
|
68 | | - for i in range(num_iters): # 遍历迭代次数 |
69 | | - h = np.dot(X,theta) # 计算内积,matrix可以直接乘 |
70 | | - temp[:,i] = theta - ((alpha/m)*(np.dot(np.transpose(X),h-y))) #梯度的计算 |
| 71 | + for i in range(num_iters): # 遍历迭代次数 |
| 72 | + h = np.dot(X,theta) # 计算内积,matrix可以直接乘 |
| 73 | + temp[:,i] = theta - ((alpha/m)*(np.dot(np.transpose(X),h-y))) #梯度的计算 |
71 | 74 | theta = temp[:,i] |
72 | | - J_history[i] = computerCost(X,y,theta) #调用计算代价函数 |
| 75 | + J_history[i] = computerCost(X,y,theta) #调用计算代价函数 |
73 | 76 | print '.', |
74 | 77 | return theta,J_history |
75 | 78 |
|
76 | | -# 计算代价函数 |
| 79 | +# 计算代价函数 |
77 | 80 | def computerCost(X,y,theta): |
78 | 81 | m = len(y) |
79 | 82 | J = 0 |
80 | 83 |
|
81 | | - J = (np.transpose(X*theta-y))*(X*theta-y)/(2*m) #计算代价J |
| 84 | + J = (np.transpose(X*theta-y))*(X*theta-y)/(2*m) #计算代价J |
82 | 85 | return J |
83 | 86 |
|
84 | | -# 画每次迭代代价的变化图 |
| 87 | +# 画每次迭代代价的变化图 |
85 | 88 | def plotJ(J_history,num_iters): |
86 | 89 | x = np.arange(1,num_iters+1) |
87 | 90 | plt.plot(x,J_history) |
88 | | - plt.xlabel("num_iters") |
89 | | - plt.ylabel("J") |
| 91 | + plt.xlabel(u"迭代次数",fontproperties=font) # 注意指定字体,要不然出现乱码问题 |
| 92 | + plt.ylabel(u"代价值",fontproperties=font) |
| 93 | + plt.title(u"代价随迭代次数的变化",fontproperties=font) |
90 | 94 | plt.show() |
91 | 95 |
|
92 | | -# 测试linearRegression函数 |
| 96 | +# 测试linearRegression函数 |
93 | 97 | def testLinearRegression(): |
94 | 98 | mu,sigma,theta = linearRegression(0.01,400) |
95 | | - print "\n计算的theta值为:\n",theta |
96 | | - print "\n预测结果为:%f"%predict(mu, sigma, theta) |
| 99 | + print u"\n计算的theta值为:\n",theta |
| 100 | + print u"\n预测结果为:%f"%predict(mu, sigma, theta) |
97 | 101 |
|
98 | | -# 测试学习效果(预测) |
| 102 | +# 测试学习效果(预测) |
99 | 103 | def predict(mu,sigma,theta): |
100 | 104 | result = 0 |
101 | | - # 注意归一化 |
| 105 | + # 注意归一化 |
102 | 106 | predict = np.array([1650,3]) |
103 | 107 | norm_predict = (predict-mu)/sigma |
104 | 108 | final_predict = np.hstack((np.ones((1)),norm_predict)) |
105 | 109 |
|
106 | | - result = np.dot(final_predict,theta) # 预测结果 |
| 110 | + result = np.dot(final_predict,theta) # 预测结果 |
107 | 111 | return result |
108 | 112 |
|
109 | 113 |
|
|
0 commit comments