_session_preparation.py 4.5 KB

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