_session_preparation.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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
  15. import os.path as osp
  16. import paddle.fluid as fluid
  17. import paddlex as pdx
  18. import numpy as np
  19. from paddle.fluid.param_attr import ParamAttr
  20. from paddlex.interpret.as_data_reader.readers import preprocess_image
  21. def gen_user_home():
  22. if "HOME" in os.environ:
  23. home_path = os.environ["HOME"]
  24. if os.path.exists(home_path) and os.path.isdir(home_path):
  25. return home_path
  26. return os.path.expanduser('~')
  27. def paddle_get_fc_weights(var_name="fc_0.w_0"):
  28. fc_weights = fluid.global_scope().find_var(var_name).get_tensor()
  29. return np.array(fc_weights)
  30. def paddle_resize(extracted_features, outsize):
  31. resized_features = fluid.layers.resize_bilinear(extracted_features,
  32. outsize)
  33. return resized_features
  34. def get_precomputed_normlime_weights():
  35. root_path = gen_user_home()
  36. root_path = osp.join(root_path, '.paddlex')
  37. h_pre_models = osp.join(root_path, "pre_models")
  38. normlime_weights_file = osp.join(
  39. h_pre_models, "normlime_weights_imagenet_resnet50vc.npy")
  40. return np.load(normlime_weights_file, allow_pickle=True).item()
  41. def compute_features_for_kmeans(data_content):
  42. root_path = gen_user_home()
  43. root_path = osp.join(root_path, '.paddlex')
  44. h_pre_models = osp.join(root_path, "pre_models")
  45. if not osp.exists(h_pre_models):
  46. if not osp.exists(root_path):
  47. os.makedirs(root_path)
  48. url = "https://bj.bcebos.com/paddlex/interpret/pre_models.tar.gz"
  49. pdx.utils.download_and_decompress(url, path=root_path)
  50. def conv_bn_layer(input,
  51. num_filters,
  52. filter_size,
  53. stride=1,
  54. groups=1,
  55. act=None,
  56. name=None,
  57. is_test=True,
  58. global_name='for_kmeans_'):
  59. conv = fluid.layers.conv2d(
  60. input=input,
  61. num_filters=num_filters,
  62. filter_size=filter_size,
  63. stride=stride,
  64. padding=(filter_size - 1) // 2,
  65. groups=groups,
  66. act=None,
  67. param_attr=ParamAttr(name=global_name + name + "_weights"),
  68. bias_attr=False,
  69. name=global_name + name + '.conv2d.output.1')
  70. if name == "conv1":
  71. bn_name = "bn_" + name
  72. else:
  73. bn_name = "bn" + name[3:]
  74. return fluid.layers.batch_norm(
  75. input=conv,
  76. act=act,
  77. name=global_name + bn_name + '.output.1',
  78. param_attr=ParamAttr(global_name + bn_name + '_scale'),
  79. bias_attr=ParamAttr(global_name + bn_name + '_offset'),
  80. moving_mean_name=global_name + bn_name + '_mean',
  81. moving_variance_name=global_name + bn_name + '_variance',
  82. use_global_stats=is_test)
  83. startup_prog = fluid.default_startup_program().clone(for_test=True)
  84. prog = fluid.Program()
  85. with fluid.program_guard(prog, startup_prog):
  86. with fluid.unique_name.guard():
  87. image_op = fluid.data(
  88. name='image', shape=[None, 3, 224, 224], dtype='float32')
  89. conv = conv_bn_layer(
  90. input=image_op,
  91. num_filters=32,
  92. filter_size=3,
  93. stride=2,
  94. act='relu',
  95. name='conv1_1')
  96. conv = conv_bn_layer(
  97. input=conv,
  98. num_filters=32,
  99. filter_size=3,
  100. stride=1,
  101. act='relu',
  102. name='conv1_2')
  103. conv = conv_bn_layer(
  104. input=conv,
  105. num_filters=64,
  106. filter_size=3,
  107. stride=1,
  108. act='relu',
  109. name='conv1_3')
  110. extracted_features = conv
  111. resized_features = fluid.layers.resize_bilinear(extracted_features,
  112. image_op.shape[2:])
  113. gpu_id = int(os.environ.get('FLAGS_selected_gpus', 0))
  114. place = fluid.CUDAPlace(gpu_id)
  115. # place = fluid.CPUPlace()
  116. exe = fluid.Executor(place)
  117. exe.run(startup_prog)
  118. fluid.io.load_persistables(exe, h_pre_models, prog)
  119. images = preprocess_image(
  120. data_content) # transpose to [N, 3, H, W], scaled to [0.0, 1.0]
  121. result = exe.run(prog,
  122. fetch_list=[resized_features],
  123. feed={'image': images})
  124. return result[0][0]