源自课程:《PyTorch深度学习实践》完结合集
Chapter2 线性模型
"""
寻找特定的w使得均方误差最小
"""
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
# 定义损失函数
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
# 迭代计算与输出信息
w_list = []
mse_list = []
for w in np.arange(0.0, 4.1, 0.1):
print("w = ", w)
l_sum = 0
for x_var, y_var in zip(x_data, y_data):
y_pred_var = forward(x_var)
loss_val = loss(x_var, y_var)
l_sum += loss_val
print('\t', x_var, y_var, y_pred_var, loss_val)
print("MSE = ", l_sum / 3)
w_list.append(w)
mse_list.append(l_sum / 3)
plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()