hjmjohnson: @Nic-Ma Exceptional addition!!!   I was putting just this type of debugging in by hand.
Nic-Ma: > @Nic-Ma Exceptional addition!!! I was putting just this type of debugging in by hand.

Cool, glad to see it's helpful. I will try to complete it ASAP.
Thanks.
Nic-Ma: Hi @ericspod and @wyli ,

I already rebased this PR. Could you please help review it?
As there are many args in this transform, so for dictionary-based `DataStatsd`, I didn't implement tuple format for every arg. Instead, if users want to print different content for different keys, suggest using this transform multiple times.
For example:
```py
{
    ... ...
    DataStatsd(keys=('image', 'label'), prefix='image and label', data_shape=True, ...),
    DataStatsd(keys='affine', prefix='affine matrix', data_value=True, ...)
    ... ...
}
Thanks.
hjmjohnson: @Nic-Ma I would recommend that we drop python 3.5.  

It appears that PyTorch is well on the way to removing python 3.5 support already.  The main readme list 3.6, 3.7, 3.8 in its table of supported versions.

https://github.com/pytorch/pytorch


ericspod: I encountered an issue with 3.5 as well so I agree it's time to drop it.
Nic-Ma: Thanks for your comments guys.
OK, I will try to update the code and remove python 3.5 dependency.
Thanks.
Nic-Ma: Hi @ericspod ,

I updated the PR with "f string", could you please help review it again?
Thanks.
wyli: /black
diff --git a/docs/source/transforms.rst b/docs/source/transforms.rst
index 4e32153a..4c766996 100644
--- a/docs/source/transforms.rst
+++ b/docs/source/transforms.rst
@@ -303,6 +303,12 @@ Vanilla Transforms
     :members:
     :special-members: __call__
 
+`DataStats`
+~~~~~~~~~~~
+.. autoclass:: DataStats
+    :members:
+    :special-members: __call__
+
 `SimulateDelay`
 ~~~~~~~~~~~~~~~
 .. autoclass:: SimulateDelay
@@ -555,6 +561,11 @@ Dictionary-based Transforms
     :members:
     :special-members: __call__
 
+`DataStatsd`
+~~~~~~~~~~~~
+.. autoclass:: DataStatsd
+    :members:
+    :special-members: __call__
 
 `SimulateDelayd`
 ~~~~~~~~~~~~~~~~
diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py
index 5583bd74..73853010 100644
--- a/monai/transforms/utility/array.py
+++ b/monai/transforms/utility/array.py
@@ -14,6 +14,8 @@ https://github.com/Project-MONAI/MONAI/wiki/MONAI_Design
 """
 import time
 
+from typing import Callable
+import logging
 import numpy as np
 import torch
 
@@ -166,6 +168,64 @@ class SqueezeDim(Transform):
         return np.squeeze(img, self.dim)
 
 
+class DataStats(Transform):
+    """
+    Utility transform to show the statistics of data for debug or analysis.
+    It can be inserted into any place of a transform chain and check results of previous transforms.
+    """
+
+    def __init__(
+        self,
+        prefix="Data",
+        data_shape=True,
+        intensity_range=True,
+        data_value=False,
+        additional_info: Callable = None,
+        logger_handler=None,
+    ):
+        """
+        Args:
+            prefix (string): will be printed in format: "{prefix} statistics".
+            data_shape (bool): whether to show the shape of input data.
+            intensity_range (bool): whether to show the intensity value range of input data.
+            data_value (bool): whether to show the raw value of input data.
+                a typical example is to print some properties of Nifti image: affine, pixdim, etc.
+            additional_info (Callable): user can define callable function to extract additional info from input data.
+            logger_handler (logging.handler): add additional handler to output data: save to file, etc.
+                add existing python logging handlers: https://docs.python.org/3/library/logging.handlers.html
+        """
+        assert isinstance(prefix, str), "prefix must be a string."
+        self.prefix = prefix
+        self.data_shape = data_shape
+        self.intensity_range = intensity_range
+        self.data_value = data_value
+        if additional_info is not None:
+            assert isinstance(additional_info, Callable), "additional_info must be a Callable function."
+        self.additional_info = additional_info
+        self.output = None
+        logging.basicConfig(level=logging.NOTSET)
+        self._logger = logging.getLogger("DataStats")
+        if logger_handler is not None:
+            self._logger.addHandler(logger_handler)
+
+    def __call__(self, img):
+        lines = [f"{self.prefix} statistics:"]
+
+        if self.data_shape:
+            lines.append(f"Shape: {img.shape}")
+        if self.intensity_range:
+            lines.append(f"Intensity range: ({np.min(img)}, {np.max(img)})")
+        if self.data_value:
+            lines.append(f"Value: {img}")
+        if self.additional_info:
+            lines.append(f"Additional info: {self.additional_info(img)}")
+        separator = "\n"
+        self.output = f"{separator.join(lines)}"
+        self._logger.debug(self.output)
+
+        return img
+
+
 class SimulateDelay(Transform):
     """
     This is a pass through transform to be used for testing purposes. It allows
diff --git a/monai/transforms/utility/dictionary.py b/monai/transforms/utility/dictionary.py
index 4c420829..4a7a1a3d 100644
--- a/monai/transforms/utility/dictionary.py
+++ b/monai/transforms/utility/dictionary.py
@@ -26,6 +26,7 @@ from monai.transforms.utility.array import (
     CastToType,
     RepeatChannel,
     SqueezeDim,
+    DataStats,
     SimulateDelay,
 )
 
@@ -201,6 +202,44 @@ class SqueezeDimd(MapTransform):
         return d
 
 
+class DataStatsd(MapTransform):
+    """
+    Dictionary-based wrapper of :py:class:`monai.transforms.DataStats`.
+    """
+
+    def __init__(
+        self,
+        keys,
+        prefix="Data",
+        data_shape=True,
+        intensity_range=True,
+        data_value=False,
+        additional_info=None,
+        logger_handler=None,
+    ):
+        """
+        Args:
+            keys (hashable items): keys of the corresponding items to be transformed.
+                See also: :py:class:`monai.transforms.compose.MapTransform`
+            prefix (string): will be printed in format: "{prefix} statistics".
+            data_shape (bool): whether to show the shape of input data.
+            intensity_range (bool): whether to show the intensity value range of input data.
+            data_value (bool): whether to show the raw value of input data.
+                a typical example is to print some properties of Nifti image: affine, pixdim, etc.
+            additional_info (Callable): user can define callable function to extract additional info from input data.
+            logger_handler (logging.handler): add additional handler to output data: save to file, etc.
+                add existing python logging handlers: https://docs.python.org/3/library/logging.handlers.html
+        """
+        super().__init__(keys)
+        self.printer = DataStats(prefix, data_shape, intensity_range, data_value, additional_info, logger_handler)
+
+    def __call__(self, data):
+        d = dict(data)
+        for key in self.keys:
+            d[key] = self.printer(d[key])
+        return d
+
+
 class SimulateDelayd(MapTransform):
     """
     dictionary-based wrapper of :py:class:monai.transforms.utility.array.SimulateDelay.
@@ -238,4 +277,5 @@ CastToTypeD = CastToTypeDict = CastToTyped
 ToTensorD = ToTensorDict = ToTensord
 DeleteKeysD = DeleteKeysDict = DeleteKeysd
 SqueezeDimD = SqueezeDimDict = SqueezeDimd
+DataStatsD = DataStatsDict = DataStatsd
 SimulateDelayD = SimulateDelayDict = SimulateDelayd

add StatsTransform to debug data in transform chain
**Is your feature request related to a problem? Please describe.**
Currently, our transforms compose a chain and hard to know the data after every transform and debug, need to add StatsTransform which can be inserted into the chain to print expected info.

diff --git a/tests/test_data_stats.py b/tests/test_data_stats.py
new file mode 100644
index 00000000..ace79c6e
--- /dev/null
+++ b/tests/test_data_stats.py
@@ -0,0 +1,122 @@
+# Copyright 2020 MONAI Consortium
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#     http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+import os
+import logging
+import tempfile
+import numpy as np
+from parameterized import parameterized
+from monai.transforms import DataStats
+
+TEST_CASE_1 = [
+    {
+        "prefix": "test data",
+        "data_shape": False,
+        "intensity_range": False,
+        "data_value": False,
+        "additional_info": None,
+        "logger_handler": None,
+    },
+    np.array([[0, 1], [1, 2]]),
+    "test data statistics:",
+]
+
+TEST_CASE_2 = [
+    {
+        "prefix": "test data",
+        "data_shape": True,
+        "intensity_range": False,
+        "data_value": False,
+        "additional_info": None,
+        "logger_handler": None,
+    },
+    np.array([[0, 1], [1, 2]]),
+    "test data statistics:\nShape: (2, 2)",
+]
+
+TEST_CASE_3 = [
+    {
+        "prefix": "test data",
+        "data_shape": True,
+        "intensity_range": True,
+        "data_value": False,
+        "additional_info": None,
+        "logger_handler": None,
+    },
+    np.array([[0, 1], [1, 2]]),
+    "test data statistics:\nShape: (2, 2)\nIntensity range: (0, 2)",
+]
+
+TEST_CASE_4 = [
+    {
+        "prefix": "test data",
+        "data_shape": True,
+        "intensity_range": True,
+        "data_value": True,
+        "additional_info": None,
+        "logger_handler": None,
+    },
+    np.array([[0, 1], [1, 2]]),
+    "test data statistics:\nShape: (2, 2)\nIntensity range: (0, 2)\nValue: [[0 1]\n [1 2]]",
+]
+
+TEST_CASE_5 = [
+    {
+        "prefix": "test data",
+        "data_shape": True,
+        "intensity_range": True,
+        "data_value": True,
+        "additional_info": lambda x: np.mean(x),
+        "logger_handler": None,
+    },
+    np.array([[0, 1], [1, 2]]),
+    "test data statistics:\nShape: (2, 2)\nIntensity range: (0, 2)\nValue: [[0 1]\n [1 2]]\nAdditional info: 1.0",
+]
+
+TEST_CASE_6 = [
+    np.array([[0, 1], [1, 2]]),
+    "test data statistics:\nShape: (2, 2)\nIntensity range: (0, 2)\nValue: [[0 1]\n [1 2]]\nAdditional info: 1.0\n",
+]
+
+
+class TestDataStats(unittest.TestCase):
+    @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5])
+    def test_value(self, input_param, input_data, expected_print):
+        transform = DataStats(**input_param)
+        _ = transform(input_data)
+        self.assertEqual(transform.output, expected_print)
+
+    @parameterized.expand([TEST_CASE_6])
+    def test_file(self, input_data, expected_print):
+        with tempfile.TemporaryDirectory() as tempdir:
+            filename = os.path.join(tempdir, "test_stats.log")
+            handler = logging.FileHandler(filename, mode="w")
+            input_param = {
+                "prefix": "test data",
+                "data_shape": True,
+                "intensity_range": True,
+                "data_value": True,
+                "additional_info": lambda x: np.mean(x),
+                "logger_handler": handler,
+            }
+            transform = DataStats(**input_param)
+            _ = transform(input_data)
+            handler.stream.close()
+            transform._logger.removeHandler(handler)
+            with open(filename, "r") as f:
+                content = f.read()
+                self.assertEqual(content, expected_print)
+            os.remove(filename)
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/test_data_statsd.py b/tests/test_data_statsd.py
new file mode 100644
index 00000000..9466584a
--- /dev/null
+++ b/tests/test_data_statsd.py
@@ -0,0 +1,123 @@
+# Copyright 2020 MONAI Consortium
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#     http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+import os
+import logging
+import tempfile
+import numpy as np
+from parameterized import parameterized
+from monai.transforms import DataStatsd
+
+TEST_CASE_1 = [
+    {
+        "keys": "img",
+        "prefix": "test data",
+        "data_shape": False,
+        "intensity_range": False,
+        "data_value": False,
+        "additional_info": None,
+    },
+    {"img": np.array([[0, 1], [1, 2]])},
+    "test data statistics:",
+]
+
+TEST_CASE_2 = [
+    {
+        "keys": "img",
+        "prefix": "test data",
+        "data_shape": True,
+        "intensity_range": False,
+        "data_value": False,
+        "additional_info": None,
+    },
+    {"img": np.array([[0, 1], [1, 2]])},
+    "test data statistics:\nShape: (2, 2)",
+]
+
+TEST_CASE_3 = [
+    {
+        "keys": "img",
+        "prefix": "test data",
+        "data_shape": True,
+        "intensity_range": True,
+        "data_value": False,
+        "additional_info": None,
+    },
+    {"img": np.array([[0, 1], [1, 2]])},
+    "test data statistics:\nShape: (2, 2)\nIntensity range: (0, 2)",
+]
+
+TEST_CASE_4 = [
+    {
+        "keys": "img",
+        "prefix": "test data",
+        "data_shape": True,
+        "intensity_range": True,
+        "data_value": True,
+        "additional_info": None,
+    },
+    {"img": np.array([[0, 1], [1, 2]])},
+    "test data statistics:\nShape: (2, 2)\nIntensity range: (0, 2)\nValue: [[0 1]\n [1 2]]",
+]
+
+TEST_CASE_5 = [
+    {
+        "keys": "img",
+        "prefix": "test data",
+        "data_shape": True,
+        "intensity_range": True,
+        "data_value": True,
+        "additional_info": lambda x: np.mean(x),
+    },
+    {"img": np.array([[0, 1], [1, 2]])},
+    "test data statistics:\nShape: (2, 2)\nIntensity range: (0, 2)\nValue: [[0 1]\n [1 2]]\nAdditional info: 1.0",
+]
+
+TEST_CASE_6 = [
+    {"img": np.array([[0, 1], [1, 2]])},
+    "test data statistics:\nShape: (2, 2)\nIntensity range: (0, 2)\nValue: [[0 1]\n [1 2]]\nAdditional info: 1.0\n",
+]
+
+
+class TestDataStatsd(unittest.TestCase):
+    @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5])
+    def test_value(self, input_param, input_data, expected_print):
+        transform = DataStatsd(**input_param)
+        _ = transform(input_data)
+        self.assertEqual(transform.printer.output, expected_print)
+
+    @parameterized.expand([TEST_CASE_6])
+    def test_file(self, input_data, expected_print):
+        with tempfile.TemporaryDirectory() as tempdir:
+            filename = os.path.join(tempdir, "test_stats.log")
+            handler = logging.FileHandler(filename, mode="w")
+            input_param = {
+                "keys": "img",
+                "prefix": "test data",
+                "data_shape": True,
+                "intensity_range": True,
+                "data_value": True,
+                "additional_info": lambda x: np.mean(x),
+                "logger_handler": handler,
+            }
+            transform = DataStatsd(**input_param)
+            _ = transform(input_data)
+            handler.stream.close()
+            transform.printer._logger.removeHandler(handler)
+            with open(filename, "r") as f:
+                content = f.read()
+                self.assertEqual(content, expected_print)
+            os.remove(filename)
+
+
+if __name__ == "__main__":
+    unittest.main()

pip install -e .[all]
parse_log_pytest
requirements.txt
pytest black flake8 mypy pytype
apt-get update apt-get install -y gcc
3.6
requirements.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
absl-py==1.4.0
attrs==22.2.0
black==22.8.0
cachetools==4.2.4
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
cycler==0.11.0
dataclasses==0.8
decorator==4.4.2
flake8==5.0.4
google-auth==2.22.0
google-auth-oauthlib==0.4.6
grpcio==1.48.2
idna==3.10
imageio==2.15.0
importlab==0.8.1
importlib-metadata==4.8.3
iniconfig==1.1.1
kiwisolver==1.3.1
libcst==0.4.1
Markdown==3.3.7
matplotlib==3.3.4
mccabe==0.7.0
-e git+https://github.com/Project-MONAI/MONAI.git@f67defaaa58d025ec06e00331806734abc02c35a#egg=monai
mypy==0.971
mypy-extensions==1.0.0
networkx==2.5.1
nibabel==3.2.2
ninja==1.11.1.1
numpy==1.19.5
oauthlib==3.2.2
packaging==21.3
parameterized==0.8.1
pathspec==0.9.0
Pillow==8.4.0
platformdirs==2.4.0
pluggy==1.0.0
protobuf==3.19.6
py==1.11.0
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
pytorch-ignite==0.3.0
pytype==2022.1.5
PyWavelets==1.1.1
PyYAML==6.0.1
requests==2.27.1
requests-oauthlib==2.0.0
rsa==4.9
scikit-image==0.17.2
scipy==1.5.4
six==1.17.0
tabulate==0.8.10
tensorboard==2.10.1
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.8.1
tifffile==2020.9.3
toml==0.10.2
tomli==1.2.3
torch==1.10.2
typed-ast==1.5.5
typing-inspect==0.9.0
typing_extensions==4.1.1
urllib3==1.26.20
Werkzeug==2.0.3
zipp==3.6.0

name: MONAI
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=21.2.2=py36h06a4308_0
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - absl-py==1.4.0
      - attrs==22.2.0
      - black==22.8.0
      - cachetools==4.2.4
      - charset-normalizer==2.0.12
      - click==8.0.4
      - coverage==6.2
      - cycler==0.11.0
      - dataclasses==0.8
      - decorator==4.4.2
      - flake8==5.0.4
      - google-auth==2.22.0
      - google-auth-oauthlib==0.4.6
      - grpcio==1.48.2
      - idna==3.10
      - imageio==2.15.0
      - importlab==0.8.1
      - importlib-metadata==4.8.3
      - iniconfig==1.1.1
      - kiwisolver==1.3.1
      - libcst==0.4.1
      - markdown==3.3.7
      - matplotlib==3.3.4
      - mccabe==0.7.0
      - mypy==0.971
      - mypy-extensions==1.0.0
      - networkx==2.5.1
      - nibabel==3.2.2
      - ninja==1.11.1.1
      - numpy==1.19.5
      - oauthlib==3.2.2
      - packaging==21.3
      - parameterized==0.8.1
      - pathspec==0.9.0
      - pillow==8.4.0
      - platformdirs==2.4.0
      - pluggy==1.0.0
      - protobuf==3.19.6
      - py==1.11.0
      - pyasn1==0.5.1
      - pyasn1-modules==0.3.0
      - pycodestyle==2.9.1
      - pyflakes==2.5.0
      - pyparsing==3.1.4
      - pytest==7.0.1
      - python-dateutil==2.9.0.post0
      - pytorch-ignite==0.3.0
      - pytype==2022.1.5
      - pywavelets==1.1.1
      - pyyaml==6.0.1
      - requests==2.27.1
      - requests-oauthlib==2.0.0
      - rsa==4.9
      - scikit-image==0.17.2
      - scipy==1.5.4
      - six==1.17.0
      - tabulate==0.8.10
      - tensorboard==2.10.1
      - tensorboard-data-server==0.6.1
      - tensorboard-plugin-wit==1.8.1
      - tifffile==2020.9.3
      - toml==0.10.2
      - tomli==1.2.3
      - torch==1.10.2
      - typed-ast==1.5.5
      - typing-extensions==4.1.1
      - typing-inspect==0.9.0
      - urllib3==1.26.20
      - werkzeug==2.0.3
      - zipp==3.6.0
prefix: /opt/conda/envs/MONAI

tests/test_data_stats.py::TestDataStats::test_value_0 tests/test_data_stats.py::TestDataStats::test_value_1 tests/test_data_stats.py::TestDataStats::test_value_2 tests/test_data_stats.py::TestDataStats::test_value_3 tests/test_data_stats.py::TestDataStats::test_value_4 tests/test_data_statsd.py::TestDataStatsd::test_value_0 tests/test_data_statsd.py::TestDataStatsd::test_value_1 tests/test_data_statsd.py::TestDataStatsd::test_value_2 tests/test_data_statsd.py::TestDataStatsd::test_value_3 tests/test_data_statsd.py::TestDataStatsd::test_value_4
tests/test_data_stats.py::TestDataStats::test_file_0 tests/test_data_statsd.py::TestDataStatsd::test_file_0
monai/transforms/utility/dictionary.py monai/transforms/utility/array.py docs/source/transforms.rst
monai/transforms/utility/dictionary.py monai/transforms/utility/array.py docs/source/transforms.rst