pytorch

Форк
0
/
geometric.py 
128 строк · 4.5 Кб
1
from numbers import Number
2

3
import torch
4
from torch.distributions import constraints
5
from torch.distributions.distribution import Distribution
6
from torch.distributions.utils import (
7
    broadcast_all,
8
    lazy_property,
9
    logits_to_probs,
10
    probs_to_logits,
11
)
12
from torch.nn.functional import binary_cross_entropy_with_logits
13

14
__all__ = ["Geometric"]
15

16

17
class Geometric(Distribution):
18
    r"""
19
    Creates a Geometric distribution parameterized by :attr:`probs`,
20
    where :attr:`probs` is the probability of success of Bernoulli trials.
21

22
    .. math::
23

24
        P(X=k) = (1-p)^{k} p, k = 0, 1, ...
25

26
    .. note::
27
        :func:`torch.distributions.geometric.Geometric` :math:`(k+1)`-th trial is the first success
28
        hence draws samples in :math:`\{0, 1, \ldots\}`, whereas
29
        :func:`torch.Tensor.geometric_` `k`-th trial is the first success hence draws samples in :math:`\{1, 2, \ldots\}`.
30

31
    Example::
32

33
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
34
        >>> m = Geometric(torch.tensor([0.3]))
35
        >>> m.sample()  # underlying Bernoulli has 30% chance 1; 70% chance 0
36
        tensor([ 2.])
37

38
    Args:
39
        probs (Number, Tensor): the probability of sampling `1`. Must be in range (0, 1]
40
        logits (Number, Tensor): the log-odds of sampling `1`.
41
    """
42
    arg_constraints = {"probs": constraints.unit_interval, "logits": constraints.real}
43
    support = constraints.nonnegative_integer
44

45
    def __init__(self, probs=None, logits=None, validate_args=None):
46
        if (probs is None) == (logits is None):
47
            raise ValueError(
48
                "Either `probs` or `logits` must be specified, but not both."
49
            )
50
        if probs is not None:
51
            (self.probs,) = broadcast_all(probs)
52
        else:
53
            (self.logits,) = broadcast_all(logits)
54
        probs_or_logits = probs if probs is not None else logits
55
        if isinstance(probs_or_logits, Number):
56
            batch_shape = torch.Size()
57
        else:
58
            batch_shape = probs_or_logits.size()
59
        super().__init__(batch_shape, validate_args=validate_args)
60
        if self._validate_args and probs is not None:
61
            # Add an extra check beyond unit_interval
62
            value = self.probs
63
            valid = value > 0
64
            if not valid.all():
65
                invalid_value = value.data[~valid]
66
                raise ValueError(
67
                    "Expected parameter probs "
68
                    f"({type(value).__name__} of shape {tuple(value.shape)}) "
69
                    f"of distribution {repr(self)} "
70
                    f"to be positive but found invalid values:\n{invalid_value}"
71
                )
72

73
    def expand(self, batch_shape, _instance=None):
74
        new = self._get_checked_instance(Geometric, _instance)
75
        batch_shape = torch.Size(batch_shape)
76
        if "probs" in self.__dict__:
77
            new.probs = self.probs.expand(batch_shape)
78
        if "logits" in self.__dict__:
79
            new.logits = self.logits.expand(batch_shape)
80
        super(Geometric, new).__init__(batch_shape, validate_args=False)
81
        new._validate_args = self._validate_args
82
        return new
83

84
    @property
85
    def mean(self):
86
        return 1.0 / self.probs - 1.0
87

88
    @property
89
    def mode(self):
90
        return torch.zeros_like(self.probs)
91

92
    @property
93
    def variance(self):
94
        return (1.0 / self.probs - 1.0) / self.probs
95

96
    @lazy_property
97
    def logits(self):
98
        return probs_to_logits(self.probs, is_binary=True)
99

100
    @lazy_property
101
    def probs(self):
102
        return logits_to_probs(self.logits, is_binary=True)
103

104
    def sample(self, sample_shape=torch.Size()):
105
        shape = self._extended_shape(sample_shape)
106
        tiny = torch.finfo(self.probs.dtype).tiny
107
        with torch.no_grad():
108
            if torch._C._get_tracing_state():
109
                # [JIT WORKAROUND] lack of support for .uniform_()
110
                u = torch.rand(shape, dtype=self.probs.dtype, device=self.probs.device)
111
                u = u.clamp(min=tiny)
112
            else:
113
                u = self.probs.new(shape).uniform_(tiny, 1)
114
            return (u.log() / (-self.probs).log1p()).floor()
115

116
    def log_prob(self, value):
117
        if self._validate_args:
118
            self._validate_sample(value)
119
        value, probs = broadcast_all(value, self.probs)
120
        probs = probs.clone(memory_format=torch.contiguous_format)
121
        probs[(probs == 1) & (value == 0)] = 0
122
        return value * (-probs).log1p() + self.probs.log()
123

124
    def entropy(self):
125
        return (
126
            binary_cross_entropy_with_logits(self.logits, self.probs, reduction="none")
127
            / self.probs
128
        )
129

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.