import numpy as np
import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
a = 0.01
x = np.array([[2104,3],
[1600,3],
[2400,3],
[1416,2],
[3000,4]])
t = np.array([[400],
[330],
[369],
[232],
[540]])
h = np.array([[0],
[0],
[0],
[0],
[0]
])
E = 10e-4
e0 =0
e1 =0
e2 =0
b0 = 0
b1 = 0
b2 = 0
for i in range(0, 5):
e0 = e0 + (h[i] - t[i])
e1 = e1 + (h[i] - t[i]) * x[i, 0]
e2 = e2 + (h[i] - t[i]) * x[i, 1]
while 1:
b0 = random.random()
b1 = random.random()
b2 = random.random()
for i in range(0, 5):
h[i] = b0 + b1 * x[i, 0] + b2 * x[i, 1]
if e0>=E or e1>=E or e2>=E:
b0 = b0 - a*e0
b1 = b1 - a*e1
b2 = b2 - a*e2
for i in range(0, 5):
e0 = e0 + (h[i] - t[i])
e1 = e1 + (h[i] - t[i]) * x[i, 0]
e2 = e2 + (h[i] - t[i]) * x[i, 1]
else:
break
print(b0 , b1 , b2)
def fun(x1,x2):
return b0 + b1 * x1 + b2 * x2
fig1=plt.figure()#创建一个绘图对象
ax=Axes3D(fig1)#用这个绘图对象创建一个Axes对象(有3D坐标)
x1=np.arange(500,5000,10)
x2=np.arange(0,10,1)#创建了从0到100,步长为1的arange对象
#至此X,Y分别表示了取样点的横纵坐标的可能取值
#用这两个arange对象中的可能取值一一映射去扩充为所有可能的取样点
x1,x2=np.meshgrid(x1,x2)
h=fun(x1,x2)#用取样点横纵坐标去求取样点Z坐标
plt.title("This is main title")#总标题
ax.plot_surface(x1, x2, h, rstride=1, cstride=1, cmap=plt.cm.coolwarm)#用取样点(x,y,h)去构建曲面
ax.set_xlabel('x label', color='r')
ax.set_ylabel('y label', color='g')
ax.set_zlabel('z label', color='b')#给三个坐标轴注明
plt.show()#显示模块中的所有绘图对象
运行结果:
0.17456628634090443 0.2934875788695881 0.26886273388138415
生成图像: