``
看了刘老师的课,自己看了官方文档以及底下评论的一个大佬,自己综合了一下!
以下是我写的代码:
**import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
# X,Y数据
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
# 函数定义
def forward(x):
return x * w + b
def loss(x,y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
mse_list = []
# 定义坐标轴
W = np.arange(0.0, 4.1, 0.1)
B = np.arange(-2.0, 2.0, 0.1)
[w, b] = np.meshgrid(W,B)
# 数据处理
l_sum = 0
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
# Add a color bar which maps values to colors.
# Plot the surface.
surf = ax.plot_surface(w, b, l_sum/3, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.set_zlim(0, 35)
ax.zaxis.set_major_locator(LinearLocator(8))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.0f'))
ax.text2D(0.4, 0.92, "Cost Values", transform=ax.transAxes)
# 设置坐标轴名称
ax.set_xlabel('w')
ax.set_ylabel('b')
ax.set_zlabel('loss')
plt.show()**
最终的效果图如下:
![侧面图](https://img-blog.csdnimg.cn/20210411092254363.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyOTUzMDM2,size_16,color_FFFFFF,t_70#pic_center)
以下是官方文档的地址以及我参考的代码:
[参考代码:](https://blog.csdn.net/weixin_42296879/article/details/113573275?spm=1001.2014.3001.5501)
[3D绘图代码](https://www.cnblogs.com/wuwen19940508/p/8638266.html)