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.4 kB

2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. '''
  12. from model import Model
  13. import numpy as np
  14. import torch
  15. from torchvision.datasets import mnist
  16. from torch.nn import CrossEntropyLoss
  17. from torch.optim import SGD
  18. from torch.utils.data import DataLoader
  19. from torchvision.transforms import ToTensor
  20. import argparse
  21. import os
  22. #导入c2net包
  23. from c2net.context import prepare
  24. # Training settings
  25. parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
  26. parser.add_argument('--epoch_size', type=int, default=10, help='how much epoch to train')
  27. parser.add_argument('--batch_size', type=int, default=256, help='how much batch_size in epoch')
  28. # 参数声明
  29. WORKERS = 0 # dataloder线程数
  30. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  31. model = Model().to(device)
  32. optimizer = SGD(model.parameters(), lr=1e-1)
  33. cost = CrossEntropyLoss()
  34. # 模型训练
  35. def train(model, train_loader, epoch):
  36. model.train()
  37. train_loss = 0
  38. for i, data in enumerate(train_loader, 0):
  39. x, y = data
  40. x = x.to(device)
  41. y = y.to(device)
  42. optimizer.zero_grad()
  43. y_hat = model(x)
  44. loss = cost(y_hat, y)
  45. loss.backward()
  46. optimizer.step()
  47. train_loss += loss
  48. loss_mean = train_loss / (i+1)
  49. print('Train Epoch: {}\t Loss: {:.6f}'.format(epoch, loss_mean.item()))
  50. # 模型测试
  51. def test(model, test_loader, test_data):
  52. model.eval()
  53. test_loss = 0
  54. correct = 0
  55. with torch.no_grad():
  56. for i, data in enumerate(test_loader, 0):
  57. x, y = data
  58. x = x.to(device)
  59. y = y.to(device)
  60. optimizer.zero_grad()
  61. y_hat = model(x)
  62. test_loss += cost(y_hat, y).item()
  63. pred = y_hat.max(1, keepdim=True)[1]
  64. correct += pred.eq(y.view_as(pred)).sum().item()
  65. test_loss /= (i+1)
  66. print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
  67. test_loss, correct, len(test_data), 100. * correct / len(test_data)))
  68. if __name__ == '__main__':
  69. args, unknown = parser.parse_known_args()
  70. #初始化导入数据集和预训练模型到容器内
  71. c2net_context = prepare()
  72. #获取数据集路径
  73. checkpoint_lenet_1_1875_path = c2net_context.dataset_path+"/"+"checkpoint_lenet-1_1875"
  74. MnistDataset_torch = c2net_context.dataset_path+"/"+"MnistDataset_torch"
  75. #获取预训练模型路径
  76. mnist_example_test2_model_djts_path = c2net_context.pretrain_model_path+"/"+"MNIST_Example_test2_model_djts"
  77. #log output
  78. print('cuda is available:{}'.format(torch.cuda.is_available()))
  79. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  80. batch_size = args.batch_size
  81. epochs = args.epoch_size
  82. train_dataset = mnist.MNIST(root=os.path.join(MnistDataset_torch, "train"), train=True, transform=ToTensor(),download=False)
  83. test_dataset = mnist.MNIST(root=os.path.join(MnistDataset_torch, "test"), train=False, transform=ToTensor(),download=False)
  84. train_loader = DataLoader(train_dataset, batch_size=batch_size)
  85. test_loader = DataLoader(test_dataset, batch_size=batch_size)
  86. #如果有保存的模型,则加载模型,并在其基础上继续训练
  87. if os.path.exists(os.path.join(mnist_example_test2_model_djts_path, "mnist_epoch1_0.76.pkl")):
  88. checkpoint = torch.load(os.path.join(mnist_example_test2_model_djts_path, "mnist_epoch1_0.76.pkl"))
  89. model.load_state_dict(checkpoint['model'])
  90. optimizer.load_state_dict(checkpoint['optimizer'])
  91. start_epoch = checkpoint['epoch']
  92. print('加载 epoch {} 权重成功!'.format(start_epoch))
  93. else:
  94. start_epoch = 0
  95. print('无保存模型,将从头开始训练!')
  96. for epoch in range(start_epoch+1, epochs):
  97. train(model, train_loader, epoch)
  98. test(model, test_loader, test_dataset)
  99. # 将模型保存到c2net_context.output_path
  100. state = {'model':model.state_dict(), 'optimizer':optimizer.state_dict(), 'epoch':epoch}
  101. torch.save(state, '{}/mnist_epoch{}.pkl'.format(c2net_context.output_path, epoch))

No Description