_session_preparation.py 4.5 KB

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