Pytorch深度学习:线性模型

问题:

        若x=1,2,3与y=2,4,6一一对应,那么当x等于4时,y等于?

解决过程:

①构建模型:

        模型有线性,抛物线性,指数型模型,这里讨论线性模型,f(x)=w*x+b,这里由数据易简化为f(x)=w*x。

②求未知参数w

        y_pred=x*w,w为可变参数。

        loss = (y_pred-y)*(y_pred-y) ,得出损失值

        l_sum为所有该w的loss值相加,为总损失值

        mse = l_sum/3,当mse达到最小时,代表直线拟合程度最高,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 = 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)
        sum += loss_val
        print("\t",x_val,y_val,y_pred_val,loss_val)
    print("mse = ",sum/3)
    w_list.append(w)
    mse_list.append(sum/3)
plt.plot(w_list,mse_list)
plt.ylabel('loss')
plt.xlabel('w')
plt.show()
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 = 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)
        sum += loss_val
        print("\t",x_val,y_val,y_pred_val,loss_val)
    print("mse = ",sum/3)
    w_list.append(w)
    mse_list.append(sum/3)
plt.plot(w_list,mse_list)
plt.ylabel('loss')
plt.xlabel('w')
plt.show()

打印图表:

Pytorch深度学习:线性模型_第1张图片

可得当w = 2时,直线拟合程度最高,故 y = 2*x。

 

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