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_for_c2net.py 5.7 kB

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