You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

train.py 4.0 kB

3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/python
  2. #coding=utf-8
  3. '''
  4. If there are Chinese comments in the code,please add at the beginning:
  5. #!/usr/bin/python
  6. #coding=utf-8
  7. Due to the adaptability of a100, before using the training environment, please use the recommended image of the
  8. platform with cuda 11.Then adjust the code and submit the image.
  9. The image of this example is: dockerhub.pcl.ac.cn:5000/user-images/openi:cuda111_python37_pytorch191
  10. In the training environment, the uploaded dataset will be automatically placed in the /dataset directory.
  11. If it is a single dataset:
  12. if MnistDataset_torch.zip is selected,Then the dataset directory is /dataset/train, /dataset/test;
  13. If it is a multiple dataset:
  14. If MnistDataset_torch.zip and checkpoint_epoch1_0.73.zip are selected,
  15. the dataset directory is /dataset/MnistDataset_torch/train, /dataset/MnistDataset_torch/test
  16. and /dataset/checkpoint_epoch1_0.73/mnist_epoch1_0.73.pkl
  17. The model download path is under /model by default. Please specify the model output location to /model,
  18. and the Qizhi platform will provide file downloads under the /model directory.
  19. '''
  20. from model import Model
  21. import numpy as np
  22. import torch
  23. from torchvision.datasets import mnist
  24. from torch.nn import CrossEntropyLoss
  25. from torch.optim import SGD
  26. from torch.utils.data import DataLoader
  27. from torchvision.transforms import ToTensor
  28. import argparse
  29. # Training settings
  30. parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
  31. #The dataset location is placed under /dataset
  32. parser.add_argument('--traindata', default="/dataset/train" ,help='path to train dataset')
  33. parser.add_argument('--testdata', default="/dataset/test" ,help='path to test dataset')
  34. parser.add_argument('--epoch_size', type=int, default=1, help='how much epoch to train')
  35. parser.add_argument('--batch_size', type=int, default=20, help='how much batch_size in epoch')
  36. if __name__ == '__main__':
  37. args, unknown = parser.parse_known_args()
  38. #log output
  39. print('cuda is available:{}'.format(torch.cuda.is_available()))
  40. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  41. batch_size = args.batch_size
  42. train_dataset = mnist.MNIST(root=args.traindata, train=True, transform=ToTensor(),download=False)
  43. test_dataset = mnist.MNIST(root=args.testdata, train=False, transform=ToTensor(),download=False)
  44. train_loader = DataLoader(train_dataset, batch_size=batch_size)
  45. test_loader = DataLoader(test_dataset, batch_size=batch_size)
  46. model = Model().to(device)
  47. sgd = SGD(model.parameters(), lr=1e-1)
  48. cost = CrossEntropyLoss()
  49. epoch = args.epoch_size
  50. print('epoch_size is:{}'.format(epoch))
  51. for _epoch in range(epoch):
  52. print('the {} epoch_size begin'.format(_epoch + 1))
  53. model.train()
  54. for idx, (train_x, train_label) in enumerate(train_loader):
  55. train_x = train_x.to(device)
  56. train_label = train_label.to(device)
  57. label_np = np.zeros((train_label.shape[0], 10))
  58. sgd.zero_grad()
  59. predict_y = model(train_x.float())
  60. loss = cost(predict_y, train_label.long())
  61. if idx % 10 == 0:
  62. print('idx: {}, loss: {}'.format(idx, loss.sum().item()))
  63. loss.backward()
  64. sgd.step()
  65. correct = 0
  66. _sum = 0
  67. model.eval()
  68. for idx, (test_x, test_label) in enumerate(test_loader):
  69. test_x = test_x
  70. test_label = test_label
  71. predict_y = model(test_x.to(device).float()).detach()
  72. predict_ys = np.argmax(predict_y.cpu(), axis=-1)
  73. label_np = test_label.numpy()
  74. _ = predict_ys == test_label
  75. correct += np.sum(_.numpy(), axis=-1)
  76. _sum += _.shape[0]
  77. print('accuracy: {:.2f}'.format(correct / _sum))
  78. #The model output location is placed under /model
  79. torch.save(model, '/model/mnist_epoch{}_{:.2f}.pkl'.format(_epoch+1, correct / _sum))