(刘二大人)PyTorch深度学习实践-线性模型

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.4399999999999984
MSE: 0.746666666666666
w= 1.7000000000000002
	 1.0 2.0 1.7000000000000002 0.0899999999999999
	 2.0 4.0 3.4000000000000004 0.3599999999999996
	 3.0 6.0 5.1000000000000005 0.809999999999999
MSE: 0.4199999999999995
w= 1.8
	 1.0 2.0 1.8 0.03999999999999998
	 2.0 4.0 3.6 0.15999999999999992
	 3.0 6.0 5.4 0.3599999999999996
MSE: 0.1866666666666665
w= 1.9000000000000001
	 1.0 2.0 1.9000000000000001 0.009999999999999974
	 2.0 4.0 3.8000000000000003 0.0399999999999999
	 3.0 6.0 5.7 0.0899999999999999
MSE: 0.046666666666666586
w= 2.0
	 1.0 2.0 2.0 0.0
	 2.0 4.0 4.0 0.0
	 3.0 6.0 6.0 0.0
MSE: 0.0
w= 2.1
	 1.0 2.0 2.1 0.010000000000000018
	 2.0 4.0 4.2 0.04000000000000007
	 3.0 6.0 6.300000000000001 0.09000000000000043
MSE: 0.046666666666666835
w= 2.2
	 1.0 2.0 2.2 0.04000000000000007
	 2.0 4.0 4.4 0.16000000000000028
	 3.0 6.0 6.6000000000000005 0.36000000000000065
MSE: 0.18666666666666698
w= 2.3000000000000003
	 1.0 2.0 2.3000000000000003 0.09000000000000016
	 2.0 4.0 4.6000000000000005 0.36000000000000065
	 3.0 6.0 6.9 0.8100000000000006
MSE: 0.42000000000000054
w= 2.4000000000000004
	 1.0 2.0 2.4000000000000004 0.16000000000000028
	 2.0 4.0 4.800000000000001 0.6400000000000011
	 3.0 6.0 7.200000000000001 1.4400000000000026
MSE: 0.7466666666666679
w= 2.5
	 1.0 2.0 2.5 0.25
	 2.0 4.0 5.0 1.0
	 3.0 6.0 7.5 2.25
MSE: 1.1666666666666667

3.图像查看

(刘二大人)PyTorch深度学习实践-线性模型_第1张图片

 

你可能感兴趣的:(PyTorch,深度学习,pytorch,python)