visualize.py 2.6 KB

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