当前位置:   article > 正文

Mac上使用GPU加速训练模型_mac上可以训练nnunetv2模型吗

mac上可以训练nnunetv2模型吗

文章目录

前言

上一篇文章中我介绍了使用pytorch的一个完整模型训练套路,其中没有使用gpu,如果要使用gpu的话,win上我们可以使用cuda,mac上可以使用mps,而我自己是mac电脑,需要进行如下修改。

使用GPU

import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from model2 import *
import time

# 创建数据集
train_data = torchvision.datasets.CIFAR10("./source", train=True,
                                          transform=torchvision.transforms.ToTensor(), download=True)
test_data = torchvision.datasets.CIFAR10("./source", train=False,
                                          transform=torchvision.transforms.ToTensor(), download=True)

# 加载数据集
train_loader = DataLoader(train_data, batch_size=64)
test_loader = DataLoader(test_data, batch_size=64)

# 查看数据集长度
train_data_size = len(train_data)
test_data_size = len(test_data)
print(f"训练数据集的大小为{train_data_size}")
print(f"测试数据集的大小为{test_data_size}")

# 创建网络模型 搭建神经网络
# class Aniu(nn.Module):
#     def __init__(self):
#         super(Aniu, 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

# 定义训练的设备
device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
# 创建神经网络模型
aniu = Aniu()
aniu = aniu.to(device)

# 定义损失函数
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)
# 定义优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(aniu.parameters(), lr=learning_rate)

# 训练网络:

# 设置训练网络的一些参数:
# 总共训练次数
total_train_step = 0
# 总共测试次数
total_test_step = 0
# 总轮次
epoch = 50

# 添加 tensorboard 以便观察
writer = SummaryWriter("./log_train2")
start_time = time.time()
for i in range(epoch):
    print(f"------------第{i+1}轮训练开始------------")

    # 训练开始
    aniu.train()
    for data in train_loader:
        imgs, targets = data
        imgs = imgs.to(device)
        targets = targets.to(device)
        output = aniu(imgs)
        loss = loss_fn(output, targets)

        # 优化器优化模型
        optimizer.zero_grad() # 优化器梯度清零
        loss.backward()
        optimizer.step()

        total_train_step += 1
        if total_train_step % 100 == 0 :
            end_time = time.time()
            print(end_time - start_time)
            print(f"训练次数{total_train_step},Loss:{loss.item()}")
            writer.add_scalar("train_loss", loss.item(), total_train_step)

    # 测试步骤开始:
    aniu.eval()
    total_test_loss = 0

    # 整体正确的个数
    total_accuracy = 0
    with torch.no_grad():
        for data in test_loader:
            imgs, targets = data
            imgs = imgs.to(device)
            targets = targets.to(device)
            output = aniu(imgs)
            loss = loss_fn(output, targets)
            total_test_loss += loss.item()
            accuracy = (output.argmax(1) == targets).sum()
            total_accuracy = total_accuracy + accuracy

    print(f"整体测试集上的Loss为{total_test_loss}")
    print(f"整体测试集上的正确率:{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 += 1

    torch.save(aniu, f"aniu_{i}.pth")
    print("模型已保存")

writer.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122

总的来说就是添加了几行代码:

# 定义训练的设备
device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")

aniu = aniu.to(device)

loss_fn = loss_fn.to(device)

output = aniu(imgs)

loss = loss_fn(output, targets)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

速度大概快了10几倍。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号