【PyTorch深度学习实践】-- 线性模型

学习视频:B站 刘二大人《PyTorch深度学习实践》完结合集

一、线性模型

三个步骤:

  • 数据集
  • 选择模型
  • 训练

image-20230225082543139

损失函数:

image-20230225083857429

代码:

import numpy as np
import matplotlib.pyplot as plt

x_data = [1.0,2.0,3.0]  #输入x
y_data = [2.0,4.0,6.0]  #输出y

def forward(x):    #线性模型
    return x * w

def loss(x,y):
    y_pred = forward(x)  #计算y_hat
    return (y_pred - y) * (y_pred - y) #损失函数,(y_hat-y)的平方

w_list = []  #记录下w与其对应的mse
mse_list = []
for w in np.arange(0.0,4.1,0.1):  #列举w
    print("w",w)
    l_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)
        l_sum += loss_val
        print('\t',x_val,y_val,y_pred_val,loss_val)  #输出x,y以及y_hat,还有loss
    print("MSE=",l_sum / 3)
    w_list.append(w)
    mse_list.append(l_sum / 3)

plt.plot(w_list,mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()

运行结果:

image-20230225090048088

课后习题:

image-20230225085807158

代码:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from pylab import *

#这里假设模型是y = 2*x + 2
x_data = [1.0,2.0,3.0]  #输入x
y_data = [4.0,6.0,8.0]  #输出y

def forward(x):    #线性模型
    return x * w + b

def loss(x,y):
    y_pred = forward(x)  #计算y_hat
    return (y_pred - y) * (y_pred - y) #损失函数,(y_hat-y)的平方

mse_list = []
W = np.arange(0.0,4.1,0.1)
B = np.arange(0.0,4.1,0.1)
[w,b] = np.meshgrid(W,B)

l_sum = np.zeros_like(w)
for x_val,y_val in zip(x_data,y_data):
    y_pred_val = forward(x_val)
    loss_val = loss(x_val,y_val)
    l_sum += loss_val
    print('\t',x_val,y_val,y_pred_val,loss_val)  #输出x,y以及y_hat,还有loss

# #查找loss最低的w,b取值
target = {'loss':float('inf'),'w':0,'b':0}  #定义字典 将loss设为正无穷大,w=0,b=0
for i in range(l_sum.shape[0]): #读取l_sum的行数
    for j in range(l_sum.shape[1]):  #读取列数
        if l_sum[i][j] < target['loss']:
            target['loss'] = l_sum[i][j]
            target['w'] = w[i][j]
            target['b'] = b[i][j]
print('target linear model is y = %.2f * x + %.2f' % (target['w'], target['b']))

#定义三维坐标轴
fig = plt.figure()
ax = Axes3D(fig)
fig.add_axes(ax)

ax.plot_surface(w, b, l_sum/3,cmap=plt.cm.coolwarm)
ax.set_xlabel('w')
ax.set_ylabel('b')
ax.set_zlabel('loss')
plt.show()

image-20230225094156522

参考资料:

https://blog.csdn.net/qq_36271858/article/details/115868825

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值