一、利用GPU训练
方式一 .cuda()
网络模型
数据(输入,标注)
损失函数
调用 .cuda()
方式二 .to(device)
.to(device)
device = torch.device( "cpu" )
torch.device( "cuda" )
电脑中有多张显卡
torch.device( "cuda:0" )
torch.device( "cuda:1" )
只有数据、图片、标注需要.to() 后进行赋值
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
如果cuda.is_available() 可用,则使用cuda,否则使用cpu
具体代码
# 网络数据 数据(输入、标注) 损失函数 .cuda()
import torch
from torch import nn
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time
# 准备数据集
train_data = torchvision.datasets.CIFAR10(root="./dataset", train=True,
transform=torchvision.transforms.ToTensor(), download=True)
test_data = torchvision.datasets.CIFAR10(root="./dataset", train=False,
transform=torchvision.transforms.ToTensor(), download=True)
# 使用指定设备运行
# device = torch.device("cpu")
# device = torch.device("cuda:0")
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# length长度
train_data_size = len(train_data)
test_data_size = len(test_data)
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 TestNN(nn.Module):
def __init__(self):
super(TestNN, self).__init__()
self.model1 = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, padding=2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, padding=2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, padding=2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64 * 4 * 4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model1(x)
return x
tnn = TestNN()
# tnn.to(device)
if torch.cuda.is_available():
tnn = tnn.cuda()
# 损失函数
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
loss_fn = loss_fn.cuda()
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(tnn.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 添加tensorboard
writer = SummaryWriter("logs")
epoch = 10
start_time = time.time()
for i in range(epoch):
print("---第{}轮训练开始---".format(i + 1))
# 训练步骤开始
tnn.train()
for data in train_dataLoader:
images, targets = data
# images = images.to(device)
# targets = targets.to(device)
if torch.cuda.is_available():
images = images.cuda()
targets = targets.cuda()
outputs = tnn(images)
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()))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
tnn.eval()
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_dataLoader:
images, targets = data
if torch.cuda.is_available():
images = images.cuda()
targets = targets.cuda()
output = tnn(images)
loss = loss_fn(output, targets)
total_test_loss = total_test_loss + loss
accuracy = (output.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(tnn, "tnn_{}.pth".format(i))
print("模型已保存")
writer.close()
二、模型验证
模型验证方法
完整的模型验证(测试、demo),利用已经训练好的模型,给其提供输入
torch.load("加载训练好的数据集", map_location="cpu") 当输入类型为cpu报错时使用
使用中注意图片的大小是否符合训练集和测试集的要求
model.eval()
with torch.no_grad():
output = model(image)
对指定图片测试,判断图片的类别
注意:如果图片是png格式,因为png是4通道,要转换image=convert('RGB')
具体代码
import torchvision
from PIL import Image
from test_model import *
image = Image.open("image/plane.jpg")
print(image)
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Resize((32, 32))
])
# 如果是png格式,因为Png是4通道,要转换image = image.convert('RGB')
image = transform(image)
print(image.shape)
model = torch.load("tnn_29.pth", map_location="cpu")
print(model)
image = torch.reshape(image, (1, 3, 32, 32))
model.eval()
with torch.no_grad():
output = model(image)
print(output)
print(output.argmax(1))