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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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=img.convert("RGB").resize((224,224))
  27. mean = np.array([0.485 * 255, 0.456 * 255, 0.406 * 255])
  28. std = np.array([0.229 * 255, 0.224 * 255, 0.225 * 255])
  29. image = np.array(image)
  30. image = (image - mean) / std
  31. image = image.astype(np.float32)
  32. image = np.transpose(image, (2, 0, 1))
  33. image = np.expand_dims(image, axis=0)
  34. return image
  35. class Estimator:
  36. def __init__(self,**kwargs):
  37. self.trained_ckpt_url=None
  38. def train(self, train_data,base_model_url, trained_ckpt_url, valid_data=None, epochs=10, **kwargs):
  39. network=mobilenet_v2_fine_tune(base_model_url).get_train_network()
  40. network_opt=nn.Momentum(params=network.trainable_params(), learning_rate=0.01, momentum=0.9)
  41. network_loss=CrossEntropySmooth(sparse=True, reduction="mean", smooth_factor=0.1, classes_num=2)
  42. metrics = {"Accuracy": nn.Accuracy()}
  43. model=ms.Model(network, loss_fn=network_loss, optimizer=network_opt, metrics=metrics)
  44. num_epochs = epochs
  45. model.train(num_epochs, train_data, callbacks=[ValAccMonitor(model, valid_data, num_epochs, save_best_ckpt=True, ckpt_directory=trained_ckpt_url), ms.TimeMonitor()])
  46. self.trained_ckpt_url = trained_ckpt_url+"/best.ckpt"
  47. def evaluate(self,data,model_path="", class_name="", input_shape=(224, 224), **kwargs):
  48. # load
  49. network = mobilenet_v2_fine_tune(model_path).get_eval_network()
  50. # eval
  51. network_loss = CrossEntropySmooth(sparse=True,
  52. reduction="mean",
  53. smooth_factor=0.1,
  54. classes_num=2)
  55. model = ms.Model(network, loss_fn=network_loss, optimizer=None, metrics={'acc'})
  56. acc=model.eval(data, dataset_sink_mode=False)
  57. print(acc)
  58. return acc
  59. def predict(self, data, model, input_shape=None, **kwargs):
  60. # preprocess
  61. preprocessed_data=preprocess(data)
  62. # predict
  63. pre=model.predict(ms.Tensor(preprocessed_data))
  64. return pre
  65. def save(self, model_path=None):
  66. if not model_path:
  67. return
  68. network = mobilenet_v2_fine_tune(self.trained_ckpt_url).get_eval_network()
  69. ms.save_checkpoint(network, model_path)