问题描述
问题分析
代码
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) * (y_pred - y)
# w权重, mes 平方误差
w_list = []
mes_list = []
# 权重采样
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_prea_val = forward(x_val) # 计算预测
loss_val = loss(x_val, y_val) # 计算损失
l_sum += loss_val
print('\t', x_val, y_val, y_prea_val, loss_val)
print('MES = ', l_sum / 3)
w_list.append(w)
mes_list.append(l_sum / 3)
# 绘图展示
plt.plot(w_list, mes_list)
plt.ylabel('Loss')
plt.xlabel('W')
plt.show()
实现效果
课后练习
传送门线性模型课后练习
参考资料
传送门线性模型