Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add batch and event shape to repr. #1946

Merged
merged 1 commit into from
Jan 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions numpyro/distributions/distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,13 @@ def icdf(self, q: ArrayLike) -> ArrayLike:
def is_discrete(self):
return self.support.is_discrete

def __repr__(self) -> str:
cls = self.__class__
return (
f"<{cls.__module__}.{cls.__name__} object at {id(self):#x} with batch "
Copy link
Member

@OlaRonning OlaRonning Jan 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the behavior of :#x in the f-string?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The :#x formats the id of the object as a 0x[hex] to keep the repr method consistent with the default other than adding the shapes.

>>> from numpyro import distributions as dists
>>> 
>>> d = dists.Normal().expand((5, 10, 7)).to_event(2)
>>> d
<numpyro.distributions.distribution.Independent object at 0x10723f7c0 with batch shape (5,) and event shape (10, 7)>
>>> object.__repr__(d)
'<numpyro.distributions.distribution.Independent object at 0x10723f7c0>'

f"shape {self.batch_shape} and event shape {self.event_shape}>"
)


@runtime_checkable
class DistributionLike(Protocol):
Expand Down
6 changes: 6 additions & 0 deletions test/test_distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3681,3 +3681,9 @@ def icdf(self, q):

assert my_dist.mean.shape == (2, 3, 4)
assert my_dist.variance.shape == (2, 3, 4)


def test_distribution_repr():
result = repr(dist.Wishart(7, jnp.eye(5)).expand([3, 4]).to_event(1))
assert "batch shape (3,)" in result
assert "event shape (4, 5, 5)"
Loading