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.

pretrain.py 5.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. 1,The dataset structure of the single-dataset in this example
  8. MnistDataset_torch.zip
  9. ├── test
  10. └── train
  11. 2,Due to the adaptability of a100, before using the training environment, please use the recommended image of the
  12. platform with cuda 11.Then adjust the code and submit the image.
  13. The image of this example is: dockerhub.pcl.ac.cn:5000/user-images/openi:cuda111_python37_pytorch191
  14. In the training environment, the uploaded dataset will be automatically placed in the /dataset directory.
  15. Note: the paths are different when selecting a single dataset and multiple datasets.
  16. (1)If it is a single dataset: if MnistDataset_torch.zip is selected,
  17. the dataset directory is /dataset/train, /dataset/test;
  18. If it is a multiple dataset: if MnistDataset_torch.zip is selected,
  19. the dataset directory is /dataset/MnistDataset_torch/train, /dataset/MnistDataset_torch/test;
  20. (2)If the pre-training model file is selected, the selected pre-training model path save as parameter ckpt_url;
  21. The model download path is under /model by default. Please specify the model output location to /model,
  22. and the Qizhi platform will provide file downloads under the /model directory.
  23. '''
  24. from model import Model
  25. import numpy as np
  26. import torch
  27. from torchvision.datasets import mnist
  28. from torch.nn import CrossEntropyLoss
  29. from torch.optim import SGD
  30. from torch.utils.data import DataLoader
  31. from torchvision.transforms import ToTensor
  32. import argparse
  33. import os
  34. # Training settings
  35. parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
  36. #The dataset location is placed under /dataset
  37. parser.add_argument('--traindata', default="/dataset/train" ,help='path to train dataset')
  38. parser.add_argument('--testdata', default="/dataset/test" ,help='path to test dataset')
  39. parser.add_argument('--epoch_size', type=int, default=10, help='how much epoch to train')
  40. parser.add_argument('--batch_size', type=int, default=256, help='how much batch_size in epoch')
  41. #获取模型文件名称
  42. parser.add_argument('--ckpt_url', default="", help='pretrain model path')
  43. # 参数声明
  44. WORKERS = 0 # dataloder线程数
  45. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  46. model = Model().to(device)
  47. optimizer = SGD(model.parameters(), lr=1e-1)
  48. cost = CrossEntropyLoss()
  49. # 模型训练
  50. def train(model, train_loader, epoch):
  51. model.train()
  52. train_loss = 0
  53. for i, data in enumerate(train_loader, 0):
  54. x, y = data
  55. x = x.to(device)
  56. y = y.to(device)
  57. optimizer.zero_grad()
  58. y_hat = model(x)
  59. loss = cost(y_hat, y)
  60. loss.backward()
  61. optimizer.step()
  62. train_loss += loss
  63. loss_mean = train_loss / (i+1)
  64. print('Train Epoch: {}\t Loss: {:.6f}'.format(epoch, loss_mean.item()))
  65. # 模型测试
  66. def test(model, test_loader, test_data):
  67. model.eval()
  68. test_loss = 0
  69. correct = 0
  70. with torch.no_grad():
  71. for i, data in enumerate(test_loader, 0):
  72. x, y = data
  73. x = x.to(device)
  74. y = y.to(device)
  75. optimizer.zero_grad()
  76. y_hat = model(x)
  77. test_loss += cost(y_hat, y).item()
  78. pred = y_hat.max(1, keepdim=True)[1]
  79. correct += pred.eq(y.view_as(pred)).sum().item()
  80. test_loss /= (i+1)
  81. print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
  82. test_loss, correct, len(test_data), 100. * correct / len(test_data)))
  83. def main():
  84. # 如果有保存的模型,则加载模型,并在其基础上继续训练
  85. if os.path.exists(args.ckpt_url):
  86. checkpoint = torch.load(args.ckpt_url)
  87. model.load_state_dict(checkpoint['model'])
  88. optimizer.load_state_dict(checkpoint['optimizer'])
  89. start_epoch = checkpoint['epoch']
  90. print('加载 epoch {} 权重成功!'.format(start_epoch))
  91. else:
  92. start_epoch = 0
  93. print('无保存模型,将从头开始训练!')
  94. for epoch in range(start_epoch+1, epochs):
  95. train(model, train_loader, epoch)
  96. test(model, test_loader, test_dataset)
  97. # 保存模型
  98. state = {'model':model.state_dict(), 'optimizer':optimizer.state_dict(), 'epoch':epoch}
  99. torch.save(state, '/model/mnist_epoch{}.pkl'.format(epoch))
  100. if __name__ == '__main__':
  101. args, unknown = parser.parse_known_args()
  102. #log output
  103. print('cuda is available:{}'.format(torch.cuda.is_available()))
  104. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  105. batch_size = args.batch_size
  106. epochs = args.epoch_size
  107. train_dataset = mnist.MNIST(root=args.traindata, train=True, transform=ToTensor(),download=False)
  108. test_dataset = mnist.MNIST(root=args.testdata, train=False, transform=ToTensor(),download=False)
  109. train_loader = DataLoader(train_dataset, batch_size=batch_size)
  110. test_loader = DataLoader(test_dataset, batch_size=batch_size)
  111. main()