赞
踩
如何在pytorch中指定CPU和GPU进行训练,以及cpu和gpu之间切换
由CPU切换到GPU,要修改的几个地方:
网络模型、损失函数、数据(输入,标注)
- # 创建网络模型
- tudui = Tudui()
- if torch.cuda.is_available():
- tudui = tudui.cuda()
-
- # 损失函数
- loss_fn = nn.CrossEntropyLoss()
- if torch.cuda.is_available():
- loss_fn = loss_fn.cuda()
-
- # 数据输入 包括训练和测试的代码,二者都需要添加此代码
- if torch.cuda.is_available():
- imgs = imgs.cuda()
- targets = targets.cuda()
1.不知道电脑GPU可不可用时:
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )
- a.to(device)
第一行代码的意思是判断电脑GPU可不可用,如果可用的话device就采用cuda()即调用GPU,不可用的话就采用cpu()即调用CPU。
第二行代码的意思就是把变量放到对应的device上(当然如果你用的是CPU的话就不用这一步了,因为变量默认是存在CPU上的,调用GPU的话要先把变量放到GPU上跑,跑完之后再调回CPU上)
2.指定GPU时
- # 定义训练的设备
- device = torch.device("cuda:0")
-
- # 网络模型创建
- tudui = Tudui()
- tudui = tudui.to(device)
-
- # 损失函数
- loss_fn = nn.CrossEntropyLoss()
- loss_fn = loss_fn.to(device)
-
- # 训练步骤开始
- tudui.train()
- for data in train_dataloader:
- imgs, targets=data
- imgs = imgs.to(device)
- targets = targets.to(device)
- outputs = tudui(imgs)
- loss = loss_fn(outputs, targets)
-
- # 测试步骤开始
- tudui.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 = tudui(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
3.指定cpu时:
device = torch.device('cpu')
1、需要修改的
- # 三种常见的写法
- device = torch.device('cuda')
- device = torch.device('cuda: 0')
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
2、代码
- # 创建模型
- tudui = Tudui()
- if torch.cuda.is_available():
- tudui = tudui.cuda()
-
- # 损失函数
- loss_fn = nn.CrossEntropyLoss()
- if torch.cuda.is_available():
- loss_fn = loss_fn.cuda()
-
- # 训练步骤开始
- tudui.train()
- for data in train_dataloader:
- imgs, targets=data
- if torch.cuda.is_available():
- imgs = imgs.cuda()
- targets = targets.cuda()
- outputs = tudui(imgs)
- loss = loss_fn(outputs, targets)
-
- # 测试步骤开始
- tudui.eval()
- total_test_loss = 0
- total_accuracy = 0
- with torch.no_grad():
- for data in test_dataloader:
- imgs, targets=data
- if torch.cuda.is_available():
- imgs = imgs.cuda()
- targets = targets.cuda()
- outputs = tudui(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
推荐方法一,如果自己电脑是只有CPU,可以推荐使用云端服务器,比如PaddlePaddle,Google colab,这些服务器由每周免费八个小时的使用时间,可供我们基本的需求。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。