绘制Loss曲线
b站课程链接:https://www.bilibili.com/video/BV1Y7411d7Ys?p=2
import绘制曲线的库和numpy库
import numpy as np
import matplotlib.pyplot as plt # 画图库
设置数据
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
定义模型
def forward(x):
return x * w
定义Loss函数
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
定义权重和MSE(均方误差)的list
w_list = []
mse_list = []
计算MSE(均方误差)
for w in np.arange(0.0, 4.1, 0.1):
print('w=', w)
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) # 计算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)
w_list.append(w) # 权重w的list
mse_list.append(l_sum / 3) # 均方误差
输出
绘制Loss曲线
plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()
输出