1 - 模型训练与测试代码
import torch.optim
import torchvision
from torch.utils.tensorboard import SummaryWriter
from model import * # 引入model文件
# 准备数据集
from torch import nn
from torch.utils.data import DataLoader
train_data = torchvision.datasets.CIFAR10('./dataset', train=True, transform=torchvision.transforms.ToTensor())
test_data = torchvision.datasets.CIFAR10('./dataset', train=False, transform=torchvision.transforms.ToTensor())
# length求长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 如果train_data_size=10, 训练数据集的长度为:10
print("训练数据集的长度为:{}".format(train_data_size))
# 光标移到代码行上按ctrl+d,可以复制这一行代码
print("测试数据集的长度为:{}".format(test_data_size))
# 输出 训练数据集长度为:50000 测试数据集长度为:10000
# 利用Dataloader加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# 创建网络模型
model = Model()
# 损失函数 使用交叉熵
loss_fn = nn.CrossEntropyLoss()
# 优化器
learning_rate = 1e-2
# learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter("./logs_train")
for i in range(epoch):
print("--------第 {} 轮训练开始--------".format(i+1))
# 训练步骤开始
for data in train_dataloader:
imgs, targets = data
outputs = model(imgs)
loss = loss_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())) # loss.item 转化为数字
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
total_test_loss = 0
total_accuracy = 0 # 整体正确个数
with torch.no_grad(): # 没有梯度,因为是测试,不要再调整梯度参数了
for data in test_dataloader:
imgs, targets = data
outputs = model(imgs)
loss = loss_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, 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(model, "model_{}.pth".format(i))
print("模型已保存")
writer.close()
其中.model
文件为
# 搭建神经网络 10分类网络 单独用python文件
import torch
from torch import nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, 2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64 * 4 * 4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
# 测试网络的正确性
if __name__ == '__main__':
model = Model()
input = torch.ones((64, 3, 32, 32)) # 64张图片
output = model(input)
print(output.shape)
# 输出 torch.Size([64, 10])
输出结果为
2 - GPU训练
2.1 - GPU训练方式1
找到:
- 网络模型
- (训练、测试步骤的)数据
- 损失函数
在后面加上.cuda()
即可
import time
import torch.optim
import torchvision
from torch.utils.tensorboard import SummaryWriter
# from model import * # 引入model文件
# 准备数据集
from torch import nn
from torch.utils.data import DataLoader
train_data = torchvision.datasets.CIFAR10('./dataset', train=True, transform=torchvision.transforms.ToTensor())
test_data = torchvision.datasets.CIFAR10('./dataset', train=False, transform=torchvision.transforms.ToTensor())
# length求长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 如果train_data_size=10, 训练数据集的长度为:10
print("训练数据集的长度为:{}".format(train_data_size))
# 光标移到代码行上按ctrl+d,可以复制这一行代码
print("测试数据集的长度为:{}".format(test_data_size))
# 输出 训练数据集长度为:50000 测试数据集长度为:10000
# 利用Dataloader加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# 创建网络模型
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, 2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64 * 4 * 4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
model = Model()
# 使用cuda
model = model.cuda()
# 损失函数 使用交叉熵
loss_fn = nn.CrossEntropyLoss()
# 使用cuda
loss_fn = loss_fn.cuda()
# 优化器
learning_rate = 1e-2
# learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter("./logs_train")
start_time = time.time()
for i in range(epoch):
print("--------第 {} 轮训练开始--------".format(i+1))
# 训练步骤开始
for data in train_dataloader:
imgs, targets = data
# 使用cuda
imgs = imgs.cuda()
targets = targets.cuda()
outputs = model(imgs)
loss = loss_fn(outputs, targets)
# 梯度清零
optimizer.zero_grad()
# 反向传播
loss.backward()
# 使用优化器优化模型
optimizer.step()
total_train_step = total_train_step + 1
if total_train_step % 100 == 0:
end_time = time.time()
print(end_time - start_time)
print("训练次数:{}, Loss:{}".format(total_train_step, loss.item())) # loss.item 转化为数字
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
total_test_loss = 0
total_accuracy = 0 # 整体正确个数
with torch.no_grad(): # 没有梯度,因为是测试,不要再调整梯度参数了
for data in test_dataloader:
imgs, targets = data
# 使用cuda
imgs = imgs.cuda()
targets = targets.cuda()
outputs = model(imgs)
loss = loss_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, 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(model, "model_{}.pth".format(i))
print("模型已保存")
writer.close()
2.2 - 使用Google Colab
Google CoLab
2.3 - GPU训练方式2(常用)
.to(device)
device=torch.device(‘CPU’)
torch.device(‘cuda’)
import time
import torch.optim
import torchvision
from torch.utils.tensorboard import SummaryWriter
# from model import * # 引入model文件
# 准备数据集
from torch import nn
from torch.utils.data import DataLoader
# 定义训练的设备
device = torch.device('cuda')
train_data = torchvision.datasets.CIFAR10('./dataset', train=True, transform=torchvision.transforms.ToTensor())
test_data = torchvision.datasets.CIFAR10('./dataset', train=False, transform=torchvision.transforms.ToTensor())
# length求长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 如果train_data_size=10, 训练数据集的长度为:10
print("训练数据集的长度为:{}".format(train_data_size))
# 光标移到代码行上按ctrl+d,可以复制这一行代码
print("测试数据集的长度为:{}".format(test_data_size))
# 输出 训练数据集长度为:50000 测试数据集长度为:10000
# 利用Dataloader加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# 创建网络模型
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, 2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64 * 4 * 4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
model = Model()
# 使用cuda
model = model.to(device)
# 损失函数 使用交叉熵
loss_fn = nn.CrossEntropyLoss()
# 使用cuda
loss_fn = loss_fn.to(device)
# 优化器
learning_rate = 1e-2
# learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter("./logs_train")
start_time = time.time()
for i in range(epoch):
print("--------第 {} 轮训练开始--------".format(i+1))
# 训练步骤开始
for data in train_dataloader:
imgs, targets = data
# 使用cuda
imgs = imgs.to(device)
targets = targets.to(device)
outputs = model(imgs)
loss = loss_fn(outputs, targets)
# 梯度清零
optimizer.zero_grad()
# 反向传播
loss.backward()
# 使用优化器优化模型
optimizer.step()
total_train_step = total_train_step + 1
if total_train_step % 100 == 0:
end_time = time.time()
print(end_time - start_time)
print("训练次数:{}, Loss:{}".format(total_train_step, loss.item())) # loss.item 转化为数字
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
total_test_loss = 0
total_accuracy = 0 # 整体正确个数
with torch.no_grad(): # 没有梯度,因为是测试,不要再调整梯度参数了
for data in test_dataloader:
imgs, targets = data
# 使用cuda
imgs = imgs.to(device)
targets = targets.to(device)
outputs = model(imgs)
loss = loss_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, 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(model, "model_{}.pth".format(i))
print("模型已保存")
writer.close()