Pytorch CNN结构特点:
Pytorch CNN实例:
*根据LeNet5的结构模型编写LeNet网络:
图像经过卷积、池化等步骤的尺寸计算方式如下:
图像的尺寸为,其中为width, h为height,c为channel;
卷积核尺寸为,个数为;
步幅stride为;
填充padding为
卷积后图像的尺寸大小为:
池化后的图像尺寸大小为:(通常k=S)
参数量:,其中1指偏置
通过以上介绍可以完成各部分参数的设置,接下来介绍常用的函数:
True:改变当前的原始对象
'''
layer2 = nn.Sequential()
layer2.add_module('conv2', nn.Conv2d(64,64,kernel_size=3,padding=1))
layer2.add_module('BN2',nn.BatchNorm2d(64))
layer2.add_module('relu2',nn.ReLU(True))
layer2.add_module('pool2',nn.MaxPool2d(kernel_size=2,stride=2))
self.layer2 = layer2
'''
self.layer2 = nn.Sequential(
nn.Conv2d(64,64,kernel_size=3,padding=1),
nn.BatchNorm2d(64),
nn.ReLU(True),
nn.MaxPool2d(kernel_size=2,stride=2)),
)
self.classifier = nn.Sequential(
nn.Linear(4096,num_classes),
)
out = out.view(out.size(0), -1)
out = self.classifier(out)
整体代码:
import torch
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.mp = nn.MaxPool2d(2)
# fully connect
self.fc = nn.Linear(320, 10)
def forward(self, x):
# in_size = 64
in_size = x.size(0) # one batch
# x: 64*10*12*12
x = F.relu(self.mp(self.conv1(x)))
# x: 64*20*4*4
x = F.relu(self.mp(self.conv2(x)))
# x: 64*320
x = x.view(in_size, -1) # flatten the tensor
# x: 64*10
x = self.fc(x)
return F.log_softmax(x)
if __name__ == '__main__':
use_cuda = torch.cuda.is_available()
device = torch.device('cuda' if use_cuda else 'cpu')
net = LeNet().to(device)
print(net)