pytorch学习笔记(三)Pytorch 神经网络

mac2026-05-27  1

参考package的使用方法:https://pytorch-cn.readthedocs.io/zh/latest/

神经网络可以通过 torch.nn 包来构建。一个典型的神经网络训练过程包括以下:

定义一个包含可训练参数的神经网络迭代整个输入通过神经网络处理输入计算损失loss反向传播梯度到神经网络的参数更新网络的参数,典型的更新方法是:weight = weight - learning_rate *gradient

例子:

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)

class torch.nn.Module 该类是所有网络的基类,Modules也可以包含其它Modules,允许使用树结构嵌入他们。你可以将子模块赋值给模型属性。

forward(* input):定义了每次执行的 计算步骤。 在所有的子类中都需要重写这个函数。

卷积层 一维卷积层:class torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

Parameters:

in_channels(int) – 输入信号的通道out_channels(int) – 卷积产生的通道kerner_size(int or tuple) - 卷积核的尺寸stride(int or tuple, optional) - 卷积步长padding (int or tuple, optional)- 输入的每一条边补充0的层数dilation(int or tuple, `optional``) – 卷积核元素之间的间距groups(int, optional) – 从输入通道到输出通道的阻塞连接数bias(bool, optional) - 如果bias=True,添加偏置

二维卷积层:class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

三维卷积层:class torch.nn.Conv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

Linear layers class torch.nn.Linear(in_features, out_features, bias=True) 对输入数据做线性变换:y=Ax+b

Parameters:

in_features - 每个输入样本的大小out_features - 每个输出样本的大小bias - 若设置为False,这层不会学习偏置。默认值:True

F.max_pool2d torch.nn.functional.max_pool2d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False)

Parameters:

input – 输入的张量 (minibatch x in_channels x iH x iW)kernel_size – 池化区域的大小,可以是单个数字或者元组 (kh x kw)stride – 池化操作的步长,可以是单个数字或者元组 (sh x sw)。默认等于核的大小padding – 在输入上隐式的零填充,可以是单个数字或者一个元组 (padh x padw),默认: 0ceil_mode – 定义空间输出形状的操作count_include_pad – 除以原始非填充图像内的元素数量或kh * kw

非线性激活函数 torch.nn.functional.relu(input, inplace=False)

打印出上述网络: 我们定义了一个前馈函数,然后反向传播函数被自动通过 autograd 定义,可以使用任何张量操作在前馈函数上。

一个模型可训练的参数可以通过调用 net.parameters() 返回:

params = list(net.parameters()) print(len(params)) print(params[0].size()) # conv1's .weight

随机生成一个 32x32 的输入,并让它经过我们的网络:

input = torch.randn(1, 1, 32, 32) out = net(input) print(out)

把所有参数梯度缓存器置零,用随机的梯度来反向传播。

net.zero_grad() out.backward(torch.randn(1, 10))

接下来需要计算损失函数和更新网络中的权重。 一个损失函数需要一对输入:模型输出和目标,然后计算一个值来评估输出距离目标有多远。

有一些不同的损失函数在 nn 包中。一个简单的损失函数就是 nn.MSELoss ,其计算了均方误差。

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)

现在,如果你跟随损失到反向传播路径,可以使用它的 .grad_fn 属性,你将会看到一个这样的计算图: input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d -> view -> linear -> relu -> linear -> relu -> linear -> MSELoss -> loss 所以,当我们调用 loss.backward(),整个图都会微分,而且所有的在图中的requires_grad=True 的张量将会让他们的 grad 张量累计梯度。

为了实现反向传播损失,我们所有需要做的事情仅仅是使用 loss.backward()。你需要清空现存的梯度,要不然梯度将会和现存的梯度累计到一起。

调用 loss.backward() ,然后看一下 con1 的偏置项在反向传播之前和之后的变化。

net.zero_grad() # zeroes the gradient buffers of all parameters print('conv1.bias.grad before backward') print(net.conv1.bias.grad) loss.backward() print('conv1.bias.grad after backward') print(net.conv1.bias.grad)

接下来需要更新神经网络: 最简单的更新规则就是随机梯度下降。 weight = weight - learning_rate * gradient

learning_rate = 0.01 for f in net.parameters(): f.data.sub_(f.grad.data * learning_rate)

如果想使用不同的更新规则,类似于 SGD, Nesterov-SGD, Adam, RMSProp, 等。为了让这可行,我们建立了一个小包:torch.optim 实现了所有的方法。

import torch.optim as optim # create your optimizer optimizer = optim.SGD(net.parameters(), lr=0.01) # in your training loop: optimizer.zero_grad() # zero the gradient buffers output = net(input) loss = criterion(output, target) loss.backward() optimizer.step() # Does the update
最新回复(0)