总结搭建神经网络一般流程总结
一、数据准备
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 DataLoader
iteration=5
batch_size=60
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):
train_data,labels=data
optimizer.zero_grad()
pred=model(train_data)
loss=criterion(pred,labels)
l+=loss
_,pred_labels=torch.max(pred,dim=1)
total+=(pred_labels==labels).sum().item()
loss.backward()
optimizer.step()
schedular.step()
if batch_index%50==0:
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=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损失函数曲线
|