导入函数库
import torch
import torchvision
import torch.nn as nn
from torch.autograd import Variable
import torch.untils.data as Data
import matlibplot.pyplot as plt
参数设置
EPOCH=1#训练一次
BATCH_SIZE=50#分组训练每次训练50个
LR=0.001#学习速度为0.001
DOWNLOAD_MNIST=False#已经下载完毕
训练的数据
train_data = torchvision.datasets.MNIST(
root='./mnist/', # 保存或者提取位置
train=True, # this is training data
transform=torchvision.transforms.ToTensor(), # 转换 PIL.Image or numpy.ndarray 成
# torch.FloatTensor (C x H x W), 训练的时候 normalize 成 [0.0, 1.0] 区间
download=DOWNLOAD_MNIST, # 没下载就下载, 下载了就不用再下了
)
输出图片样例,以及训练数据的类型格式
print(train_data.train_data.size())
print(train_data.train_labels.size())
plt.imshow(train_data.train_data[0].numpy(), cmap='gray')
plt.title('%i'% train_data.train_labels[0])
plt.show()
说明有60000组数据,每组数据的格式为28*28
torch.Size([60000, 28, 28])
torch.Size([60000])
手写图片为
数据载体
train_loader=Data.DataLoader(dataset=train_data,
batch_size=BATCH_SIZE,
shuffle=True,
num_workers=2)
#其中dataset为所需要处理的数据,batch_size每次处理所需要的规格,
shuffle随机处理,num_workers=2双线程
test_data=torchvision.dataset.MNIST(root='./mnist/',train=False)
test_x=Variable(torch.unsqueeze(test_data.test_data,dim=1),volatile=True).type(torch.FloatTensor)[:2000]/255.#图片中的数据化为可以处理的Variable,
test_y=test_data.test_label[:2000]#所代表的数据设置为test_y
搭建CNN网络
class CNN(nn.Module):
def __init__(self):
super(CNN,self).__init__()
self.conv1=nn.Sequential(
nn.Conv2d(
in_channels=1,
out_channels=16,#16个扫描片同时扫描
kernel_size=5,#5*5扫描
stride=1,#步长
padding=2,#加的周围空白
#if stride=1,padding=(kernel_size-1)/2=2,围上了一圈0,黑色,255白色
),#卷积层,过滤器
nn.ReLU(),#网络
nn.MacPool2d(
kernel_size=2,
),#池化层
)
self.conv2=nn.Sequential(
nn.Conv2d=(16,32,5,1,2),
nn.ReLU(),
nn.MaxPool2d(2),
)
self.out=nn.Linear(32*7*7,10)#三维数据展平
def forward(self,x):
x=self.conv1(x),
x=self.conv2(x),#(batch,32,7,7)
x=x.view(x.size(0),-1)#(batch,32*7*7)
output=self.out(x)
return output
cnn=CNN()
print(cnn)
输出网络格式
CNN(
(conv1): Sequential(
(0): Conv2d(1, 16, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(1): ReLU()
(2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(conv2): Sequential(
(0): Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(1): ReLU()
(2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(out): Linear(in_features=1568, out_features=10, bias=True)
)
优化器
optimizer=torch.optimAdam()
loss_fuc=nn.CrossEntropyLoss()
开始训练
if __name__='__main__':
for epoch in range(EPOCH):
for step,(x,y) in enumerate(train_loader):
b_x=Variable(x)
b_y=Variable(y)
output=cnn(x)
loss=loss_func(output,b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step%50==0:
test_output=cnn(test_x)
pred_y = torch.max(test_output, 1)[1].data.squeeze()
accuracy = sum(pred_y == test_y) / test_y.size(0)
print('Epoch: ', epoch, '| train loss: %.4f' % loss.item(), '| test accuracy: %.4f'% accuracy.data.numpy())
训练成功之后,查看前十个数字以及其预估值的比较
test_output = cnn(test_x[:10])
pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()
#torch.max(a,1) 返回每一行中最大值的那个元素,且返回其索引
print(pred_y, 'prediction number')
print(test_y[:10].numpy(), 'real number')