Skip to content

Commit b1768b8

Browse files
committed
Linear Regression
1 parent 0c9437e commit b1768b8

3 files changed

Lines changed: 50 additions & 43 deletions

File tree

‎LinearRegression/LinearRegression.py‎

Lines changed: 44 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,113 @@
1+
#-*- coding: utf-8 -*-
12
import numpy as np
23
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环境下画图汉字乱码问题
36

47

58
def linearRegression(alpha=0.01,num_iters=400):
6-
print "加载数据...\n"
9+
print u"加载数据...\n"
710

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的列数
1316

14-
X,mu,sigma = featureNormaliza(X) # 归一化
15-
plot_X1_X2(X) # 画图看一下归一化效果
17+
X,mu,sigma = featureNormaliza(X) # 归一化
18+
plot_X1_X2(X) # 画图看一下归一化效果
1619

17-
X = np.hstack((np.ones((m,1)),X)) # 在X前加一列1
20+
X = np.hstack((np.ones((m,1)),X)) # 在X前加一列1
1821

19-
print "\n执行梯度下降算法....\n"
22+
print u"\n执行梯度下降算法....\n"
2023

2124
theta = np.zeros((col,1))
22-
y = y.reshape(-1,1) #将行向量转化为列
25+
y = y.reshape(-1,1) #将行向量转化为列
2326
theta,J_history = gradientDescent(X, y, theta, alpha, num_iters)
2427

2528
plotJ(J_history, num_iters)
2629

27-
return mu,sigma,theta #返回均值mu,标准差sigma,和学习的结果theta
30+
return mu,sigma,theta #返回均值mu,标准差sigma,和学习的结果theta
2831

2932

30-
# 加载txt和csv文件
33+
# 加载txt和csv文件
3134
def loadtxtAndcsv_data(fileName,split,dataType):
3235
return np.loadtxt(fileName,delimiter=split,dtype=dataType)
3336

34-
# 加载npy文件
37+
# 加载npy文件
3538
def loadnpy_data(fileName):
3639
return np.load(fileName)
3740

38-
# 归一化feature
41+
# 归一化feature
3942
def featureNormaliza(X):
40-
X_norm = np.array(X) #将X转化为numpy数组对象,才可以进行矩阵的运算
41-
#定义所需变量
43+
X_norm = np.array(X) #将X转化为numpy数组对象,才可以进行矩阵的运算
44+
#定义所需变量
4245
mu = np.zeros((1,X.shape[1]))
4346
sigma = np.zeros((1,X.shape[1]))
4447

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] # 归一化
4952

5053
return X_norm,mu,sigma
5154

52-
# 画二维图
55+
# 画二维图
5356
def plot_X1_X2(X):
5457
plt.scatter(X[:,0],X[:,1])
5558
plt.show()
5659

5760

58-
# 梯度下降算法
61+
# 梯度下降算法
5962
def gradientDescent(X,y,theta,alpha,num_iters):
6063
m = len(y)
6164
n = len(theta)
6265

63-
temp = np.matrix(np.zeros((n,num_iters))) # 暂存每次迭代计算的theta,转化为矩阵形式
66+
temp = np.matrix(np.zeros((n,num_iters))) # 暂存每次迭代计算的theta,转化为矩阵形式
6467

6568

66-
J_history = np.zeros((num_iters,1)) #记录每次迭代计算的代价值
69+
J_history = np.zeros((num_iters,1)) #记录每次迭代计算的代价值
6770

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))) #梯度的计算
7174
theta = temp[:,i]
72-
J_history[i] = computerCost(X,y,theta) #调用计算代价函数
75+
J_history[i] = computerCost(X,y,theta) #调用计算代价函数
7376
print '.',
7477
return theta,J_history
7578

76-
# 计算代价函数
79+
# 计算代价函数
7780
def computerCost(X,y,theta):
7881
m = len(y)
7982
J = 0
8083

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
8285
return J
8386

84-
# 画每次迭代代价的变化图
87+
# 画每次迭代代价的变化图
8588
def plotJ(J_history,num_iters):
8689
x = np.arange(1,num_iters+1)
8790
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)
9094
plt.show()
9195

92-
# 测试linearRegression函数
96+
# 测试linearRegression函数
9397
def testLinearRegression():
9498
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)
97101

98-
# 测试学习效果(预测)
102+
# 测试学习效果(预测)
99103
def predict(mu,sigma,theta):
100104
result = 0
101-
# 注意归一化
105+
# 注意归一化
102106
predict = np.array([1650,3])
103107
norm_predict = (predict-mu)/sigma
104108
final_predict = np.hstack((np.ones((1)),norm_predict))
105109

106-
result = np.dot(final_predict,theta) # 预测结果
110+
result = np.dot(final_predict,theta) # 预测结果
107111
return result
108112

109113

‎images/LinearRegression_01.png‎

5.03 KB
Loading

‎readme.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,10 @@ def featureNormaliza(X):
7474
```
7575
- 注意预测的时候也需要均值归一化数据
7676

77-
### 3、最终运行结果
78-
![enter code here][1]
77+
### 4、最终运行结果
78+
![enter description here][1]
7979

80-
[1]: ./images/LinearRegression_01.png "LinearRegression_01.png"
80+
81+
[1]: ./images/LinearRegression_01.png "LinearRegression_01.png"
82+
83+
## 逻辑回归

0 commit comments

Comments
 (0)