目录

概率分布 - torch.distributions

distributions 包含可参数化的概率分布和采样函数。这允许构建随机计算图和用于优化的随机梯度估计器。此包通常遵循 TensorFlow Distributions 包的设计。

无法直接对随机样本进行反向传播。然而,有两种主要方法可以创建可以通过反向传播的替代函数。这些是得分函数估计器/似然比估计器/REINFORCE和路径导数估计器。REINFORCE通常被视为强化学习中策略梯度方法的基础,而路径导数估计器在变分自编码器的重参数化技巧中常见。尽管得分函数仅需要样本值 f(x)f(x),路径导数还需要导数值 f(x)f'(x)。接下来的章节将在强化学习示例中讨论这两种方法。更多细节请参见 使用随机计算图进行梯度估计

评分函数

当概率密度函数对其参数可微分时,我们只需要 sample()log_prob() 来实现 REINFORCE:

Δθ=αrlogp(aπθ(s))θ\Delta\theta = \alpha r \frac{\partial\log p(a|\pi^\theta(s))}{\partial\theta}

其中 θ\theta 是参数,α\alpha 是学习率, rr 是奖励,p(aπθ(s))p(a|\pi^\theta(s)) 是在状态 ss 下根据策略 πθ\pi^\theta 采取行动 aa 的概率。

在实践中,我们会从网络的输出中采样一个动作,在环境中应用这个动作,然后使用log_prob来构建一个等效的损失函数。请注意,我们使用负号是因为优化器使用梯度下降,而上述规则假设的是梯度上升。对于类别型策略,实现REINFORCE的代码如下所示:

probs = policy_network(state)
# Note that this is equivalent to what used to be called multinomial
m = Categorical(probs)
action = m.sample()
next_state, reward = env.step(action)
loss = -m.log_prob(action) * reward
loss.backward()

路径导数

另一种实现这些随机/策略梯度的方法是使用 rsample() 方法中的重参数技巧,其中参数化的随机变量可以通过一个以无参数随机变量为参数的确定性函数构造。因此,重参数化的样本变得可微分。实现路径导数的代码如下所示:

params = policy_network(state)
m = Normal(*params)
# Any distribution with .has_rsample == True could work based on the application
action = m.rsample()
next_state, reward = env.step(action)  # Assuming that reward is differentiable
loss = -reward
loss.backward()

分布

class torch.distributions.distribution.Distribution(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)[source]

基础: object

分布是概率分布的抽象基类。

property arg_constraints: Dict[str, Constraint]

返回一个字典,键为参数名称,值为应由该分布的每个参数满足的 Constraint 对象。非张量类型的参数无需出现在此字典中。

property batch_shape: Size

返回参数批处理的形状。

cdf(value)[source]

返回在位置value处计算的累积密度/质量函数。

Parameters

(张量) –

Return type

张量

entropy()[source]

返回在 batch_shape 上成批的分布熵。

Returns

批次形状的张量。

Return type

张量

enumerate_support(expand=True)[source]

返回包含离散分布所支持的所有值的张量。结果将在维度0上枚举,因此结果的形状将是(cardinality,) + batch_shape + event_shape (对于一元分布,event_shape = ())。

注意,这以同步方式遍历所有批处理张量。[[0, 0], [1, 1], …]。使用expand=False时,枚举会在dim 0进行,但剩余的批处理维度将是单例维度,[[0], [1], ..

使用itertools.product(m.enumerate_support())来遍历整个笛卡尔积。

Parameters

展开 (bool) – 是否在批次维度上扩展以匹配分布的batch_shape

Returns

在维度 0 上迭代张量。

Return type

张量

property event_shape: Size

返回单个样本的形状(不包括批处理)。

expand(batch_shape, _instance=None)[source]

返回一个新的分布实例(或者填充由派生类提供的现有实例)并将其批次维度扩展到batch_shape。此方法调用expand在分布的参数上。因此,这不会为扩展的分布实例分配新的内存。此外,在第一次创建实例时,__init__.py中也不会重复任何参数检查或参数广播。

Parameters
  • 批次形状 (torch.Size) – 所需的扩展大小。

  • _instance – 由子类提供的新实例,需要重写.expand

Returns

新的分布实例,批处理维度扩展到 batch_size

icdf(value)[source]

返回在位置value处计算的逆累积密度/质量函数。

Parameters

(张量) –

Return type

张量

log_prob(value)[source]

返回在 value 处计算的概率密度/质量函数的对数。

Parameters

(张量) –

Return type

张量

property mean: Tensor

返回分布的均值。

property mode: Tensor

返回分布的众数。

perplexity()[source]

返回在 batch_shape 上批量处理的分布的困惑度。

Returns

批次形状的张量。

Return type

张量

rsample(sample_shape=torch.Size([]))[source]

生成一个 sample_shape 形状的可重参数化样本,或者如果分布参数是批量的,则生成一个 sample_shape 形状的批量可重参数化样本。

Return type

张量

sample(sample_shape=torch.Size([]))[source]

生成一个 sample_shape 形状的样本,或者如果分布参数是批量的,则生成一个 sample_shape 形状的批量样本。

Return type

张量

sample_n(n)[source]

生成 n 个样本或如果分布参数是批量的则生成 n 批样本。

Return type

张量

static set_default_validate_args(value)[source]

设置验证是否启用或禁用。

默认行为模仿了Python的assert语句:默认情况下会进行验证,但如果以优化模式运行Python(通过python -O),则会禁用验证。验证可能代价高昂,因此一旦模型正常工作后,您可能希望将其禁用。

Parameters

value (bool) – 是否启用验证。

property stddev: Tensor

返回分布的标准差。

property support: Optional[Any]

返回一个Constraint对象, 表示此分布的支持。

property variance: Tensor

返回分布的方差。

ExponentialFamily

class torch.distributions.exp_family.ExponentialFamily(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)[source]

基础: Distribution

指数族是属于指数族的概率分布的抽象基类,其概率质量/密度函数的形式如下定义。

pF(x;θ)=exp(t(x),θF(θ)+k(x))p_{F}(x; \theta) = \exp(\langle t(x), \theta\rangle - F(\theta) + k(x))

其中 θ\theta 表示自然参数,t(x)t(x) 表示充分统计量, F(θ)F(\theta) 是给定族的对数正规化函数,k(x)k(x) 是承载度量。

注意

此类是Distribution类和属于指数族的分布之间的中介,主要用于检查.entropy()和解析KL散度方法的正确性。我们使用此类通过AD框架和Bregman散度(由Frank Nielsen和Richard Nock提供,参见《指数族的熵与交叉熵》)来计算熵和KL散度。

entropy()[source]

使用对数归一化 Bregman 散度计算熵的方法。

伯努利

class torch.distributions.bernoulli.Bernoulli(probs=None, logits=None, validate_args=None)[source]

Bases: ExponentialFamily

创建一个由 probslogits (但不是两者同时)参数化的伯努利分布。

样本是二进制的(0或1)。它们以概率p取值1,以概率1 - p取值0

Example:

>>> m = Bernoulli(torch.tensor([0.3]))
>>> m.sample()  # 30% chance 1; 70% chance 0
tensor([ 0.])
Parameters
  • probs (数字, 张量) – 采样1的概率

  • logits (数字, 张量) – 采样1的对数几率

arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}
entropy()[source]
enumerate_support(expand=True)[source]
expand(batch_shape, _instance=None)[source]
has_enumerate_support = True
log_prob(value)[source]
property logits
property mean
property mode
property param_shape
property probs
sample(sample_shape=torch.Size([]))[source]
support = Boolean()
property variance

测试版

class torch.distributions.beta.Beta(concentration1, concentration0, validate_args=None)[source]

Bases: ExponentialFamily

Beta分布由concentration1concentration0参数化。

Example:

>>> m = Beta(torch.tensor([0.5]), torch.tensor([0.5]))
>>> m.sample()  # Beta distributed with concentration concentration1 and concentration0
tensor([ 0.1046])
Parameters
  • concentration1 (floatTensor) – 分布的第一个浓度参数 (通常称为 alpha)

  • concentration0 (浮点数张量) – 分布的第二个浓度参数 (通常称为beta)

arg_constraints = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)}
property concentration0
property concentration1
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=())[source]
Return type

