1、生成5阶单位矩阵
import numpy as np
np.identity(5)###任选一种
np.eye(5)
结果为:
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
2、获取ex1data1.txt文件数据,生成散点图
import matplotlib.pyplot as plt
data=np.loadtxt(r'D:\PYTHON\machine_learning\ML-homework\ex1-linear regression\ex1data1.txt',delimiter=",",dtype="float")####获取ex1data1,
#print(data)
x=data[:,0]
y=data[:,1]
plt.scatter(x,y,marker='x',color='red') ####画散点图
plt.xlabel('Profit in $10,000s')
plt.ylabel('Population of City in 10,000s')
plt.show()
得出散点图:
3、初始化数据并计算代价函数的值
###初始化数据
X=[np.ones(m),x]
X=np.array(X)
theta=np.zeros(2)
alpha=0.01
iterations=1500##迭代次数
J=0
for a in range(0,m):
J_1=theta[0]+theta[1]*X[1,a]-y[a]
print(J_1)
J_1=J_1*J_1
J=J+J_1
J=J/2/m
结果为32.072733877455654
4、梯度下降
代价函数是theta的函数
###初始化数据
X=[np.ones(m),x]#####加一列为了方便计算theta[0]+theta[1]*X[1,a] theta*X
X=np.array(X)
theta=np.zeros(2)
alpha=0.01
iterations=1500##迭代次数
for b in range(0,iterations):
J=0
for c in range(0, m):
J_1 = theta[0] + theta[1] * X[1, c] - y[c]
J = J + J_1
theta_0=theta[0]-J/m*alpha
J = 0
for c in range(0, m):
J_1 = (theta[0] + theta[1] * X[1, c] - y[c])*X[1, c]
J = J + J_1
theta_1 = theta[1] - J / m * alpha
theta[0]=theta_0
theta[1]=theta_1
print(theta)
print(np.matrix(theta).shape)
print(np.matrix([1,3.5]).shape)
print(np.matrix([1,3.5])*np.matrix(theta).T)
print(np.matrix([1,7])*np.matrix(theta).T)
输出结果:
[-3.63029144 1.16636235]
(1, 2)
(1, 2)
[[0.45197679]]
[[4.53424501]]
5、绘制一次函数的图像
J_2=theta[0]+theta[1]*x
plt.plot(x,J_2)
plt.show()
该链接为笔记链接 https://www.notion.so/cd5d8e24c8644d17a54bc29ca3c7999f
由于本人对numpy并不熟练,代码写不不太好,仅供参考