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.

interface.py 4.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # Copyright 2021 The KubeEdge Authors.
  2. #
  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. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import division
  15. import os
  16. import PIL
  17. import numpy as np
  18. from PIL import Image
  19. import mindspore as ms
  20. import mindspore.nn as nn
  21. from mindvision.engine.loss import CrossEntropySmooth
  22. from mindvision.engine.callback import ValAccMonitor
  23. from mobilenet_v2 import mobilenet_v2_fine_tune
  24. os.environ['BACKEND_TYPE'] = 'MINDSPORE'
  25. def preprocess(img:PIL.Image.Image):
  26. #image=Image.open(img_path).convert("RGB").resize((224 ,224))
  27. image=img.convert("RGB").resize((224,224))
  28. mean = np.array([0.485 * 255, 0.456 * 255, 0.406 * 255])
  29. std = np.array([0.229 * 255, 0.224 * 255, 0.225 * 255])
  30. image = np.array(image)
  31. image = (image - mean) / std
  32. image = image.astype(np.float32)
  33. image = np.transpose(image, (2, 0, 1))
  34. image = np.expand_dims(image, axis=0)
  35. return image
  36. class Estimator:
  37. def __init__(self,**kwargs):
  38. self.trained_ckpt_url=None
  39. # TODO:save url
  40. # example : https://www.mindspore.cn/doc/programming_guide/zh-CN/r1.0/train.html#id3
  41. def train(self, train_data,base_model_url, trained_ckpt_url, valid_data=None,epochs=10, **kwargs):
  42. network=mobilenet_v2_fine_tune(base_model_url).get_train_network()
  43. network_opt=nn.Momentum(params=network.trainable_params(),learning_rate=0.01,momentum=0.9)
  44. network_loss=CrossEntropySmooth(sparse=True, reduction="mean", smooth_factor=0.1, classes_num=2)
  45. metrics = {"Accuracy" : nn.Accuracy()}
  46. model=ms.Model(network, loss_fn=network_loss, optimizer=network_opt, metrics=metrics)
  47. num_epochs = epochs
  48. #best_ckpt_name=deploy_model_url.split(r"/")[-1]
  49. #ckpt_dir=deploy_model_url.replace(best_ckpt_name, "")
  50. model.train(num_epochs, train_data, callbacks=[ValAccMonitor(model, valid_data, num_epochs, save_best_ckpt=True, ckpt_directory=trained_ckpt_url), ms.TimeMonitor()])
  51. self.trained_ckpt_url=trained_ckpt_url+"/best.ckpt"
  52. # sedna will save model checkpoint in the path which is the value of MODEL_URL or MODEL_PATH
  53. #ms.save_checkpoint(network, deploy_model_url)
  54. def evaluate(self,data,model_path="",class_name="",input_shape=(224,224),**kwargs):
  55. # load
  56. network = mobilenet_v2_fine_tune(model_path).get_eval_network()
  57. # eval
  58. network_loss = CrossEntropySmooth(sparse=True,
  59. reduction="mean",
  60. smooth_factor=0.1,
  61. classes_num=2)
  62. model = ms.Model(network, loss_fn=network_loss, optimizer=None, metrics={'acc'})
  63. acc=model.eval(data, dataset_sink_mode=False)
  64. print(acc)
  65. return acc
  66. def predict(self, data,model, input_shape=None, **kwargs):
  67. # load
  68. # preprocess
  69. preprocessed_data=preprocess(data)
  70. # predict
  71. pre=model.predict(ms.Tensor(preprocessed_data))
  72. result=np.argmax(pre)
  73. class_name={0:"Croissants", 1:"Dog"}
  74. #print(class_name[result])
  75. #return class_name[result]
  76. return pre
  77. def load(self, model_url):
  78. pass
  79. def save(self, model_path=None):
  80. if not model_path:
  81. return
  82. #model_dir, model_name = os.path.split(model_path)
  83. network = mobilenet_v2_fine_tune(self.trained_ckpt_url).get_eval_network()
  84. ms.save_checkpoint(network, model_path)