update_vgg16_params.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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 paddle
  15. def update_vgg16_params(model_path):
  16. param_state_dict = paddle.load(model_path)
  17. # first conv weight name _conv_block_1._conv_1.weight, shape is [64, 3, ,3, 3]
  18. # first fc weight name: _fc1.weight, shape is [25088, 4096]
  19. for k, v in param_state_dict.items():
  20. print(k, v.shape)
  21. # # first weight
  22. weight = param_state_dict['_conv_block_1._conv_1.weight'] # [64, 3,3,3]
  23. print('ori shape: ', weight.shape)
  24. zeros_pad = paddle.zeros((64, 1, 3, 3))
  25. param_state_dict['_conv_block_1._conv_1.weight'] = paddle.concat(
  26. [weight, zeros_pad], axis=1)
  27. print('shape after padding',
  28. param_state_dict['_conv_block_1._conv_1.weight'].shape)
  29. # fc1
  30. weight = param_state_dict['_fc1.weight']
  31. weight = paddle.transpose(weight, [1, 0])
  32. print('after transpose: ', weight.shape)
  33. weight = paddle.reshape(weight, (4096, 512, 7, 7))
  34. print('after reshape: ', weight.shape)
  35. weight = weight[0:512, :, 2:5, 2:5]
  36. print('after crop: ', weight.shape)
  37. param_state_dict['_conv_6.weight'] = weight
  38. del param_state_dict['_fc1.weight']
  39. del param_state_dict['_fc1.bias']
  40. del param_state_dict['_fc2.weight']
  41. del param_state_dict['_fc2.bias']
  42. del param_state_dict['_out.weight']
  43. del param_state_dict['_out.bias']
  44. paddle.save(param_state_dict, 'VGG16_pretrained.pdparams')
  45. if __name__ == "__main__":
  46. paddle.set_device('cpu')
  47. model_path = '~/.paddleseg/pretrained_model/dygraph/VGG16_pretrained.pdparams'
  48. update_vgg16_params(model_path)