利用GPU训练

方法一

  1. 修改网络类
  1. l = Lcy()
  2. if torch.cuda.is_available():
  3. l.cuda()
  1. 修改损失函数
  1. loss_function = nn.CrossEntropyLoss()
  2. if torch.cuda.is_available():
  3. loss_function.cuda()
  1. 修改数据
  1. for data in dataloader:
  2. img,target = data
  3. if torch.cuda.is_available():
  4. img = img.cuda()
  5. target = target.cuda()

方法二

  1. 设置设备
  1. device = device("cpu")
  2. device = device("cuda")
  3. device = device("cuda:0")
  4. device = device("cuda" if torch.cuda.is_available() else "cpu")
  1. 修改网络类
  1. l = Lcy()
  2. l = l.to(device)
  1. 修改损失函数
  1. loss_function = nn.CrossEntropyLoss()
  2. loss_function = loss_function.to(device)
  1. 修改数据
  1. for data in dataloader:
  2. img,target = data
  3. img = img.to(device)
  4. target = target.to(device)