visualize.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. 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, scope=model.scope)
  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, max(np.array(x)) + 0.01, 0.05)
  47. my_y_ticks = np.arange(0.05, 1, 0.05)
  48. plt.xticks(my_x_ticks, rotation=15, fontsize=8)
  49. plt.yticks(my_y_ticks, fontsize=8)
  50. for a, b in zip(x, y):
  51. plt.text(
  52. a,
  53. b, (float('%0.3f' % a), float('%0.3f' % b)),
  54. ha='center',
  55. va='bottom',
  56. fontsize=8)
  57. plt.rcParams['savefig.dpi'] = 120
  58. plt.rcParams['figure.dpi'] = 150
  59. suffix = osp.splitext(sensitivities_file)[-1]
  60. plt.savefig(osp.join(save_dir, 'sensitivities.png'))
  61. plt.close()
  62. import pickle
  63. coor = dict(zip(x, y))
  64. output = open(osp.join(save_dir, 'sensitivities_xy.pkl'), 'wb')
  65. pickle.dump(coor, output)