user3180
user3180

Reputation: 1487

Print torch tensor without extra spacing in between scalars

There is a huge space in between elements of my tensors when printing. I cannot read the tensor easily with this space. How do I minimize it?

print settings I used:

torch.set_printoptions(sci_mode=False, precision=4, linewidth=200, profile="full")
np.set_printoptions(suppress=True, precision=4, linewidth=200)

Here is a torch array: enter image description here

Here is the same shape np array but much more readable because no spacing: enter image description here

Upvotes: 2

Views: 52

Answers (1)

DerekG
DerekG

Reputation: 3938

The issue boils down to the Formatter class code in _tensor_str.py and your use of sci_mode = False.

When determining the width for each element in the tensor representation, the code first determines whether scientific notation should be used based on some numerical criteria:

if (
        nonzero_finite_max / nonzero_finite_min > 1000.0
        or nonzero_finite_max > 1.0e8
   ):
        self.sci_mode = True

then determines the max element width, assuming scientific notation is used. Finally, the code overwrites self.sci_mode based on PRINTOPTIONS. So, in the case that you specify self.sci_mode = False but the above criteria are met, the code will allocate enough spacing per element to accommodate the scientific notation representation, but will not actually use the scientific mode representation.

A brief example:

torch.set_printoptions(sci_mode=False, precision=4, linewidth=200, profile="full")
arr = torch.rand(100,100)

print(arr)                     # prints with extra space because max_element/min_element > 1000
arr = arr.round(decimals = 3)  # max element is now strictly < min_element*1000
print(arr)                     # prints with correct spacing

The issue has been raised on github, addressed by an external contributor, and closed as of May 2024, but is awaiting review. You can go and add a comment expressing your interest in it being reviewed and maybe we can get it merged!

Upvotes: 0

Related Questions