Pytorch中定义神经网络
深度学习使用人工神经网络(模型),它是由许多层相互连接的单元组成的计算系统。通过将数据传递给这些相互连接的单元,神经网络能够学习如何近似计算将输入转换成输出。在PyTorch中,神经网络能够使用torch.nn包来构建。
介绍
Pytorch提供了优雅设计的模块和类,包括torch.nn,帮助我们创建和训练神经网络。一个nn.Module 包括layers,和forward(input)方法,然后返回一个输出。
步骤
1. 导入包
2. 定义和初始化神经网络
3. 指定数据如何贯穿模型
4. 测试
1. Import necessary libraries for loading our data
import torch
import torch.nn as nn
import torch.nn.functional as F
2. Define and intialize the neural network
我们的网络可以识别图像。我们将使用PyTorch内置的一个叫做卷积的过程。卷积是将图像中的每个元素与它的局部邻居相加,由一个核函数或一个小的martrix加权,帮助我们从输入图像中提取某些特征(如边缘检测、锐度、模糊度等)。
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 labels
self.fc2 = nn.Linear(128, 10)
my_nn = Net()
print(my_nn)
3. Specify how data will pass through your model
当您使用PyTorch构建模型时,您只需定义forward函数,它将数据传递到计算图(即我们的神经网络)。这代表了我们的前馈(feed-forward)算法。
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. [Optional] Pass data through your model to test
为了确保我们收到我们想要的输出,让我们通过传递一些随机数据来测试我们的模型。
# Equates to one random 28x28 image
random_data = torch.rand((1,1,28,28))
my_nn = Net()
result = my_nn(random_data)
print(result)