1)目标
使用线性回归,预测房价。自变量有两个,分别为屋子数量和面积。使用这些数据来学习并预测未来某房屋价格。
2)总结
- 使用np做矩阵运算时可以时常用assert断言检查矩阵维数是否正确,防止不知名Bug产生。
- 设置向量时不要设置成数组型向量,要写成[[x,x2,x3]]这种形式或者将np.array的两个维度写全,避免向量被建立成数组格式,会遭遇无法转置等愚蠢的情况(血的教训)。
import numpy as np
a=np.ones(3)
b=a.T
print(a,'\n',b,)
输出如下,无法转置。
改成np.ones([1,3])后,
import numpy as np
a=np.ones([1,3])
b=a.T
print(a,'\n',b,)
输出如下,可以成功转置。
- 选择学习率时若学习率过小会发生无法拟合的情况,多次选择学习率,在保证运行效率的同时避免发散。
图:学习率=0.1683时,梯度上升。
3)代码
import numpy as np
import matplotlib.pyplot as plt
#导入数据
data = np.loadtxt('D:\python\homewrok\data_sets\ex1data2.txt', delimiter=",")
x1 = data[:,0]
x2 = data[:,1]
y = data[:,2]
#变量初始化
m = len(data)
n = 3
thetaT = np.zeros((n,1))
aerfa = 0.05
time=0
beilv=max(x1)-min(x1)
JJ=[]
x0=np.ones((m,1))
x1=x1/beilv
x1=x1.reshape(m,1)
x2=x2.reshape(m,1)
x = np.hstack((x0,x1,x2))
JJcost=0
#原函数h
def h(thetaT,x):
theta = thetaT.reshape(1, n) #参数向量转置
y = theta @ x
return y
#代价函数
def J(thetaT,x,y):
theta = thetaT.reshape(1, n)
J=(h(thetaT,x)-y)**2*(1/2/m)
#主循环
while time<5000:
JJcost=0
costT=np.zeros((n,1)) #中间向量归零
for i in range(m):
xT=x[i].reshape(n,1)
costT+=(h(thetaT,xT)-y[i])*xT
JJcost+=(h(thetaT,xT)-y[i])**2
JJ.append(JJcost[0,0]/2/m)
thetaT = thetaT - aerfa * costT / m
time+=1
plt.subplot(211)
plt.plot(range(0,5000),JJ)
plt.show()
print(thetaT,time,beilv)
4)运行结果
分别为theta0,theta1,theta2.
4)语法总结
A=np.zeros((3,3))
A=np.zeros_like(B)
data=np.arange(起始值,终值,步长)
data.reshape((4,5))