xref: /aosp_15_r20/external/pytorch/torch/distributions/logistic_normal.py (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1 # mypy: allow-untyped-defs
2 from torch.distributions import constraints
3 from torch.distributions.normal import Normal
4 from torch.distributions.transformed_distribution import TransformedDistribution
5 from torch.distributions.transforms import StickBreakingTransform
6 
7 
8 __all__ = ["LogisticNormal"]
9 
10 
11 class LogisticNormal(TransformedDistribution):
12     r"""
13     Creates a logistic-normal distribution parameterized by :attr:`loc` and :attr:`scale`
14     that define the base `Normal` distribution transformed with the
15     `StickBreakingTransform` such that::
16 
17         X ~ LogisticNormal(loc, scale)
18         Y = log(X / (1 - X.cumsum(-1)))[..., :-1] ~ Normal(loc, scale)
19 
20     Args:
21         loc (float or Tensor): mean of the base distribution
22         scale (float or Tensor): standard deviation of the base distribution
23 
24     Example::
25 
26         >>> # logistic-normal distributed with mean=(0, 0, 0) and stddev=(1, 1, 1)
27         >>> # of the base Normal distribution
28         >>> # xdoctest: +IGNORE_WANT("non-deterministic")
29         >>> m = LogisticNormal(torch.tensor([0.0] * 3), torch.tensor([1.0] * 3))
30         >>> m.sample()
31         tensor([ 0.7653,  0.0341,  0.0579,  0.1427])
32 
33     """
34     arg_constraints = {"loc": constraints.real, "scale": constraints.positive}
35     support = constraints.simplex
36     has_rsample = True
37 
38     def __init__(self, loc, scale, validate_args=None):
39         base_dist = Normal(loc, scale, validate_args=validate_args)
40         if not base_dist.batch_shape:
41             base_dist = base_dist.expand([1])
42         super().__init__(
43             base_dist, StickBreakingTransform(), validate_args=validate_args
44         )
45 
46     def expand(self, batch_shape, _instance=None):
47         new = self._get_checked_instance(LogisticNormal, _instance)
48         return super().expand(batch_shape, _instance=new)
49 
50     @property
51     def loc(self):
52         return self.base_dist.base_dist.loc
53 
54     @property
55     def scale(self):
56         return self.base_dist.base_dist.scale
57