utils.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from dataclasses import dataclass, field
  18. from enum import Enum
  19. from typing import Any, Callable, Dict, Tuple
  20. from kornia.core import Module, Tensor
  21. from kornia.metrics.average_meter import AverageMeter
  22. # import yaml
  23. class TrainerState(Enum):
  24. STARTING = 0
  25. TRAINING = 1
  26. VALIDATE = 2
  27. TERMINATE = 3
  28. # NOTE: this class needs to be redefined according to the needed parameters.
  29. @dataclass
  30. class Configuration:
  31. data_path: str = field(default="./", metadata={"help": "The input data directory."})
  32. batch_size: int = field(default=1, metadata={"help": "The number of batches for the training dataloader."})
  33. num_epochs: int = field(default=1, metadata={"help": "The number of epochs to run the training."})
  34. lr: float = field(default=1e-3, metadata={"help": "The learning rate to be used for the optimize."})
  35. output_path: str = field(default="./output", metadata={"help": "The output data directory."})
  36. image_size: Tuple[int, int] = field(default=(224, 224), metadata={"help": "The input image size."})
  37. # TODO: possibly remove because hydra already do this
  38. # def __init__(self, **entries):
  39. # for k, v in entries.items():
  40. # self.__dict__[k] = Configuration(**v) if isinstance(v, dict) else v
  41. # @classmethod
  42. # def from_yaml(cls, config_file: str):
  43. # """Create an instance of the configuration from a yaml file."""
  44. # with open(config_file) as f:
  45. # data = yaml.safe_load(f)
  46. # return cls(**data)
  47. class Lambda(Module):
  48. """Module to create a lambda function as Module.
  49. Args:
  50. fcn: a pointer to any function.
  51. Example:
  52. >>> import torch
  53. >>> import kornia as K
  54. >>> fcn = Lambda(lambda x: K.geometry.resize(x, (32, 16)))
  55. >>> fcn(torch.rand(1, 4, 64, 32)).shape
  56. torch.Size([1, 4, 32, 16])
  57. """
  58. def __init__(self, fcn: Callable[..., Any]) -> None:
  59. super().__init__()
  60. self.fcn = fcn
  61. def forward(self, x: Tensor) -> Any:
  62. return self.fcn(x)
  63. class StatsTracker:
  64. """Stats tracker for computing metrics on the fly."""
  65. def __init__(self) -> None:
  66. self._stats: Dict[str, AverageMeter] = {}
  67. @property
  68. def stats(self) -> Dict[str, AverageMeter]:
  69. return self._stats
  70. def update(self, key: str, val: float, batch_size: int) -> None:
  71. """Update the stats by the key value pair."""
  72. if key not in self._stats:
  73. self._stats[key] = AverageMeter()
  74. self._stats[key].update(val, batch_size)
  75. def update_from_dict(self, dic: Dict[str, float], batch_size: int) -> None:
  76. """Update the stats by the dict."""
  77. for k, v in dic.items():
  78. self.update(k, v, batch_size)
  79. def __repr__(self) -> str:
  80. return " ".join([f"{k.upper()}: {v.val:.2f} {v.val:.2f} " for k, v in self._stats.items()])
  81. def as_dict(self) -> Dict[str, AverageMeter]:
  82. """Return the dict format."""
  83. return self._stats