1# mypy: allow-untyped-defs 2import torch 3from torch.distributions import constraints 4from torch.distributions.exponential import Exponential 5from torch.distributions.gumbel import euler_constant 6from torch.distributions.transformed_distribution import TransformedDistribution 7from torch.distributions.transforms import AffineTransform, PowerTransform 8from torch.distributions.utils import broadcast_all 9 10 11__all__ = ["Weibull"] 12 13 14class Weibull(TransformedDistribution): 15 r""" 16 Samples from a two-parameter Weibull distribution. 17 18 Example: 19 20 >>> # xdoctest: +IGNORE_WANT("non-deterministic") 21 >>> m = Weibull(torch.tensor([1.0]), torch.tensor([1.0])) 22 >>> m.sample() # sample from a Weibull distribution with scale=1, concentration=1 23 tensor([ 0.4784]) 24 25 Args: 26 scale (float or Tensor): Scale parameter of distribution (lambda). 27 concentration (float or Tensor): Concentration parameter of distribution (k/shape). 28 """ 29 arg_constraints = { 30 "scale": constraints.positive, 31 "concentration": constraints.positive, 32 } 33 support = constraints.positive 34 35 def __init__(self, scale, concentration, validate_args=None): 36 self.scale, self.concentration = broadcast_all(scale, concentration) 37 self.concentration_reciprocal = self.concentration.reciprocal() 38 base_dist = Exponential( 39 torch.ones_like(self.scale), validate_args=validate_args 40 ) 41 transforms = [ 42 PowerTransform(exponent=self.concentration_reciprocal), 43 AffineTransform(loc=0, scale=self.scale), 44 ] 45 super().__init__(base_dist, transforms, validate_args=validate_args) 46 47 def expand(self, batch_shape, _instance=None): 48 new = self._get_checked_instance(Weibull, _instance) 49 new.scale = self.scale.expand(batch_shape) 50 new.concentration = self.concentration.expand(batch_shape) 51 new.concentration_reciprocal = new.concentration.reciprocal() 52 base_dist = self.base_dist.expand(batch_shape) 53 transforms = [ 54 PowerTransform(exponent=new.concentration_reciprocal), 55 AffineTransform(loc=0, scale=new.scale), 56 ] 57 super(Weibull, new).__init__(base_dist, transforms, validate_args=False) 58 new._validate_args = self._validate_args 59 return new 60 61 @property 62 def mean(self): 63 return self.scale * torch.exp(torch.lgamma(1 + self.concentration_reciprocal)) 64 65 @property 66 def mode(self): 67 return ( 68 self.scale 69 * ((self.concentration - 1) / self.concentration) 70 ** self.concentration.reciprocal() 71 ) 72 73 @property 74 def variance(self): 75 return self.scale.pow(2) * ( 76 torch.exp(torch.lgamma(1 + 2 * self.concentration_reciprocal)) 77 - torch.exp(2 * torch.lgamma(1 + self.concentration_reciprocal)) 78 ) 79 80 def entropy(self): 81 return ( 82 euler_constant * (1 - self.concentration_reciprocal) 83 + torch.log(self.scale * self.concentration_reciprocal) 84 + 1 85 ) 86