1.将建立的深度学习的模型放入一个py文件中,在mian函数中进行全1的模型检测
import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten,Linear,Sequential
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.model1 = Sequential(
Conv2d(3, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 64, 5, padding=2),
MaxPool2d(2),
Flatten(),
Linear(1024, 64),
Linear(64, 10)
)
def forward(self,x):
x = self.model1(x)
return x
if __name__ == '__main__':
tudui = Tudui()
input = torch.ones((64,3,32,32))
output = tudui(input)
print(output.shape)
2.模板大概流程:(1)读取训练集,测试集数据,获取数据总数量
(2)建立训练集,测试集loader
(3)引入网络模型
(4)设置损失函数
(5)建立优化器
(6)设置训练轮数后开始训练和测试。训练时先将数据放入网络得到output,调用loss函数,将优化器梯度归零,loss函数反向传播,返回梯度,优化器根据梯度进行训练,最终显示loss;测试时首先要在梯度为0的情况下开始进行测试,同样得到output,调用loss函数,可以测试正确率,最终显示总测试集的loss。期间可以用tensorboard将数据可视化。
(7)保存模型,每轮换进行一次保存
import torch
from torch import nn
import torchvision
from model import Tudui
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter("train")
test_data = torchvision.datasets.CIFAR10("./dataset0",False,torchvision.transforms.ToTensor(),
download=True)
train_data = torchvision.datasets.CIFAR10("./dataset0",True,torchvision.transforms.ToTensor(),
download=True)
test_loader = DataLoader(test_data,64)
train_loader = DataLoader(train_data,64)
test_data_size = len(test_data)
#创建网络模型
tudui = Tudui()
#损失函数
loss_fn = nn.CrossEntropyLoss()
#优化器
learn_rate = 1e-2
optim = torch.optim.SGD(tudui.parameters(),lr=learn_rate)
#训练的参数
#训练的次数
total_train_step = 0
#测试的次数
total_test_step = 0
#训练的轮数
epoch = 10
for i in range(epoch):
print("---------第{}轮训练开始----------".format(i+1))
#开始训练
tudui.train()
for data in train_loader:
imgs,target = data
outputs = tudui(imgs)
loss = loss_fn(outputs,target)
#优化器优化模型
optim.zero_grad()
loss.backward()
optim.step()
total_train_step = total_train_step+1
if total_train_step%100 == 0:
print("训练次数为:{},loss:{}".format(total_train_step,loss.item()))
writer.add_scalar("train_loss",loss.item(),total_train_step)
#测试步骤
tudui.eval()
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_loader:
imgs,targets = data
output = tudui(imgs)
loss = loss_fn(output,targets)
total_test_loss = total_test_loss+loss.item()
accurracy = (output.argmax(1)==targets).sum()
total_accuracy = total_accuracy+accurracy
print("整体测试上的loss:{}".format(total_test_loss))
print("整体测试上的正确率:{}".format(total_accuracy/test_data_size))
writer.add_scalar("test_loss",total_test_loss,total_test_step)
writer.add_scalar("test_accuracy",total_accuracy/test_data_size,total_test_step)
total_test_step = total_test_step+1
# torch.save(tudui,"tudui{}.pth".format(i))
# print("模型已经保存")
writer.close()