加入我们要用两层卷积神经网络来提取特征对mnist数据集进行分类,在pytorch中,我们应该如何设计网络?最基本的卷机层与池化层怎么去搭配,如何计算?
目录
1.理论设计
2.利用工具进行计算
3.代码实现
4.参考资料
首先mnist数据集是28*28单通道的图片数据,这里卷积核的size一般可以试着调试,这里一般采用size=5,然后通道个数也就是我们的输出的特征图(feature map),一般也是尝试性的参数,可能看代码能更直观一点,有什么可以提问。
通过卷积层和池化层后输出大小怎么得出_GoGoingB的博客-CSDN博客_卷积层和池化层输出大小
卷积核尺寸如何选取呢? - 那抹阳光1994 - 博客园
# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
def __init__(self, num_classes=10):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),#一般Kernel_size=5,padding=2
nn.BatchNorm2d(16),#make feature's mean_value=1,variance=1,learn or fit better from good distribution
nn.ReLU(),#standard activation fuction for cnn
nn.MaxPool2d(kernel_size=2, stride=2))#demension_reduce
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(7*7*32, num_classes)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out
这是个可以把你的模型在线显示出关系的图https://netron.app/
一个在线卷积池化计算器-推荐不会计算的同学_老炉传说的专栏-CSDN博客_卷积计算器在线
self.fc = nn.Linear(7*7*32, num_classes)
你看第二层卷机层的输出通道是32,然后计算出来的featuremap大小是7*7,我们通过flatten或者out.reshape(out.size(0), -1)来扁平化数据使得数据能输入给全连接层。
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
# Device configuration
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# Hyper parameters
num_epochs = 5
num_classes = 10
batch_size = 100
learning_rate = 0.001
# MNIST dataset
train_dataset = torchvision.datasets.MNIST(root='../../data/',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = torchvision.datasets.MNIST(root='../../data/',
train=False,
transform=transforms.ToTensor())
# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
def __init__(self, num_classes=10):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),#一般Kernel_size=5,padding=2
nn.BatchNorm2d(16),#make feature's mean_value=1,variance=1,learn or fit better from good distribution
nn.ReLU(),#standard activation fuction for cnn
nn.MaxPool2d(kernel_size=2, stride=2))#demension_reduce
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(7*7*32, num_classes)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out
model = ConvNet(num_classes).to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
# Test the model
model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
# Save the model checkpoint
# torch.save(model.state_dict(), 'model.ckpt')
# torch.save(model.state_dict(), "my_model.pth") # 只保存模型的参数
torch.save(model,"./my_model.pth") # 保存整个模型
pytorch-tutorial/main.py at master · yunjey/pytorch-tutorial · GitHub
PyTorch卷积神经网络实例深度分析——以MNIST数据集为例_零度不知寒的博客-CSDN博客