visualize.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. import os.path as osp
  15. import tqdm
  16. import numpy as np
  17. from .prune import cal_model_size
  18. from paddleslim.prune import load_sensitivities
  19. def visualize(model, sensitivities_file, save_dir='./'):
  20. """将模型裁剪率和每个参数裁剪后精度损失的关系可视化。
  21. 可视化结果纵轴为eval_metric_loss参数值,横轴为对应的模型被裁剪的比例
  22. Args:
  23. model (paddlex.cv.models): paddlex中的模型。
  24. sensitivities_file (str): 敏感度文件存储路径。
  25. """
  26. import matplotlib
  27. matplotlib.use('Agg')
  28. import matplotlib.pyplot as plt
  29. program = model.test_prog
  30. place = model.places[0]
  31. fig = plt.figure()
  32. plt.xlabel("model prune ratio")
  33. plt.ylabel("evaluation loss")
  34. title_name = osp.split(sensitivities_file)[-1].split('.')[0]
  35. plt.title(title_name)
  36. plt.grid(linestyle='--', linewidth=0.5)
  37. x = list()
  38. y = list()
  39. for loss_thresh in tqdm.tqdm(list(np.arange(0.05, 1, 0.05))):
  40. prune_ratio = 1 - cal_model_size(
  41. program, place, sensitivities_file, eval_metric_loss=loss_thresh)
  42. x.append(prune_ratio)
  43. y.append(loss_thresh)
  44. plt.plot(x, y, color='green', linewidth=0.5, marker='o', markersize=3)
  45. my_x_ticks = np.arange(
  46. min(np.array(x)) - 0.01,
  47. max(np.array(x)) + 0.01, 0.05)
  48. my_y_ticks = np.arange(0.05, 1, 0.05)
  49. plt.xticks(my_x_ticks, fontsize=3)
  50. plt.yticks(my_y_ticks, fontsize=3)
  51. for a, b in zip(x, y):
  52. plt.text(
  53. a,
  54. b, (float('%0.4f' % a), float('%0.3f' % b)),
  55. ha='center',
  56. va='bottom',
  57. fontsize=3)
  58. suffix = osp.splitext(sensitivities_file)[-1]
  59. plt.savefig('sensitivities.png', dpi=800)
  60. plt.close()