谨此纪念刚入门的我在卷积神经网络上面的摸爬滚打
这个代码是在网上寻找的,具体来源不明,可以正常运行测试,自己添加了一些注释,方便查看。
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
# Device configuration
#这里是个python的三元表达式,如果cuda存在的话,divice='cuda:0',否者就是'cpu'
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
#下载训练数据集,位置放在本文件的父文件夹下的data文件夹里面,数据需要转换格式为Tensor
#如果想要更改数据集下载位置,可以改为root='./data/'
train_dataset = torchvision.datasets.FashionMNIST(root='../data/',
train=True,
transform=transforms.ToTensor(),
download=True)
#下载测试集,位置放在放在本文件的父文件夹下的data文件夹里面,数据需要转换为Tensor格式
#如果想要更改数据集下载位置,可以改为root='./data/'
test_dataset = torchvision.datasets.FashionMNIST(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)
#定义一个卷积类,这里需要继承nn.Module
class ConvNet(nn.Module):
def __init__(self, num_classes=10):
#调用父类的初始化函数
super(ConvNet, self).__init__()
#
self.layer1 = nn.Sequential(
#输入通道数1,输出通道数16,卷积核大小为5*5,步长为1,零填充2圈
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
#BatchNorm2d是卷积网络中防止梯度消失或爆炸的函数,参数是卷积的输出通道数
nn.BatchNorm2d(16),
#激活函数
nn.ReLU(),
#池化
nn.MaxPool2d(kernel_size=2, stride=2))
#两层
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')
原文:https://www.cnblogs.com/alking1001/p/11938454.html