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 6.1 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. """
  2. ######################## single-dataset inference lenet example ########################
  3. This example is a single-dataset inference tutorial.
  4. ######################## Instructions for using the inference environment ########################
  5. 1、Inference task requires predefined functions
  6. (1)Copy single dataset from obs to inference image.
  7. function ObsToEnv(obs_data_url, data_dir)
  8. (2)Copy ckpt file from obs to inference image.
  9. function ObsUrlToEnv(obs_ckpt_url, ckpt_url)
  10. (3)Copy the output result to obs.
  11. function EnvToObs(train_dir, obs_train_url)
  12. 3、4 parameters need to be defined.
  13. --data_url is the dataset you selected on the Qizhi platform
  14. --ckpt_url is the weight file you choose on the Qizhi platform
  15. --data_url,--ckpt_url,--result_url,--device_target,These 4 parameters must be defined first in a single dataset,
  16. otherwise an error will be reported.
  17. There is no need to add these parameters to the running parameters of the Qizhi platform,
  18. because they are predefined in the background, you only need to define them in your code.
  19. 4、How the dataset is used
  20. Inference task uses data_url as the input, and data_dir (ie: '/cache/data') as the calling method
  21. of the dataset in the image.
  22. For details, please refer to the following sample code.
  23. """
  24. import os
  25. import argparse
  26. import moxing as mox
  27. import mindspore.nn as nn
  28. from mindspore import context
  29. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  30. from mindspore.train import Model
  31. from mindspore.nn.metrics import Accuracy
  32. from mindspore import Tensor
  33. import numpy as np
  34. from glob import glob
  35. from dataset import create_dataset
  36. from config import mnist_cfg as cfg
  37. from lenet import LeNet5
  38. ### Copy single dataset from obs to inference image ###
  39. def ObsToEnv(obs_data_url, data_dir):
  40. try:
  41. mox.file.copy_parallel(obs_data_url, data_dir)
  42. print("Successfully Download {} to {}".format(obs_data_url, data_dir))
  43. except Exception as e:
  44. print('moxing download {} to {} failed: '.format(obs_data_url, data_dir) + str(e))
  45. return
  46. ### Copy ckpt file from obs to inference image###
  47. ### To operate on folders, use mox.file.copy_parallel. If copying a file.
  48. ### Please use mox.file.copy to operate the file, this operation is to operate the file
  49. def ObsUrlToEnv(obs_ckpt_url, ckpt_url):
  50. try:
  51. mox.file.copy(obs_ckpt_url, ckpt_url)
  52. print("Successfully Download {} to {}".format(obs_ckpt_url,ckpt_url))
  53. except Exception as e:
  54. print('moxing download {} to {} failed: '.format(obs_ckpt_url, ckpt_url) + str(e))
  55. return
  56. ### Copy the output result to obs###
  57. def EnvToObs(train_dir, obs_train_url):
  58. try:
  59. mox.file.copy_parallel(train_dir, obs_train_url)
  60. print("Successfully Upload {} to {}".format(train_dir,obs_train_url))
  61. except Exception as e:
  62. print('moxing upload {} to {} failed: '.format(train_dir,obs_train_url) + str(e))
  63. return
  64. ### --data_url,--ckpt_url,--result_url,--device_target,These 4 parameters must be defined first in a inference task,
  65. ### otherwise an error will be reported.
  66. ### There is no need to add these parameters to the running parameters of the Qizhi platform,
  67. ### because they are predefined in the background, you only need to define them in your code.
  68. parser = argparse.ArgumentParser(description='MindSpore Lenet Example')
  69. parser.add_argument('--data_url',
  70. type=str,
  71. default= '/cache/data/',
  72. help='path where the dataset is saved')
  73. parser.add_argument('--ckpt_url',
  74. help='model to save/load',
  75. default= '/cache/checkpoint.ckpt')
  76. parser.add_argument('--result_url',
  77. help='result folder to save/load',
  78. default= '/cache/result/')
  79. parser.add_argument('--device_target', type=str, default="Ascend", choices=['Ascend', 'GPU', 'CPU'],
  80. help='device where the code will be implemented (default: Ascend)')
  81. if __name__ == "__main__":
  82. args = parser.parse_args()
  83. ###Initialize the data and result directories in the inference image###
  84. data_dir = '/cache/data'
  85. result_dir = '/cache/result'
  86. ckpt_url = '/cache/checkpoint.ckpt'
  87. if not os.path.exists(data_dir):
  88. os.makedirs(data_dir)
  89. if not os.path.exists(result_dir):
  90. os.makedirs(result_dir)
  91. ###Copy dataset from obs to inference image
  92. ObsToEnv(args.data_url, data_dir)
  93. ###Copy ckpt file from obs to inference image
  94. ObsUrlToEnv(args.ckpt_url, ckpt_url)
  95. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  96. network = LeNet5(cfg.num_classes)
  97. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  98. repeat_size = cfg.epoch_size
  99. net_opt = nn.Momentum(network.trainable_params(), cfg.lr, cfg.momentum)
  100. model = Model(network, net_loss, net_opt, metrics={"Accuracy": Accuracy()})
  101. print("============== Starting Testing ==============")
  102. param_dict = load_checkpoint(os.path.join(ckpt_url))
  103. load_param_into_net(network, param_dict)
  104. ds_test = create_dataset(os.path.join(data_dir, "test"), batch_size=1).create_dict_iterator()
  105. data = next(ds_test)
  106. images = data["image"].asnumpy()
  107. labels = data["label"].asnumpy()
  108. print('Tensor:', Tensor(data['image']))
  109. output = model.predict(Tensor(data['image']))
  110. predicted = np.argmax(output.asnumpy(), axis=1)
  111. pred = np.argmax(output.asnumpy(), axis=1)
  112. print('predicted:', predicted)
  113. print('pred:', pred)
  114. print(f'Predicted: "{predicted[0]}", Actual: "{labels[0]}"')
  115. filename = 'result.txt'
  116. file_path = os.path.join(result_dir, filename)
  117. with open(file_path, 'a+') as file:
  118. file.write(" {}: {:.2f} \n".format("Predicted", predicted[0]))
  119. ###Copy result data from the local running environment back to obs,
  120. ###and download it in the inference task corresponding to the Qizhi platform
  121. EnvToObs(result_dir, args.result_url)