先说一下我的代码中一些函数的意思
np.dot(x,y) 是将两个矩阵进行点乘
np.loadtxt() 从文件中读取数据
np.vstack() 将矩阵叠加在一起,在此处就是给刚从文件中读取的X再加全为1的一列
plt.plot(x,y,“r-”) 绘图,x为横坐标,y为纵坐标,后面的参数意思是“红的 直线 ”
import numpy as np
import matplotlib.pyplot as plt
def computecost(x,y,m,theta):
return(float(((np.dot(x,theta) - y).dot(np.dot(x,theta) - y)) / (2 * m)))
def gradientDescent(x,y,m,theta,J,num_iters,alpha):
for i in range(num_iters):
delta = np.dot(x.T , np.dot(x,theta) - y) / m
theta = theta - alpha * delta
J[i] = computecost(x,y,m,theta)
return theta,J
data = np.loadtxt(“ex1data1.txt”,delimiter=’,’)
x = data[:,0]
y = data[:,1]
#先将数据以红色的点绘制出来
plt.plot(x,y,“ro”)
plt.xlabel(“population”)
plt.ylabel(“profit”)
plt.title(“po-pr”)
plt.show()
m = np.size(y,0)
#将X变为两列,第一列全为一
x = np.vstack((np.ones((m,)),x)).T
#制造theta
theta = np.zeros((2,))
#步长和迭代次数
alpha = 0.01
num_iters = 1000
#制造J函数
J = np.zeros((num_iters,))
#计算theta和J函数
theta,J = gradientDescent(x,y,m,theta,J,num_iters,alpha)
#绘制最终效果图
plt.plot(x[:,1],y,‘ro’,label = ‘Training data’)
plt.plot(x[:,1],np.dot(x,theta),‘b-’,label = ‘Lineer regression’)
plt.xlabel(“population”)
plt.ylabel(“profit”)
plt.title(“po-pr”)
plt.show()