方式一

在“完整的模型训练”基础上加上如下代码。
'''创建网络模型'''model = Model()if torch.cuda.is_available():model = model.cuda()
'''损失函数'''loss_fn = nn.CrossEntropyLoss()if torch.cuda.is_available():loss_fn = loss_fn.cuda()
'''训练步骤开始'''for data in train_dataloader:imgs, targets = dataif torch.cuda.is_available():imgs = imgs.cuda()targets = targets.cuda()
'''测试步骤开始'''total_test_loss = 0total_accuracy = 0with torch.no_grad():for data in test_dataloader:imgs, targets = dataif torch.cuda.is_available():imgs = imgs.cuda()targets = targets.cuda()
方式二

在“完整的模型训练”基础上加上如下代码。
'''定义训练的设备'''device = torch.device("cpu" if torch.cuda.is_available() else "cpu")
'''创建网络模型'''model = Model()model = model.to(device)
'''损失函数'''loss_fn = nn.CrossEntropyLoss()loss_fn = loss_fn.to(device)
'''训练步骤开始'''for data in train_dataloader:imgs, targets = dataimgs = imgs.to(device)targets = targets.to(device)
'''测试步骤开始'''total_test_loss = 0total_accuracy = 0with torch.no_grad():for data in test_dataloader:imgs, targets = dataimgs = imgs.to(device)targets = targets.to(device)
