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.

inference.py 3.0 kB

1 year ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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
  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 test(model, test_loader, data_length):
  36. model.eval()
  37. test_loss = 0
  38. correct = 0
  39. with torch.no_grad():
  40. for i, data in enumerate(test_loader, 0):
  41. x, y = data
  42. x = x.to(device)
  43. y = y.to(device)
  44. y_hat = model(x)
  45. test_loss += cost(y_hat, y).item()
  46. pred = y_hat.max(1, keepdim=True)[1]
  47. correct += pred.eq(y.view_as(pred)).sum().item()
  48. test_loss /= (i+1)
  49. # 结果写入输出文件夹
  50. filename = 'result.txt'
  51. file_path = os.path.join('/tmp/output', filename)
  52. with open(file_path, 'w') as file:
  53. file.write('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
  54. test_loss, correct, data_length, 100. * correct / data_length))
  55. if __name__ == '__main__':
  56. args, unknown = parser.parse_known_args()
  57. #初始化导入数据集和预训练模型到容器内
  58. c2net_context = prepare()
  59. #获取数据集路径
  60. checkpoint_lenet_1_1875_path = c2net_context.dataset_path+"/"+"checkpoint_lenet-1_1875"
  61. MnistDataset_torch = c2net_context.dataset_path+"/"+"MnistDataset_torch"
  62. #获取预训练模型路径
  63. mnist_example_test2_model_djts_path = c2net_context.pretrain_model_path+"/"+"MNIST_Example_test2_model_djts"
  64. #log output
  65. print('cuda is available:{}'.format(torch.cuda.is_available()))
  66. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  67. batch_size = args.batch_size
  68. epochs = args.epoch_size
  69. test_dataset = mnist.MNIST(root=mnist_example_test2_model_djts_path + "/test", train=False, transform=ToTensor(),download=False)
  70. test_loader = DataLoader(test_dataset, batch_size=batch_size)
  71. model = Model().to(device)
  72. checkpoint = torch.load(mnist_example_test2_model_djts_path + "/mnist_epoch1_0.73.pkl")
  73. model.load_state_dict(checkpoint['model'])
  74. test(model,test_loader,len(test_dataset))

No Description