alex_bn_lee

导航

【674】PyTorch —— 神经网络

PyTorch 神经网络

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

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

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

  3. 计算损失(loss)

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

  5. 更新网络的参数


 

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

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

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

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

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

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

  • net.parameters():一个模型可训练的参数
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. 通过神经网络处理输入

  • 创建网络
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)

#把所有参数梯度缓存器置零,用随机的梯度来反向传播
net.zero_grad()
out.backward(torch.randn(1, 10))

 

3. 计算损失(loss)

  • 定义损失函数
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 2021-12-13 20:32  McDelfino  阅读(134)  评论(0)    收藏  举报