1.关于查看损失与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)*(y_pred - y)
w_list = []
mse_list = []
for w in np.arange(0.0,4.1,0.1):
print('w=',w)
sum_l = 0
for x_val,y_val in zip(x_data,y_data):
y_pred = forward(x_val)
loss_val = loss(x_val,y_val)
print('\t',x_val,y_val,y_pred,loss_val)
sum_l += loss_val
w_list.append(w)
mse_list.append(sum_l/3)
print("MSE:",sum_l/3)
plt.plot(w_list,mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()
2.部分结果输出(w=1.6-2.5,当w=2时MSE最小)
w= 1.6
1.0 2.0 1.6 0.15999999999999992
2.0 4.0 3.2 0.6399999999999997
3.0 6.0 4.800000000000001 1.43999999999