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.

common_inference_service.py 3.5 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """
  2. Copyright 2020 Tianshu AI Platform. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. """
  13. import os
  14. import io
  15. import torch
  16. import torch.nn.functional as functional
  17. from PIL import Image
  18. from torchvision import transforms
  19. from imagenet1000_clsidx_to_labels import clsidx_2_labels
  20. from logger import Logger
  21. log = Logger().logger
  22. #只能定义一个class
  23. class CommonInferenceService:
  24. # __init__初始化方法中接收args参数(其中模型路径参数为args.model_path,是否使用gpu参数为args.use_gpu),并加载模型(方法用户可自定义)
  25. def __init__(self, args):
  26. self.args = args
  27. self.model = self.load_model()
  28. def load_data(self, data_path):
  29. image = open(data_path, 'rb').read()
  30. image = Image.open(io.BytesIO(image))
  31. if image.mode != 'RGB':
  32. image = image.convert("RGB")
  33. image = transforms.Resize((self.args.reshape_size[0], self.args.reshape_size[1]))(image)
  34. image = transforms.ToTensor()(image)
  35. image = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])(image)
  36. image = image[None]
  37. if self.args.use_gpu:
  38. image = image.cuda()
  39. return image
  40. def load_model(self):
  41. if os.path.isfile(self.args.model_path):
  42. self.checkpoint = torch.load(self.args.model_path)
  43. else:
  44. for file in os.listdir(self.args.model_path):
  45. self.checkpoint = torch.load(self.args.model_path + file)
  46. model = self.checkpoint["model"]
  47. model.load_state_dict(self.checkpoint['state_dict'])
  48. for parameter in model.parameters():
  49. parameter.requires_grad = False
  50. if self.args.use_gpu:
  51. model.cuda()
  52. model.eval()
  53. return model
  54. # inference方法名称固定
  55. def inference(self, data):
  56. result = {"data_name": data['data_name']}
  57. data = self.load_data(data['data_path'])
  58. preds = functional.softmax(self.model(data), dim=1)
  59. predictions = torch.topk(preds.data, k=5, dim=1)
  60. result['predictions'] = list()
  61. for prob, label in zip(predictions[0][0], predictions[1][0]):
  62. predictions = {"label": clsidx_2_labels[int(label)], "probability": "{:.3f}".format(float(prob))}
  63. result['predictions'].append(predictions)
  64. return result
  65. if __name__=="__main__":
  66. import argparse
  67. parser = argparse.ArgumentParser(description='tianshu serving')
  68. parser.add_argument('--model_path', type=str, default='./res4serving.pth', help="model path")
  69. parser.add_argument('--use_gpu', type=bool, default=True, help="use gpu or not")
  70. parser.add_argument('--reshape_size', type=list, default=[224,224], help="use gpu or not")
  71. args = parser.parse_args()
  72. server = CommonInferenceService(args)
  73. image_path = "./cat.jpg"
  74. image = {"data_name": "cat.jpg", "data_path": image_path}
  75. re = server.inference(image)
  76. print(re)

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能

Contributors (1)