alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

【674】PyTorch —— 神经网络

PyTorch 神经网络

 一个典型的神经网络训练过程包括以下几点:

  1. 定义一个包含可训练参数的神经网络

  2. 通过神经网络处理输入

  3. 计算损失(loss)

  4. 反向传播梯度到神经网络的参数

  5. 更新网络的参数


 

1. 定义一个包含可训练参数的神经网络

  • torch.nn 定义了相关神经网络层

  • torch.nn.functional 定义了相关函数

  • 自定义的函数就是为了获取除batch size外的总元素个数

  • __init__(self) 函数:用来初始化层的结构

  • forward(self, x) 函数:通过函数将数据流建立起来

  • net.parameters():一个模型可训练的参数
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
36
37
38
39
import torch
import torch.nn as nn
import torch.nn.functional as F
 
 
class Net(nn.Module):
 
    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
 
    def forward(self, x):
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x
 
    def num_flat_features(self, x):
        size = x.size()[1:]  # all dimensions except the batch dimension
        num_features = 1
        for s in size:
            num_features *= s
        return num_features
 
 
net = Net()
print(net)

 

2. 通过神经网络处理输入

  • 创建网络
1
2
3
4
5
6
7
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
 
#把所有参数梯度缓存器置零,用随机的梯度来反向传播
net.zero_grad()
out.backward(torch.randn(1, 10))

 

3. 计算损失(loss)

  • 定义损失函数
1
2
3
4
5
6
7
output = net(input)
target = torch.randn(10# a dummy target, for example
target = target.view(1, -1# make it the same shape as output
criterion = nn.MSELoss()
 
loss = criterion(output, target)
print(loss)

 

还有添加 optimizer 以及其他训练策略

posted on   McDelfino  阅读(129)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示