_session_preparation.py 4.0 KB

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