Pytorch是一个机遇Torch的python第三方库,是当前最流行的机器学习库之一。本文讲讲述如何搭建一个简易的神经网络。
- 将自定义神经网络封装在一个类(Net类)中,此类需要继承nn.Module。
- Net类需要重写父类的两个函数,分别是构造函数和前向传播。
- 构造函数:在这里定义前向传播函数中需要用到的层,如卷积层,全连接层。这里定义的层通常是比较复杂,需要参数的。
- 前向传播:定义了神经网络从输入,到隐层再到输出的运算过程。这里包含简单的前向传播函数,如有激活函数(如Sigmoid,Relu等),也包含构造函数中定义的层。
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as Data
class Net(nn.Module):
#构造函数
def __init__(self):
super(Net, self).__init__()
#卷积层三个参数:in_channel, out_channels, 5*5 kernal
self.con1 = nn.Conv2d(3, 116, 5)
self.con2 = nn.Conv2d(116, 100, 5)
#全连接层两个参数:in_channels, out_channels
self.fc1 = nn.Linear(100 * 5 * 5, 500)
self.fc2 = nn.Linear(500, 84)
self.fc3 = nn.Linear(84, 10)
#前向传播
def forward(self, input):
#卷积 --> 激活函数(Relu) --> 池化
x = self.con1(input)
x = F.relu(x)
x = F.max_pool2d(x, (2, 2))
#重复上述过程
x = self.con2(x)
x = F.relu(x)
x = F.max_pool2d(x, (2, 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:]
num_features = 1
for i in size:
num_features = num_features * i
return num_features
实验
这部分随机初始化一个向量,并计算其输出。实际上,神经网络就是一个复杂的函数族,其函数形式是确定的,具体的函数表达式取决于神经网络中的参数(权重和偏差)
这里定义的神经网络接受n*3*32*32的输入,输出是1*10的张量。
net = Net()
input = torch.randn((1, 3, 32, 32))
out = net(input)
print(out.size())