From 3b61d0668040ff69878ea91d1bea95031d8f8e53 Mon Sep 17 00:00:00 2001 From: Leo Chen Date: Sun, 25 Apr 2021 10:49:07 +0800 Subject: [PATCH] fix tensor to_string when shape contains zero (#32501) --- python/paddle/fluid/tests/unittests/test_var_base.py | 12 ++++++++++++ python/paddle/tensor/to_string.py | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/python/paddle/fluid/tests/unittests/test_var_base.py b/python/paddle/fluid/tests/unittests/test_var_base.py index 76c871f372..77432a59de 100644 --- a/python/paddle/fluid/tests/unittests/test_var_base.py +++ b/python/paddle/fluid/tests/unittests/test_var_base.py @@ -631,6 +631,18 @@ class TestVarBase(unittest.TestCase): self.assertEqual(a_str, expected) paddle.enable_static() + def test_tensor_str_shape_with_zero(self): + paddle.disable_static(paddle.CPUPlace()) + x = paddle.ones((10, 10)) + y = paddle.fluid.layers.where(x == 0) + a_str = str(y) + + expected = '''Tensor(shape=[0, 2], dtype=int64, place=CPUPlace, stop_gradient=True, + [])''' + + self.assertEqual(a_str, expected) + paddle.enable_static() + def test_print_tensor_dtype(self): paddle.disable_static(paddle.CPUPlace()) a = paddle.rand([1]) diff --git a/python/paddle/tensor/to_string.py b/python/paddle/tensor/to_string.py index 778a391df6..e5148d039c 100644 --- a/python/paddle/tensor/to_string.py +++ b/python/paddle/tensor/to_string.py @@ -93,6 +93,10 @@ def set_printoptions(precision=None, def _to_sumary(var): edgeitems = DEFAULT_PRINT_OPTIONS.edgeitems + # Handle tensor of shape contains 0, like [0, 2], [3, 0, 3] + if np.prod(var.shape) == 0: + return np.array([]) + if len(var.shape) == 0: return var elif len(var.shape) == 1: -- GitLab