张量

support = Interval(lower_bound=0.0, upper_bound=1.0)
property variance

二项式

class torch.distributions.binomial.Binomial(total_count=1, probs=None, logits=None, validate_args=None)[source]

基础: Distribution

创建一个由 total_count 参数化的二项分布,并且是 probslogits (但不是两者都使用)。total_count 必须与 probs/logits 可广播。

Example:

>>> m = Binomial(100, torch.tensor([0 , .2, .8, 1]))
>>> x = m.sample()
tensor([   0.,   22.,   71.,  100.])

>>> m = Binomial(torch.tensor([[5.], [10.]]), torch.tensor([0.5, 0.8]))
>>> x = m.sample()
tensor([[ 4.,  5.],
        [ 7.,  6.]])
Parameters
  • total_count (intTensor) – 伯努利试验的次数

  • probs (Tensor) – 事件概率

  • logits (Tensor) – 事件的对数几率

arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0), 'total_count': IntegerGreaterThan(lower_bound=0)}
entropy()[source]
enumerate_support(expand=True)[source]
expand(batch_shape, _instance=None)[source]
has_enumerate_support = True
log_prob(value)[source]
property logits
property mean
property mode
property param_shape
property probs
sample(sample_shape=torch.Size([]))[source]
property support
property variance

分类的

class torch.distributions.categorical.Categorical(probs=None, logits=None, validate_args=None)[source]

基础: Distribution

创建一个由probslogits(但不是两者同时)参数化的分类分布。

注意

它相当于从torch.multinomial()中采样的分布。

样本是从{0,,K1}\{0, \ldots, K-1\}开始的整数,其中Kprobs.size(-1)

如果probs是一维且长度为K,则每个元素是该索引处采样类别的相对概率。

如果probs是N维的,那么前N-1维被视作相对概率向量的批次。

注意

probs 参数必须是非负、有限且最后一维之和不为零, 并将沿最后一维归一化为和为1。probs 将返回这个归一化的值。 logits 参数将被解释为未归一化的对数概率, 因此可以是任何实数。它也将被归一化,使得最后的结果概率沿最后一维之和为1。logits 将返回这个归一化的值。

另请参阅:torch.multinomial()

Example:

>>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ]))
>>> m.sample()  # equal probability of 0, 1, 2, 3
tensor(3)
Parameters
  • probs (Tensor) – 事件概率

  • logits (Tensor) – 事件日志概率(未归一化)

arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}
entropy()[source]
enumerate_support(expand=True)[source]
expand(batch_shape, _instance=None)[source]
has_enumerate_support = True
log_prob(value)[source]
property logits
property mean
property mode
property param_shape
property probs
sample(sample_shape=torch.Size([]))[source]
property support
property variance

柯西

class torch.distributions.cauchy.Cauchy(loc, scale, validate_args=None)[source]

基础: Distribution

从洛伦兹(Cauchy)分布中采样。两个独立的均值为0的正态分布随机变量的比率服从Cauchy分布。

Example:

>>> m = Cauchy(torch.tensor([0.0]), torch.tensor([1.0]))
>>> m.sample()  # sample from a Cauchy distribution with loc=0 and scale=1
tensor([ 2.3214])
Parameters
arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(value)[source]
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

support = Real()
property variance

中文简体文本:中文简体文本

class torch.distributions.chi2.Chi2(df, validate_args=None)[source]

基础: Gamma

创建一个由形状参数df参数化的卡方分布。 这与Gamma(alpha=0.5*df, beta=0.5)完全等价。

Example:

>>> m = Chi2(torch.tensor([1.0]))
>>> m.sample()  # Chi2 distributed with shape df=1
tensor([ 0.1046])
Parameters

df (浮点数张量) – 分布的形状参数

arg_constraints = {'df': GreaterThan(lower_bound=0.0)}
property df
expand(batch_shape, _instance=None)[source]

ContinuousBernoulli

class torch.distributions.continuous_bernoulli.ContinuousBernoulli(probs=None, logits=None, lims=(0.499, 0.501), validate_args=None)[source]

Bases: ExponentialFamily

创建由 probslogits (但不是两者同时)参数化的连续伯努利分布。

该分布支持在 [0, 1] 范围内,并由 'probs'(在 (0,1) 内)或 'logits'(实数值)参数化。请注意,与伯努利分布不同,'probs' 并不对应于概率,'logits' 也不对应于对数几率,但出于与伯努利分布的相似性,仍使用相同的名称。更多细节请参见 [1]。

Example:

>>> m = ContinuousBernoulli(torch.tensor([0.3]))
>>> m.sample()
tensor([ 0.2538])
Parameters
  • probs (数字, 张量) – (0,1) 范围的参数

  • logits (数字, 张量) – 实数值参数,其sigmoid函数与“probs”匹配

[1] 连续伯努利分布:修复变分自编码器中的一个普遍错误,Loaiza-Ganem G 和 Cunningham JP,NeurIPS 2019。 https://arxiv.org/abs/1907.06845

arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(value)[source]
log_prob(value)[source]
property logits
property mean
property param_shape
property probs
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

sample(sample_shape=torch.Size([]))[source]
property stddev
support = Interval(lower_bound=0.0, upper_bound=1.0)
property variance

狄利克雷

class torch.distributions.dirichlet.Dirichlet(concentration, validate_args=None)[source]

Bases: ExponentialFamily

创建一个由浓度参数concentration定义的Dirichlet分布。

Example:

>>> m = Dirichlet(torch.tensor([0.5, 0.5]))
>>> m.sample()  # Dirichlet distributed with concentration [0.5, 0.5]
tensor([ 0.1046,  0.8954])
Parameters

浓度 (张量) – 分布的浓度参数 (通常称为alpha)

arg_constraints = {'concentration': IndependentConstraint(GreaterThan(lower_bound=0.0), 1)}
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=())[source]
Return type

张量

support = Simplex()
property variance

指数的

class torch.distributions.exponential.Exponential(rate, validate_args=None)[source]

Bases: ExponentialFamily

创建由rate参数化的指数分布。

Example:

>>> m = Exponential(torch.tensor([1.0]))
>>> m.sample()  # Exponential distributed with rate=1
tensor([ 0.1046])
Parameters

rate (floatTensor) – rate = 分布的 scale 的倒数

arg_constraints = {'rate': GreaterThan(lower_bound=0.0)}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(value)[source]
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

property stddev
support = GreaterThanEq(lower_bound=0.0)
property variance

FisherSnedecor

class torch.distributions.fishersnedecor.FisherSnedecor(df1, df2, validate_args=None)[source]

基础: Distribution

创建一个由df1df2参数化的Fisher-Snedecor分布。

Example:

>>> m = FisherSnedecor(torch.tensor([1.0]), torch.tensor([2.0]))
>>> m.sample()  # Fisher-Snedecor-distributed with df1=1 and df2=2
tensor([ 0.2453])
Parameters
arg_constraints = {'df1': GreaterThan(lower_bound=0.0), 'df2': GreaterThan(lower_bound=0.0)}
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

support = GreaterThan(lower_bound=0.0)
property variance

伽玛

class torch.distributions.gamma.Gamma(concentration, rate, validate_args=None)[source]

Bases: ExponentialFamily

创建由形状参数concentrationrate定义的伽马分布。

Example:

>>> m = Gamma(torch.tensor([1.0]), torch.tensor([1.0]))
>>> m.sample()  # Gamma distributed with concentration=1 and rate=1
tensor([ 0.1046])
Parameters
  • 浓度 (浮点数张量) – 分布的形状参数 (通常称为alpha)

  • 比率 (floatTensor) – 比率 = 分布的尺度的倒数 (通常称为 beta)

arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

support = GreaterThanEq(lower_bound=0.0)
property variance

几何图形

class torch.distributions.geometric.Geometric(probs=None, logits=None, validate_args=None)[source]

基础: Distribution

创建一个由probs参数化的几何分布, 其中probs是伯努利试验成功的概率。

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

注意

torch.distributions.geometric.Geometric() (k+1)(k+1)-次试验是第一次成功,因此在{0,1,}\{0, 1, \ldots\}中抽取样本,而torch.Tensor.geometric_() k-次试验是第一次成功,因此在{1,2,}\{1, 2, \ldots\}中抽取样本。

