task: 绘制二维参数的损失函数

Python代码实现
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
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
return l_sum/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)
fig = plt.figure()
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()

得到三维图像