方式一

image.png
在“完整的模型训练”基础上加上如下代码。

  1. '''创建网络模型'''
  2. model = Model()
  3. if torch.cuda.is_available():
  4. model = model.cuda()
  1. '''损失函数'''
  2. loss_fn = nn.CrossEntropyLoss()
  3. if torch.cuda.is_available():
  4. loss_fn = loss_fn.cuda()
  1. '''训练步骤开始'''
  2. for data in train_dataloader:
  3. imgs, targets = data
  4. if torch.cuda.is_available():
  5. imgs = imgs.cuda()
  6. targets = targets.cuda()
  1. '''测试步骤开始'''
  2. total_test_loss = 0
  3. total_accuracy = 0
  4. with torch.no_grad():
  5. for data in test_dataloader:
  6. imgs, targets = data
  7. if torch.cuda.is_available():
  8. imgs = imgs.cuda()
  9. targets = targets.cuda()

方式二

image.png
在“完整的模型训练”基础上加上如下代码。

  1. '''定义训练的设备'''
  2. device = torch.device("cpu" if torch.cuda.is_available() else "cpu")
  1. '''创建网络模型'''
  2. model = Model()
  3. model = model.to(device)
  1. '''损失函数'''
  2. loss_fn = nn.CrossEntropyLoss()
  3. loss_fn = loss_fn.to(device)
  1. '''训练步骤开始'''
  2. for data in train_dataloader:
  3. imgs, targets = data
  4. imgs = imgs.to(device)
  5. targets = targets.to(device)
  1. '''测试步骤开始'''
  2. total_test_loss = 0
  3. total_accuracy = 0
  4. with torch.no_grad():
  5. for data in test_dataloader:
  6. imgs, targets = data
  7. imgs = imgs.to(device)
  8. targets = targets.to(device)