赞
踩
今天学习卷积神经网络的构建
分别构建训练集和测试集(验证集);用DataLoader来迭代取数据:
- import torch
- import torch.nn as nn
- import torch.optim as optim
- import torch.nn.functional as F
- import matplotlib.pyplot as plt
- from torchvision import datasets,transforms
- import numpy as np
-
- #定义超参数
- input_size = 28 #图像尺寸为28*28
- num_classes = 10 #标签的种类数
- num_epochs = 3 #训练的总循环周期
- batch_size = 64 #批处理的数量
-
- #训练集,这里基于datasets里的Mnist模块读取
- train_dataset = datasets.MNIST(root='./data',
- train=True,
- transform=transforms.ToTensor(),
- download=True)
- #测试集
- test_dataset = datasets.MNIST(root='./data',
- train=False,
- transform=transforms.ToTensor())
-
- #构建batch数据
- 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 = True)
一般卷积层,relu层,池化层可以写为一个套餐;注意卷积最后结果是特征图,需要把图转换为向量才能做分类或者回归任务:
- class CNN(nn.Module):
- def __init__(self):
- super(CNN,self).__init__()
- self.conv1 = nn.Sequential( #输入为(1,28,28)
- nn.Conv2d(
- in_channels=1, #通道数,这里灰度图为1
- out_channels=16, #要得到几个特征图,即卷积核个数
- kernel_size=5, #卷积核大小
- stride=1, #步长
- padding=2, #如果希望卷积后大小和原来一样,需要设置padding=(kernel_size-1)/2 if stride=1
- ),
- nn.ReLU(),
- nn.MaxPool2d(kernel_size=2), #输出结果为(16,14,14)
- )
- self.conv2 = nn.Sequential( #输入为(16,14,14)
- nn.Conv2d(16,32,5,1,2),
- nn.ReLU(),
- nn.MaxPool2d(2), #输出为(32,7,7)
- )
- self.out = nn.Linear(32*7*7,10)
-
- def forward(self,x):
- x = self.conv1(x)
- x = self.conv2(x)
- x = x.view(x.size(0),-1) #flatten操作,结果为:(batch_size,32*7*7)
- print(x.size())
- out = self.out(x)
- return out
- #设置准确率函数作为评估标准
- def accuracy(predictions,labels):
- pred = torch.max(predictions.data,1)[1]
- rights = pred.eq(labels.data.view_as(pred)).sum()
- return rights, len(labels)
-
- #实例化
- net = CNN()
- #损失函数
- criterion = nn.CrossEntropyLoss()
- #优化器
- optimizer = optim.Adam(net.parameters(),lr=0.001)
-
- #开始训练循环
- for epoch in range(num_epochs):
- #当前epoch的结果保存下来
- train_rights = []
-
- for batch_idx, (data,target) in enumerate(train_loader): #对容器中的每一个批次进行循环
- net.train()
- output = net(data)
- loss = criterion(output,target)
- optimizer.zero_grad()
- loss.backward()
- optimizer.step()
- right = accuracy(output,target)
- train_rights.append(right)
-
- if batch_idx % 100 == 0:
- net.eval()
- val_rights = []
-
- for (data,target) in test_loader:
- output = net(data)
- right = accuracy(output,target)
- val_rights.append(right)
-
- #准确率计算
- train_r = (sum([tup[0] for tup in train_rights]),sum([tup[1] for tup in train_rights]))
- val_r = (sum([tup[0] for tup in val_rights]),sum([tup[1] for tup in val_rights]))
-
- print('当前epoch:{} [{}/{} ({:.0f}%)]\t损失:{:.6f}\t训练集准确率:{:.2f}%\t测试集准确率:{:.2f}%'.format(
- epoch, batch_idx * batch_size, len(train_loader.dataset),
- 100. * batch_idx / len(train_loader),
- loss.data,
- 100. * train_r[0].numpy() / train_r[1],
- 100. * val_r[0].numpy() / val_r[1],
- ))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。