Example:

>>> m = Geometric(torch.tensor([0.3]))
>>> m.sample()  # underlying Bernoulli has 30% chance 1; 70% chance 0
tensor([ 2.])
Parameters
  • probs (数字, 张量) – 采样1的概率。必须在范围 (0, 1] 内

  • logits (数字, 张量) – 采样1的对数几率。

arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}
entropy()[source]
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
property logits
property mean
property mode
property probs
sample(sample_shape=torch.Size([]))[source]
support = IntegerGreaterThan(lower_bound=0)
property variance

耿贝尔分布

class torch.distributions.gumbel.Gumbel(loc, scale, validate_args=None)[source]

Bases: TransformedDistribution

从Gumbel分布中采样。

Examples:

>>> m = Gumbel(torch.tensor([1.0]), torch.tensor([2.0]))
>>> m.sample()  # sample from Gumbel distribution with loc=1, scale=2
tensor([ 1.0124])
Parameters
arg_constraints: Dict[str, Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
entropy()[source]
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
property mean
property mode
property stddev
support = Real()
property variance

HalfCauchy

class torch.distributions.half_cauchy.HalfCauchy(scale, validate_args=None)[source]

Bases: TransformedDistribution

创建一个由scale参数化的半柯西分布,其中:

X ~ Cauchy(0, scale)
Y = |X| ~ HalfCauchy(scale)

Example:

>>> m = HalfCauchy(torch.tensor([1.0]))
>>> m.sample()  # half-cauchy distributed with scale=1
tensor([ 2.3214])
Parameters

scale (floatTensor) – 完整柯西分布的尺度

arg_constraints: Dict[str, Constraint] = {'scale': GreaterThan(lower_bound=0.0)}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(prob)[source]
log_prob(value)[source]
property mean
property mode
property scale
support = GreaterThanEq(lower_bound=0.0)
property variance

HalfNormal

class torch.distributions.half_normal.HalfNormal(scale, validate_args=None)[source]

Bases: TransformedDistribution

创建一个由scale参数化的半正态分布,其中:

X ~ Normal(0, scale)
Y = |X| ~ HalfNormal(scale)

Example:

>>> m = HalfNormal(torch.tensor([1.0]))
>>> m.sample()  # half-normal distributed with scale=1
tensor([ 0.1046])
Parameters

scale (floatTensor) – 正态分布的尺度

arg_constraints: Dict[str, Constraint] = {'scale': GreaterThan(lower_bound=0.0)}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(prob)[source]
log_prob(value)[source]
property mean
property mode
property scale
support = GreaterThanEq(lower_bound=0.0)
property variance

独立的

class torch.distributions.independent.Independent(base_distribution, reinterpreted_batch_ndims, validate_args=None)[source]

基础: Distribution

重新解释分布的一些批处理维度为事件维度。

这主要用于改变结果的形状。 log_prob()。例如,要创建一个与多元正态分布具有相同形状的对角正态分布(因此它们可以互换),你可以这样做:

>>> from torch.distributions.multivariate_normal import MultivariateNormal
>>> from torch.distributions.normal import Normal
>>> loc = torch.zeros(3)
>>> scale = torch.ones(3)
>>> mvn = MultivariateNormal(loc, scale_tril=torch.diag(scale))
>>> [mvn.batch_shape, mvn.event_shape]
[torch.Size([]), torch.Size([3])]
>>> normal = Normal(loc, scale)
>>> [normal.batch_shape, normal.event_shape]
[torch.Size([3]), torch.Size([])]
>>> diagn = Independent(normal, 1)
>>> [diagn.batch_shape, diagn.event_shape]
[torch.Size([]), torch.Size([3])]
Parameters
arg_constraints: Dict[str, Constraint] = {}
entropy()[source]
enumerate_support(expand=True)[source]
expand(batch_shape, _instance=None)[source]
property has_enumerate_support
property has_rsample
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

sample(sample_shape=torch.Size([]))[source]
property support
property variance

InverseGamma

class torch.distributions.inverse_gamma.InverseGamma(concentration, rate, validate_args=None)[source]

Bases: TransformedDistribution

创建由concentrationrate参数化的逆伽玛分布,其中:

X ~ Gamma(concentration, rate)
Y = 1 / X ~ InverseGamma(concentration, rate)

Example:

>>> m = InverseGamma(torch.tensor([2.0]), torch.tensor([3.0]))
>>> m.sample()
tensor([ 1.2953])
Parameters
  • 浓度 (浮点数张量) – 分布的形状参数 (通常称为alpha)

  • 比率 (floatTensor) – 比率 = 分布的尺度的倒数 (通常称为 beta)

arg_constraints: Dict[str, Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}
property concentration
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
property mean
property mode
property rate
support = GreaterThan(lower_bound=0.0)
property variance

库马拉斯瓦米

class torch.distributions.kumaraswamy.Kumaraswamy(concentration1, concentration0, validate_args=None)[source]

Bases: TransformedDistribution

从 Kumaraswamy 分布中抽取样本。

Example:

>>> m = Kumaraswamy(torch.tensor([1.0]), torch.tensor([1.0]))
>>> m.sample()  # sample from a Kumaraswamy distribution with concentration alpha=1 and beta=1
tensor([ 0.1729])
Parameters
  • concentration1 (floatTensor) – 分布的第一个浓度参数 (通常称为 alpha)

  • concentration0 (浮点数张量) – 分布的第二个浓度参数 (通常称为beta)

arg_constraints: Dict[str, Constraint] = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)}
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
property mean
property mode
support = Interval(lower_bound=0.0, upper_bound=1.0)
property variance

LKJCholesky

class torch.distributions.lkj_cholesky.LKJCholesky(dim, concentration=1.0, validate_args=None)[source]

基础: Distribution

LKJ 分布用于相关矩阵的下三角 Cholesky 因子。 该分布由 concentration 个参数 η\eta 控制, 以使从 Cholesky 因子生成的相关矩阵 MM 的概率与 det(M)η1\det(M)^{\eta - 1} 成正比。 因此,当 concentration == 1 时,我们有相关矩阵的 Cholesky 因子的均匀分布:

L ~ LKJCholesky(dim, concentration)
X = L @ L' ~ LKJCorr(dim, concentration)

请注意,此分布对相关矩阵的Cholesky分解进行采样,而不是直接对相关矩阵进行采样,因此与[1]中关于LKJCorr分布的推导略有不同。在采样时,它使用了[1]第3节中的洋葱方法。

Example:

>>> l = LKJCholesky(3, 0.5)
>>> l.sample()  # l @ l.T is a sample of a correlation 3x3 matrix
tensor([[ 1.0000,  0.0000,  0.0000],
        [ 0.3516,  0.9361,  0.0000],
        [-0.1899,  0.4748,  0.8593]])
Parameters
  • 维度 (dim) – 矩阵的维度

  • 集中度 (float张量) – 分布的集中度/形状参数(通常称为eta)

参考文献

[1] Generating random correlation matrices based on vines and extended onion method (2009), Daniel Lewandowski, Dorota Kurowicka, Harry Joe. 多元分析杂志. 100. 10.1016/j.jmva.2009.04.008

arg_constraints = {'concentration': GreaterThan(lower_bound=0.0)}
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
sample(sample_shape=torch.Size([]))[source]
support = CorrCholesky()

拉普拉斯

class torch.distributions.laplace.Laplace(loc, scale, validate_args=None)[source]

基础: Distribution

创建一个由 locscale 参数化的拉普拉斯分布。

Example:

>>> m = Laplace(torch.tensor([0.0]), torch.tensor([1.0]))
>>> m.sample()  # Laplace distributed with loc=0, scale=1
tensor([ 0.1046])
Parameters
arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(value)[source]
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

property stddev
support = Real()
property variance

LogNormal

class torch.distributions.log_normal.LogNormal(loc, scale, validate_args=None)[source]

Bases: TransformedDistribution

创建一个由locscale参数化的对数正态分布,其中:

X ~ Normal(loc, scale)
Y = exp(X) ~ LogNormal(loc, scale)

Example:

