总结搭建神经网络一般流程总结
一、数据准备 1、数据下载/读取、格式转换、标准化(读取的数据一般要自行构造数据集类,torchvision自带的数据集操作简单一些)
2、数据载入、设置batch_size、shuffle
二、搭建神经网络: 1、设置输入层、隐藏层、输出层所用的神经元、选择激活函数;
2、重写向前传播函数”def forward():“
3、设置验证集(开发集)进行交叉检验(可以确定优化方向、判断数据是否过拟合)
三、选择损失函数、优化器,设置学习率衰减(可选)
四、编写测试函数、计算测试集准确率
五、训练过程可视化(有利于调节超参)
代码及注释:
import torch
import torchvision
import numpy as np
import matplotlib.pyplot as plt
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoaderiteration=5#迭代次数设置
batch_size=60#batch的大小
#数据准备
trans=transforms.Compose([transforms.ToTensor(),transforms.Normalize(0.15,0.30)])
train_set=datasets.MNIST("D:\Multitask",download=False,train=True,transform=trans)
test_set=datasets.MNIST("D:\Multitask",download=False,train=False,transform=trans)
train_loader=DataLoader(train_set,batch_size=batch_size,shuffle=True)
test_loader=DataLoader(test_set,shuffle=False,batch_size=batch_size)#存放用于绘图的损失函数值
loss_list=[]
#搭建神经网络
class Network(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear1=torch.nn.Linear(784,1000)
self.linear2=torch.nn.Linear(1000,600)
self.linear3=torch.nn.Linear(600,300)
self.linear4=torch.nn.Linear(300,100)
self.relu=torch.nn.ReLU()def forward(self,x):
x=x.view(-1,784)
x=self.relu(self.linear1(x))
x=self.relu(self.linear2(x))
x=self.relu(self.linear3(x))
x=self.relu(self.linear4(x))
return x#设置损失函数、优化器和学习率衰减
model=Network()
criterion=torch.nn.CrossEntropyLoss()
optimizer=torch.optim.Adam(model.parameters(),lr=0.01)
schedular=torch.optim.lr_scheduler.ExponentialLR(optimizer,gamma=0.999)#训练函数
def train():
for epoch in range(iteration):
total=0.0
l=0.0
for batch_index,data in enumerate(train_loader,0):#每个batch的数据数量为batch_size,此处设为60
train_data,labels=data
optimizer.zero_grad()#训练前务必先清零梯度
pred=model(train_data)
loss=criterion(pred,labels)
l+=loss#统计损失函数值
_,pred_labels=torch.max(pred,dim=1)#torch.max()的返回值为(每行最大值tensor,最大值的索引位置)
total+=(pred_labels==labels).sum().item()#dim为1则寻找每列的最大值
loss.backward()#反向传播
optimizer.step()#梯度下降
schedular.step()#学习率衰减
if batch_index%50==0:#每50个batch输出一次损失值,用于观察训练情况
loss_list.append(l)
print("epoch:",epoch,"batch_number:",batch_index/50,"loss:",loss.data.item())#测试函数
def test():
with torch.no_grad():
total = 0.0
counter=0.0
for i,data in enumerate(test_loader,0):
test_data,test_labels=data
pred_data=https://www.it610.com/article/model(test_data)
_,pred_labels=torch.max(pred_data,dim=1)
total+=(pred_labels==test_labels).sum().item()#统计预测正确的样本数量
counter+=test_labels.shape[0]#统计测试集的样本数量
print("counter:",counter,"预测准确率为:",100*total/counter,"%")#绘制损失函数曲线,进行可视化
def plot():
plt.plot(range(len(loss_list)),loss_list,color="red",label="损失值")
plt.show()train()
test()
plot()
输出结果 准确率:

文章图片
c损失函数曲线 【pytorch|Pytorch全连接层神经网络(基于MNIST数据集的手写数字识别)】

文章图片
推荐阅读
- 深度学习|草图转换网络(SketchyGAN 和 style2paints)
- 手把手写深度学习|手把手写深度学习(10)(用Pix2Pix GANs实现sketch-to-image跨模态任务(理论基础))
- 视觉检测图像分割干货|mmdetection小技巧(逐步完善中)
- 报错|安装PyTorch后jupyter notebook中仍出现“No module named torch“
- 技术笔记|深度学习远程服务器配置
- 深度学习|详解深度学习之 Embedding
- 深度学习|深度学习每日一问(为什么要对数据归一化(数据预处理))
- 深度学习相关|深度学习常用的训练数据集介绍以及下载
- pytorch|PyTorch 被大量网友反馈,TorchRec 这一新库“诞生”且规模宏大