1. 模型训练步骤
1. 创建网络模型
class myModule(nn.Module):
def __init__(self):
super(myModule, self).__init__()
self.module1 = 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.module1(x)
return x
# 测试 模型是否正常 运行
if __name__ == '__main__':
mymodel = myModule()
input = torch.ones((64,3,32,32))
output = mymodel(input)
print(output.shape)
2. 加载数据集
train_data = torchvision.datasets.CIFAR10("../TorchVersion/dataset",train=True,transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10("../TorchVersion/dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
# 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 训练数据集的长度为:50000
# 测试数据集的长度为:10000
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))
# 利用 dataloader 来加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)
3. 导入网络模型
from myModel import * # 导入自己的模型
# 创建网络模型
myModel = myModule()
4. 创建损失函数与优化器
# 损失函数 -- 因为是 图像分类,故使用该函数
loos_fn = nn.CrossEntropyLoss()
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(myModel.parameters(),lr=learning_rate)
5. 设置一些训练参数
# 设置训练网络的一些参数
total_train_step = 0
# 记录测试的次数
total_test = 0
# 训练的轮数
epoch = 10
# 添加 tensorboard
writer = SummaryWriter("logs")
6. 使用训练集训练
# 训练步骤开始
myModel.train()
for data in train_dataloader:
imgs, targets = data
outputs = myModel(imgs)
loss = loos_fn(outputs,targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.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)
7. 使用测试集测试
# 测试步骤开始
myModel.eval()
total_test_loss = 0 # 整体测试损失值
total_accuracy = 0 # 总体 正确率
with torch.no_grad(): # 在 测试时,一定要这样 用
for data in test_dataloader:
imgs, targets = data
outputs = myModel(imgs)
loss = loos_fn(outputs,targets)
total_test_loss = total_test_loss + loss.item()
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的Loss: {}".format(total_test_loss))
print("整体测试集上的正确率: {}".format(total_accuracy/test_data_size))
writer.add_scalar("test_loss",total_test_loss,i)
writer.add_scalar("test_acc",total_accuracy/test_data_size,i)
8. 每轮训练之后保存模型
# 保存 模型的参数数据
torch.save(myModel.state_dict(),"myModel_训练后得到的参数_{}.pth".format(i))
print("模型已经成功保存")
2. 注意事项
- 注意使用优化器优化模型时的操作
- 注意 获取测试结果的 正确率 acc
- 在 训练之前 应该使用:myModel.train(), 在测试之前使用:myModel.eval()
- 在 测试时 使用:
with torch.no_grad(): # 在 测试时,一定要这样 ,避免梯度- 如果使用的 GPU 上训练的模型,最后想要在 cpu 上运行,则:
torch.load("vgg_saveModel2.pth",map_location=torch.device("cpu"))
3. 全部代码
myModel.py
import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
class myModule(nn.Module):
def __init__(self):
super(myModule, self).__init__()
self.module1 = 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.module1(x)
return x
# 测试 模型是否正常 运行
if __name__ == '__main__':
mymodel = myModule()
input = torch.ones((64,3,32,32))
output = mymodel(input)
print(output.shape)
训练与测试文件
import torch
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from myModel import * # 导入自己的模型
train_data = torchvision.datasets.CIFAR10("../TorchVersion/dataset",train=True,transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10("../TorchVersion/dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
# 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 训练数据集的长度为:50000
# 测试数据集的长度为:10000
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))
# 利用 dataloader 来加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)
# 创建网络模型
myModel = myModule()
# 损失函数 -- 因为是 图像分类,故使用该函数
loos_fn = nn.CrossEntropyLoss()
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(myModel.parameters(),lr=learning_rate)
# 设置训练网络的一些参数
total_train_step = 0
# 记录测试的次数
total_test = 0
# 训练的轮数
epoch = 10
# 添加 tensorboard
writer = SummaryWriter("logs")
for i in range(epoch):
print("---------第 {} 轮训练开始---------".format(i+1))
# 训练步骤开始
myModel.train()
for data in train_dataloader:
imgs, targets = data
outputs = myModel(imgs)
loss = loos_fn(outputs,targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.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)
# 测试步骤开始
myModel.eval()
total_test_loss = 0 # 整体测试损失值
total_accuracy = 0 # 总体 正确率
with torch.no_grad(): # 在 测试时,一定要这样 用
for data in test_dataloader:
imgs, targets = data
outputs = myModel(imgs)
loss = loos_fn(outputs,targets)
total_test_loss = total_test_loss + loss.item()
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的Loss: {}".format(total_test_loss))
print("整体测试集上的正确率: {}".format(total_accuracy/test_data_size))
writer.add_scalar("test_loss",total_test_loss,i)
writer.add_scalar("test_acc",total_accuracy/test_data_size,i)
# 保存 模型的参数数据
torch.save(myModel.state_dict(),"myModel_训练后得到的参数_{}.pth".format(i))
print("模型已经成功保存")
writer.close()
4. 实验结果
5. 使用 CUDA
可以使用 CUDA 的数据:
1. 网络模型
2. 损失函数
3. dataloader 加载后的数据
1. 方式一
在对应的 地方,添加该代码:
if torch.cuda.is_available():
myModel = myModel.cuda()
if torch.cuda.is_available():
loos_fn = loos_fn.cuda()
# 在测试集与训练集中加载该数据
if torch.cuda.is_available():
imgs = imgs.cuda()
targets = targets.cuda()
2. 方式二
1. 网络模型 --- 无需重新赋值
2. 损失函数 --- 无需重新赋值
3. dataloader 加载后的数据 --- 需重新赋值
# 定义 使用的 设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# --- 无需重新赋值
myModel.to(device)
loos_fn.to(device)
#--- 需重新赋值
imgs = imgs.to(device)
targets = targets.to(device)
3. 使用 cuda 后的版本
import torch
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from myModel import * # 导入自己的模型
# 定义 使用的 设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_data = torchvision.datasets.CIFAR10("../TorchVersion/dataset",train=True,transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10("../TorchVersion/dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
# 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 训练数据集的长度为:50000
# 测试数据集的长度为:10000
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))
# 利用 dataloader 来加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)
class myModule(nn.Module):
def __init__(self):
super(myModule, self).__init__()
self.module1 = 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.module1(x)
return x
# 创建网络模型
myModel = myModule()
myModel.to(device)
# 损失函数 -- 因为是 图像分类,故使用该函数
loos_fn = nn.CrossEntropyLoss()
loos_fn.to(device)
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(myModel.parameters(),lr=learning_rate)
# 设置训练网络的一些参数
total_train_step = 0
# 记录测试的次数
total_test = 0
# 训练的轮数
epoch = 10
# 添加 tensorboard
writer = SummaryWriter("logs")
for i in range(epoch):
print("---------第 {} 轮训练开始---------".format(i+1))
# 训练步骤开始
myModel.train()
for data in train_dataloader:
imgs, targets = data
imgs = imgs.to(device)
targets = targets.to(device)
outputs = myModel(imgs)
loss = loos_fn(outputs,targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.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)
# 测试步骤开始
myModel.eval()
total_test_loss = 0 # 整体测试损失值
total_accuracy = 0 # 总体 正确率
with torch.no_grad(): # 在 测试时,一定要这样 用
for data in test_dataloader:
imgs, targets = data
imgs = imgs.to(device)
targets = targets.to(device)
outputs = myModel(imgs)
loss = loos_fn(outputs,targets)
total_test_loss = total_test_loss + loss.item()
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的Loss: {}".format(total_test_loss))
print("整体测试集上的正确率: {}".format(total_accuracy/test_data_size))
writer.add_scalar("test_loss",total_test_loss,i)
writer.add_scalar("test_acc",total_accuracy/test_data_size,i)
# 保存 模型的参数数据
torch.save(myModel.state_dict(),"myModel_训练后得到的参数_{}.pth".format(i))
print("模型已经成功保存")
writer.close()
标签:loss,训练,套路,模型,train,test,total,data,myModel
From: https://blog.csdn.net/SILVERCROWNAGE/article/details/141432661