>>> m = LogNormal(torch.tensor([0.0]), torch.tensor([1.0]))
>>> m.sample()  # log-normal distributed with mean=0 and stddev=1
tensor([ 0.1046])
Parameters
arg_constraints: Dict[str, Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
property loc
property mean
property mode
property scale
support = GreaterThan(lower_bound=0.0)
property variance

LowRankMultivariateNormal

class torch.distributions.lowrank_multivariate_normal.LowRankMultivariateNormal(loc, cov_factor, cov_diag, validate_args=None)[source]

基础: Distribution

创建一个协方差矩阵具有低秩形式的多元正态分布,该形式由参数cov_factorcov_diag定义:

covariance_matrix = cov_factor @ cov_factor.T + cov_diag

示例

>>> m = LowRankMultivariateNormal(torch.zeros(2), torch.tensor([[1.], [0.]]), torch.ones(2))
>>> m.sample()  # normally distributed with mean=`[0,0]`, cov_factor=`[[1],[0]]`, cov_diag=`[1,1]`
tensor([-0.2102, -0.5429])
Parameters
  • loc (Tensor) – 分布的均值,形状为 batch_shape + event_shape

  • cov_factor (张量) – 协方差矩阵低秩形式的因子部分,形状为 batch_shape + event_shape + (rank,)

  • cov_diag (张量) – 协方差矩阵低秩形式的对角部分,形状为 batch_shape + event_shape

注意

避免计算协方差矩阵的行列式和逆,当 cov_factor.shape[1] << cov_factor.shape[0] 时,这是由于使用了 伍德伯里矩阵恒等式矩阵行列式引理。 借助这些公式,我们只需要计算小尺寸“电容”矩阵的行列式和逆:

capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor
arg_constraints = {'cov_diag': IndependentConstraint(GreaterThan(lower_bound=0.0), 1), 'cov_factor': IndependentConstraint(Real(), 2), 'loc': IndependentConstraint(Real(), 1)}
property covariance_matrix
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
property mean
property mode
property precision_matrix
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

property scale_tril
support = IndependentConstraint(Real(), 1)
property variance

MixtureSameFamily

class torch.distributions.mixture_same_family.MixtureSameFamily(mixture_distribution, component_distribution, validate_args=None)[source]

基础: Distribution

MixtureSameFamily 分布实现了一个(批量)混合分布,其中所有组件都来自同一分布类型的不同的参数化形式。它由一个Categorical“选择分布”(在k组件上)和一个组件分布进行参数化,即一个具有右侧批次形状(等于[k])的Distribution,该形状索引每个(批量)组件。

Examples:

>>> # Construct Gaussian Mixture Model in 1D consisting of 5 equally
>>> # weighted normal distributions
>>> mix = D.Categorical(torch.ones(5,))
>>> comp = D.Normal(torch.randn(5,), torch.rand(5,))
>>> gmm = MixtureSameFamily(mix, comp)

>>> # Construct Gaussian Mixture Model in 2D consisting of 5 equally
>>> # weighted bivariate normal distributions
>>> mix = D.Categorical(torch.ones(5,))
>>> comp = D.Independent(D.Normal(
...          torch.randn(5,2), torch.rand(5,2)), 1)
>>> gmm = MixtureSameFamily(mix, comp)

>>> # Construct a batch of 3 Gaussian Mixture Models in 2D each
>>> # consisting of 5 random weighted bivariate normal distributions
>>> mix = D.Categorical(torch.rand(3,5))
>>> comp = D.Independent(D.Normal(
...         torch.randn(3,5,2), torch.rand(3,5,2)), 1)
>>> gmm = MixtureSameFamily(mix, comp)
Parameters
  • 混合分布torch.distributions.Categorical-like 实例。管理选择组件的概率。 类别数量必须与component_distribution的最右端批次维度匹配。 必须有与component_distribution.batch_shape[:-1]匹配的标量batch_shapebatch_shape

  • 组件分布torch.distributions.Distribution-like 实例。最右端的批次维度索引组件。

arg_constraints: Dict[str, Constraint] = {}
cdf(x)[source]
property component_distribution
expand(batch_shape, _instance=None)[source]
has_rsample = False
log_prob(x)[source]
property mean
property mixture_distribution
sample(sample_shape=torch.Size([]))[source]
property support
property variance

多项式

class torch.distributions.multinomial.Multinomial(total_count=1, probs=None, logits=None, validate_args=None)[source]

基础: Distribution

创建一个由 total_count 参数化的多项式分布,并且 可以是 probs 或者 logits (但不是两者)。probs 的最内层维度索引类别。所有其他维度索引批次。

请注意,如果只调用 log_prob(),则无需指定 total_count(见下面的示例)

注意

probs 参数必须是非负、有限且最后一维之和不为零, 并将沿最后一维归一化为和为1。probs 将返回这个归一化的值。 logits 参数将被解释为未归一化的对数概率, 因此可以是任何实数。它也将被归一化,使得最后的结果概率沿最后一维之和为1。logits 将返回这个归一化的值。

  • sample() 需要为所有参数和样本共享一个单一的total_count

  • log_prob() 允许每个参数和样本有不同的total_count

Example:

>>> m = Multinomial(100, torch.tensor([ 1., 1., 1., 1.]))
>>> x = m.sample()  # equal probability of 0, 1, 2, 3
tensor([ 21.,  24.,  30.,  25.])

>>> Multinomial(probs=torch.tensor([1., 1., 1., 1.])).log_prob(x)
tensor([-4.1338])
Parameters
  • total_count (int) – 次数

  • probs (Tensor) – 事件概率

  • logits (Tensor) – 事件日志概率(未归一化)

arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}
entropy()[source]
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
property logits
property mean
property param_shape
property probs
sample(sample_shape=torch.Size([]))[source]
property support
total_count: int
property variance

MultivariateNormal

class torch.distributions.multivariate_normal.MultivariateNormal(loc, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[source]

基础: Distribution

创建一个由均值向量和协方差矩阵参数化的多元正态(也称为高斯)分布。

多元正态分布可以用以下方式参数化: 可以使用正定协方差矩阵 Σ\mathbf{\Sigma}, 或者使用正定精度矩阵 Σ1\mathbf{\Sigma}^{-1}, 或者使用具有正值对角线元素的下三角矩阵 L\mathbf{L},使得 Σ=LL\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top。这个三角矩阵可以通过例如协方差的乔莱斯基分解获得。

示例

>>> m = MultivariateNormal(torch.zeros(2), torch.eye(2))
>>> m.sample()  # normally distributed with mean=`[0,0]` and covariance_matrix=`I`
tensor([-0.2102, -0.5429])
Parameters
  • loc (张量) – 分布的均值

  • 协方差矩阵 (张量) – 正定的协方差矩阵

  • precision_matrix (Tensor) – 正定精度矩阵

  • scale_tril (张量) – 协方差的下三角因子,对角线元素为正值

注意

只能指定 covariance_matrixprecision_matrixscale_tril 中的一个。

使用 scale_tril 将更高效:所有内部计算都基于 scale_tril。如果传递 covariance_matrixprecision_matrix,则仅用于通过 Cholesky 分解计算相应的下三角矩阵。

arg_constraints = {'covariance_matrix': PositiveDefinite(), 'loc': IndependentConstraint(Real(), 1), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}
property covariance_matrix
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
property mean
property mode
property precision_matrix
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

property scale_tril
support = IndependentConstraint(Real(), 1)
property variance

NegativeBinomial

class torch.distributions.negative_binomial.NegativeBinomial(total_count, probs=None, logits=None, validate_args=None)[source]

基础: Distribution

创建一个负二项式分布,即在达到total_count次失败之前成功独立且相同的伯努利试验次数的分布。每次伯努利试验成功的概率为probs

Parameters
  • total_count (floatTensor) – 非负的伯努利试验次数,用于停止,尽管分布对于实数值计数仍然有效

  • probs (Tensor) – 成功事件的概率,位于半开区间 [0, 1) 内

  • logits (Tensor) – 成功概率的事件对数几率

arg_constraints = {'logits': Real(), 'probs': HalfOpenInterval(lower_bound=0.0, upper_bound=1.0), 'total_count': GreaterThanEq(lower_bound=0)}
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
property logits
property mean
property mode
property param_shape
property probs
sample(sample_shape=torch.Size([]))[source]
support = IntegerGreaterThan(lower_bound=0)
property variance

常规

class torch.distributions.normal.Normal(loc, scale, validate_args=None)[source]

Bases: ExponentialFamily

创建一个由 locscale 参数化的正态分布(也称为高斯分布)。

Example:

>>> m = Normal(torch.tensor([0.0]), torch.tensor([1.0]))
>>> m.sample()  # normally distributed with loc=0 and scale=1
tensor([ 0.1046])
Parameters
  • loc (浮点数张量) – 分布的均值(通常称为 mu)

  • scale (floatTensor) – 分布的标准差 (通常称为 sigma)

arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(value)[source]
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

sample(sample_shape=torch.Size([]))[source]
property stddev
support = Real()
property variance

OneHotCategorical

class torch.distributions.one_hot_categorical.OneHotCategorical(probs=None, logits=None, validate_args=None)[source]

基础: Distribution

创建一个由 probslogits 参数化的 one-hot 分类分布。

样本是一组大小为 probs.size(-1) 的独热编码向量。

注意

probs 参数必须是非负、有限且最后一维之和不为零, 并将沿最后一维归一化为和为1。probs 将返回这个归一化的值。 logits 参数将被解释为未归一化的对数概率, 因此可以是任何实数。它也将被归一化,使得最后的结果概率沿最后一维之和为1。logits 将返回这个归一化的值。

另请参阅:torch.distributions.Categorical() 有关probslogits 的规格说明。

Example:

>>> m = OneHotCategorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ]))
>>> m.sample()  # equal probability of 0, 1, 2, 3
tensor([ 0.,  0.,  0.,  1.])
Parameters
  • probs (Tensor) – 事件概率

  • logits (Tensor) – 事件日志概率(未归一化)

arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}
entropy()[source]
enumerate_support(expand=True)[source]
expand(batch_shape, _instance=None)[source]
has_enumerate_support = True
log_prob(value)[source]
property logits
property mean
property mode
property param_shape
property probs
sample(sample_shape=torch.Size([]))[source]
support = OneHot()
property variance

帕累托图

class torch.distributions.pareto.Pareto(scale, alpha, validate_args=None)[source]

Bases: TransformedDistribution

从Pareto分布类型1中抽取的样本。

Example:

>>> m = Pareto(torch.tensor([1.0]), torch.tensor([1.0]))
>>> m.sample()  # sample from a Pareto distribution with scale=1 and alpha=1
tensor([ 1.5623])
Parameters
arg_constraints: Dict[str, Constraint] = {'alpha': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)}
entropy()[source]
expand(batch_shape, _instance=None)[source]
property mean
property mode
property support
property variance

泊松分布

class torch.distributions.poisson.Poisson(rate, validate_args=None)[source]

Bases: ExponentialFamily

创建一个由rate参数化的泊松分布,该参数为速率参数。

样本是非负整数,其概率质量函数由以下给出

ratekeratek!\mathrm{rate}^k \frac{e^{-\mathrm{rate}}}{k!}

Example:

>>> m = Poisson(torch.tensor([4]))
>>> m.sample()
tensor([ 3.])
Parameters

比率 (Number, 张量) – 比率参数

arg_constraints = {'rate': GreaterThanEq(lower_bound=0.0)}
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
property mean
property mode
sample(sample_shape=torch.Size([]))[source]
support = IntegerGreaterThan(lower_bound=0)
property variance

RelaxedBernoulli

class torch.distributions.relaxed_bernoulli.RelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)[source]

Bases: TransformedDistribution

创建一个RelaxedBernoulli分布,由 temperature 参数化,并且可以是 probslogits (但不是两者)。这是 Bernoulli 分布的放松版本, 因此值在 (0, 1) 范围内,并且具有可重参数化的样本。

Example:

>>> m = RelaxedBernoulli(torch.tensor([2.2]),
...                      torch.tensor([0.1, 0.2, 0.3, 0.99]))
>>> m.sample()
tensor([ 0.2951,  0.3442,  0.8918,  0.9021])
Parameters
  • 温度 (张量) – 退火温度

  • probs (数字, 张量) – 采样1的概率

  • logits (数字, 张量) – 采样1的对数几率

arg_constraints: Dict[str, Constraint] = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}
expand(batch_shape, _instance=None)[source]
has_rsample = True
property logits
property probs
support = Interval(lower_bound=0.0, upper_bound=1.0)
property temperature

LogitRelaxedBernoulli

class torch.distributions.relaxed_bernoulli.LogitRelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)[source]

基础: Distribution

创建由 probslogits (但不是两者)参数化的LogitRelaxedBernoulli分布,这是RelaxedBernoulli分布的logit。

示例为 (0, 1) 区间内的对数几率值。详情请参见 [1]。

Parameters
  • 温度 (张量) – 退火温度

  • probs (数字, 张量) – 采样1的概率

  • logits (数字, 张量) – 采样1的对数几率

[1] Concrete 分布:离散随机变量的连续松弛(Maddison 等,2017)

[2] 使用Gumbel-Softmax的分类重参数化 (Jang等人,2017)

arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
property logits
property param_shape
property probs
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

support = Real()

RelaxedOneHotCategorical

class torch.distributions.relaxed_categorical.RelaxedOneHotCategorical(temperature, probs=None, logits=None, validate_args=None)[source]

Bases: TransformedDistribution

创建一个由temperature参数化的RelaxedOneHotCategorical分布,且可以是probslogits。 这是一个OneHotCategorical分布的放松版本,因此其样本位于单纯形上,并且可以重新参数化。

Example:

>>> m = RelaxedOneHotCategorical(torch.tensor([2.2]),
...                              torch.tensor([0.1, 0.2, 0.3, 0.4]))
>>> m.sample()
tensor([ 0.1294,  0.2324,  0.3859,  0.2523])
Parameters
  • 温度 (张量) – 退火温度

  • probs (Tensor) – 事件概率

  • logits (Tensor) – 每个事件的未归一化对数概率

arg_constraints: Dict[str, Constraint] = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}
expand(batch_shape, _instance=None)[source]
has_rsample = True
property logits
property probs
support = Simplex()
property temperature

StudentT

class torch.distributions.studentT.StudentT(df, loc=0.0, scale=1.0, validate_args=None)[source]

基础: Distribution

创建一个由自由度 df、均值 loc 和尺度 scale 参数化的学生t分布。

Example:

>>> m = StudentT(torch.tensor([2.0]))
>>> m.sample()  # Student's t-distributed with degrees of freedom=2
tensor([ 0.1046])
Parameters
arg_constraints = {'df': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

support = Real()
property variance

TransformedDistribution

class torch.distributions.transformed_distribution.TransformedDistribution(base_distribution, transforms, validate_args=None)[source]

基础: Distribution

Distribution 类的扩展,它对基础分布应用一系列变换。设 f 为所应用变换的复合函数:

X ~ BaseDistribution
Y = f(X) ~ TransformedDistribution(BaseDistribution, f)
log p(Y) = log p(X) + log |det (dX/dY)|

请注意,.event_shapeTransformedDistribution 是其基础分布及其变换的最大形状,因为变换可以引入事件之间的相关性。

使用TransformedDistribution的一个示例为:

# Building a Logistic Distribution
# X ~ Uniform(0, 1)
# f = a + b * logit(X)
# Y ~ f(X) ~ Logistic(a, b)
base_distribution = Uniform(0, 1)
transforms = [SigmoidTransform().inv, AffineTransform(loc=a, scale=b)]
logistic = TransformedDistribution(base_distribution, transforms)

查看更多示例,请查看以下实现: GumbelHalfCauchyHalfNormalLogNormalParetoWeibullRelaxedBernoulliRelaxedOneHotCategorical

arg_constraints: Dict[str, Constraint] = {}
cdf(value)[source]

通过反转变换并计算基础分布的得分来计算累积分布函数。

expand(batch_shape, _instance=None)[source]
property has_rsample
icdf(value)[source]

使用变换(s)计算逆累积分布函数,并计算基础分布的得分。

log_prob(value)[source]

通过反转变换并使用基础分布的得分和雅可比行列式的绝对值的对数来计算样本的得分。

rsample(sample_shape=torch.Size([]))[source]

生成一个形状为 sample_shape 的重参数化样本,或者如果分布参数被批量处理,则生成一批形状为 sample_shape 的重参数化样本。首先从基础分布中采样,然后对列表中的每个变换应用 transform()

Return type

张量

sample(sample_shape=torch.Size([]))[source]

生成一个形状为 sample_shape 的样本,或者如果分布参数被批量处理,则生成一个形状为 sample_shape 的样本批次。首先从基础分布中采样,然后对列表中的每个变换应用 transform()

property support

统一格式

class torch.distributions.uniform.Uniform(low, high, validate_args=None)[source]

基础: Distribution

从半开区间生成均匀分布的随机样本 [low, high)

Example:

>>> m = Uniform(torch.tensor([0.0]), torch.tensor([5.0]))
>>> m.sample()  # uniformly distributed in the range [0.0, 5.0)
tensor([ 2.3418])
Parameters
arg_constraints = {'high': Dependent(), 'low': Dependent()}
cdf(value)[source]
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(value)[source]
log_prob(value)[source]
property mean
property mode
rsample(sample_shape=torch.Size([]))[source]
Return type

张量

property stddev
property support
property variance

VonMises

class torch.distributions.von_mises.VonMises(loc, concentration, validate_args=None)[source]

基础: Distribution

一个圆形米塞斯分布。

该实现使用极坐标。locvalue 参数 可以是任何实数(以方便无约束优化),但会被解释为模 2 pi 的角度。

Example::
>>> m = VonMises(torch.tensor([1.0]), torch.tensor([1.0]))
>>> m.sample()  # von Mises distributed with loc=1 and concentration=1
tensor([1.9777])
Parameters
arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'loc': Real()}
expand(batch_shape)[source]
has_rsample = False
log_prob(value)[source]
property mean

