注意
转到页面底部 下载完整示例代码。
在 PyTorch 中定义神经网络#
创建日期:2020年4月17日 | 最后更新:2024年2月6日 | 最后验证:2024年11月5日
深度学习使用人工神经网络(模型),即由许多相互连接的单元层组成的计算系统。通过将数据传导至这些互连单元,神经网络能够学习如何近似处理将输入转换为输出所需的计算。在 PyTorch 中,可以使用 torch.nn 包来构建神经网络。
简介#
PyTorch 提供了设计优雅的模块和类(包括 torch.nn),以帮助你创建和训练神经网络。nn.Module 包含各层,以及一个返回 output 的 forward(input) 方法。
在本篇配方(recipe)中,我们将使用 torch.nn 来定义一个专用于 MNIST 数据集 的神经网络。
设置#
在开始之前,如果尚未安装 torch,我们需要安装它。
pip install torch
步骤#
导入加载数据所需的所有库
定义并初始化神经网络
指定数据如何通过你的模型
[可选] 将数据传导至模型进行测试
1. 导入加载数据所需的库#
对于本篇配方,我们将使用 torch 及其子模块 torch.nn 和 torch.nn.functional。
import torch
import torch.nn as nn
import torch.nn.functional as F
2. 定义并初始化神经网络#
我们的网络将用于识别图像。我们将使用 PyTorch 内置的一种称为卷积(convolution)的过程。卷积将图像的每个元素与其局部邻域相加,并由一个核(kernel)或小型矩阵进行加权,这有助于我们从输入图像中提取特定特征(如边缘检测、清晰度、模糊度等)。
定义模型 Net 类有两个要求。第一个是编写一个引用 nn.Module 的 __init__ 函数。在此函数中,你将定义神经网络中的全连接层。
使用卷积,我们将定义模型以接收 1 个输入图像通道,并输出匹配我们目标的 10 个标签(代表数字 0 到 9)。该算法由你自主创建,我们将遵循标准的 MNIST 算法。
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# First 2D convolutional layer, taking in 1 input channel (image),
# outputting 32 convolutional features, with a square kernel size of 3
self.conv1 = nn.Conv2d(1, 32, 3, 1)
# Second 2D convolutional layer, taking in the 32 input layers,
# outputting 64 convolutional features, with a square kernel size of 3
self.conv2 = nn.Conv2d(32, 64, 3, 1)
# Designed to ensure that adjacent pixels are either all 0s or all active
# with an input probability
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
# First fully connected layer
self.fc1 = nn.Linear(9216, 128)
# Second fully connected layer that outputs our 10 labels
self.fc2 = nn.Linear(128, 10)
my_nn = Net()
print(my_nn)
我们已经完成了神经网络的定义,现在必须定义数据将如何通过它。
3. 指定数据如何通过你的模型#
当你使用 PyTorch 构建模型时,只需定义 forward 函数,它会将数据传入计算图(即我们的神经网络)。这将体现我们的前馈(feed-forward)算法。
你可以在 forward 函数中使用任何张量(Tensor)操作。
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
# x represents our data
def forward(self, x):
# Pass data through conv1
x = self.conv1(x)
# Use the rectified-linear activation function over x
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
# Run max pooling over x
x = F.max_pool2d(x, 2)
# Pass data through dropout1
x = self.dropout1(x)
# Flatten x with start_dim=1
x = torch.flatten(x, 1)
# Pass data through ``fc1``
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
# Apply softmax to x
output = F.log_softmax(x, dim=1)
return output
4. [可选] 将数据传导至模型进行测试#
为确保获得预期的输出,让我们通过传入一些随机数据来测试模型。
# Equates to one random 28x28 image
random_data = torch.rand((1, 1, 28, 28))
my_nn = Net()
result = my_nn(random_data)
print (result)
所得张量中的每个数字都等同于随机张量所关联标签的预测结果。
恭喜!你已成功在 PyTorch 中定义了一个神经网络。
了解更多#
查看这些其他秘籍以继续您的学习