code: def main():
      # 自适应使用GPU还是CPU
      device = torch.device(
          "cuda" if torch.cuda.is_available() else "cpu"
      )
  
      model = Net().to(device)
  
      optimizer = torch.optim.Adam(model.parameters())
      loss_func = torch.nn.CrossEntropyLoss()
  
      train_loader = Data.DataLoader(
          dataset=train_data, batch_size=batch_size, shuffle=True
      )
      test_loader = Data.DataLoader(
          dataset=test_data, batch_size=batch_size
      )
  
      for epoch in range(epochs):
          sum_loss = 0.0
          for i, data in enumerate(train_loader):
              inputs, labels = data
              inputs, labels = inputs.to(device), labels.to(device)
  
              # 梯度清零
              optimizer.zero_grad()
  
              # forward + backward
              outputs = model(inputs)
  
              loss = loss_func(outputs, labels)
              loss.backward()
              optimizer.step()
  
              # 每训练100个batch打印一次平均loss
              sum_loss += loss.item()
              if i % 50 == 0:
                  print(
                      "epoch=%d, batch=%d loss: %.04f"
                      % (epoch + 1, i, old_div(sum_loss, 100))
                  )
                  sum_loss = 0.0
          # 每跑完一次epoch测试一下准确率 进入测试模式 禁止梯度传递
          with torch.no_grad():
              correct = 0
              total = 0
              for data in test_loader:
                  images, labels = data
                  images, labels = images.to(device), labels.to(device)
                  outputs = model(images)
                  # 取得分最高的那个类
                  _, predicted = torch.max(outputs.data, 1)
                  total += labels.size(0)
                  correct += (predicted == labels).sum()
              print(
                  "epoch=%d accuracy=%.02f%%"
                  % (epoch + 1, (old_div(100 * correct, total)))
              )
  
      torch.save(model.state_dict(), "./mnist-pytorch/net.pth")
  
file_path: AdvBox/tutorials/mnist_model_pytorch.py
imports: from __future__ import print_function
  from __future__ import division
  from builtins import range
  from past.utils import old_div
  import os
  import torch
  import torchvision
  from torch.autograd import Variable
  import torch.utils.data.dataloader
label_desc: Use image node_id 1 for calling a global function with example usage: main() without return types