⼿把⼿教pytorch搭建卷积⽹络实现mnist分类任务(完整代码,详细注释)利⽤pytorch随便搭建⼀个卷积神经⽹络,实现mnist的分类任务,准确率达到100%。
代码如下(训练时可将数据可视化模块代码注释掉):
import torch
import torchvision
import matplotlib.pyplot as plt
as nn
import torch.utils.data as Data
喜出望外什么意思EPOCH=1#训练整批数据多少次
BATCH_SIZE=64#每次批数的数据量
LR=0.001#学习率,学习率的设置直接影响着神经⽹络的训练效果
train_data=torchvision.datats.MNIST(#训练数据
root='./mnist_data/',
train=True,
ansforms.ToTensor(),
download=True
)
test_data = torchvision.datats.MNIST(
root='./mnist_data/',
train=Fal,
ansforms.ToTensor(),
download=True
)
# 批量加载
train_loader = Data.DataLoader(datat=train_data, batch_size=BATCH_SIZE, shuffle=True)
test_loader = Data.DataLoader(datat=test_data, batch_size=BATCH_SIZE, shuffle=Fal)
# 数据可视化
images, label =next(iter(train_loader))
images_example = torchvision.utils.make_grid(images)
images_example = images_example.numpy().transpo(1,2,0)# 将图像的通道值置换到最后的维度,符合图像的格式
秋天英文单词mean =[0.5,0.5,0.5]
std =[0.5,0.5,0.5]
images_example = images_example * std + mean
plt.imshow(images_example )
plt.show()
image_array,_=train_data[0]#把⼀个批数的训练数据的第⼀个取出
image_array=shape(28,28)#转换成28*28的矩阵
plt.imshow(image_array)
plt.show()
class CNN(nn.Module):
def__init__(lf):
super(CNN, lf).__init__()空心泡
nn.Conv2d(
in_channels=1,# input height输⼊
out_channels=16,# n_filters输出六年级英语阅读
kernel_size=5,# filter size滤波核⼤⼩
stride=1,# filter movement/step步长
padding=2,# 如果想要 con2d 出来的图⽚长宽没有变化, padding=,(kernel_size-1)/2 当 stride=1填充
灌溉渠道
),# output shape (16, 28, 28)
nn.ReLU(),# activation
尚西山
nn.MaxPool2d(kernel_size=2),# 在 2x2 空间⾥向下采样, output shape (16, 14, 14)
)
nn.Conv2d(16,32,5,1,2),# output shape (32, 14, 14)
nn.ReLU(),# activation
nn.MaxPool2d(2),# output shape (32, 7, 7)
)
lf.out = nn.Linear(32*7*7,10)# fully connected layer, output 10 class
def forward(lf, x):
x = lf.conv1(x)
x = lf.conv2(x)
x = x.view(x.size(0),-1)# 展平多维的卷积图成 (batch_size, 32 * 7 * 7)
output = lf.out(x)
return output
新华字典有多少个字
cnn = CNN().cuda()
print(cnn)# 显⽰神经⽹络
optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)# Adam优化函数
loss_func = nn.CrossEntropyLoss()# 损失函数(损失函数分很多种,CrossEntropyLoss适⽤于作为多分类问题的损失函数)
# training and testing
for epoch in range(EPOCH):#训练批数
for step,(x, y)in enumerate(train_loader):# 每个批数的批量
石室岩
b_x = x.cuda()# batch x
b_y = y.cuda()# batch y
output = cnn(b_x)# cnn output
loss = loss_func(output, b_y)# cross entropy loss
print('epoch: %s step: %s loss: %s'%(epoch, step, loss))
<_grad()# 梯度清零
loss.backward()# 损失函数的反向传导
optimizer.step()# 对神经⽹络中的参数进⾏更新
#在测试集上测试,并计算准确率
print('**********************开始测试************************')
for step,(x, y)in enumerate(test_loader):
test_x, test_y = x.cuda(), y.cuda()
test_output = cnn(test_x)
# 以下三⾏为pytorch标准计算准确率的⽅法,⼗分推荐,简洁明了易操作
pred_y = torch.max(test_output.cpu(),1)[1].numpy()
label_y = test_y.cpu().numpy()
accuracy =(pred_y == label_y).sum()/len(label_y)
print(test_output)#查看⼀下预测输出值
print('acc: ', accuracy)
代码运⾏结果:
可视化输出的第⼀个图
可视化输出的第⼆个图:
训练及测试图: