custom_trainer.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # Copyright (c) 2022 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 inspect
  15. import paddle
  16. import paddlers
  17. from paddlers.tasks.change_detector import BaseChangeDetector
  18. from attach_tools import Attach
  19. attach = Attach.to(paddlers.tasks.change_detector)
  20. def make_trainer(net_type, *args, **kwargs):
  21. def _init_func(self,
  22. num_classes=2,
  23. use_mixed_loss=False,
  24. losses=None,
  25. **params):
  26. sig = inspect.signature(net_type.__init__)
  27. net_params = {
  28. k: p.default
  29. for k, p in sig.parameters.items() if not p.default is p.empty
  30. }
  31. net_params.pop('self', None)
  32. net_params.pop('num_classes', None)
  33. net_params.update(params)
  34. super(trainer_type, self).__init__(
  35. model_name=net_type.__name__,
  36. num_classes=num_classes,
  37. use_mixed_loss=use_mixed_loss,
  38. losses=losses,
  39. **net_params)
  40. if not issubclass(net_type, paddle.nn.Layer):
  41. raise TypeError("net must be a subclass of paddle.nn.Layer")
  42. trainer_name = net_type.__name__
  43. trainer_type = type(trainer_name, (BaseChangeDetector, ),
  44. {'__init__': _init_func})
  45. return trainer_type(*args, **kwargs)
  46. @attach
  47. class CustomTrainer(BaseChangeDetector):
  48. def __init__(self,
  49. num_classes=2,
  50. use_mixed_loss=False,
  51. losses=None,
  52. in_channels=3,
  53. att_types='ct',
  54. use_dropout=False,
  55. **params):
  56. params.update({
  57. 'in_channels': in_channels,
  58. 'att_types': att_types,
  59. 'use_dropout': use_dropout
  60. })
  61. super().__init__(
  62. model_name='CustomModel',
  63. num_classes=num_classes,
  64. use_mixed_loss=use_mixed_loss,
  65. losses=losses,
  66. **params)