提供的均值是圆形的。

property mode
sample(sample_shape=torch.Size([]))[source]

冯·米塞斯分布的采样算法基于以下论文:D.J. Best 和 N.I. Fisher,《冯·米塞斯分布的有效模拟》。应用统计学(1979):152-157。

采样始终在双精度内部进行,以避免在浓度较小值时 `_rejection_sample()` 函数出现挂起问题,这在单精度下大约从 1e-4 开始发生(参见 #88443 问题)。

support = Real()
property variance

提供的方差是圆形的。

威布尔分布

class torch.distributions.weibull.Weibull(scale, concentration, validate_args=None)[source]

Bases: TransformedDistribution

来自两个参数的威布尔分布样本。

示例

>>> m = Weibull(torch.tensor([1.0]), torch.tensor([1.0]))
>>> m.sample()  # sample from a Weibull distribution with scale=1, concentration=1
tensor([ 0.4784])
Parameters
  • scale (floatTensor) – 分布的缩放参数(lambda)。

  • 浓度 (浮点数张量) – 分布的浓度参数(k/形状)。

arg_constraints: Dict[str, Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)}
entropy()[source]
expand(batch_shape, _instance=None)[source]
property mean
property mode
support = GreaterThan(lower_bound=0.0)
property variance

威沙特

