Pytorch练习--使用Axes3D的库绘制3D的Loss曲线
程序员文章站
2022-07-13 10:38:59
...
使用Axes3D的库绘制3D的Loss曲线
Data
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
使用线性模型y = w*x + b 绘制Loss曲线
带入numpy库和matplotlib库
import numpy as np
import matplotlib.pyplot as plt
定义模型
def forward(x):
return x * w + b
定义Loss函数
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
计算Loss
w_list = []
b_list = []
mse_list = np.zeros((20, 20), dtype=float) # 定义一个二维的list
for i, w in enumerate(np.arange(0.0, 4.0, 0.2)): # 权重w
print('w=', w)
for j, b in enumerate(np.arange(-2.0, 2.0, 0.2)): # bias
print('b=', b)
l_sum = 0.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) # 计算loss
l_sum += loss_val # loss的总和
print('\t', x_val, y_val, y_pred_val, loss_val) # x的真实值,y的真实值,y的预测值,loss值
print('MSE=', l_sum / 3)
mse_list[i][j] = l_sum / 3
if w==0:
b_list.append(b) # bias的list
w_list.append(w) # 权重w的list
输出
使用numpy的meshgrid函数将w_list和b_list组成二维的numpy类型的数组,以及将mse_list转换为numpy类型的数组
x, y= np.meshgrid(w_list, b_list)
z = np.array(mse_list)
当前w_list, b_list, mse_list的维度就变成了
print("w的维度:", x.shape)
print("b的维度:", y.shape)
print("mse的维度:", z.shape)
绘制3D的Loss曲线
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, z, rstride = 1, # row行步长
cstride = 2, # colum列步长
cmap = 'rainbow') # 渐变颜色
plt.show()