PyTorch搭建神经网络
1. 导入库
1 | import torch |
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 | class Net(nn.Module): |
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 | for step in range(epoch): |