0%

PyTorch Study

PyTorch搭建神经网络

1. 导入库

1
2
import torch 
import torch.nn as nn

2. 搭建卷积神经网络

网络定义一般由两部分组成:

1
def __init__(self):		# 用来定义网络节点参数

将节点连接成图

1
def forward(self, x):

卷积计算规则:

对我们输入形状1, 1, 64, 64.四个维度分别是(batch, channel, height, width)

new_height = (height - kernel_size) + s * padding / (stride[0]) + 1

即在周围补一圈0, stride默认为1.因此

new_height = new_width = (64 - 3) / 1 + 1 = 62

由于输出通道是6,所以通过卷积层后维度为(1, 6, 62, 62)

经过pooling后,(1, 6, 31, 31)

x.view(1, -1)把x伸缩为(1 : ?)的维度。这样整个网络其实输入(1, 1, 64, 64),输出为(1, 10)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=3)
self.linear = nn.Leaner(5766, 10)
self.relu = nn.ReLU(inplace=True)
self.maxpooling = nn.MaxPool2d((2, 2))

def forward(self, x):
x = self.conv(x)
# print (x.shape)
x = self.maxpooling(x)
# print(x.shape)
x = self.relu(x)
x = view(1, -1)
# print (x.shape)
x = self.linear(x)
return x

3. 添加训练数据

optimizer:是优化器,即所谓的反向传播算法。criterion = nn.MSELoss()定义损失函数。

input = torch.randn(1, 1, 64, 64).cuda()

output = torch.ones(1, 10).cuda()

定义训练样本,注意如果实在gpu中训练,在pytorch中需要.cuda()把数据从cpu中导入到gpu中

网络的功能是给定随机噪声向量,输出是逼近1的单位向量

4. 训练

1
2
3
4
5
6
7
8
9
10
11
for step in range(epoch):
prediction = net(input)
loss = creterion(prediction, output)
optimizer.zero_grad()
# 消除优化器梯度
loss.backward()
# 指自动求导
optimizer.step()
# 根据自动求导反向传播优化参数
if step % 10 == 0:
print("EPOCH: {}, Loss:{:4f}").format(step, loss))