class torch.distributions.wishart.Wishart(df, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[source]

Bases: ExponentialFamily

创建一个由对称正定矩阵参数化的Wishart分布Σ\Sigma, 或者它的Cholesky分解Σ=LL\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top

示例

>>> m = Wishart(torch.Tensor([2]), covariance_matrix=torch.eye(2))
>>> m.sample()  # Wishart distributed with mean=`df * I` and
>>>             # variance(x_ij)=`df` for i != j and variance(x_ij)=`2 * df` for i == j
Parameters
  • df (浮点数张量) – 大于 (方阵维度) - 1 的实数值参数

  • 协方差矩阵 (张量) – 正定的协方差矩阵

  • precision_matrix (Tensor) – 正定精度矩阵

  • scale_tril (张量) – 协方差的下三角因子,对角线元素为正值

注意

只能指定 covariance_matrixprecision_matrixscale_tril 中的一个。 使用 scale_tril 会更高效:所有内部计算都基于 scale_tril。如果传递了 covariance_matrixprecision_matrix,它仅用于通过 Cholesky 分解计算相应的下三角矩阵。 ‘torch.distributions.LKJCholesky’ 是一个受限的 Wishart 分布。[1]

参考文献

[1] 王, Z., 吴, Y. 和 朱, H., 2018. On equivalence of the LKJ distribution and the restricted Wishart distribution. [2] 赛勒, S., 2007. Wishart Distributions and Inverse-Wishart Sampling. [3] 安德森, T. W., 2003. An Introduction to Multivariate Statistical Analysis (3rd ed.). [4] 奥德尔, P. L. & 菲夫森, A. H., 1966. A Numerical Procedure to Generate a SampleCovariance Matrix. JASA, 61(313):199-203. [5] 库, Y.-C. & 布卢姆菲尔德, P., 2010. Generating Random Wishart Matrices with Fractional Degrees of Freedom in OX.

arg_constraints = {'covariance_matrix': PositiveDefinite(), 'df': GreaterThan(lower_bound=0), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}
property covariance_matrix
entropy()[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
property mean
property mode
property precision_matrix
rsample(sample_shape=torch.Size([]), max_try_correction=None)[source]

警告

在某些情况下,基于Bartlett分解的采样算法可能会返回奇异矩阵样本。 默认情况下会进行多次尝试以修正奇异样本,但最终仍可能返回 奇异矩阵样本。奇异样本可能会在.log_prob()中返回-inf值。 在这种情况下,用户应验证样本并修复df的值 或相应地调整.rsample中的max_try_correction参数值。

Return type

张量

property scale_tril
support = PositiveDefinite()
property variance

KL Divergence

torch.distributions.kl.kl_divergence(p, q)[source]

计算两个分布之间的Kullback-Leibler散度 KL(pq)KL(p \| q)

KL(pq)=p(x)logp(x)q(x)dxKL(p \| q) = \int p(x) \log\frac {p(x)} {q(x)} \,dx
Parameters
  • p (分布) – 一个 Distribution 对象。

  • q (分布) – 一个 Distribution 对象。

Returns

形状为batch_shape的KL散度批次。

Return type

张量

Raises

NotImplementedError – 如果分布类型未通过 register_kl() 注册。

KL divergence is currently implemented for the following distribution pairs:
  • BernoulliBernoulli

  • BernoulliPoisson

  • BetaBeta

  • BetaContinuousBernoulli

  • BetaExponential

  • BetaGamma

  • BetaNormal

  • BetaPareto

  • BetaUniform

  • BinomialBinomial

  • CategoricalCategorical

  • CauchyCauchy

  • ContinuousBernoulliContinuousBernoulli

  • ContinuousBernoulliExponential

  • ContinuousBernoulliNormal

  • ContinuousBernoulliPareto

  • ContinuousBernoulliUniform

  • DirichletDirichlet

  • ExponentialBeta

  • ExponentialContinuousBernoulli

  • ExponentialExponential

  • ExponentialGamma

  • ExponentialGumbel

  • ExponentialNormal

  • ExponentialPareto

  • ExponentialUniform

  • ExponentialFamilyExponentialFamily

  • GammaBeta

  • GammaContinuousBernoulli

  • GammaExponential

  • GammaGamma

  • GammaGumbel

  • GammaNormal

  • GammaPareto

  • GammaUniform

  • GeometricGeometric

  • GumbelBeta

  • GumbelContinuousBernoulli

  • GumbelExponential

  • GumbelGamma

  • GumbelGumbel

  • GumbelNormal

  • GumbelPareto

  • GumbelUniform

  • HalfNormalHalfNormal

  • IndependentIndependent

  • LaplaceBeta

  • LaplaceContinuousBernoulli

  • LaplaceExponential

  • LaplaceGamma

  • LaplaceLaplace

  • LaplaceNormal

  • LaplacePareto

  • LaplaceUniform

  • LowRankMultivariateNormalLowRankMultivariateNormal

  • LowRankMultivariateNormalMultivariateNormal

  • MultivariateNormalLowRankMultivariateNormal

  • MultivariateNormalMultivariateNormal

  • NormalBeta

  • NormalContinuousBernoulli

  • NormalExponential

  • NormalGamma

  • NormalGumbel

  • NormalLaplace

  • NormalNormal

  • NormalPareto

  • NormalUniform

  • OneHotCategoricalOneHotCategorical

  • ParetoBeta

  • ParetoContinuousBernoulli

  • ParetoExponential

  • ParetoGamma

  • ParetoNormal

  • ParetoPareto

  • ParetoUniform

  • PoissonBernoulli

  • PoissonBinomial

  • PoissonPoisson

  • TransformedDistributionTransformedDistribution

  • UniformBeta

  • UniformContinuousBernoulli

  • UniformExponential

  • UniformGamma

  • UniformGumbel

  • UniformNormal

  • UniformPareto

  • UniformUniform

torch.distributions.kl.register_kl(type_p, type_q)[source]

装饰器用于注册一个成对函数与 kl_divergence()。 用法:

@register_kl(Normal, Normal)
def kl_normal_normal(p, q):
    # insert implementation here

查找返回最具体的(type,type)匹配,并按子类排序。如果匹配存在歧义,则引发RuntimeWarning异常。例如,解决歧义情况:

@register_kl(BaseP, DerivedQ)
def kl_version1(p, q): ...
@register_kl(DerivedP, BaseQ)
def kl_version2(p, q): ...

你应该注册第三个最具体的实现,例如:

register_kl(DerivedP, DerivedQ)(kl_version1)  # Break the tie.
Parameters
  • type_p (类型) – Distribution 的一个子类。

  • type_q (类型) – Distribution 的一个子类。

Transforms

class torch.distributions.transforms.AbsTransform(cache_size=0)[source]

通过映射y=xy = |x|进行转换。

class torch.distributions.transforms.AffineTransform(loc, scale, event_dim=0, cache_size=0)[source]

通过逐点仿射映射转换 y=loc+scale×xy = \text{loc} + \text{scale} \times x

Parameters
  • loc (张量浮点数) – 位置参数。

  • scale (张量浮点数) – 缩放参数。

  • event_dim (int) – 可选大小为 event_shape。对于单变量随机变量,此值应为零; 对于向量上的分布,此值应为 1;对于矩阵上的分布,此值应为 2,依此类推。

class torch.distributions.transforms.CatTransform(tseq, dim=0, lengths=None, cache_size=0)[source]

逐元素应用变换序列的变换函数tseq 对长度为lengths[dim]的每个子矩阵dim进行操作, 以与torch.cat()兼容的方式。

Example:

x0 = torch.cat([torch.range(1, 10), torch.range(1, 10)], dim=0)
x = torch.cat([x0, x0], dim=0)
t0 = CatTransform([ExpTransform(), identity_transform], dim=0, lengths=[10, 10])
t = CatTransform([t0, t0], dim=0, lengths=[20, 20])
y = t(x)
class torch.distributions.transforms.ComposeTransform(parts, cache_size=0)[source]

将多个变换组合成一个链。所组成的变换负责缓存。

Parameters
  • 部分Transform 的列表) – 要组合的转换列表。

  • cache_size (int) – 缓存大小。如果为零,则不进行缓存。如果为一,将缓存最新的单个值。仅支持0和1。

class torch.distributions.transforms.CorrCholeskyTransform(cache_size=0)[source]

将一个无约束实向量xx(长度为D(D1)/2D*(D-1)/2)转换为D维相关矩阵的Cholesky因子。该Cholesky因子是一个下三角矩阵,具有正对角线和每行单位欧几里得范数。 变换过程如下:

  1. First we convert x into a lower triangular matrix in row order.

  2. For each row XiX_i of the lower triangular part, we apply a signed version of class StickBreakingTransform to transform XiX_i into a unit Euclidean length vector using the following steps: - Scales into the interval (1,1)(-1, 1) domain: ri=tanh(Xi)r_i = \tanh(X_i). - Transforms into an unsigned domain: zi=ri2z_i = r_i^2. - Applies si=StickBreakingTransform(zi)s_i = StickBreakingTransform(z_i). - Transforms back into signed domain: yi=sign(ri)siy_i = sign(r_i) * \sqrt{s_i}.

class torch.distributions.transforms.CumulativeDistributionTransform(distribution, cache_size=0)[source]

通过概率分布的累积分布函数进行转换。

Parameters

分布 (Distribution) – 用于变换的累积分布函数。

Example:

# Construct a Gaussian copula from a multivariate normal.
base_dist = MultivariateNormal(
    loc=torch.zeros(2),
    scale_tril=LKJCholesky(2).sample(),
)
transform = CumulativeDistributionTransform(Normal(0, 1))
copula = TransformedDistribution(base_dist, [transform])
class torch.distributions.transforms.ExpTransform(cache_size=0)[source]

通过映射y=exp(x)y = \exp(x)进行转换。

class torch.distributions.transforms.IndependentTransform(base_transform, reinterpreted_batch_ndims, cache_size=0)[source]

包装另一个转换器,将最右边的额外 reinterpreted_batch_ndims个维度视为依赖。这对正向或反向转换没有影响, 但在 log_abs_det_jacobian() 中对最右边的额外 reinterpreted_batch_ndims个维度进行求和。

Parameters
  • base_transform (Transform) – 一个基础转换。

  • reinterpreted_batch_ndims (int) – 将额外的最右端维度视为依赖项的数量。

class torch.distributions.transforms.LowerCholeskyTransform(cache_size=0)[source]

从无约束矩阵转换为具有非负对角元素的下三角矩阵。

这在用它们的Cholesky分解参数化正定矩阵时非常有用。

class torch.distributions.transforms.PositiveDefiniteTransform(cache_size=0)[source]

从非约束矩阵转换为正定矩阵。

class torch.distributions.transforms.PowerTransform(exponent, cache_size=0)[source]

通过映射y=xexponenty = x^{\text{exponent}}进行转换。

class torch.distributions.transforms.ReshapeTransform(in_shape, out_shape, cache_size=0)[source]

对张量的最右部分进行雅可比变换以重塑形状。

注意,in_shapeout_shape 的元素数量必须相同,就像 torch.Tensor.reshape() 一样。

Parameters
  • 输入形状 (torch.Size) – 输入事件的形状。

  • 输出形状 (torch.Size) – 输出事件的形状。

class torch.distributions.transforms.SigmoidTransform(cache_size=0)[source]

通过映射 y=11+exp(x)y = \frac{1}{1 + \exp(-x)}x=logit(y)x = \text{logit}(y) 进行转换。

class torch.distributions.transforms.SoftplusTransform(cache_size=0)[source]

通过映射Softplus(x)=log(1+exp(x))\text{Softplus}(x) = \log(1 + \exp(x))进行转换。 实现方式在x>20x > 20时退化为线性函数。

class torch.distributions.transforms.TanhTransform(cache_size=0)[source]

通过映射y=tanh(x)y = \tanh(x)进行转换。

它相当于 ` ComposeTransform([AffineTransform(0., 2.), SigmoidTransform(), AffineTransform(-1., 2.)]) ` 然而,这在数值上可能不稳定,因此建议使用TanhTransform代替。

注意,在涉及NaN/Inf值时,应该使用cache_size=1

class torch.distributions.transforms.SoftmaxTransform(cache_size=0)[source]

通过y=exp(x)y = \exp(x)变换将未约束空间转换到单纯形,然后进行归一化。

这不是双射的,不能用于HMC。然而,它主要在坐标上起作用(除了最后的归一化),因此适用于坐标上的优化算法。

class torch.distributions.transforms.StackTransform(tseq, dim=0, cache_size=0)[source]

逐元素应用变换序列的转换函数tseq 在每个子矩阵的dim 上以与torch.stack()兼容的方式进行。

Example:

x = torch.stack([torch.range(1, 10), torch.range(1, 10)], dim=1)
t = StackTransform([ExpTransform(), identity_transform], dim=1)
y = t(x)
class torch.distributions.transforms.StickBreakingTransform(cache_size=0)[source]

通过棒断裂过程将无约束空间转换为额外维度的单纯形。

这种变换是在 Dirichlet 分布的 stick-breaking 构造中通过迭代 sigmoid 变换得到的:第一个 logit 通过 sigmoid 转换为第一个概率和其余部分的概率,然后该过程递归进行。

这是双射的,适用于HMC;然而它混合了坐标,并且不太适合优化。

class torch.distributions.transforms.Transform(cache_size=0)[source]

抽象类,用于可逆转换且可计算对数雅可比行列式的变换。它们主要用在 torch.distributions.TransformedDistribution

缓存对于那些逆变换昂贵或数值不稳定的变换是有用的。请注意,使用记忆化值时必须小心,因为自动微分图可能会被反转。例如,下面的例子在启用或禁用缓存的情况下都能正常工作:

y = t(x)
t.log_abs_det_jacobian(x, y).backward()  # x will receive gradients.

然而,在缓存时由于依赖关系反转,以下情况会出错:

y = t(x)
z = t.inv(y)
grad(z.sum(), [y])  # error because z is x

派生类应实现 _call()_inverse() 中的一个或两个。设置 bijective=True 的派生类还应实现 log_abs_det_jacobian()

Parameters

cache_size (int) – 缓存大小。如果为零,则不进行缓存。如果为一,将缓存最新的单个值。仅支持0和1。

Variables
  • domain (Constraint) – 表示此变换有效输入的约束。

  • 值域 (Constraint) – 表示此变换的有效输出的约束,这些输出是逆变换的输入。

  • 双射 (布尔值) – 此变换是否为双射。一个变换 t 是双射的,当且仅当对于定义域中的每个 x 和陪域中的每个 y,满足 t.inv(t(x)) == xt(t.inv(y)) == y。非双射的变换至少应保持较弱的伪逆性质 t(t.inv(t(x)) == t(x)t.inv(t(t.inv(y))) == t.inv(y)

  • sign (intTensor) – 对于双射的一元变换,这应该根据变换是单调递增还是递减来确定为 +1 或 -1。

property inv

返回此变换的逆 Transform。这应满足 t.inv.inv is t

property sign

返回雅可比行列式的符号(如果适用)。通常,这仅对双射变换有意义。

log_abs_det_jacobian(x, y)[source]

给定输入和输出,计算雅可比行列式的对数 log |dy/dx|

forward_shape(shape)[source]

根据输入形状推断前向计算的形状。默认情况下保持形状不变。

inverse_shape(shape)[source]

根据输出形状推断逆计算的形状。默认情况下保持形状不变。

Constraints

以下约束已实现:

  • constraints.boolean

  • constraints.cat

  • constraints.corr_cholesky

  • constraints.dependent

  • constraints.greater_than(lower_bound)

  • constraints.greater_than_eq(lower_bound)

  • constraints.independent(constraint, reinterpreted_batch_ndims)

  • constraints.integer_interval(lower_bound, upper_bound)

  • constraints.interval(lower_bound, upper_bound)

  • constraints.less_than(upper_bound)

  • constraints.lower_cholesky

  • constraints.lower_triangular

  • constraints.multinomial

  • constraints.nonnegative

  • constraints.nonnegative_integer

  • constraints.one_hot

  • constraints.positive_integer

  • constraints.positive

  • constraints.positive_semidefinite

  • constraints.positive_definite

  • constraints.real_vector

  • constraints.real

  • constraints.simplex

  • constraints.symmetric

  • constraints.stack

  • constraints.square

  • constraints.symmetric

  • constraints.unit_interval

class torch.distributions.constraints.Constraint[source]

抽象基类用于约束。

约束对象表示变量有效的区域,例如变量可以在此区域内进行优化。

Variables
  • is_discrete (bool) – 约束空间是否为离散的。 默认为 False。

  • event_dim (int) – 右侧最右边的维度数量,这些维度共同定义了一个事件。当计算有效性时,check() 方法将移除这些维度。

check(value)[source]

返回一个字节张量 sample_shape + batch_shape,表示 value 中的每个事件是否满足此约束。

torch.distributions.constraints.cat

...的别名 _Cat

torch.distributions.constraints.dependent_property

...的别名 _DependentProperty

torch.distributions.constraints.greater_than

...的别名 _GreaterThan

torch.distributions.constraints.greater_than_eq

...的别名 _GreaterThanEq

torch.distributions.constraints.independent

...的别名 _IndependentConstraint

torch.distributions.constraints.integer_interval

...的别名 _IntegerInterval

torch.distributions.constraints.interval

...的别名 _Interval

torch.distributions.constraints.half_open_interval

...的别名 _HalfOpenInterval

torch.distributions.constraints.is_dependent(constraint)[source]

检查 constraint 是否为 _Dependent 类型的对象。

Parameters

约束 – 一个 Constraint 对象。

Returns

如果 0 可以细化为类型 1,则返回 True,否则返回 False。

Return type

bool

示例

>>> import torch
>>> from torch.distributions import Bernoulli
>>> from torch.distributions.constraints import is_dependent
>>> dist = Bernoulli(probs = torch.tensor([0.6], requires_grad=True))
>>> constraint1 = dist.arg_constraints["probs"]
>>> constraint2 = dist.arg_constraints["logits"]
>>> for constraint in [constraint1, constraint2]:
>>>     if is_dependent(constraint):
>>>         continue
torch.distributions.constraints.less_than

...的别名 _LessThan

torch.distributions.constraints.multinomial

...的别名 _Multinomial

torch.distributions.constraints.stack

...的别名 _Stack

Constraint Registry

PyTorch 提供两个全局 ConstraintRegistry 对象,用于将 Constraint 对象与 Transform 对象关联。这两个对象都 输入约束并返回变换,但在双射性上具有不同的保证。

  1. biject_to(constraint) 用于查找一个双射 Transform,该双射将 constraints.real 映射到给定的 constraint。返回的变换保证具有 .bijective = True 并且应实现 .log_abs_det_jacobian()

  2. transform_to(constraint) 用于查找一个不一定是双射的 Transform,从 constraints.real 到给定的 constraint。返回的转换不一定实现 .log_abs_det_jacobian()

transform_to() 注册表对于在概率分布的约束参数上执行无约束优化非常有用,这些参数由每个分布的 .arg_constraints 字典指示。这些变换通常会过度参数化一个空间以避免旋转;因此,它们更适合于像 Adam 这样的坐标级优化算法:

loc = torch.zeros(100, requires_grad=True)
unconstrained = torch.zeros(100, requires_grad=True)
scale = transform_to(Normal.arg_constraints['scale'])(unconstrained)
loss = -Normal(loc, scale).log_prob(data).sum()

biject_to() 注册表对于哈密顿蒙特卡洛(Hamiltonian Monte Carlo)很有用,其中 从具有约束 .support 的概率分布中采样的样本在无约束空间中传播, 并且算法通常是旋转不变的。:

dist = Exponential(rate)
unconstrained = torch.zeros(100, requires_grad=True)
sample = biject_to(dist.support)(unconstrained)
potential_energy = -dist.log_prob(sample).sum()

注意

一个transform_tobiject_to不同的例子是constraints.simplextransform_to(constraints.simplex)返回一个SoftmaxTransform,它只是对其输入进行指数运算并归一化;这是一个廉价且大部分是逐元素的操作,适用于像SVI这样的算法。相比之下,biject_to(constraints.simplex)返回一个StickBreakingTransform,它将输入双射到一个维度少一的空间;这是一个更昂贵且数值稳定性较差的变换,但对像HMC这样的算法是必需的。

biject_totransform_to 对象可以通过用户定义的约束和转换进行扩展,使用它们的 .register() 方法作为单个约束上的函数:

transform_to.register(my_constraint, my_transform)

或者作为参数化约束的装饰器:

@transform_to.register(MyConstraintClass)
def my_factory(constraint):
    assert isinstance(constraint, MyConstraintClass)
    return MyTransform(constraint.param1, constraint.param2)

您可以创建自己的注册表,通过创建一个新的 ConstraintRegistry 对象。

class torch.distributions.constraint_registry.ConstraintRegistry[source]

注册表,用于将约束条件与变换关联起来。

register(constraint, factory=None)[source]

在此注册表中注册一个 Constraint 子类。用法:

@my_registry.register(MyConstraintClass)
def construct_transform(constraint):
    assert isinstance(constraint, MyConstraint)
    return MyTransform(constraint.arg_constraints)
Parameters
  • 约束 (是 Constraint 的子类) – Constraint 的一个子类,或者 所需类的单例对象。

  • factory (可调用对象) – 一个输入约束对象并返回 一个 Transform 对象的可调用对象。

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源