visualize.py 2.6 KB

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