/tests/test_handler_tb_stats.py

https://github.com/Project-MONAI/MONAI
Python | 72 lines | 38 code | 16 blank | 18 comment | 3 complexity | 353f31178c7ac3bdf5b80a1f5a631114 MD5 | raw file
  1. # Copyright 2020 MONAI Consortium
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import glob
  12. import tempfile
  13. import unittest
  14. from ignite.engine import Engine, Events
  15. from torch.utils.tensorboard import SummaryWriter
  16. from monai.handlers import TensorBoardStatsHandler
  17. class TestHandlerTBStats(unittest.TestCase):
  18. def test_metrics_print(self):
  19. with tempfile.TemporaryDirectory() as tempdir:
  20. # set up engine
  21. def _train_func(engine, batch):
  22. return batch + 1.0
  23. engine = Engine(_train_func)
  24. # set up dummy metric
  25. @engine.on(Events.EPOCH_COMPLETED)
  26. def _update_metric(engine):
  27. current_metric = engine.state.metrics.get("acc", 0.1)
  28. engine.state.metrics["acc"] = current_metric + 0.1
  29. # set up testing handler
  30. stats_handler = TensorBoardStatsHandler(log_dir=tempdir)
  31. stats_handler.attach(engine)
  32. engine.run(range(3), max_epochs=2)
  33. # check logging output
  34. self.assertTrue(len(glob.glob(tempdir)) > 0)
  35. def test_metrics_writer(self):
  36. with tempfile.TemporaryDirectory() as tempdir:
  37. # set up engine
  38. def _train_func(engine, batch):
  39. return batch + 1.0
  40. engine = Engine(_train_func)
  41. # set up dummy metric
  42. @engine.on(Events.EPOCH_COMPLETED)
  43. def _update_metric(engine):
  44. current_metric = engine.state.metrics.get("acc", 0.1)
  45. engine.state.metrics["acc"] = current_metric + 0.1
  46. # set up testing handler
  47. writer = SummaryWriter(log_dir=tempdir)
  48. stats_handler = TensorBoardStatsHandler(
  49. writer, output_transform=lambda x: {"loss": x * 2.0}, global_epoch_transform=lambda x: x * 3.0
  50. )
  51. stats_handler.attach(engine)
  52. engine.run(range(3), max_epochs=2)
  53. # check logging output
  54. self.assertTrue(len(glob.glob(tempdir)) > 0)
  55. if __name__ == "__main__":
  56. unittest.main()