UP:B站-刘二大人
原视频链接:2.线性模型_哔哩哔哩_bilibili
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-y_pred) * (y-y_pred)
w_list = []
mse_list = []
for w in np.arange(0.0, 4.1, 0.1):
print("w=", w)
loss_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_sum += loss_val
print("mse=", loss_sum/len(x_data))
w_list.append(w)
mse_list.append(loss_sum/len(x_data))
plt.plot(w_list, mse_list)
plt.xlabel(w_list)
plt.ylabel(mse_list)
plt.show()