#变量初始化#要从文件中将X和Y的值分离出来
cols = data.shape[1]#shape[1]是矩阵的第二维长度,也就是列数#iloc函数的用法#比如iloc[ : , 0:2 ] 第一个“:”是遍历的意思 第二个“0:2” 是从是第0、1列 #因为在python中“:”是左闭右开的区间 0:2 等价于[0,2)
X = data.iloc[:,0:cols-1]#X是原矩阵去掉最后一列组成的的矩阵
Y = data.iloc[:,cols-1:cols]#Y是最后一列组成的矩阵
#预览一下X
X.head()#head()是观察前5行
Ones
Population
0
1
6.1101
1
1
5.5277
2
1
8.5186
3
1
7.0032
4
1
5.8598
#预览一下Y
Y.head()
Profit
0
17.5920
1
9.1302
2
13.6620
3
11.8540
4
6.8233
#np.matrix函数:创建一个新的相同的矩阵。当修改新矩阵时,原来的矩阵不会改变。#values函数:获取值
X = np.matrix(X.values)
Y = np.matrix(Y.values)#np.array函数:创建一个数组#然后再用np.matrix把它转成矩阵
theta = np.matrix(np.array([0,0]))
#查看一下它们的形状
X.shape, theta.shape, Y.shape
((97, 2), (1, 2), (97, 1))
#梯度下降函数#alpha是学习速率,iters是迭代次数()defgradientDescent(X, Y, theta, alpha, iters):#np.zeros是产生一个给定形状和类型的用0填充的数组
temp = np.matrix(np.zeros(theta.shape))#定义一个和theta相同形状的零矩阵
parameters =int(theta.ravel().shape[1])#ravel函数:ravel是散开的意思,就是把theta第二列散开成一维数组#这个函数产生的是副本,不会改变原来的theta矩阵
cost = np.zeros(iters)#以下是梯度下降公式的实现for i inrange(iters):
error =(X * theta.T)- Y
for j inrange(parameters):
term = np.multiply(error, X[:,j])
temp[0,j]= theta[0,j]-((alpha /len(X))* np.sum(term))
theta = temp
cost[i]= computeCost(X, Y, theta)return theta, cost