```python
#1. 导入库
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#2. 定义函数
def forward(x):
return x*w+b
def loss(x,y):
y_pred=forward(x)
return (y_pred-y)*(y_pred-y)
def MSE(w,b):
l_sum=0
print('w=',w,'\n','b=',b)
for x_val,y_val in zip(x_data,y_data):
y_pred_val=forward(x_val)
loss_val=loss(x_val,y_val)
l_sum+=loss_val
#print("\n",x_val,y_val,y_pred_val,'loss=',loss_val,'l_sum=',l_sum)
return l_sum/3
#3. 生成二维平面
x_data=[1.0,2.0,3.0]
y_data=[2.0,4.0,6.0]
w = np.arange(0.0,4.1,0.05)
b = np.arange(-2.0, 2.1, 0.05)
w, b = np.meshgrid(w, b)
h=MSE(w,b)
print('h=',h)
#4. 绘图
fig = plt.figure()
#ax = Axes3D(fig)#画不出图,不明白为什么
#有博主说:import matplotlib; matplotlib.use('TkAgg')
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(w, b, h,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/7fc6401d92ea403ab46fb9d90eb99a37.png#pic_center)