《PyTorch深度学习实践》01.PyTorch实现Linear Regression

Nannan Lv5

《PyTorch深度学习实践》.PyTorch实现Linear Regression

image-20240710161936109

一、步骤

  1. Prepare dataset
  2. Design model using Class
    • inherit from nn.Module
  3. Construct loss and optimizer
    • using PyTorch API
  4. Training cycle
    • forward(算损失), backward(梯度设为0,并反向传播算梯度), update(梯度下降更新梯度)

Step1:Prepare dataset

image-20240710163204541

Step2:Design model

image-20240710163543174

继承nn.Module:

image-20240710163814466

至少实现两个函数,_ init _构造函数和forward()前馈函数

backward()会根据我们的计算图自动构建,可以继承Functions(类)来构建自己的计算块(如果我们的计算块不能用现成的构造,我们可以自己写)

image-20240710164016222

我们分别来看这两个函数:

image-20240710165352381

PyTorch的nn.Linear()是用于设置网络中的全连接层的,其用法和形参说明如下:

image-20240710164743872

  • in_features指的是输入的二维张量的大小,即输入的[batch_size, size]中的size。

  • out_features指的是输出的二维张量的大小,即输出的二维张量的形状为[batch_size,output_size],当然,它也代表了该全连接层的神经元个数。   

    从输入输出的张量的shape角度来理解,相当于一个输入为[batch_size, in_features]的张量变换成了[batch_size, out_features]的输出张量。

image-20240710165203556

我们继续看forward函数:

image-20240710165326636

我们看到,直接在对象后面加()是什么意思呢?

这也是函数和类的一个区别,为了使得类/实例能够像函数一样使用,成为可调用对象,call()魔法方法出现了。

在PyTorch源码的torch/nn/modules/module.py文件中,有一条_ call _语句和一条forward语句,如下:

1
2
__call__ : Callable[…, Any] = _call_impl
forward: Callable[…, Any] = _forward_unimplemented

在PyTorch中nn.Module类是所有神经网络模块的基类,你的网络也应该继承这个类,需要重载_ init _和forward函数)。

pytorch主要也是按照__call__, __init__,forward三个函数实现网络层之间的架构的

我们举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
class Foobar:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print("Hello" + str(args[0]))
forward(self,)
foobar = Foobar()
foobar(1,2,3)# Hello1
def func(*args, **kwargs):
print(args) #(1,2,3,4)
print(kwargs) #['x':3,'y':5]
func(1,2,3,4,x=3,y=5)

Step3:Construct Loss and Optimizer

image-20240710181745528

Step4:Traing Cycle

image-20240710182832924

②loss ③backward ④update

Step5: Test Model

image-20240710183026692

weight是一个矩阵,我们用.item()让它显示这里面的数值。

image-20240710183251259

二、Code

image-20240710184921119
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import torch

x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[2.0],[4.0],[6.0]])

class LinerModel(torch.nn.Model):
def __init__(self):
super(LinerModel,self.__init__)
self.liner = torch.nn.liner(1,1)

def forward(self,x):
y_pred = self.liner(x)
return y_pred

model = LinerModel()

criterion = torch.nn.MSELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)

for epoch in range(100):
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
print(epoch,loss)

optimizer.zero_grad()
loss.backward()
optimizer.step()


print('w=',model.liner.weight.item())
print('b=',model.liner.bias.item())

x_test = torch.Tensor([4.0])
y_test = model(x_test)
print('y_pred=',y_test.data)
  • Title: 《PyTorch深度学习实践》01.PyTorch实现Linear Regression
  • Author: Nannan
  • Created at : 2024-07-11 20:52:41
  • Updated at : 2024-09-30 19:15:09
  • Link: https://redefine.ohevan.com/2024/07/11/【实践】01.Linear Regression/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments