分布

PyTorch 分布

Pyro 中的大多数分布都是 PyTorch 分布的薄包装。 有关 PyTorch 分布接口的详细信息,请参阅 torch.distributions.distribution.Distribution。 有关 Pyro 和 PyTorch 接口之间的差异,请参阅 TorchDistributionMixin

伯努利

class Bernoulli(probs=None, logits=None, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.bernoulli.Bernoulli

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

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

示例:

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

  • logits (Number, Tensor) – 采样 1 的对数几率

贝塔

class Beta(concentration1, concentration0, validate_args=None)[源代码]

使用TorchDistributionMixin包装torch.distributions.beta.Beta

concentration1concentration0参数化的Beta分布。

示例:

>>> 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 (floatTensor) – 分布的第二个浓度参数 (通常称为 beta)

二项式

class Binomial(total_count=1, probs=None, logits=None, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.binomial.Binomial

创建一个由total_countprobslogits(但不能同时使用两者)参数化的二项分布。total_count必须与probs/logits可广播。

示例:

>>> 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) – 事件对数几率

分类

class Categorical(probs=None, logits=None, validate_args=None)[源代码]

使用TorchDistributionMixin包装torch.distributions.categorical.Categorical

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

注意

它等同于torch.multinomial()从中采样的分布。

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

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

如果 probs 是N维的,前N-1维被视为一批相对概率向量。

注意

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

另请参阅:torch.multinomial()

示例:

>>> 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) – 事件对数概率(未归一化)

柯西

class Cauchy(loc, scale, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.cauchy.Cauchy

来自柯西(洛伦兹)分布的样本。具有均值0的独立正态分布随机变量的比率分布遵循柯西分布。

示例:

>>> 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
  • loc (floatTensor) – 分布的众数或中位数。

  • scale (floatTensor) – 半高处的半宽度。

卡方检验

class Chi2(df, validate_args=None)

使用 TorchDistributionMixin 包装 torch.distributions.chi2.Chi2

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

示例:

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

df (floatTensor) – 分布的形状参数

连续伯努利

class ContinuousBernoulli(probs=None, logits=None, lims=(0.499, 0.501), validate_args=None)

使用TorchDistributionMixin包装torch.distributions.continuous_bernoulli.ContinuousBernoulli

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

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

示例:

>>> m = ContinuousBernoulli(torch.tensor([0.3]))
>>> m.sample()
tensor([ 0.2538])
Parameters
  • probs (Number, Tensor) – (0,1) 值的参数

  • logits (Number, Tensor) – 其sigmoid与‘probs’匹配的实值参数

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

狄利克雷

class Dirichlet(concentration, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.dirichlet.Dirichlet

创建一个由浓度参数 concentration 参数化的狄利克雷分布。

示例:

>>> 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)

指数

class Exponential(rate, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.exponential.Exponential

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

示例:

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

rate (floatTensor) – rate = 1 / 分布的尺度

指数族

class ExponentialFamily(batch_shape: torch.Size = torch.Size([]), event_shape: torch.Size = torch.Size([]), validate_args: Optional[bool] = None)

torch.distributions.exp_family.ExponentialFamilyTorchDistributionMixin进行封装。

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

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

其中 \(\theta\) 表示自然参数,\(t(x)\) 表示充分统计量, \(F(\theta)\) 是给定族的对数归一化函数,\(k(x)\) 是载体 测量。

注意

该类是Distribution类和属于指数族的分布之间的中介,主要用于检查.entropy()和分析KL散度方法的正确性。我们使用该类通过AD框架和Bregman散度来计算熵和KL散度(感谢:Frank Nielsen和Richard Nock,指数族的熵和交叉熵)。

费希尔-斯内德科尔

class FisherSnedecor(df1, df2, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.fishersnedecor.FisherSnedecor

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

示例:

>>> 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
  • df1 (floatTensor) – 自由度参数 1

  • df2 (floatTensor) – 自由度参数 2

伽马

class Gamma(concentration, rate, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.gamma.Gamma

创建一个由形状concentrationrate参数化的Gamma分布。

示例:

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

  • rate (floatTensor) – rate = 1 / 分布的尺度 (通常称为 beta)

几何

class Geometric(probs=None, logits=None, validate_args=None)[源代码]

使用TorchDistributionMixin包装torch.distributions.geometric.Geometric

创建一个由probs参数化的几何分布, 其中probs是伯努利试验成功的概率。 它表示在\(k + 1\)次伯努利试验中, 前\(k\)次试验失败,然后才看到成功的概率。

样本是非负整数 [0, \(\inf\))。

示例:

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

  • logits (Number, Tensor) – 采样 1 的对数几率。

Gumbel

class Gumbel(loc, scale, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.gumbel.Gumbel

来自Gumbel分布的样本。

示例:

>>> 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
  • loc (floatTensor) – 分布的位置参数

  • scale (floatTensor) – 分布的尺度参数

半柯西分布

class HalfCauchy(scale, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.half_cauchy.HalfCauchy

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

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

示例:

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

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

半正态分布

class HalfNormal(scale, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.half_normal.HalfNormal

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

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

示例:

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

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

独立

class Independent(base_distribution, reinterpreted_batch_ndims, validate_args=None)[源代码]

使用TorchDistributionMixin包装torch.distributions.independent.Independent

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

这主要用于改变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

库马拉斯瓦米

class Kumaraswamy(concentration1, concentration0, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.kumaraswamy.Kumaraswamy

来自Kumaraswamy分布的样本。

示例:

>>> 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 (floatTensor) – 分布的第二个浓度参数 (通常称为 beta)

LKJCholesky

class LKJCholesky(dim, concentration=1.0, validate_args=None)

torch.distributions.lkj_cholesky.LKJCholeskyTorchDistributionMixin进行封装。

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

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

请注意,此分布采样的是相关矩阵的Cholesky因子,而不是相关矩阵本身,因此与[1]中关于LKJCorr分布的推导略有不同。在采样时,使用了[1]第3节中的Onion方法。

示例:

>>> 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) – 矩阵的维度

  • 浓度 (floatTensor) – 分布的浓度/形状参数(通常称为 eta)

参考文献

[1] 基于藤蔓和扩展洋葱方法生成随机相关矩阵 (2009), Daniel Lewandowski, Dorota Kurowicka, Harry Joe. 多元分析杂志. 100. 10.1016/j.jmva.2009.04.008

拉普拉斯

class Laplace(loc, scale, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.laplace.Laplace

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

示例:

>>> m = Laplace(torch.tensor([0.0]), torch.tensor([1.0]))
>>> m.sample()  # Laplace distributed with loc=0, scale=1
tensor([ 0.1046])
Parameters
  • loc (floatTensor) – 分布的均值

  • scale (floatTensor) – 分布的尺度

对数正态分布

class LogNormal(loc, scale, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.log_normal.LogNormal

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

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

示例:

>>> 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
  • loc (floatTensor) – 分布的对数均值

  • scale (floatTensor) – 分布对数的标准差

LogisticNormal

class LogisticNormal(loc, scale, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.logistic_normal.LogisticNormal

创建一个由locscale参数化的逻辑正态分布,这些参数定义了基础Normal分布,并通过StickBreakingTransform进行转换,使得:

X ~ LogisticNormal(loc, scale)
Y = log(X / (1 - X.cumsum(-1)))[..., :-1] ~ Normal(loc, scale)
Parameters
  • loc (floatTensor) – 基础分布的均值

  • scale (floatTensor) – 基础分布的标准差

示例:

>>> # logistic-normal distributed with mean=(0, 0, 0) and stddev=(1, 1, 1)
>>> # of the base Normal distribution
>>> m = LogisticNormal(torch.tensor([0.0] * 3), torch.tensor([1.0] * 3))
>>> m.sample()
tensor([ 0.7653,  0.0341,  0.0579,  0.1427])

低秩多元正态分布

class LowRankMultivariateNormal(loc, cov_factor, cov_diag, validate_args=None)[源代码]

使用TorchDistributionMixin包装torch.distributions.lowrank_multivariate_normal.LowRankMultivariateNormal

创建一个具有低秩形式的协方差矩阵的多元正态分布,该矩阵由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 (Tensor) – 协方差矩阵低秩形式的因子部分,形状为 batch_shape + event_shape + (rank,)

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

注意

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

capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor

混合相同家族

class MixtureSameFamily(mixture_distribution, component_distribution, validate_args=None)

torch.distributions.mixture_same_family.MixtureSameFamilyTorchDistributionMixin进行封装。

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

示例:

>>> # 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 Modle 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
  • mixture_distributiontorch.distributions.Categorical 类似的实例。管理选择组件的概率。类别数量必须与 component_distribution 的最右侧批次维度匹配。必须具有标量 batch_shape 或与 component_distribution.batch_shape[:-1] 匹配的 batch_shape

  • component_distributiontorch.distributions.Distribution-like 实例。最右边的批次维度索引组件。

多项式

class Multinomial(total_count=1, probs=None, logits=None, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.multinomial.Multinomial

创建一个由total_countprobslogits(但不能同时使用两者)参数化的多项分布。probs的最内层维度表示类别。所有其他维度表示批次。

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

注意

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

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

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

示例:

>>> 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) – 事件对数概率(未归一化)

多元正态分布

class MultivariateNormal(loc, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.multivariate_normal.MultivariateNormal

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

多元正态分布可以通过正定协方差矩阵 \(\mathbf{\Sigma}\) 或正定精度矩阵 \(\mathbf{\Sigma}^{-1}\) 或具有正对角线的下三角矩阵 \(\mathbf{L}\) 进行参数化,使得 \(\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top\)。这个三角矩阵可以通过例如协方差的Cholesky分解获得。

示例

>>> 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 (Tensor) – 分布的均值

  • covariance_matrix (Tensor) – 正定协方差矩阵

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

  • scale_tril (Tensor) – 协方差的下三角因子,具有正值的对角线

注意

只能指定covariance_matrixprecision_matrixscale_tril中的一个。

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

负二项分布

class NegativeBinomial(total_count, probs=None, logits=None, validate_args=None)

torch.distributions.negative_binomial.NegativeBinomialTorchDistributionMixin进行封装。

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

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

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

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

正常

class Normal(loc, scale, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.normal.Normal

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

示例:

>>> 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 (floatTensor) – 分布的均值(通常称为 mu)

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

OneHotCategorical

class OneHotCategorical(probs=None, logits=None, validate_args=None)[来源]

使用TorchDistributionMixin包装torch.distributions.one_hot_categorical.OneHotCategorical

创建一个由probslogits参数化的一热分类分布。

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

注意

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

另请参阅:torch.distributions.Categorical() 以了解 probslogits 的规范。

示例:

>>> 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) – 事件对数概率(未归一化)

OneHotCategoricalStraightThrough

class OneHotCategoricalStraightThrough(probs=None, logits=None, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.one_hot_categorical.OneHotCategoricalStraightThrough

创建一个可重新参数化的OneHotCategorical分布,基于[1]中的直通梯度估计器。

[1] 通过随机神经元估计或传播梯度以进行条件计算 (Bengio 等人, 2013)

帕累托

class Pareto(scale, alpha, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.pareto.Pareto

来自帕累托类型1分布的样本。

示例:

>>> 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
  • scale (floatTensor) – 分布的尺度参数

  • alpha (floatTensor) – 分布的形状参数

泊松

class Poisson(rate, *, is_sparse=False, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.poisson.Poisson

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

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

\[\mathrm{rate}^k \frac{e^{-\mathrm{rate}}}{k!}\]

示例:

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

rate (Number, Tensor) – 速率参数

松弛伯努利

class RelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.relaxed_bernoulli.RelaxedBernoulli

创建一个RelaxedBernoulli分布,参数化为 temperature,以及probslogits (但不能同时使用两者)。这是Bernoulli分布的松弛版本, 因此值在(0,1)之间,并且具有可重新参数化的样本。

示例:

>>> 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
  • temperature (Tensor) – 松弛温度

  • probs (Number, Tensor) – 采样 1 的概率

  • logits (Number, Tensor) – 采样 1 的对数几率

松弛的OneHot分类

class RelaxedOneHotCategorical(temperature, probs=None, logits=None, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.relaxed_categorical.RelaxedOneHotCategorical

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

示例:

>>> 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
  • temperature (Tensor) – 松弛温度

  • probs (Tensor) – 事件概率

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

学生T分布

class StudentT(df, loc=0.0, scale=1.0, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.studentT.StudentT

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

示例:

>>> m = StudentT(torch.tensor([2.0]))
>>> m.sample()  # Student's t-distributed with degrees of freedom=2
tensor([ 0.1046])
Parameters
  • df (floatTensor) – 自由度

  • loc (floatTensor) – 分布的均值

  • scale (floatTensor) – 分布的尺度

转换分布

class TransformedDistribution(base_distribution, transforms, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.transformed_distribution.TransformedDistribution

Distribution类的扩展,它对基础分布应用一系列Transforms。设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)

更多示例,请查看以下实现: Gumbel, HalfCauchy, HalfNormal, LogNormal, Pareto, Weibull, RelaxedBernoulliRelaxedOneHotCategorical

均匀分布

class Uniform(low, high, validate_args=None)[source]

使用TorchDistributionMixin包装torch.distributions.uniform.Uniform

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

示例:

>>> 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
  • low (floatTensor) – 下限(包含)。

  • high (floatTensor) – 上限(不包括)。

冯·米塞斯

class VonMises(loc, concentration, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.von_mises.VonMises

一个圆形冯·米塞斯分布。

此实现使用极坐标。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

威布尔

class Weibull(scale, concentration, validate_args=None)

使用TorchDistributionMixin包装torch.distributions.weibull.Weibull

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

示例

>>> 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)。

  • 浓度 (floatTensor) – 分布的浓度参数 (k/形状)。

Wishart

class Wishart(df: Union[torch.Tensor, numbers.Number], covariance_matrix: torch.Tensor = None, precision_matrix: torch.Tensor = None, scale_tril: torch.Tensor = None, validate_args=None)

torch.distributions.wishart.WishartTorchDistributionMixin进行封装。

创建一个由对称正定矩阵\(\Sigma\)或其Cholesky分解\(\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top\)参数化的Wishart分布。

示例

>>> m = Wishart(torch.eye(2), torch.Tensor([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
  • covariance_matrix (Tensor) – 正定协方差矩阵

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

  • scale_tril (Tensor) – 协方差的下三角因子,具有正值的对角线

  • df (floatTensor) – 实值参数大于(方阵的维度)- 1

注意

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

参考文献

[1] 王, Z., 吴, Y. 和 楚, H., 2018. 关于LKJ分布和受限Wishart分布的等价性. [2] 索耶, S., 2007. Wishart分布和逆Wishart采样. [3] 安德森, T. W., 2003. 多元统计分析导论(第三版). [4] 奥德尔, P. L. & 费维森, A. H., 1966. 生成样本协方差矩阵的数值程序. JASA, 61(313):199-203. [5] 库, Y.-C. & 布鲁姆菲尔德, P., 2010. 在OX中生成具有分数自由度的随机Wishart矩阵.

Pyro 分布

抽象分布

class Distribution(*args, **kwargs)[source]

基础类:object

参数化概率分布的基类。

Pyro中的分布是具有sample()log_prob()方法的随机函数对象。分布是具有固定参数的随机函数:

d = dist.Bernoulli(param)
x = d()                                # Draws a random sample.
p = d.log_prob(x)                      # Evaluates log probability of x.

实现新分布:

派生类必须实现以下方法:sample(), log_prob().

示例:

看看示例,了解它们如何与推理算法交互。

has_rsample = False
has_enumerate_support = False
__call__(*args, **kwargs)[source]

随机采样一个值(只是.sample(*args, **kwargs)的别名)。

对于张量分布,返回的张量应具有与参数相同的.shape

Returns

一个随机值。

Return type

torch.Tensor

abstract sample(*args, **kwargs)[source]

随机采样一个值。

对于张量分布,返回的张量应具有与参数相同的.shape,除非另有说明。

Parameters

sample_shape (torch.Size) – 从分布中抽取的独立同分布批次的大小。

Returns

一个随机值或一批随机值(如果参数是批处理的)。结果的形状应为self.shape()

Return type

torch.Tensor

abstract log_prob(x, *args, **kwargs)[source]

评估一批样本中每个样本的对数概率密度。

Parameters

x (torch.Tensor) – 单个值或沿轴0批处理的一批值。

Returns

对数概率密度作为一维的 Tensor,其批量大小与值和参数相同。结果的形状应为 self.batch_size

Return type

torch.Tensor

score_parts(x, *args, **kwargs)[source]

计算ELBO的随机梯度估计器的成分。

默认实现对于非重新参数化和完全重新参数化的分布都是正确的。部分重新参数化的分布应重写此方法以计算正确的.score_function.entropy_term部分。

在分布实例上设置 .has_rsample 将决定像 SVI 这样的推理引擎是否使用重参数化采样器或得分函数估计器。

Parameters

x (torch.Tensor) – 单个值或一批值。

Returns

一个包含ELBO估计器部分的ScoreParts对象。

Return type

分数部分

enumerate_support(expand: bool = True) torch.Tensor[source]

返回参数化分布支持的表示,沿着第一维度。这仅由离散分布实现。

请注意,这将返回所有批处理随机变量的支持值,而不是完整的笛卡尔积。

Parameters

expand (bool) – 是否将结果扩展为形状为 (n,) + batch_shape + event_shape 的张量。如果为 false,返回值 具有未扩展的形状 (n,) + (1,)*len(batch_shape) + event_shape 可以广播到完整形状。

Returns

遍历分布的离散支持的迭代器。

Return type

迭代器

conjugate_update(other)[source]

实验性的 创建一个更新的分布,融合来自另一个兼容分布的信息。这仅由少数共轭分布支持。

这应该满足方程:

fg, log_normalizer = f.conjugate_update(g)
assert f.log_prob(x) + g.log_prob(x) == fg.log_prob(x) + log_normalizer

请注意,这相当于在Funsor分布上的funsor.ops.add,但我们返回一个懒求和(updated, log_normalizer),因为PyTorch分布必须被归一化。因此,conjugate_update()应该与dist_to_funsor()tensor_to_funsor()交换。

dist_to_funsor(f) + dist_to_funsor(g)
  == dist_to_funsor(fg) + tensor_to_funsor(log_normalizer)
Parameters

其他 – 一个表示 p(data|latent) 的分布,但 在 latent 上归一化,而不是在 data 上。这里 latent 是来自 self 的候选样本,而 data 是一个不相关类型的 实际观察值。

Returns

一对 (updated,log_normalizer) 其中 updated 是 类型为 type(self) 的更新分布,而 log_normalizer 是一个 Tensor 表示归一化因子。

has_rsample_(value)[source]

强制对单个分布实例进行重新参数化或分离采样。这会就地设置.has_rsample属性。

这对于指示推理算法避免对不连续确定下游控制流的变量使用重新参数化的梯度是有用的。

Parameters

value (bool) – 样本是否将是路径可微的。

Returns

self

Return type

Distribution

property rv

实验性的 切换到随机变量DSL以应用变换到随机变量。支持链式操作或算术运算符重载。

示例用法:

# This should be equivalent to an Exponential distribution.
Uniform(0, 1).rv.log().neg().dist

# These two distributions Y1, Y2 should be the same
X = Uniform(0, 1).rv
Y1 = X.mul(4).pow(0.5).sub(1).abs().neg().dist
Y2 = (-abs((4*X)**(0.5) - 1)).dist
Returns

A :class: ~pyro.contrib.randomvariable.random_variable.RandomVariable 对象包装此分布。

Return type

RandomVariable

TorchDistributionMixin

class TorchDistributionMixin(*args, **kwargs)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

为PyTorch分布提供Pyro兼容性的Mixin。

你应该使用TorchDistribution来创建新的分布类。

这主要用于包装现有的PyTorch分布以便在Pyro中使用。派生类必须首先继承自 torch.distributions.distribution.Distribution,然后继承自 TorchDistributionMixin

__call__(sample_shape: torch.Size = torch.Size([])) torch.Tensor[来源]

随机采样一个值。

这在可能的情况下会重新参数化,调用 rsample() 用于 重新参数化的分布,以及 sample() 用于 非重新参数化的分布。

Parameters

sample_shape (torch.Size) – 从分布中抽取的独立同分布批次的大小。

Returns

一个随机值或一批随机值(如果参数是批处理的)。结果的形状应为self.shape()

Return type

torch.Tensor

property batch_shape: torch.Size

参数批处理的形状。 :rtype: torch.Size

Type

返回

property event_shape: torch.Size

从分布中抽取的单个样本的形状(不进行批处理)。 :rtype: torch.Size

Type

返回

property event_dim: int

单个事件的维度数量。 :rtype: int

Type

返回

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

从该分布中抽取的样本的张量形状。

样本的形状为:

d.shape(sample_shape) == sample_shape + d.batch_shape + d.event_shape
Parameters

sample_shape (torch.Size) – 从分布中抽取的独立同分布批次的大小。

Returns

样本的张量形状。

Return type

torch.Size

classmethod infer_shapes(**arg_shapes)[source]

推断 batch_shapeevent_shape 给定参数的形状到 __init__()

注意

这假设分布形状仅取决于张量输入的形状,而不是这些输入中包含的数据。

Parameters

**arg_shapes – 关键字映射输入参数的名称到 torch.Size 或表示每个张量输入大小的元组。

Returns

一对(batch_shape, event_shape),表示使用给定形状的输入参数创建的分布的形状。

Return type

tuple

expand(batch_shape, _instance=None) pyro.distributions.torch_distribution.ExpandedDistribution[source]

返回一个新的ExpandedDistribution实例,其批次维度扩展为batch_shape

Parameters
  • batch_shape (tuple) – 要扩展到的批次形状。

  • _instance – 未使用的参数,用于与 torch.distributions.Distribution.expand() 兼容

Returns

一个ExpandedDistribution的实例。

Return type

ExpandedDistribution

expand_by(sample_shape)[source]

通过在其batch_shape的左侧添加sample_shape来扩展分布。

要将self.batch_shape的内部维度从1扩展到更大的值,请使用expand()代替。

Parameters

sample_shape (torch.Size) – 从分布中抽取的独立同分布批次的大小。

Returns

此分布的扩展版本。

Return type

ExpandedDistribution

reshape(sample_shape=None, extra_event_dims=None)[source]
to_event(reinterpreted_batch_ndims=None)[来源]

将此分布的n个最右边的维度重新解释为事件维度,并将它们添加到event_shape的左侧。

示例

>>> [d1.batch_shape, d1.event_shape]
[torch.Size([2, 3]), torch.Size([4, 5])]
>>> d2 = d1.to_event(1)
>>> [d2.batch_shape, d2.event_shape]
[torch.Size([2]), torch.Size([3, 4, 5])]
>>> d3 = d1.to_event(2)
>>> [d3.batch_shape, d3.event_shape]
[torch.Size([]), torch.Size([2, 3, 4, 5])]
Parameters

reinterpreted_batch_ndims (int) – 要重新解释为事件维度的批次维度数量。可以为负数以从pyro.distributions.torch.Independent中移除维度。如果为None,则将所有维度转换为事件维度。

Returns

此分布的重新塑造版本。

Return type

pyro.distributions.torch.Independent

independent(reinterpreted_batch_ndims=None)[source]
mask(mask)[source]

通过一个布尔值或布尔值的张量来掩盖分布,该张量可以广播到分布的 batch_shape

Parameters

mask (booltorch.Tensor) – 一个布尔值或布尔值的张量。

Returns

此分布的掩码副本。

Return type

MaskedDistribution

TorchDistribution

class TorchDistribution(batch_shape: torch.Size = torch.Size([]), event_shape: torch.Size = torch.Size([]), validate_args: Optional[bool] = None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

具有Pyro支持的PyTorch兼容分布的基础类。

这应该是几乎所有新的Pyro分布的基础类。

注意

参数和数据类型应为Tensor,除非另有说明,所有方法返回类型为Tensor

张量形状:

TorchDistributions 提供了一个方法 .shape() 用于获取样本的张量形状:

x = d.sample(sample_shape)
assert x.shape == d.shape(sample_shape)

Pyro 遵循与 PyTorch 相同的分布形状语义。它区分了样本张量形状的三种不同角色:

  • 样本形状 对应于从分布中抽取的独立同分布样本的形状。 这是由分布的 sample 方法作为参数接收的。

  • 批量形状对应于从分布的参数形状推断出的非相同(独立)参数化。这对于分布实例是固定的。

  • 事件形状对应于分布的维度,这对于一个分布类是固定的。当我们尝试通过d.log_prob(x)对分布中的样本进行评分时,这些维度会被折叠。

这些形状通过以下方程相关联:

assert d.shape(sample_shape) == sample_shape + d.batch_shape + d.event_shape

分布提供了一个向量化的 log_prob() 方法,该方法 独立评估批次中每个事件的对数概率密度,返回一个形状为 sample_shape + d.batch_shape 的张量:

x = d.sample(sample_shape)
assert x.shape == d.shape(sample_shape)
log_p = d.log_prob(x)
assert log_p.shape == sample_shape + d.batch_shape

实现新分布:

派生类必须实现方法 sample() (或 rsample() 如果 .has_rsample == True)和 log_prob(),并且必须 实现属性 batch_shape, 和 event_shape。 离散类还可以实现 enumerate_support() 方法来改进梯度估计并设置 .has_enumerate_support = True

expand(batch_shape, _instance=None) pyro.distributions.torch_distribution.ExpandedDistribution

返回一个新的ExpandedDistribution实例,其批次维度扩展为batch_shape

Parameters
  • batch_shape (tuple) – 要扩展到的批次形状。

  • _instance – 未使用的参数,用于与 torch.distributions.Distribution.expand() 兼容

Returns

一个ExpandedDistribution的实例。

Return type

ExpandedDistribution

仿射Beta

class AffineBeta(concentration1, concentration0, loc, scale, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

Beta分布通过scale进行缩放,并通过loc进行平移:

X ~ Beta(concentration1, concentration0)
f(X) = loc + scale * X
Y = f(X) ~ AffineBeta(concentration1, concentration0, loc, scale)
Parameters
arg_constraints: Dict[str, torch.distributions.constraints.Constraint] = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
property concentration0
property concentration1
expand(batch_shape, _instance=None)[source]
property high
static infer_shapes(concentration1, concentration0, loc, scale)[source]
property loc
property low
property mean
rsample(sample_shape=torch.Size([]))[source]

Beta分布生成样本并应用AffineTransform。 此外,为了避免梯度中的NaNInf值,对输出进行了钳制。

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

Beta分布生成样本并应用AffineTransform。 此外,为了避免梯度中的NaNInf值,对输出进行了钳制。

property sample_size
property scale
property support
property variance

非对称拉普拉斯

class AsymmetricLaplace(loc, scale, asymmetry, *, validate_args=None)[来源]

基础类:pyro.distributions.distribution.Distribution, Callable

Laplace 分布的非对称版本。

loc 的左侧,其行为类似于 -Exponential(1/(asymmetry*scale));在 loc 的右侧,其行为 类似于 Exponential(asymmetry/scale)。密度是连续的,因此 在 loc 处的左右密度一致。

Parameters
  • loc – 位置参数,即模式。

  • scale – 比例参数 = 左右比例几何平均值。

  • 不对称性 – 左右比例的平方。

arg_constraints = {'asymmetry': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
expand(batch_shape, _instance=None)[source]
has_rsample = True
property left_scale
log_prob(value)[source]
property mean
property right_scale
rsample(sample_shape=torch.Size([]))[来源]
support = Real()
property variance

AVF多元正态分布

class AVFMultivariateNormal(loc, scale_tril, control_var)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

多元正态(高斯)分布,采用受输运方程启发的控制变量(自适应速度场)。

一个向量上的分布,其中所有元素都具有联合高斯密度。

Parameters
  • loc (torch.Tensor) – D维均值向量。

  • scale_tril (torch.Tensor) – 协方差矩阵的Cholesky分解;D x D 矩阵。

  • control_var (torch.Tensor) – 2 x L x D 张量,用于参数化控制变量; L 是一个任意的正整数。这个参数需要被学习(即调整)以实现更低的方差梯度。在典型的使用场景中,这个参数将与定义分布的 locscale_tril 同时进行调整。

示例用法:

control_var = torch.tensor(0.1 * torch.ones(2, 1, D), requires_grad=True)
opt_cv = torch.optim.Adam([control_var], lr=0.1, betas=(0.5, 0.999))

for _ in range(1000):
    d = AVFMultivariateNormal(loc, scale_tril, control_var)
    z = d.rsample()
    cost = torch.pow(z, 2.0).sum()
    cost.backward()
    opt_cv.step()
    opt_cv.zero_grad()
arg_constraints = {'control_var': Real(), 'loc': Real(), 'scale_tril': LowerTriangular()}
rsample(sample_shape=torch.Size([]))[source]

Beta二项分布

class BetaBinomial(concentration1, concentration0, total_count=1, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

由贝塔-二项式对组成的复合分布。成功的概率(对于Binomial分布的probs)是未知的,并且在给定total_count的伯努利试验之前,从Beta分布中随机抽取。

Parameters
approx_log_prob_tol = 0.0
arg_constraints = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0), 'total_count': IntegerGreaterThan(lower_bound=0)}
property concentration0
property concentration1
enumerate_support(expand=True)[来源]
expand(batch_shape, _instance=None)[来源]
has_enumerate_support = True
log_prob(value)[source]
property mean
sample(sample_shape=())[来源]
property support
property variance

合并时间

class CoalescentTimes(leaf_times, rate=1.0, *, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

给定不规则采样的leaf_times和恒定人口规模,排序合并时间的分布。

样本值将是排序的二元合并时间集合。每个样本value的基数将是value.size(-1) = leaf_times.size(-1) - 1,以便系统发育树是完全二叉树。因此,这个分布可以在给定固定(数量的)叶时间的情况下,对多个系统发育树样本进行批处理,例如来自BEAST或MrBayes的系统发育树样本。

参考文献

[1] J.F.C. Kingman (1982)

“关于大种群的系谱” 应用概率杂志

[2] J.F.C. Kingman (1982)

“合并” 随机过程及其应用

Parameters
  • leaf_times (torch.Tensor) – 采样事件的时间向量,即 系统发育中的叶节点。这些可以是任意实数,具有 任意的顺序和重复。

  • rate (torch.Tensor) – 在恒定种群大小模型下的基础合并率(成对合并率)。默认为1。

arg_constraints = {'leaf_times': Real(), 'rate': GreaterThan(lower_bound=0.0)}
log_prob(value)[source]
sample(sample_shape=torch.Size([]))[source]
property support

合并时间与速率

class CoalescentTimesWithRate(leaf_times, rate_grid, *, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

给定不规则采样的leaf_times和在规则时间网格上定义的分段恒定合并率,合并时间的分布。

这假设了一个分段常数的基础合并率,指定在时间区间 (-inf,1], [1,2], …, [T-1,inf) 上,其中 T = rate_grid.size(-1)。叶子可以在任意实数时间被采样,但通常在区间 [0, T] 内采样。

样本值将是有序的二元合并时间集合。每个样本 value 的基数将是 value.size(-1) = leaf_times.size(-1) - 1,因此系统发育树是完全二叉树。因此,这个分布可以在给定固定(数量的)叶子时间的情况下,对多个系统发育树样本进行批处理,例如来自BEAST或MrBayes的系统发育树样本。

此分布实现了log_prob(),但没有实现.sample()

另请参阅 CoalescentRateLikelihood

参考文献

[1] J.F.C. Kingman (1982)

“关于大种群的系谱” 应用概率杂志

[2] J.F.C. Kingman (1982)

“合并” 随机过程及其应用

[3] A. Popinga, T. Vaughan, T. Statler, A.J. Drummond (2014)

“使用贝叶斯合并推断推断流行病学动态: 确定性和随机模型的优点” https://arxiv.org/pdf/1407.1792.pdf

Parameters
  • leaf_times (torch.Tensor) – 采样事件时间的张量,即 系统发育中的叶节点。这些可以是任意实数,具有 任意顺序和重复。

  • rate_grid (torch.Tensor) – 基础合并率的张量(成对合并率)。例如,在一个简单的SIR模型中,这可能是beta S / I。最右边的维度是时间,这个张量表示在时间上是分段恒定的一组(批)速率。

arg_constraints = {'leaf_times': Real(), 'rate_grid': GreaterThan(lower_bound=0.0)}
property duration
expand(batch_shape, _instance=None)[来源]
log_prob(value)[来源]

计算如[3]中公式7-8所示的似然。

这具有时间复杂度 O(T + S N log(N)),其中 T 是 时间步数,N 是叶子节点数,S = sample_shape.numel()value 的样本数。

Parameters

value (torch.Tensor) – 一个合并时间的张量。这些表示沿尾随维度的大小为 leaf_times.size(-1) - 1 的集合,并且应该沿该维度排序。

Returns

似然 p(coal_times | leaf_times, rate_grid)

Return type

torch.Tensor

property support

条件分布

class ConditionalDistribution[source]

基础类:abc.ABC

abstract condition(context)[source]
Return type

torch.distributions.Distribution

条件变换分布

class ConditionalTransformedDistribution(base_dist, transforms)[来源]

基础类:pyro.distributions.conditional.ConditionalDistribution

clear_cache()[source]
condition(context)[source]

Delta

class Delta(v, log_density=0.0, event_dim=0, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

退化离散分布(单点)。

离散分布,在其支持集中的单个元素上分配概率为一。由随机选择参数化的Delta分布不应与基于MCMC的推断一起使用,因为这样做会产生不正确的结果。

Parameters
  • v (torch.Tensor) – 单一支持元素。

  • log_density (torch.Tensor) – 这个Delta的可选密度。这对于保持Delta分布类在可微分变换下的封闭性非常有用。

  • event_dim (int) – 可选的事件维度,默认为零。

arg_constraints = {'log_density': Real(), 'v': Dependent()}
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(x)[source]
property mean
rsample(sample_shape=torch.Size([]))[source]
property support
property variance

DirichletMultinomial

class DirichletMultinomial(concentration, total_count=1, is_sparse=False, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

由狄利克雷-多项式对组成的复合分布。类的概率(对于Multinomial分布的probs)是未知的,并且在给定total_count的某些分类试验之前,从Dirichlet分布中随机抽取。

Parameters
  • 浓度 (floattorch.Tensor) – Dirichlet分布的浓度参数(alpha)。

  • total_count (inttorch.Tensor) – 分类试验的数量。

  • is_sparse (bool) – 在计算log_prob()时,是否假设值大多为零,这可以在数据稀疏时加快计算速度。

arg_constraints = {'concentration': IndependentConstraint(GreaterThan(lower_bound=0.0), 1), 'total_count': IntegerGreaterThan(lower_bound=0)}
property concentration
expand(batch_shape, _instance=None)[source]
static infer_shapes(concentration, total_count=())[source]
log_prob(value)[来源]
property mean
sample(sample_shape=())[source]
property support
property variance

离散隐马尔可夫模型

class DiscreteHMM(initial_logits, transition_logits, observation_dist, validate_args=None, duration=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

具有离散潜在状态和任意观测分布的隐马尔可夫模型。

这使用[1]在时间上进行并行化,实现了O(log(time))的并行复杂度,用于计算log_prob()filter()sample()

此分布的 event_shape 在左侧包括时间:

event_shape = (num_steps,) + observation_dist.event_shape

此分布支持transition_logitsobservation_dist的任何同质/异质时间依赖组合。然而,由于时间包含在此分布的event_shape中,同质+同质情况将具有可广播的event_shape,其中num_steps = 1,允许log_prob()处理任意长度的数据:

# homogeneous + homogeneous case:
event_shape = (1,) + observation_dist.event_shape

参考文献:

[1] Simo Sarkka, Angel F. Garcia-Fernandez (2019)

“贝叶斯滤波器和平滑器的时间并行化” https://arxiv.org/pdf/1905.13002.pdf

Parameters
  • initial_logits (Tensor) – 一个用于初始潜在状态分类分布的logits张量。应具有最右侧大小为state_dim,并且可以广播到batch_shape + (state_dim,)

  • transition_logits (Tensor) – 一个用于潜在状态之间转移条件分布的对数张量。应具有最右侧的形状 (state_dim, state_dim)(旧,新),并且可以广播到 batch_shape + (num_steps, state_dim, state_dim)

  • observation_dist (分布) – 一个基于潜在状态的条件分布,用于观察数据。其.batch_shape的最右侧大小应为state_dim,并且可以广播到batch_shape + (num_steps, state_dim)。其.event_shape可以是任意的。

  • duration (int) – 时间轴的可选大小 event_shape[0]。 当从参数未沿时间轴扩展的齐次HMMs中采样时,这是必需的。

arg_constraints = {'initial_logits': Real(), 'transition_logits': Real()}
expand(batch_shape, _instance=None)[source]
filter(value)[source]

根据一系列观测值计算最终状态的后验概率。

Parameters

value (Tensor) – 一系列观测值。

Returns

在最终时间步的潜在状态的后验分布。result.logits 然后可以用作顺序 Pyro 模型中的 initial_logits 进行预测。

Return type

Categorical

log_prob(value)[来源]
sample(sample_shape=torch.Size([]))[source]
property support

经验分布

class Empirical(samples, log_weights, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

与采样数据相关的经验分布。请注意,log_weights的形状要求是其形状必须与samples的最左侧形状匹配。样本沿着aggregation_dim进行聚合,这是log_weights的最右侧维度。

示例:

>>> emp_dist = Empirical(torch.randn(2, 3, 10), torch.ones(2, 3))
>>> emp_dist.batch_shape
torch.Size([2])
>>> emp_dist.event_shape
torch.Size([10])
>>> single_sample = emp_dist.sample()
>>> single_sample.shape
torch.Size([2, 10])
>>> batch_sample = emp_dist.sample((100,))
>>> batch_sample.shape
torch.Size([100, 2, 10])
>>> emp_dist.log_prob(single_sample).shape
torch.Size([2])
>>> # Vectorized samples cannot be scored by log_prob.
>>> with pyro.validation_enabled():
...     emp_dist.log_prob(batch_sample).shape
Traceback (most recent call last):
...
ValueError: ``value.shape`` must be torch.Size([2, 10])
Parameters
  • 样本 (torch.Tensor) – 来自经验分布的样本。

  • log_weights (torch.Tensor) – 对数权重(可选)对应于样本。

arg_constraints = {}
enumerate_support(expand=True)[source]

参见 pyro.distributions.torch_distribution.TorchDistribution.enumerate_support()

property event_shape

参见 pyro.distributions.torch_distribution.TorchDistribution.event_shape()

has_enumerate_support = True
log_prob(value)[source]

返回在value处评估的概率质量函数的对数。 请注意,目前仅支持对具有空sample_shape的评分值进行评分。

Parameters

value (torch.Tensor) – 要评分的标量或张量值。

property log_weights
property mean

参见 pyro.distributions.torch_distribution.TorchDistribution.mean()

sample(sample_shape=torch.Size([]))[来源]

参见 pyro.distributions.torch_distribution.TorchDistribution.sample()

property sample_size

构成经验分布的样本数量。

Return int

收集的样本数量。

support = Real()
property variance

参见 pyro.distributions.torch_distribution.TorchDistribution.variance()

扩展贝塔二项分布

class ExtendedBetaBinomial(concentration1, concentration0, total_count=1, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

实验性的 BetaBinomial 分布 扩展到具有逻辑支持整个整数,并允许任意整数 total_count。数值支持仍然是整数区间 [0, total_count]

arg_constraints = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0), 'total_count': Integer}
log_prob(value)[source]
support = Integer

扩展二项式

class ExtendedBinomial(total_count=1, probs=None, logits=None, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

实验性的 Binomial 分布扩展到 具有逻辑支持的整个整数,并允许任意整数 total_count。数值支持仍然是整数区间 [0, total_count]

arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0), 'total_count': Integer}
log_prob(value)[source]
support = Integer

折叠分布

class FoldedDistribution(base_dist, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

等同于 TransformedDistribution(base_dist, AbsTransform()), 但额外支持 log_prob()

Parameters

base_dist (Distribution) – 要反射的分布。

expand(batch_shape, _instance=None)[来源]
log_prob(value)[来源]
support = GreaterThan(lower_bound=0.0)

GammaGaussianHMM

class GammaGaussianHMM(scale_dist, initial_dist, transition_matrix, transition_dist, observation_matrix, observation_dist, validate_args=None, duration=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

隐马尔可夫模型与初始状态、隐藏状态和观测状态的联合分布是MultivariateStudentT分布,沿用了参考文献[2]和[3]的思路。此模型适应了[1]以在时间上并行化,实现O(log(时间))的并行复杂度。

这个GammaGaussianHMM类对应于生成模型:

s = Gamma(df/2, df/2).sample()
z = scale(initial_dist, s).sample()
x = []
for t in range(num_events):
    z = z @ transition_matrix + scale(transition_dist, s).sample()
    x.append(z @ observation_matrix + scale(observation_dist, s).sample())

其中 scale(mvn(loc, precision), s) := mvn(loc, s * precision)

此分布的 event_shape 在左侧包括时间:

event_shape = (num_steps,) + observation_dist.event_shape

此分布支持transition_distobservation_dist的任何同质/异质时间依赖组合。然而,由于时间包含在此分布的event_shape中,同质+同质情况将具有可广播的event_shape,其中num_steps = 1,允许log_prob()处理任意长度的数据:

event_shape = (1, obs_dim)  # homogeneous + homogeneous case

参考文献:

[1] Simo Sarkka, Angel F. Garcia-Fernandez (2019)

“贝叶斯滤波器和平滑器的时间并行化” https://arxiv.org/pdf/1905.13002.pdf

[2] F. J. Giron and J. C. Rojano (1994)

“具有椭圆轮廓误差的贝叶斯卡尔曼滤波”

[3] Filip Tronarp, Toni Karvonen, and Simo Sarkka (2019)

“用于噪声尺度估计的学生t滤波器” https://users.aalto.fi/~ssarkka/pub/SPL2019.pdf

Variables
  • hidden_dim (int) – 隐藏状态的维度。

  • obs_dim (int) – 观测状态的维度。

Parameters
  • scale_dist (Gamma) – 混合分布的先验。

  • initial_dist (MultivariateNormal) – 一个具有单位尺度混合的初始状态分布。这应该具有可广播到self.batch_shape的batch_shape。这应该具有事件形状(hidden_dim,)

  • transition_matrix (Tensor) – 隐藏状态的线性变换。这应该具有可广播到self.batch_shape + (num_steps, hidden_dim, hidden_dim)的形状,其中最右边的维度按(old, new)顺序排列。

  • transition_dist (MultivariateNormal) – 一个具有单位尺度混合的过程噪声分布。这应该具有可广播到 self.batch_shape + (num_steps,) 的 batch_shape。这应该具有事件形状 (hidden_dim,)

  • observation_matrix (Tensor) – 从隐藏状态到观测状态的线性变换。这应该具有可广播到 self.batch_shape + (num_steps, hidden_dim, obs_dim) 的形状。

  • observation_dist (MultivariateNormal) – 一个具有单位尺度混合的观测噪声分布。这应该具有可广播到self.batch_shape + (num_steps,)的batch_shape。这应该具有事件形状(obs_dim,)

  • duration (int) – 时间轴的可选大小 event_shape[0]。 当从参数未沿时间轴扩展的齐次HMMs中采样时,这是必需的。

arg_constraints = {}
expand(batch_shape, _instance=None)[source]
filter(value)[source]

计算给定观测序列的乘数和最终状态的后验概率。后验概率是一对Gamma和MultivariateNormal分布(即GammaGaussian实例)。

Parameters

value (Tensor) – 一系列观测值。

Returns

在最终时间步骤上,混合和潜在状态的一对后验分布。

Return type

一个由~pyro.distributions.Gamma和~pyro.distributions.MultivariateNormal组成的元组

log_prob(value)[来源]
support = IndependentConstraint(Real(), 2)

GammaPoisson

class GammaPoisson(concentration, rate, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

由伽马-泊松对组成的复合分布,也称为伽马-泊松混合分布。rate参数对于Poisson分布是未知的,并且是从Gamma分布中随机抽取的。

注意

这可以被视为NegativeBinomial (total_count, probs) 分布的另一种参数化方式,其中 concentration = total_countrate = (1 - probs) / probs

Parameters
arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}
property concentration
expand(batch_shape, _instance=None)[source]
log_prob(value)[来源]
property mean
property rate
sample(sample_shape=())[来源]
support = IntegerGreaterThan(lower_bound=0)
property variance

高斯隐马尔可夫模型

class GaussianHMM(initial_dist, transition_matrix, transition_dist, observation_matrix, observation_dist, validate_args=None, duration=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

使用高斯分布的隐马尔可夫模型用于初始、转移和观测分布。该模型适应了[1]以在时间上并行化,以实现O(log(time))的并行复杂度,然而它的不同之处在于它跟踪了对数归一化器以确保log_prob()是可微的。

这对应于生成模型:

z = initial_distribution.sample()
x = []
for t in range(num_events):
    z = z @ transition_matrix + transition_dist.sample()
    x.append(z @ observation_matrix + observation_dist.sample())

此分布的 event_shape 在左侧包括时间:

event_shape = (num_steps,) + observation_dist.event_shape

此分布支持transition_distobservation_dist的任何同质/异质时间依赖组合。然而,由于时间包含在此分布的event_shape中,同质+同质情况将具有可广播的event_shape,其中num_steps = 1,允许log_prob()处理任意长度的数据:

event_shape = (1, obs_dim)  # homogeneous + homogeneous case

参考文献:

[1] Simo Sarkka, Angel F. Garcia-Fernandez (2019)

“贝叶斯滤波器和平滑器的时间并行化” https://arxiv.org/pdf/1905.13002.pdf

Variables
  • hidden_dim (int) – 隐藏状态的维度。

  • obs_dim (int) – 观测状态的维度。

Parameters
  • initial_dist (MultivariateNormal) – 初始状态的分布。这应该具有与self.batch_shape可广播的batch_shape。这应该具有事件形状(hidden_dim,)

  • transition_matrix (Tensor) – 隐藏状态的线性变换。这应该具有可广播到self.batch_shape + (num_steps, hidden_dim, hidden_dim)的形状,其中最右边的维度按(old, new)顺序排列。

  • transition_dist (MultivariateNormal) – 一个过程噪声分布。它应该具有可广播到self.batch_shape + (num_steps,)的batch_shape。它应该具有(hidden_dim,)的event_shape。

  • observation_matrix (Tensor) – 从隐藏状态到观测状态的线性变换。这应该具有可广播到 self.batch_shape + (num_steps, hidden_dim, obs_dim) 的形状。

  • observation_dist (MultivariateNormalNormal) – 一个观测噪声分布。它应该具有可以广播到 self.batch_shape + (num_steps,) 的 batch_shape。 它应该具有事件形状 (obs_dim,)

  • duration (int) – 时间轴的可选大小 event_shape[0]。 当从参数未沿时间轴扩展的齐次HMMs中采样时,这是必需的。

arg_constraints = {}
conjugate_update(other)[source]

实验性的 创建一个更新的 GaussianHMM,融合来自另一个兼容分布的信息。

这应该满足:

fg, log_normalizer = f.conjugate_update(g)
assert f.log_prob(x) + g.log_prob(x) == fg.log_prob(x) + log_normalizer
Parameters

其他 (多元正态分布正态分布) – 表示 p(data|self.probs) 的分布,但 在 self.probs 上归一化,而不是在 data 上。

Returns

一对 (updated,log_normalizer) 其中 updated 是一个 更新后的 GaussianHMM,而 log_normalizer 是一个 Tensor 表示归一化因子。

expand(batch_shape, _instance=None)[source]
filter(value)[来源]

根据一系列观测值计算最终状态的后验概率。

Parameters

value (Tensor) – 一系列观测值。

Returns

在最终时间步的潜在状态的后验分布。result 然后可以用作顺序 Pyro 模型中的 initial_dist 进行预测。

Return type

MultivariateNormal

has_rsample = True
log_prob(value)[source]
prefix_condition(data)[source]

实验性 给定 self 具有 event_shape == (t+f, d) 和数据 x 的形状为 batch_shape + (t, d),计算一个条件分布 的 event_shape 为 (f, d)。通常 t 是训练 时间步数,f 是预测时间步数,d 是 数据维度。

Parameters

data (Tensor) – 至少为2维的数据。

rsample(sample_shape=torch.Size([]))[source]
rsample_posterior(value, sample_shape=torch.Size([]))[来源]

实验性的 从观察条件下的潜在状态中采样。

support = IndependentConstraint(Real(), 2)

高斯马尔可夫随机场

class GaussianMRF(initial_dist, transition_dist, observation_dist, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

具有高斯因子的时间马尔可夫随机场,用于初始、转移和观测分布。这适应了[1]以在时间上并行化,以实现O(log(时间))的并行复杂度,然而它的不同之处在于它跟踪对数归一化器以确保log_prob()是可微的。

此分布的 event_shape 在左侧包括时间:

event_shape = (num_steps,) + observation_dist.event_shape

此分布支持transition_distobservation_dist的任何同质/异质时间依赖组合。然而,由于时间包含在此分布的event_shape中,同质+同质的情况将具有可广播的event_shape,其中num_steps = 1,允许log_prob()处理任意长度的数据:

event_shape = (1, obs_dim)  # homogeneous + homogeneous case

参考文献:

[1] Simo Sarkka, Angel F. Garcia-Fernandez (2019)

“贝叶斯滤波器和平滑器的时间并行化” https://arxiv.org/pdf/1905.13002.pdf

Variables
  • hidden_dim (int) – 隐藏状态的维度。

  • obs_dim (int) – 观测状态的维度。

Parameters
  • initial_dist (MultivariateNormal) – 初始状态的分布。这应该具有与self.batch_shape可广播的batch_shape。这应该具有事件形状(hidden_dim,)

  • transition_dist (MultivariateNormal) – 一对连续时间步的联合分布因子。这应该具有可广播到 self.batch_shape + (num_steps,) 的 batch_shape。这应该具有事件形状 (hidden_dim + hidden_dim,)(旧+新)。

  • observation_dist (MultivariateNormal) – 一个关于隐藏状态和观察状态的联合分布因子。它应该具有可以广播到 self.batch_shape + (num_steps,) 的 batch_shape。它应该具有事件形状 (hidden_dim + obs_dim,)

arg_constraints = {}
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
property support

高斯尺度混合

class GaussianScaleMixture(coord_scale, component_logits, component_scale)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

具有零均值和对角协方差矩阵的正态分布混合。

也就是说,这个分布是一个具有K个分量的混合分布,其中每个分量分布是一个D维的正态分布,具有零均值和D维的对角协方差矩阵。K个不同的协方差矩阵由参数coord_scalecomponent_scale控制。也就是说,第k个分量的协方差矩阵由以下公式给出:

Sigma_ii = (component_scale_k * coord_scale_i) ** 2 (i = 1, …, D)

其中component_scale_k是一个正的比例因子,coord_scale_i是所有K个组件之间共享的正比例参数。混合权重由一个K维的softmax对数向量component_logits控制。该分布实现了从分布中采样的路径导数。该分布目前不支持批量参数。

有关路径导数的实现细节,请参见参考文献[1]。如果您在研究中使用了路径导数,请考虑引用此参考文献。

[1] 多元分布的路径导数,Martin Jankowiak & Theofanis Karaletsos. arXiv:1806.01856

请注意,此分布支持偶数和奇数维度,但前者应该具有更高的精度,因为它在反向调用中不使用任何erfs。还要注意,此分布不支持D = 1。

Parameters
  • coord_scale (torch.tensor) – D维度的缩放向量

  • component_logits (torch.tensor) – K维的logits向量

  • component_scale (torch.tensor) – K维的缩放乘数向量

arg_constraints = {'component_logits': Real(), 'component_scale': GreaterThan(lower_bound=0.0), 'coord_scale': GreaterThan(lower_bound=0.0)}
has_rsample = True
log_prob(value)[source]
rsample(sample_shape=torch.Size([]))[来源]

分组正态正态

class GroupedNormalNormal(prior_loc, prior_scale, obs_scale, group_idx, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

这种可能性,适用于实值标量观测组,是通过对每个组的潜在均值进行积分得到的。每个潜在均值的先验以及每个数据点的观测可能性都是单变量正态分布。先验均值由prior_locprior_scale控制。正态可能性的观测噪声由obs_scale控制,它允许在观测之间变化。索引张量group_idx将每个观测连接到由prior_locprior_scale指定的一个组。

参见例如参考文献[1]中的公式(55),了解在标量obs_scale的简单情况下的相关表达式。

示例:

>>> num_groups = 3
>>> num_data = 4
>>> prior_loc = torch.randn(num_groups)
>>> prior_scale = torch.rand(num_groups)
>>> obs_scale = torch.rand(num_data)
>>> group_idx = torch.tensor([1, 0, 2, 1]).long()
>>> values = torch.randn(num_data)
>>> gnn = GroupedNormalNormal(prior_loc, prior_scale, obs_scale, group_idx)
>>> assert gnn.log_prob(values).shape == ()

参考文献: [1] “高斯分布的共轭贝叶斯分析,” Kevin P. Murphy.

Parameters
  • prior_loc (torch.Tensor) – 形状为 (num_groups,) 的张量,指定每个组的潜在先验均值。

  • prior_scale (torch.Tensor) – 形状为(num_groups,)的张量,指定每个组的潜在先验尺度。

  • obs_scale (torch.Tensor) – 形状为(num_data,)的张量,指定每个观测值的观测噪声的尺度。

  • group_idx (torch.LongTensor) – 形状为 (num_data,) 的索引张量,将每个观测值链接到在 prior_locprior_scale 中指定的 num_groups 组之一。

arg_constraints = {'obs_scale': GreaterThan(lower_bound=0.0), 'prior_loc': Real(), 'prior_scale': GreaterThan(lower_bound=0.0)}
expand(batch_shape, _instance=None)[source]
get_posterior(value)[source]

获取一个pyro.distributions.Normal分布,该分布编码了由prior_locprior_scale指定的潜在向量在由value指定的观测数据条件下的后验分布。

log_prob(value)[来源]
sample(sample_shape=())[来源]
support = Real()

ImproperUniform

class ImproperUniform(support, batch_shape, event_shape)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

不正确的分布,具有零log_prob()和未定义的 sample()

这对于将模型从生成DAG形式转换为因子图形式以用于HMC非常有用。例如,以下在分布上是相等的:

# Version 1. a generative dag
x = pyro.sample("x", Normal(0, 1))
y = pyro.sample("y", Normal(x, 1))
z = pyro.sample("z", Normal(y, 1))

# Version 2. a factor graph
xyz = pyro.sample("xyz", ImproperUniform(constraints.real, (), (3,)))
x, y, z = xyz.unbind(-1)
pyro.sample("x", Normal(0, 1), obs=x)
pyro.sample("y", Normal(x, 1), obs=y)
pyro.sample("z", Normal(y, 1), obs=z)

请注意,当调用sample()时,此分布会出错。要创建一个从指定分布中采样的类似分布,请考虑使用.mask(False),如下所示:

xyz = dist.Normal(0, 1).expand([3]).to_event(1).mask(False)
Parameters
  • 支持 (Constraint) – 分布的支持。

  • batch_shape (torch.Size) – 批次形状。

  • event_shape (torch.Size) – 事件形状。

arg_constraints = {}
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
sample(sample_shape=torch.Size([]))[source]
property support

独立HMM

class IndependentHMM(base_dist)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

包装类,用于将一批独立的单变量HMMs视为一个单一的多变量分布。这将分布形状转换如下:

.batch_shape

.event_shape

base_dist

形状 + (观测维度,)

(duration, 1)

结果

形状

(duration, obs_dim)

Parameters

base_dist (HiddenMarkovModel) – 一个基础的隐马尔可夫模型实例。

arg_constraints = {}
property duration
expand(batch_shape, _instance=None)[来源]
property has_rsample
log_prob(value)[来源]
rsample(sample_shape=torch.Size([]))[source]
property support

逆伽马分布

class InverseGamma(concentration, rate, validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

创建一个由concentrationrate参数化的逆伽马分布。

X ~ Gamma(浓度, 速率) Y = 1/X ~ InverseGamma(浓度, 速率)

Parameters
arg_constraints: Dict[str, torch.distributions.constraints.Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}
property concentration
expand(batch_shape, _instance=None)[source]
has_rsample = True
property rate
support = GreaterThan(lower_bound=0.0)

线性HMM

class LinearHMM(initial_dist, transition_matrix, transition_dist, observation_matrix, observation_dist, validate_args=None, duration=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

具有线性动态和观测的隐马尔可夫模型,以及初始、转移和观测分布的任意噪声。这些分布中的每一个都可以是例如 MultivariateNormalIndependentNormal, StudentT, 或 Stable。 此外,观测分布可能受到约束,例如 LogNormal

这对应于生成模型:

z = initial_distribution.sample()
x = []
for t in range(num_events):
    z = z @ transition_matrix + transition_dist.sample()
    y = z @ observation_matrix + obs_base_dist.sample()
    x.append(obs_transform(y))

其中 observation_dist 被拆分为 obs_base_dist 和一个可选的 obs_transform(默认为恒等变换)。

这实现了一个重新参数化的 rsample() 方法,但没有实现 log_prob() 方法。派生类可以实现 log_prob()

在没有log_prob()的情况下,可以使用LinearHMMReparam进行重参数化,或者使用无似然算法如EnergyDistance。请注意,虽然稳定过程通常需要一个共同的共享稳定性参数\(\alpha\),但这个分布和上述推理算法允许使用异质的稳定性参数。

此分布的 event_shape 在左侧包括时间:

event_shape = (num_steps,) + observation_dist.event_shape

此分布支持transition_distobservation_dist的任何同质/异质时间依赖组合。然而,至少有一个分布或矩阵必须扩展以包含时间维度。

Variables
  • hidden_dim (int) – 隐藏状态的维度。

  • obs_dim (int) – 观测状态的维度。

Parameters
  • initial_dist – 初始状态的分布。这应该具有与self.batch_shape可广播的batch_shape。这应该具有事件形状(hidden_dim,)

  • transition_matrix (Tensor) – 隐藏状态的线性变换。这应该具有可广播到 self.batch_shape + (num_steps, hidden_dim, hidden_dim) 的形状,其中最右边的维度按 (old, new) 顺序排列。

  • transition_dist – 过程噪声的分布。这应该具有 可广播到 self.batch_shape + (num_steps,) 的 batch_shape。这 应该具有事件形状 (hidden_dim,)

  • observation_matrix (Tensor) – 从隐藏状态到观测状态的线性变换。这应该具有可广播到 self.batch_shape + (num_steps, hidden_dim, obs_dim) 的形状。

  • observation_dist – 一个观测噪声分布。它应该具有与self.batch_shape + (num_steps,)可广播的batch_shape。它应该具有事件形状(obs_dim,)

  • duration (int) – 时间轴的可选大小 event_shape[0]。 当从参数未沿时间轴扩展的齐次HMMs中采样时,这是必需的。

arg_constraints = {}
expand(batch_shape, _instance=None)[来源]
has_rsample = True
log_prob(value)[source]
rsample(sample_shape=torch.Size([]))[source]
property support

LKJ

class LKJ(dim, concentration=1.0, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

LKJ分布用于相关矩阵。该分布由concentration参数\(\eta\)控制,使得相关矩阵\(M\)的概率与\(\det(M)^{\eta - 1}\)成正比。因此,当concentration == 1时,我们得到一个均匀分布的相关矩阵。

concentration > 1 时,分布倾向于具有大行列式的样本。这在我们事先知道基础变量不相关时非常有用。 当 concentration < 1 时,分布倾向于具有小行列式的样本。这在我们事先知道某些基础变量相关时非常有用。

Parameters
  • 维度 (int) – 矩阵的维度

  • 浓度 (ndarray) – 分布的浓度/形状参数(通常称为 eta)

参考文献

[1] 基于藤蔓和扩展洋葱方法生成随机相关矩阵, Daniel Lewandowski, Dorota Kurowicka, Harry Joe

arg_constraints: Dict[str, torch.distributions.constraints.Constraint] = {'concentration': GreaterThan(lower_bound=0.0)}
expand(batch_shape, _instance=None)[source]
property mean
support = CorrMatrix()

LKJCorrCholesky

class LKJCorrCholesky(d, eta, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

对数正态负二项分布

class LogNormalNegativeBinomial(total_count, logits, multiplicative_noise_scale, *, num_quad_points=8, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

负二项分布的三参数泛化[1]。它可以理解为负二项分布的连续混合,其中我们将正态分布的噪声注入到负二项分布的对数几率中:

\[\begin{split}\begin{eqnarray} &\rm{LNNB}(y | \rm{total\_count}=\nu, \rm{logits}=\ell, \rm{multiplicative\_noise\_scale}=sigma) = \\ &\int d\epsilon \mathcal{N}(\epsilon | 0, \sigma) \rm{NB}(y | \rm{total\_count}=\nu, \rm{logits}=\ell + \epsilon) \end{eqnarray}\end{split}\]

其中 \(y \ge 0\) 是一个非负整数。因此,虽然负二项分布可以表述为具有伽马分布速率的泊松分布,但该分布通过对数正态分布的乘法噪声进一步调节速率,从而增加了额外的变异性。

这个分布的均值由以下公式给出

\[\mathbb{E}[y] = \nu e^{\ell} = e^{\ell + \log \nu + \tfrac{1}{2}\sigma^2}\]

以及由以下公式给出的方差

\[\rm{Var}[y] = \mathbb{E}[y] + \left( e^{\sigma^2} (1 + 1/\nu) - 1 \right) \left( \mathbb{E}[y] \right)^2\]

因此,虽然给定的均值和方差共同唯一地描述了一个负二项分布,但对于给定的均值和方差,存在一个一维的对数正态负二项分布族。

请注意,在某些应用中,将logits参数化可能是有用的

\[\ell = \ell^\prime - \log \nu - \tfrac{1}{2}\sigma^2\]

因此,均值由 \(\mathbb{E}[y] = e^{\ell^\prime}\) 给出,并且不依赖于 \(\nu\)\(\sigma\),它们用于确定高阶矩。

参考文献:

[1] “对数正态和伽马混合负二项式回归,” Mingyuan Zhou, Lingbo Li, David Dunson, 和 Lawrence Carin.

Parameters
  • total_count (floattorch.Tensor) – 负伯努利试验的非负数。方差随着total_count的增加而减小。

  • logits (torch.Tensor) – 用于底层负二项分布成功概率的事件对数几率。

  • multiplicative_noise_scale (torch.Tensor) – 控制注入的正态对数噪声的水平。

  • num_quad_points (int) – 用于计算(近似)log_prob的积分点数。 默认为8。

arg_constraints = {'logits': Real(), 'multiplicative_noise_scale': GreaterThan(lower_bound=0.0), 'total_count': GreaterThanEq(lower_bound=0)}
expand(batch_shape, _instance=None)[source]
log_prob(value)[来源]
property mean
sample(sample_shape=torch.Size([]))[来源]
support = IntegerGreaterThan(lower_bound=0)
property variance

逻辑回归

class Logistic(loc, scale, *, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

逻辑分布。

这是一个具有对称渐近指数尾部和凹对数密度的平滑分布。对于标准的 loc=0, scale=1,密度由以下公式给出

\[p(x) = \frac {e^{-x}} {(1 + e^{-x})^2}\]

Laplace密度类似,这种密度具有最重的尾部(渐近地),同时仍然是对数凸的。与Laplace分布不同,这种分布在任何地方都是无限可微的,因此适合构建拉普拉斯近似。

Parameters
  • loc – 位置参数。

  • scale – 比例参数。

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)[来源]
log_prob(value)[source]
property mean
rsample(sample_shape=torch.Size([]))[source]
support = Real()
property variance

掩码分布

class MaskedDistribution(base_dist, mask)[来源]

基础类:pyro.distributions.distribution.Distribution, Callable

通过一个可以广播到分布的batch_shape的布尔张量来掩码一个分布。

在特殊情况下 mask is Falselog_prob()score_parts()kl_divergence() 的计算将被跳过,并返回常量零值。

Parameters

mask (torch.Tensorbool) – 一个布尔值或布尔值的张量。

arg_constraints = {}
conjugate_update(other)[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
rsample(sample_shape=torch.Size([]))[source]
sample(sample_shape=torch.Size([]))[source]
score_parts(value)[来源]
property support
property variance

MaskedMixture

class MaskedMixture(mask, component0, component1, validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

两个分布的掩码确定性混合。

当掩码是从另一个分布中采样时,这可能是有用的,可能在批次之间相关。通常可以通过枚举将掩码边缘化。

示例:

change_point = pyro.sample("change_point",
                           dist.Categorical(torch.ones(len(data) + 1)),
                           infer={'enumerate': 'parallel'})
mask = torch.arange(len(data), dtype=torch.long) >= changepoint
with pyro.plate("data", len(data)):
    pyro.sample("obs", MaskedMixture(mask, dist1, dist2), obs=data)
Parameters
arg_constraints = {}
expand(batch_shape)[source]
property has_rsample
log_prob(value)[source]
property mean
rsample(sample_shape=torch.Size([]))[source]
sample(sample_shape=torch.Size([]))[source]
property support
property variance

混合对角正态分布

class MixtureOfDiagNormals(locs, coord_scale, component_logits)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

具有任意均值和任意对角协方差矩阵的正态分布混合。

也就是说,这个分布是一个具有K个分量的混合分布,其中每个分量分布是一个D维正态分布,具有一个D维均值参数和一个D维对角协方差矩阵。K个不同的分量均值被收集到K x D维参数locs中,K个不同的尺度参数被收集到K x D维参数coord_scale中。混合权重由一个K维的softmax logits向量component_logits控制。这个分布实现了从分布中采样的路径导数。

有关路径导数的实现细节,请参见参考文献[1]。如果您在研究中使用了路径导数,请考虑引用此参考文献。请注意,此分布不支持维度 D = 1。

[1] 多元分布的路径导数,Martin Jankowiak & Theofanis Karaletsos. arXiv:1806.01856

Parameters
arg_constraints = {'component_logits': Real(), 'coord_scale': GreaterThan(lower_bound=0.0), 'locs': Real()}
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]
rsample(sample_shape=torch.Size([]))[source]
support = IndependentConstraint(Real(), 1)

混合对角正态共享协方差

class MixtureOfDiagNormalsSharedCovariance(locs, coord_scale, component_logits)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

具有对角协方差矩阵的正态分布混合。

也就是说,这个分布是一个具有K个分量的混合分布,其中每个分量分布是一个D维正态分布,具有D维均值参数loc和由尺度参数coord_scale指定的D维对角协方差矩阵。K个不同的分量均值被收集到参数locs中,并且尺度参数在所有K个分量之间共享。混合权重由K维的softmax logits向量component_logits控制。这个分布实现了从分布中采样的路径导数。

有关路径导数的实现细节,请参见参考文献[1]。如果您在研究中使用了路径导数,请考虑引用此参考文献。请注意,此分布不支持维度 D = 1。

[1] 多元分布的路径导数,Martin Jankowiak & Theofanis Karaletsos. arXiv:1806.01856

Parameters
arg_constraints = {'component_logits': Real(), 'coord_scale': GreaterThan(lower_bound=0.0), 'locs': Real()}
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[来源]
rsample(sample_shape=torch.Size([]))[source]
support = IndependentConstraint(Real(), 1)

多元学生T分布

class MultivariateStudentT(df, loc, scale_tril, validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

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

Parameters
  • df (Tensor) – 自由度

  • loc (Tensor) – 分布的均值

  • scale_tril (Tensor) – 分布的尺度,它是一个具有正对角元素的下三角矩阵

arg_constraints = {'df': GreaterThan(lower_bound=0.0), 'loc': IndependentConstraint(Real(), 1), 'scale_tril': LowerCholesky()}
property covariance_matrix
expand(batch_shape, _instance=None)[source]
has_rsample = True
static infer_shapes(df, loc, scale_tril)[source]
log_prob(value)[来源]
property mean
property precision_matrix
rsample(sample_shape=torch.Size([]))[source]
property scale_tril
support = IndependentConstraint(Real(), 1)
property variance

NanMaskedNormal

class NanMaskedNormal(loc, scale, validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

围绕Normal的包装器,允许部分观察到的数据,如log_prob()中由NAN元素指定的那样;这些元素的log_prob将为零。这对于具有缺失数据的似然函数非常有用。

示例:

from math import nan
data = torch.tensor([0.5, 0.1, nan, 0.9])
with pyro.plate("data", len(data)):
    pyro.sample("obs", NanMaskedNormal(0, 1), obs=data)
log_prob(value: torch.Tensor) torch.Tensor[source]

NanMaskedMultivariateNormal

class NanMaskedMultivariateNormal(loc, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

围绕MultivariateNormal的包装器,允许部分观察到的数据,这些数据由log_prob()参数中的NAN元素指定。这些事件的log_prob将对NAN元素进行边缘化。这对于处理缺失数据的似然函数非常有用。

示例:

from math import nan
data = torch.tensor([
    [0.1, 0.2, 3.4],
    [0.5, 0.1, nan],
    [0.6, nan, nan],
    [nan, 0.5, nan],
    [nan, nan, nan],
])
with pyro.plate("data", len(data)):
    pyro.sample(
        "obs",
        NanMaskedMultivariateNormal(torch.zeros(3), torch.eye(3)),
        obs=data,
    )
log_prob(value: torch.Tensor) torch.Tensor[source]

OMT多元正态分布

class OMTMultivariateNormal(loc, scale_tril)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

具有OMT梯度的多元正态(高斯)分布,适用于两个参数。请注意,相对于Cholesky因子的梯度计算成本为O(D^3),尽管通常预期结果梯度方差较低。

一个向量上的分布,其中所有元素具有联合高斯密度。

Parameters
arg_constraints = {'loc': Real(), 'scale_tril': LowerTriangular()}
rsample(sample_shape=torch.Size([]))[source]

一对一匹配

class OneOneMatching(logits, *, bp_iters=None, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

N个源到N个目标的随机完美匹配,其中每个源恰好匹配一个目标,每个目标恰好匹配一个源。

样本表示为形状为(N,)的长张量,取值在{0,...,N-1}之间,并满足上述一一对应约束。样本v的对数概率是边对数概率的总和,直到对数配分函数log Z为止:

\[\log p(v) = \sum_s \text{logits}[s, v[s]] - \log Z\]

精确计算是昂贵的。为了实现可处理的近似,通过bp_iters参数设置一定数量的信念传播迭代。log_partition_function()log_prob()方法使用Bethe近似[1,2,3,4]。

参考文献:

[1] Michael Chertkov, Lukas Kroc, Massimo Vergassola (2008)

“信念传播及粒子追踪的超越” https://arxiv.org/pdf/0806.1199.pdf

[2] Bert Huang, Tony Jebara (2009)

“使用信念传播近似永久性” https://arxiv.org/pdf/0908.1769.pdf

[3] Pascal O. Vontobel (2012)

“非负矩阵的贝特永久性” https://arxiv.org/pdf/1107.4196.pdf

[4] M Chertkov, AB Yedidia (2013)

“使用分数信念传播近似永久性” http://www.jmlr.org/papers/volume14/chertkov13a/chertkov13a.pdf

Parameters
  • logits (张量) – 一个形状为 (N, N) 的边缘 logits 张量。

  • bp_iters (int) – 可选的信念传播迭代次数。如果未指定或为None,将使用昂贵的精确算法。

arg_constraints = {'logits': Real()}
enumerate_support(expand=True)[source]
has_enumerate_support = True
property log_partition_function
log_prob(value)[source]
mode()[source]

计算最大概率匹配。

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

一二匹配

class OneTwoMatching(logits, *, bp_iters=None, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

2*N个源到N个目的地的随机匹配,其中每个源恰好匹配一个目的地,每个目的地恰好匹配两个源。

样本表示为形状为(2*N,)的长张量,取值在{0,...,N-1}中,并满足上述的一二约束。样本v的对数概率是边逻辑的总和,直到对数配分函数log Z

\[\log p(v) = \sum_s \text{logits}[s, v[s]] - \log Z\]

精确计算是昂贵的。为了实现可处理的近似,通过bp_iters参数设置一些信念传播迭代次数。log_partition_function()log_prob()方法使用Bethe近似[1,2,3,4]。

参考文献:

[1] Michael Chertkov, Lukas Kroc, Massimo Vergassola (2008)

“信念传播及粒子追踪的超越” https://arxiv.org/pdf/0806.1199.pdf

[2] Bert Huang, Tony Jebara (2009)

“使用信念传播近似永久性” https://arxiv.org/pdf/0908.1769.pdf

[3] Pascal O. Vontobel (2012)

“非负矩阵的贝特永久性” https://arxiv.org/pdf/1107.4196.pdf

[4] M Chertkov, AB Yedidia (2013)

“使用分数信念传播近似永久性” http://www.jmlr.org/papers/volume14/chertkov13a/chertkov13a.pdf

Parameters
  • logits (Tensor) – 一个形状为 (2 * N, N) 的边缘 logits 张量。

  • bp_iters (int) – 可选的信念传播迭代次数。如果未指定或为None,将使用昂贵的精确算法。

arg_constraints = {'logits': Real()}
enumerate_support(expand=True)[source]
has_enumerate_support = True
property log_partition_function
log_prob(value)[source]
mode()[source]

计算最大概率匹配。

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

有序逻辑回归

class OrderedLogistic(predictor, cutpoints, validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

分类变量分布的替代参数化。

与通常以个体类别的概率质量p来参数化分类变量的方法不同,这里提供了一种在指定有序分类模型时非常有用的替代方法。该方法接受一个cutpoints向量,这是一个有序的实数向量,表示个体类别的基线累积对数几率,以及一个模型向量predictor,该向量分别修改每个样本的基线。

这些累积对数几率随后被转换为离散的累积概率分布,最终通过差分返回指定分类分布的概率质量矩阵 p

Parameters
  • predictor (Tensor) – 一个任意形状的预测变量张量。从该分布中抽取的非批量样本的输出形状将与 predictor 的形状相同。

  • cutpoints (Tensor) – 用于确定predictor中每个条目属于给定类别的累积概率的切点张量。前cutpoints.ndim-1维度必须可广播到predictor,且-1维度是单调递增的。

arg_constraints = {'cutpoints': OrderedVector(), 'predictor': Real()}
expand(batch_shape, _instance=None)[source]

投影正态

class ProjectedNormal(concentration, *, validate_args=None)[来源]

基础类:pyro.distributions.distribution.Distribution, Callable

任意维度的投影各向同性正态分布。

这种方向性数据的分布在性质上类似于von Mises和von Mises-Fisher分布,但允许通过重新参数化的梯度进行可处理的变分推断。

要在自动引导中使用此分布,请在模型中使用poutine.reparamProjectedNormalReparam 重新参数化器,例如:

@poutine.reparam(config={"direction": ProjectedNormalReparam()})
def model():
    direction = pyro.sample("direction",
                            ProjectedNormal(torch.zeros(3)))
    ...

或者简单地包装在 MinimalReparamAutoReparam 中,例如:

@MinimalReparam()
def model():
    ...

注意

这仅为维度{2,3}实现了log_prob()

[1] D. Hernandez-Stumpfhauser, F.J. Breidt, M.J. van der Woerd (2017)

“任意维度的通用投影正态分布:建模与贝叶斯推断” https://projecteuclid.org/euclid.ba/1453211962

Parameters

浓度 (torch.Tensor) – 一个结合了位置和浓度的向量。这个向量的方向表示位置,其大小表示浓度。

arg_constraints = {'concentration': IndependentConstraint(Real(), 1)}
expand(batch_shape, _instance=None)[source]
has_rsample = True
static infer_shapes(concentration)[source]
log_prob(value)[source]
property mean

请注意,这是在子流形中作为质心的意义上,最小化预期平方测地线距离的平均值。

property mode
rsample(sample_shape=torch.Size([]))[source]
support = Sphere

RelaxedBernoulliStraightThrough

class RelaxedBernoulliStraightThrough(temperature, probs=None, logits=None, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

一个实现 RelaxedBernoulli 的直通梯度估计器。

此分布具有以下属性:

  • rsample()方法返回的样本是离散/量化的。

  • log_prob() 方法返回使用 GumbelSoftmax 分布的松弛/未量化样本的对数概率。

  • 在反向传播过程中,样本相对于分布参数的梯度使用松弛/未量化的样本。

参考文献:

[1] The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables,

克里斯·J·麦迪逊,安德里·姆尼赫,伊·怀·特

[2] Categorical Reparameterization with Gumbel-Softmax,

埃里克·张,石翔·顾,本·普尔

log_prob(value)[source]

参见 pyro.distributions.torch.RelaxedBernoulli.log_prob()

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

参见 pyro.distributions.torch.RelaxedBernoulli.rsample()

RelaxedOneHotCategoricalStraightThrough

class RelaxedOneHotCategoricalStraightThrough(temperature, probs=None, logits=None, validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

一个实现 RelaxedOneHotCategorical 的直通梯度估计器。

此分布具有以下属性:

  • rsample()方法返回的样本是离散/量化的。

  • log_prob() 方法返回使用GumbelSoftmax分布的松弛/未量化样本的对数概率。

  • 在反向传播过程中,样本相对于分布参数的梯度使用松弛/未量化的样本。

参考文献:

[1] The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables,

克里斯·J·麦迪逊,安德里·姆尼赫,伊·怀·特

[2] Categorical Reparameterization with Gumbel-Softmax,

埃里克·张,石翔·顾,本·普尔

log_prob(value)[来源]

参见 pyro.distributions.torch.RelaxedOneHotCategorical.log_prob()

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

参见 pyro.distributions.torch.RelaxedOneHotCategorical.rsample()

拒绝器

class Rejector(propose, log_prob_accept, log_scale, *, batch_shape=None, event_shape=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

给定接受率函数的拒绝采样分布。

Parameters
  • 提议 (Distribution) – 一个通过 propose() 采样批量提议的提议分布。rsample() 支持 sample_shape 参数,仅当 propose() 支持 sample_shape 参数时。

  • log_prob_accept (callable) – 一个可调用对象,输入一批提案并返回一批对数接受概率。

  • log_scale – 接受的总对数概率。

arg_constraints = {}
has_rsample = True
log_prob(x)[来源]
rsample(sample_shape=torch.Size([]))[source]
score_parts(x)[source]

正弦双变量冯·米塞斯

class SineBivariateVonMises(phi_loc, psi_loc, phi_concentration, psi_concentration, correlation=None, weighted_correlation=None, validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

在2-环面(S^1 ⨂ S^1)上两个依赖角度的单峰分布由以下给出

\[C^{-1}\exp(\kappa_1\cos(x-\mu_1) + \kappa_2\cos(x_2 -\mu_2) + \rho\sin(x_1 - \mu_1)\sin(x_2 - \mu_2))\]

\[C = (2\pi)^2 \sum_{i=0} {2i \choose i} \left(\frac{\rho^2}{4\kappa_1\kappa_2}\right)^i I_i(\kappa_1)I_i(\kappa_2),\]

其中 I_i(cdot) 是第一类修正贝塞尔函数,mu 是分布的位置,kappa 是集中度,rho 给出了角度 x_1 和 x_2 之间的相关性。

这个分布是双变量冯·米塞斯分布的一个子模型,在方向统计中称为正弦分布 [2]。

这种分布有助于建模耦合角度,例如肽链中的扭转角度。 要推断参数,请使用NUTSHMC,并使用避免分布变为双峰的参数化的先验;请参阅下面的注释。

注意

样本效率下降

\[\frac{\rho}{\kappa_1\kappa_2} \rightarrow 1\]

因为分布变得越来越双峰。为了避免双峰性,使用weighted_correlation参数,使其偏离一(例如,Beta(1,3))。weighted_correlation应在[0,1]范围内。

注意

correlation 和 weighted_correlation 参数是互斥的。

注意

SVI的上下文中,此分布可用作似然函数,但不适用于潜在变量。

** References: **
  1. 两个依赖圆形变量的概率模型 Singh, H., Hnizdo, V., 和 Demchuck, E. (2002)

  2. 蛋白质生物信息学与用于角度数据的双变量冯·米塞斯分布混合, Mardia, K. V, Taylor, T. C., 和 Subramaniam, G. (2007)

Parameters
  • phi_loc (torch.Tensor) – 第一个角度的位置

  • psi_loc (torch.Tensor) – 第二个角度的位置

  • phi_concentration (torch.Tensor) – 第一个角度的浓度

  • psi_concentration (torch.Tensor) – 第二个角度的浓度

  • correlation (torch.Tensor) – 两个角度之间的相关性

  • weighted_correlation (torch.Tensor) – 将相关性设置为 weighted_corr * sqrt(phi_conc*psi_conc) 以避免双峰性(参见注释)。weighted_correlation 应在 [0,1] 范围内。

arg_constraints = {'correlation': Real(), 'phi_concentration': GreaterThan(lower_bound=0.0), 'phi_loc': Real(), 'psi_concentration': GreaterThan(lower_bound=0.0), 'psi_loc': Real()}
expand(batch_shape, _instance=None)[source]
classmethod infer_shapes(**arg_shapes)[source]
log_prob(value)[source]
max_sample_iter = 1000
property mean
property norm_const
sample(sample_shape=torch.Size([]))[source]
** References: **
  1. 一种新的统一方法用于模拟广泛类别的方向分布 John T. Kent, Asaad M. Ganeiber & Kanti V. Mardia (2018)

support = IndependentConstraint(Real(), 1)

正弦偏斜

class SineSkewed(base_dist: pyro.distributions.torch_distribution.TorchDistribution, skewness, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

正弦偏斜 [1] 是一种用于生成在环面分布上打破点对称性的分布的过程。新分布被称为正弦偏斜 X 分布,其中 X 是(对称)基础分布的名称。

环面分布是在圆的乘积上支持的分布(即,⨂^d S^1,其中 S^1=[-pi,pi))。因此,0-环面是一个点,1-环面是一个圆,而2-环面通常与甜甜圈的形状相关联。

正弦偏斜X分布通过X事件的每个维度的权重参数进行参数化。例如,对于一个圆(1-环面)上的von Mises分布,正弦偏斜von Mises分布有一个偏斜参数。偏斜参数可以使用HMCNUTS进行推断。例如,以下代码将为2-环面生成一个均匀的偏斜先验:

def model(obs):
    # Sine priors
    phi_loc = pyro.sample('phi_loc', VonMises(pi, 2.))
    psi_loc = pyro.sample('psi_loc', VonMises(-pi / 2, 2.))
    phi_conc = pyro.sample('phi_conc', Beta(halpha_phi, beta_prec_phi - halpha_phi))
    psi_conc = pyro.sample('psi_conc', Beta(halpha_psi, beta_prec_psi - halpha_psi))
    corr_scale = pyro.sample('corr_scale', Beta(2., 5.))

    # SS prior
    skew_phi = pyro.sample('skew_phi', Uniform(-1., 1.))
    psi_bound = 1 - skew_phi.abs()
    skew_psi = pyro.sample('skew_psi', Uniform(-1., 1.))
    skewness = torch.stack((skew_phi, psi_bound * skew_psi), dim=-1)
    assert skewness.shape == (num_mix_comp, 2)

    with pyro.plate('obs_plate'):
        sine = SineBivariateVonMises(phi_loc=phi_loc, psi_loc=psi_loc,
                                     phi_concentration=1000 * phi_conc,
                                     psi_concentration=1000 * psi_conc,
                                     weighted_correlation=corr_scale)
        return pyro.sample('phi_psi', SineSkewed(sine, skewness), obs=obs)

为了确保偏斜不会改变(双变量正弦冯·米塞斯)基础分布的归一化常数,偏斜参数受到约束。该约束要求偏斜的绝对值之和小于或等于一。 因此,对于上述代码片段,必须满足以下条件:

skew_phi.abs()+skew_psi.abs() <= 1

我们在先验中通过计算 psi_bound 来处理这个问题,并使用它来缩放 skew_psi。 我们使用 psi_bound 作为:

skew_psi = pyro.sample('skew_psi', Uniform(-psi_bound, psi_bound))

因为它将使对均匀分布的支持变得动态。

SVI的上下文中,这个分布可以自由地用作似然函数,但作为潜在变量使用时,对于2维及更高维的环面会导致推理速度变慢。这是因为base_dist无法被重新参数化。

注意

基础分布中的事件必须在d-环面上,因此事件形状必须为(d,)。

注意

对于偏度参数,必须满足一个事件的权重绝对值之和小于或等于一。参见[1]中的公式2.1。

** References: **
  1. 正弦偏斜环形分布及其在蛋白质生物信息学中的应用 Ameijeiras-Alonso, J., Ley, C. (2019)

Parameters
arg_constraints = {'skewness': IndependentConstraint(Interval(lower_bound=-1.0, upper_bound=1.0), 1)}
expand(batch_shape, _instance=None)[source]
log_prob(value)[来源]
sample(sample_shape=torch.Size([]))[来源]
support = IndependentConstraint(Real(), 1)

偏斜逻辑分布

class SkewLogistic(loc, scale, asymmetry=1.0, *, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

Logistic分布的偏斜推广([1]中的类型I)。

这是一个具有渐近指数尾部和凹对数密度的平滑分布。对于标准的 loc=0, scale=1, asymmetry=α,密度由以下公式给出:

\[p(x;\alpha) = \frac {\alpha e^{-x}} {(1 + e^{-x})^{\alpha+1}}\]

AsymmetricLaplace密度类似,这种密度具有最重的尾部(渐近地),同时仍然是对数凸的。与AsymmetricLaplace分布不同,这种分布在任何地方都是无限可微的,因此适合构建拉普拉斯近似。

参考文献

[1] Generalized logistic distribution

https://en.wikipedia.org/wiki/Generalized_logistic_distribution

Parameters
  • loc – 位置参数。

  • scale – 比例参数。

  • asymmetry – 不对称参数(正数)。当 asymmetry > 1 时,分布向右偏斜;当 asymmetry < 1 时,分布向左偏斜。默认值为 asymmetry = 1,对应于标准的 Logistic 分布。

arg_constraints = {'asymmetry': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}
cdf(value)[源代码]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(value)[source]
log_prob(value)[来源]
rsample(sample_shape=torch.Size([]))[source]
support = Real()

软非对称拉普拉斯

class SoftAsymmetricLaplace(loc, scale, asymmetry=1.0, softness=1.0, *, validate_args=None)[来源]

基础类:pyro.distributions.distribution.Distribution, Callable

软不对称版本的Laplace分布。

这具有一个平滑(无限可微)的密度,带有两个不对称的渐近指数尾部,一个在左边,一个在右边。在softness 0的极限下,这会在分布上收敛到AsymmetricLaplace分布。

这相当于三个随机变量的和 z - u + v 其中:

z ~ Normal(loc, scale * softness)
u ~ Exponential(1 / (scale * asymmetry))
v ~ Exponential(asymetry / scale)

这也等同于两个随机变量的和 z + a 其中:

z ~ Normal(loc, scale * softness)
a ~ AsymmetricLaplace(0, scale, asymmetry)
Parameters
  • loc – 位置参数,即模式。

  • scale – 比例参数 = 左右比例几何平均值。

  • asymmetry – 左右比例的平方。默认为1。

  • softness – 高斯平滑器的尺度参数。默认为1。

arg_constraints = {'asymmetry': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0), 'softness': GreaterThan(lower_bound=0.0)}
expand(batch_shape, _instance=None)[source]
has_rsample = True
property left_scale
log_prob(value)[来源]
property mean
property right_scale
rsample(sample_shape=torch.Size([]))[来源]
property soft_scale
support = Real()
property variance

SoftLaplace

class SoftLaplace(loc, scale, *, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

具有类似拉普拉斯尾部行为的平滑分布。

这个分布对应于对数凸密度:

z = (value - loc) / scale
log_prob = log(2 / pi) - log(scale) - logaddexp(z, -z)

与拉普拉斯密度类似,这种密度具有最重的尾部(渐近地),同时仍然保持对数凸性。与拉普拉斯分布不同,这种分布在所有地方都是无限可微的,因此适合构建拉普拉斯近似。

Parameters
  • loc – 位置参数。

  • scale – 比例参数。

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

生成树

class SpanningTree(edge_logits, sampler_options=None, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

在固定数量的顶点 V 上的生成树的分布。

树被表示为形状为torch.LongTensor edges(V-1,2),满足以下属性:

  1. 边构成一棵树,即它们是连通的且无环。

  2. 每条边 (v1,v2) = edges[e] 都被排序,即 v1 < v2

  3. 整个张量按字典序排序。

使用 validate_edges() 来验证 edges 是否正确形成。

edge_logits 张量为完全图中的每条边都有一个条目,该完全图有 V 个顶点,边的数量为 V*(V-1)//2,其中每条边都已排序,且边的顺序是按字典序排列的:

(0,1), (0,2), (1,2), (0,3), (1,3), (2,3), (0,4), (1,4), (2,4), ...

这种排序对应于与大小无关的配对函数:

k = v1 + v2 * (v2 - 1) // 2

其中 k 是完整图中边 (v1,v2) 的排名。 要将边的逻辑矩阵转换为此处使用的线性表示:

assert my_matrix.shape == (V, V)
i, j = make_complete_graph(V)
edge_logits = my_matrix[i, j]
Parameters
  • edge_logits (torch.Tensor) – 一个长度为 V*(V-1)//2 的张量,包含完整图中所有边的 logits(即负能量)。有关边的顺序,请参见上面的注释。

  • sampler_options (dict) – 一个可选的采样器选项字典,包括: mcmc_steps 默认为单个MCMC步骤(效果相当不错); initial_edges 默认为一个廉价的近似样本; backend 可以是“python”或“cpp”,默认为“python”。

arg_constraints = {'edge_logits': Real()}
property edge_mean

计算每条边处于活动状态的边际概率。

注意

这与其他分布的.mean()方法类似,但由于此分布的值未编码为二进制矩阵,因此形状不同。

Returns

一个对称的方形(V,V)形状的矩阵,其值在[0,1]范围内,表示每条边在采样值中的边际概率。

Return type

张量

enumerate_support(expand=True)[source]

这是为最多6个顶点(和5条边)的树实现的。

has_enumerate_support = True
property log_partition_function
log_prob(edges)[source]
property mode

最大权重生成树。 :rtype: Tensor

Type

返回

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

该采样器使用MCMC运行少量步骤实现,初始化时使用了一个廉价的近似采样器。该采样器是近似且立方时间的。这比经典的Aldous-Broder采样器[1,2]更快,特别是对于具有大混合时间的图。最近的研究[3,4]提出了运行在次矩阵乘法时间内的采样器,但实现起来更为复杂。

参考文献

[1] Generating random spanning trees

安德烈·布罗德 (1989)

[2] The Random Walk Construction of Uniform Spanning Trees and Uniform Labelled Trees,

大卫·J·阿尔杜斯 (1990)

[3] Sampling Random Spanning Trees Faster than Matrix Multiplication,

David Durfee, Rasmus Kyng, John Peebles, Anup B. Rao, Sushant Sachdeva (2017) https://arxiv.org/abs/1611.07451

[4] An almost-linear time algorithm for uniform random spanning tree generation,

Aaron Schild (2017) https://arxiv.org/abs/1711.06455

support = IntegerGreaterThan(lower_bound=0)
validate_edges(edges)[source]

验证一批由sample()enumerate_support()返回的edges张量,或作为log_prob()的输入。

Parameters

edges (torch.LongTensor) – 一批边。

Raises

值错误

Returns

稳定

class Stable(stability, skew, scale=1.0, loc=0.0, coords='S0', validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

Levy \(\alpha\)-稳定分布。详情请参见[1]。

这使用了Nolan的参数化方法[2]来处理loc参数,这是为了确保连续性和可微性。这对应于[1]中的符号\(S^0_\alpha(\beta,\sigma,\mu_0)\),其中\(\alpha\) = 稳定性,\(\beta\) = 偏斜,\(\sigma\) = 尺度,\(\mu_0\) = 位置。如果要使用scipy中的S参数化,请传递coords="S",但请注意,这在stability=1时是不连续的,并且对于推理来说几何形状较差。

这实现了一个重新参数化的采样器 rsample(),以及一个相对昂贵的 log_prob() 计算,通过数值积分使得推断速度较慢(与其他分布相比),但具有更好的收敛特性,特别是对于偏斜的 \(\alpha\)-稳定分布(参见下面的 skew 参数)。可以使用无似然算法(如 EnergyDistance)或通过 reparam() 处理程序进行重新参数化,使用其中一个重新参数化器 LatentStableReparamSymmetricStableReparamStableReparam 来进行更快的推断,例如:

with poutine.reparam(config={"x": StableReparam()}):
    pyro.sample("x", Stable(stability, skew, scale, loc))

或者简单地包装在 MinimalReparamAutoReparam 中,例如:

@MinimalReparam()
def model():
    ...
[1] S. Borak, W. Hardle, R. Weron (2005).

稳定分布。 https://edoc.hu-berlin.de/bitstream/handle/18452/4526/8.pdf

[2] J.P. Nolan (1997).

稳定密度和分布函数的数值计算。

[3] Rafal Weron (1996).

关于Chambers-Mallows-Stuck方法用于模拟偏斜稳定随机变量。

[4] J.P. Nolan (2017).

稳定分布:重尾数据的模型。 https://edspace.american.edu/jpnolan/wp-content/uploads/sites/1720/2020/09/Chap1.pdf

Parameters
  • 稳定性 (张量) – Levy 稳定性参数 \(\alpha\in(0,2]\)

  • skew (Tensor) – 偏度 \(\beta\in[-1,1]\) .

  • scale (Tensor) – 比例 \(\sigma > 0\)。默认为1。

  • loc (Tensor) – 使用Nolan的S0参数化时的位置 \(\mu_0\),或使用S参数化时的 \(\mu\)。默认值为0。

  • coords (str) – 使用“S0”(默认)以使用Nolan的连续S0参数化,或使用“S”以使用不连续参数化。

arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0), 'skew': Interval(lower_bound=-1, upper_bound=1), 'stability': Interval(lower_bound=0, upper_bound=2)}
expand(batch_shape, _instance=None)[source]
has_rsample = True
log_prob(value)[source]

通过基于Chambers、Mallows和Stuck(CMS)提出的算法进行数值积分来实现,用于模拟Levy \(\alpha\)-稳定分布。CMS算法涉及将两个独立的随机变量非线性转换为一个稳定随机变量。第一个随机变量是均匀分布的,而第二个是指数分布的。数值积分是在第一个均匀分布的随机变量上进行的。

property mean
rsample(sample_shape=torch.Size([]))[source]
support = Real()
property variance

StableWithLogProb

class StableWithLogProb(stability, skew, scale=1.0, loc=0.0, coords='S0', validate_args=None)[源代码]

基础类:pyro.distributions.distribution.Distribution, Callable

Stable相同,但不会通过MinimalReparam进行重新参数化,并且会因LatentStableReparamSymmetricStableReparamStableReparam而失败。

截断PolyaGamma

class TruncatedPolyaGamma(prototype, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

这是一个被截断为在区间 (0, 2.5) 内具有有限支持的 PolyaGamma(1, 0) 分布。详情请参见 [1]。由于截断的原因,log_prob 方法仅精确到大约六位小数。此外,提供的采样器是一个粗略的近似值,仅适用于样本精度不重要的场景(例如在初始化时)。总的来说,此实现仅适用于 log_prob 的良好近似值足够的情况,例如在 HMC 中。

Parameters

prototype (tensor) – 一个任意形状的原型张量,用于确定由samplelog_prob返回的dtypedevice

参考文献

[1] ‘Bayesian inference for logistic models using Polya-Gamma latent variables’

尼古拉斯·G·波尔森, 詹姆斯·G·斯科特, 杰西·温德尔.

arg_constraints = {}
expand(batch_shape, _instance=None)[source]
has_rsample = False
log_prob(value)[source]
num_gamma_variates = 8
num_log_prob_terms = 7
sample(sample_shape=())[来源]
support = Interval(lower_bound=0.0, upper_bound=2.5)
truncation_point = 2.5

单位

class Unit(log_factor, *, has_rsample=None, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

表示单位类型的简单非归一化分布。

单元类型有一个没有数据的单一值,即 value.numel() == 0

这是用于pyro.factor()语句的。

arg_constraints = {'log_factor': Real()}
expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
rsample(sample_shape=torch.Size([]))[source]
sample(sample_shape=torch.Size([]))[source]
support = Real()

VonMises3D

class VonMises3D(concentration, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

球形冯·米塞斯分布。

此实现将方向参数和浓度参数合并为一个包含方向和幅度的组合参数。value 参数以笛卡尔坐标表示:它必须是一个位于2-球面上的归一化3-向量。

参见VonMises了解此分布的二维极坐标版本。参见projected_normal了解一个在性质上相似但实现了更多功能的分布。

目前仅实现了 log_prob()

Parameters

浓度 (torch.Tensor) – 一个结合了位置和浓度的向量。这个向量的方向表示位置,其大小表示浓度。

arg_constraints = {'concentration': Real()}
expand(batch_shape)[源代码]
log_prob(value)[来源]
support = Sphere

零膨胀分布

class ZeroInflatedDistribution(base_dist, *, gate=None, gate_logits=None, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

通用的零膨胀分布。

这可以直接使用,也可以作为基类使用,例如用于 ZeroInflatedPoissonZeroInflatedNegativeBinomial

Parameters
  • base_dist (TorchDistribution) – 基础分布。

  • gate (torch.Tensor) – 通过伯努利分布给出的额外零的概率。

  • gate_logits (torch.Tensor) – 通过伯努利分布给出的额外零的logits。

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

零膨胀负二项分布

class ZeroInflatedNegativeBinomial(total_count, *, probs=None, logits=None, gate=None, gate_logits=None, validate_args=None)[来源]

基础类:pyro.distributions.distribution.Distribution, Callable

零膨胀负二项分布。

Parameters
arg_constraints = {'gate': Interval(lower_bound=0.0, upper_bound=1.0), 'gate_logits': Real(), 'logits': Real(), 'probs': HalfOpenInterval(lower_bound=0.0, upper_bound=1.0), 'total_count': GreaterThanEq(lower_bound=0)}
property logits
property probs
support = IntegerGreaterThan(lower_bound=0)
property total_count

零膨胀泊松

class ZeroInflatedPoisson(rate, *, gate=None, gate_logits=None, validate_args=None)[source]

基础类:pyro.distributions.distribution.Distribution, Callable

零膨胀泊松分布。

Parameters
arg_constraints = {'gate': Interval(lower_bound=0.0, upper_bound=1.0), 'gate_logits': Real(), 'rate': GreaterThan(lower_bound=0.0)}
property rate
support = IntegerGreaterThan(lower_bound=0)

转换

条件转换

class ConditionalTransform[source]

基础类:abc.ABC

abstract condition(context)[source]
Return type

torch.distributions.Transform

Cholesky变换

class CholeskyTransform(cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

通过映射 \(y = safe_cholesky(x)\) 进行转换,其中 x 是一个正定矩阵。

bijective = True
codomain: torch.distributions.constraints.Constraint = LowerCholesky()
domain: torch.distributions.constraints.Constraint = PositiveDefinite()
log_abs_det_jacobian(x, y)[source]

相关矩阵Cholesky变换

class CorrMatrixCholeskyTransform(cache_size=0)[source]

基础类:pyro.distributions.transforms.cholesky.CholeskyTransform

通过映射 \(y = safe_cholesky(x)\) 进行转换,其中 x 是一个相关矩阵。

bijective = True
codomain: torch.distributions.constraints.Constraint = CorrCholesky()
domain: torch.distributions.constraints.Constraint = CorrMatrix()
log_abs_det_jacobian(x, y)[来源]

离散余弦变换

class DiscreteCosineTransform(dim=- 1, smooth=0.0, cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

类型-II的离散余弦变换。

这使用了 dct()idct() 来计算 正交DCT和逆DCT变换。雅可比行列式为1。

Parameters
  • dim (int) – 沿此维度进行变换。必须为负数。 这是从右边开始计算的绝对维度。

  • smooth (float) – 平滑参数。当为0时,这将白噪声转换为白噪声;当为1时,这将布朗噪声转换为白噪声;当为-1时,这将紫噪声转换为白噪声;等等。允许任何实数。https://en.wikipedia.org/wiki/Colors_of_noise.

bijective = True
property codomain
property domain
forward_shape(shape)[source]
inverse_shape(shape)[source]
log_abs_det_jacobian(x, y)[来源]
with_cache(cache_size=1)[source]

ELUTransform

class ELUTransform(cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

通过映射\(y = \text{ELU}(x)\)进行双射变换。

bijective = True
codomain: torch.distributions.constraints.Constraint = GreaterThan(lower_bound=0.0)
domain: torch.distributions.constraints.Constraint = Real()
log_abs_det_jacobian(x, y)[source]
sign = 1

Haar变换

class HaarTransform(dim=- 1, flip=False, cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

离散哈尔变换。

这使用了haar_transform()inverse_haar_transform()来计算 (正交的)Haar变换和逆Haar变换。雅可比行列式为1。 对于长度T不是2的幂的序列,此实现等同于一个块结构的Haar变换,其中块大小从左到右以一半的因子递减。

Parameters
  • dim (int) – 沿此维度进行变换。必须为负数。 这是从右边开始计算的绝对维度。

  • flip (bool) – 是否在应用Haar变换之前翻转时间轴。默认为false。

bijective = True
property codomain
property domain
forward_shape(shape)[source]
inverse_shape(shape)[source]
log_abs_det_jacobian(x, y)[source]
with_cache(cache_size=1)[source]

LeakyReLU变换

class LeakyReLUTransform(cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

通过映射 \(y = \text{LeakyReLU}(x)\) 进行双射变换。

bijective = True
codomain: torch.distributions.constraints.Constraint = Real()
domain: torch.distributions.constraints.Constraint = Real()
log_abs_det_jacobian(x, y)[source]
sign = 1

下三角Cholesky仿射

class LowerCholeskyAffine(loc, scale_tril, cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

一种形式的双射,

\(\mathbf{y} = \mathbf{L} \mathbf{x} + \mathbf{r}\)

其中 mathbf{L} 是一个下三角矩阵,mathbf{r 是一个向量。

Parameters
  • loc (torch.tensor) – 用于平移输入的固定D维向量。

  • scale_tril (torch.tensor) – 用于变换的 D x D 下三角矩阵。

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
log_abs_det_jacobian(x, y)[source]

计算对数雅可比行列式的逐元素行列式,即 log(abs(dy/dx))。

volume_preserving = False
with_cache(cache_size=1)[来源]

标准化

class Normalize(p=2, cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

安全地将向量投影到球体上,相对于p范数。这通过映射到向量[1, 0, 0, ..., 0]来避免在零点的奇异性。

bijective = False
codomain: torch.distributions.constraints.Constraint = Sphere
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
with_cache(cache_size=1)[source]

有序转换

class OrderedTransform(cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

将实向量转换为有序向量。

具体来说,通过变换\(y_0 = x_0\)\(y_i = \sum_{1 \le j \le i} \exp(x_i)\)在给定张量的最后一个维度上强制执行单调递增顺序。

bijective = True
codomain: torch.distributions.constraints.Constraint = OrderedVector()
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
log_abs_det_jacobian(x, y)[来源]

排列

class Permute(permutation, *, dim=- 1, cache_size=1)[source]

基础类:torch.distributions.transforms.Transform

一种重新排序输入维度的双射,即通过置换矩阵乘以输入。这在AffineAutoregressive变换之间非常有用,可以增加结果分布的灵活性并稳定学习。虽然不是自回归变换,但雅可比行列式的对数绝对值很容易计算为0。请注意,在两层AffineAutoregressive之间重新排序输入维度并不等同于在这些IAF使用的MADE网络内部重新排序维度;使用Permute变换会导致分布具有更大的灵活性。

示例用法:

>>> from pyro.nn import AutoRegressiveNN
>>> from pyro.distributions.transforms import AffineAutoregressive, Permute
>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> iaf1 = AffineAutoregressive(AutoRegressiveNN(10, [40]))
>>> ff = Permute(torch.randperm(10, dtype=torch.long))
>>> iaf2 = AffineAutoregressive(AutoRegressiveNN(10, [40]))
>>> flow_dist = dist.TransformedDistribution(base_dist, [iaf1, ff, iaf2])
>>> flow_dist.sample()  
Parameters
  • permutation (torch.LongTensor) – 应用于输入的排列顺序。

  • dim (int) – 要置换的张量维度。该值必须为负数,并将事件维度定义为 abs(dim)

bijective = True
property codomain
property domain
property inv_permutation
log_abs_det_jacobian(x, y)[source]

计算对数雅可比行列式的逐元素行列式,即 log(abs([dy_0/dx_0, …, dy_{N-1}/dx_{N-1}]))。请注意,这种类型的 变换不是自回归的,因此对数雅可比行列式不是前一个表达式的和。然而,事实证明它总是0(因为 行列式是-1或+1),所以返回一个零向量是可行的。

volume_preserving = True
with_cache(cache_size=1)[source]

正幂变换

class PositivePowerTransform(exponent, *, cache_size=0, validate_args=None)[源代码]

基础类:torch.distributions.transforms.Transform

通过映射进行转换 \(y=\operatorname{sign}(x)|x|^{\text{exponent}}\)

PowerTransform允许 任意的exponent并将定义域和值域限制为正数, 此类限制exponent > 0并允许实数的定义域和值域。

警告

雅可比矩阵在原点通常为零或无限。

bijective = True
codomain: torch.distributions.constraints.Constraint = Real()
domain: torch.distributions.constraints.Constraint = Real()
forward_shape(shape)[来源]
inverse_shape(shape)[source]
log_abs_det_jacobian(x, y)[source]
sign = 1
with_cache(cache_size=1)[source]

SimplexToOrderedTransform

class SimplexToOrderedTransform(anchor_point=None)[源代码]

基础类:torch.distributions.transforms.Transform

将单纯形转换为有序向量(通过切点之间的Logistic CDF差异) 在[1]中用于通过转换有序类别概率来诱导潜在切点的先验。

Parameters

anchor_point – 锚点是一个用于提高变换可识别性的干扰参数。 为简单起见,我们假设它是一个标量值,但它是可广播的 x.shape[:-1]。 更多详情请参阅[1]中的第2.2节

参考文献:

  1. 序数回归案例研究,第2.2节, M. Betancourt, https://betanalpha.github.io/assets/case_studies/ordinal_regression.html

codomain: torch.distributions.constraints.Constraint = OrderedVector()
domain: torch.distributions.constraints.Constraint = Simplex()
forward_shape(shape)[source]
inverse_shape(shape)[来源]
log_abs_det_jacobian(x, y)[source]

SoftplusLowerCholesky变换

class SoftplusLowerCholeskyTransform(cache_size=0)[源代码]

基础类:torch.distributions.transforms.Transform

将无约束矩阵转换为具有非负对角线元素的下三角矩阵。这对于根据其Cholesky分解参数化正定矩阵非常有用。

codomain: torch.distributions.constraints.Constraint = LowerCholesky()
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 2)

SoftplusTransform

class SoftplusTransform(cache_size=0)[source]

基础类:torch.distributions.transforms.Transform

通过映射 \(\text{Softplus}(x) = \log(1 + \exp(x))\) 进行转换。

bijective = True
codomain: torch.distributions.constraints.Constraint = GreaterThan(lower_bound=0.0)
domain: torch.distributions.constraints.Constraint = Real()
log_abs_det_jacobian(x, y)[来源]
sign = 1

单位下三角Cholesky变换

class UnitLowerCholeskyTransform(cache_size=0)[源代码]

基础类:torch.distributions.transforms.Transform

将无约束矩阵转换为具有全一对角线的下三角矩阵。

codomain: torch.distributions.constraints.Constraint = UnitLowerCholesky()
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 2)

转换模块

仿射自回归

class AffineAutoregressive(autoregressive_nn, log_scale_min_clip=- 5.0, log_scale_max_clip=3.0, sigmoid_bias=2.0, stable=False)[源代码]

基础类:pyro.distributions.torch_transform.TransformModule

逆自回归流(IAF)的双射变换的实现,默认使用Kingma等人2016年的公式(10)。

\(\mathbf{y} = \mu_t + \sigma_t\odot\mathbf{x}\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, \(\mu_t,\sigma_t\) 是从自回归网络计算得出的 \(\mathbf{x}\),且 \(\sigma_t>0\)

如果 stable 关键字参数设置为 True,则使用的转换是,

\(\mathbf{y} = \sigma_t\odot\mathbf{x} + (1-\sigma_t)\odot\mu_t\)

其中 \(\sigma_t\) 被限制在 \((0,1)\) 之间。作者声称这种IAF变体比使用公式(10)的版本在数值上更稳定,尽管在实践中它会导致可表示的分布受到限制,大概是因为输入被限制在 \((0,1)\) 之间的数进行缩放。

TransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> from pyro.nn import AutoRegressiveNN
>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> transform = AffineAutoregressive(AutoRegressiveNN(10, [40]))
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  

当需要计算样本的对数密度时,例如使用TransformedDistribution时,需要Bijector的逆操作。此实现在调用其前向操作时缓存Bijector的逆操作,例如从TransformedDistribution采样时。然而,如果缓存的值不可用,无论是由于在采样新值时被覆盖还是因为正在计算任意值的分数,它将手动计算。请注意,这是一个随着输入维度D的增加而按O(D)比例增长的操作,因此应避免在高维情况下使用。因此,一般来说,从IAF采样并计算由IAF采样的值的分数是廉价的,但计算任意值的分数是昂贵的。

Parameters
  • autoregressive_nn (callable) – 一个自回归神经网络,其前向调用返回一个实数值的均值和logit-scale作为元组

  • log_scale_min_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最小值

  • log_scale_max_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最大值

  • sigmoid_bias (float) – 在使用稳定变换时,添加到输入的对数几率的一个项。

  • stable (bool) – 当为真时,使用转换的“稳定”版本(见上文)。

参考文献:

[1] Diederik P. Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, Max Welling. 使用逆自回归流改进变分推断。 [arXiv:1606.04934]

[2] Danilo Jimenez Rezende, Shakir Mohamed. 使用归一化流的变分推断。 [arXiv:1505.05770]

[3] Mathieu Germain, Karol Gregor, Iain Murray, Hugo Larochelle. MADE: 用于分布估计的掩码自编码器。 [arXiv:1502.03509]

autoregressive = True
bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
log_abs_det_jacobian(x, y)[来源]

计算对数雅可比行列式的逐元素行列式

sign = 1

仿射耦合

class AffineCoupling(split_dim, hypernet, *, dim=- 1, log_scale_min_clip=- 5.0, log_scale_max_clip=3.0)[source]

基础类:pyro.distributions.torch_transform.TransformModule

RealNVP(Dinh等,2017)的仿射耦合层的实现,使用双射变换,

\(\mathbf{y}_{1:d} = \mathbf{x}_{1:d}\) \(\mathbf{y}_{(d+1):D} = \mu + \sigma\odot\mathbf{x}_{(d+1):D}\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 例如 \(\mathbf{x}_{1:d}\) 表示输入的前 \(d\) 个元素, 而 \(\mu,\sigma\) 是仅输入 \(\mathbf{x}_{1:d}\) 的函数输出的平移和缩放参数。

也就是说,前\(d\)个组件保持不变,随后的\(D-d\)个组件则通过前一个组件的函数进行平移和转换。

TransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> from pyro.nn import DenseNN
>>> input_dim = 10
>>> split_dim = 6
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [input_dim-split_dim, input_dim-split_dim]
>>> hypernet = DenseNN(split_dim, [10*input_dim], param_dims)
>>> transform = AffineCoupling(split_dim, hypernet)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  

当需要计算样本的对数密度时,例如使用TransformedDistribution进行评分时,需要Bijector的逆操作。此实现在调用其前向操作时缓存Bijector的逆操作,例如从TransformedDistribution进行采样时。然而,如果缓存的值不可用,无论是因为在采样新值时被覆盖,还是因为正在对任意值进行评分,它将手动计算逆操作。

这是一个按O(1)比例扩展的操作,即在输入维度上是恒定的。 因此,通常从AffineCoupling中采样评分(任意值)是廉价的。

Parameters
  • split_dim (int) – 从零开始索引的维度 \(d\),用于执行输入/输出分割以进行转换。

  • hypernet (可调用) – 一个神经网络,其前向调用返回一个实数值的均值和logit-scale作为元组。输入应具有最终维度split_dim,而输出的最终维度应为input_dim-split_dim,对于元组的每个成员都是如此。

  • dim (int) – 要在其上分割的张量维度。此值必须为负数,并将事件维度定义为 abs(dim)

  • log_scale_min_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最小值

  • log_scale_max_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最大值

参考文献:

[1] Laurent Dinh, Jascha Sohl-Dickstein, 和 Samy Bengio. 使用Real NVP进行密度估计. ICLR 2017.

bijective = True
property codomain
property domain
log_abs_det_jacobian(x, y)[来源]

计算对数雅可比行列式的逐元素行列式

批量归一化

class BatchNorm(input_dim, momentum=0.1, epsilon=1e-05)[source]

基础类:pyro.distributions.torch_transform.TransformModule

一种可以用于在归一化流中稳定训练的批量归一化类型。逆操作定义为

\(x = (y - \hat{\mu}) \oslash \sqrt{\hat{\sigma^2}} \otimes \gamma + \beta\)

即标准的批量归一化方程,其中 \(x\) 是输入, \(y\) 是输出,\(\gamma,\beta\) 是可学习的参数,而 \(\hat{\mu}\)/\(\hat{\sigma^2}\) 分别是样本均值和方差的平滑运行平均值。约束条件 \(\gamma>0\) 是为了简化对数行列式雅可比项的计算。

这是一个逐元素的变换,当应用于向量时,会为输入的每个维度学习两个参数(\(\gamma,\beta\))。

当模块设置为训练模式时,每次调用逆操作符时,样本均值和方差的移动平均值都会更新,例如,当归一化流使用log_prob方法对一个小批次进行评分时。

此外,当模块设置为训练模式时,当前小批量的样本均值和方差将用于替代平滑平均值,\(\hat{\mu}\)\(\hat{\sigma^2}\),用于逆操作。因此,在训练期间,\(x=g(g^{-1}(x))\) 并不成立,即逆操作并不是前向操作的逆。

示例用法:

>>> from pyro.nn import AutoRegressiveNN
>>> from pyro.distributions.transforms import AffineAutoregressive
>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> iafs = [AffineAutoregressive(AutoRegressiveNN(10, [40])) for _ in range(2)]
>>> bn = BatchNorm(10)
>>> flow_dist = dist.TransformedDistribution(base_dist, [iafs[0], bn, iafs[1]])
>>> flow_dist.sample()  
Parameters
  • input_dim (int) – 输入的维度

  • momentum (float) – 用于更新移动平均值的动量参数

  • epsilon (float) – 添加到方差中的小数值,以确保数值稳定性

参考文献:

[1] Sergey Ioffe 和 Christian Szegedy。批量归一化:通过减少内部协变量偏移加速深度网络训练。在国际机器学习会议上,2015年。https://arxiv.org/abs/1502.03167

[2] Laurent Dinh, Jascha Sohl-Dickstein, 和 Samy Bengio. 使用Real NVP进行密度估计。在国际学习表示会议中,2017年。 https://arxiv.org/abs/1605.08803

[3] George Papamakarios, Theo Pavlakou, 和 Iain Murray. 用于密度估计的掩码自回归流. 在神经信息处理系统中, 2017. https://arxiv.org/abs/1705.07057

bijective = True
codomain: torch.distributions.constraints.Constraint = Real()
property constrained_gamma
domain: torch.distributions.constraints.Constraint = Real()
log_abs_det_jacobian(x, y)[来源]

计算对数雅可比行列式的逐元素行列式,dx/dy

块自回归

class BlockAutoregressive(input_dim, hidden_factors=[8, 8], activation='tanh', residual=None)[源代码]

基础类:pyro.distributions.torch_transform.TransformModule

Block Neural Autoregressive Flow (block-NAF) 的实现 (De Cao 等人, 2019) 双射变换。Block-NAF 使用类似的 变换到深度密集 NAF,将自回归神经网络构建到 变换的结构中,在某种意义上。

TransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> naf = BlockAutoregressive(input_dim=10)
>>> pyro.module("my_naf", naf)  
>>> naf_dist = dist.TransformedDistribution(base_dist, [naf])
>>> naf_dist.sample()  

逆操作未实现。这需要数值反演,例如使用根查找方法 - 这是未来实现的一个可能性。

Parameters
  • input_dim (int) – 输入和输出变量的维度。

  • hidden_factors (list) – 隐藏层 i 每输入维度有 hidden_factors[i] 个隐藏单元。这对应于 De Cao 等人 (2019) 中的 \(a\)\(b\)。hidden_factors 的元素必须是整数。

  • activation (string) – 使用的激活函数。可选值为‘ELU’、‘LeakyReLU’、‘sigmoid’或‘tanh’。

  • residual (string) – 使用的残差连接类型。选项有“None”, “normal”表示\(\mathbf{y}+f(\mathbf{y})\),而“gated”表示 \(\alpha\mathbf{y} + (1 - \alpha\mathbf{y})\),其中\(\alpha\)是可学习的参数。

参考文献:

[1] Nicola De Cao, Ivan Titov, Wilker Aziz. 块神经自回归流。 [arXiv:1904.04676]

autoregressive = True
bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
log_abs_det_jacobian(x, y)[source]

计算对数雅可比行列式的逐元素行列式

条件仿射自回归

class ConditionalAffineAutoregressive(autoregressive_nn, **kwargs)[来源]

基础类:pyro.distributions.conditional.ConditionalTransformModule

逆自回归流(IAF)的双射变换的实现,该实现基于额外的上下文变量,并默认使用Kingma等人2016年的公式(10)。

\(\mathbf{y} = \mu_t + \sigma_t\odot\mathbf{x}\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, \(\mu_t,\sigma_t\) 是从自回归网络计算得出的,基于 \(\mathbf{x}\) 和上下文 \(\mathbf{z}\in\mathbb{R}^M\),并且 \(\sigma_t>0\)

如果 stable 关键字参数设置为 True,则使用的转换是,

\(\mathbf{y} = \sigma_t\odot\mathbf{x} + (1-\sigma_t)\odot\mu_t\)

其中 \(\sigma_t\) 被限制在 \((0,1)\) 之间。作者声称这种IAF变体比使用公式(10)的版本在数值上更稳定,尽管在实践中它会导致可表示的分布受到限制,大概是因为输入被限制在 \((0,1)\) 之间的数进行缩放。

ConditionalTransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> from pyro.nn import ConditionalAutoRegressiveNN
>>> input_dim = 10
>>> context_dim = 4
>>> batch_size = 3
>>> hidden_dims = [10*input_dim, 10*input_dim]
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> hypernet = ConditionalAutoRegressiveNN(input_dim, context_dim, hidden_dims)
>>> transform = ConditionalAffineAutoregressive(hypernet)
>>> pyro.module("my_transform", transform)  
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size]))  

当需要计算样本的对数密度时,例如使用TransformedDistribution时,需要Bijector的逆操作。此实现在调用其前向操作时缓存Bijector的逆操作,例如从TransformedDistribution采样时。然而,如果缓存的值不可用,无论是由于在采样新值时被覆盖还是因为正在计算任意值的分数,它将手动计算。请注意,这是一个随着输入维度D的增加而按O(D)比例增长的操作,因此应避免在高维情况下使用。因此,一般来说,从IAF采样并计算由IAF采样的值的分数是廉价的,但计算任意值的分数是昂贵的。

Parameters
  • autoregressive_nn (nn.Module) – 一个自回归神经网络,其前向调用返回一个实数值的均值和logit-scale作为元组

  • log_scale_min_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最小值

  • log_scale_max_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最大值

  • sigmoid_bias (float) – 在使用稳定变换时,添加到输入的对数几率的一个项。

  • stable (bool) – 当为真时,使用转换的“稳定”版本(见上文)。

参考文献:

[1] Diederik P. Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, Max Welling. 使用逆自回归流改进变分推断。 [arXiv:1606.04934]

[2] Danilo Jimenez Rezende, Shakir Mohamed. 使用归一化流的变分推断。 [arXiv:1505.05770]

[3] Mathieu Germain, Karol Gregor, Iain Murray, Hugo Larochelle. MADE: 用于分布估计的掩码自编码器。 [arXiv:1502.03509]

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[source]

对上下文变量的条件,返回类型为AffineAutoregressive的非条件变换。

domain = IndependentConstraint(Real(), 1)
training: bool

条件仿射耦合

class ConditionalAffineCoupling(split_dim, hypernet, **kwargs)[源代码]

基础类:pyro.distributions.conditional.ConditionalTransformModule

RealNVP(Dinh等,2017)的仿射耦合层的实现,该实现基于额外的上下文变量并使用双射变换,

\(\mathbf{y}_{1:d} = \mathbf{x}_{1:d}\) \(\mathbf{y}_{(d+1):D} = \mu + \sigma\odot\mathbf{x}_{(d+1):D}\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 例如 \(\mathbf{x}_{1:d}\) 表示输入的前 \(d\) 个元素, 而 \(\mu,\sigma\) 是作为函数输入 \(\mathbf{x}_{1:d}\) 和上下文变量 \(\mathbf{z}\in\mathbb{R}^M\) 的输出计算得到的平移和缩放参数。

也就是说,前\(d\)个组件保持不变,随后的\(D-d\)个组件则通过前一个组件的函数进行平移和转换。

ConditionalTransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> from pyro.nn import ConditionalDenseNN
>>> input_dim = 10
>>> split_dim = 6
>>> context_dim = 4
>>> batch_size = 3
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [input_dim-split_dim, input_dim-split_dim]
>>> hypernet = ConditionalDenseNN(split_dim, context_dim, [10*input_dim],
... param_dims)
>>> transform = ConditionalAffineCoupling(split_dim, hypernet)
>>> pyro.module("my_transform", transform)  
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size]))  

当需要计算样本的对数密度时,例如使用ConditionalTransformedDistribution进行评分时,需要Bijector的逆操作。此实现在调用其前向操作时缓存Bijector的逆操作,例如从ConditionalTransformedDistribution进行采样时。然而,如果缓存的值不可用,可能是因为在采样新值时被覆盖,或者正在对任意值进行评分,它将手动计算。

这是一个按O(1)比例扩展的操作,即在输入维度上是恒定的。 因此,通常从ConditionalAffineCoupling中采样评分(任意值)是廉价的。

Parameters
  • split_dim (int) – 从零开始索引的维度 \(d\),用于执行输入/输出分割以进行转换。

  • hypernet (可调用) – 一个神经网络,其前向调用返回一个实数值的均值和logit-scale作为元组。输入应具有最终维度split_dim,输出最终维度input_dim-split_dim对于元组的每个成员。网络还将上下文变量作为关键字参数输入,以便在其上条件化输出。

  • log_scale_min_clip (float) – 用于从神经网络中裁剪log(scale)的最小值

  • log_scale_max_clip (float) – 用于从神经网络中裁剪log(scale)的最大值

参考文献:

Laurent Dinh, Jascha Sohl-Dickstein, 和 Samy Bengio。使用 Real NVP 进行密度估计。ICLR 2017。

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[source]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

条件广义通道置换

class ConditionalGeneralizedChannelPermute(nn, channels=3, permutation=None)[source]

基础类:pyro.distributions.conditional.ConditionalTransformModule

一种双射,它概括了对一批2D图像通道的排列,这些图像以\([\ldots,C,H,W]\)格式存在,并且依赖于一个额外的上下文变量。具体来说,这种变换执行以下操作,

\(\mathbf{y} = \text{torch.nn.functional.conv2d}(\mathbf{x}, W)\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 而 \(W\sim C\times C\times 1\times 1\) 是用于1x1卷积的滤波器矩阵,具有 \(C\) 个输入和输出通道。

忽略最后两个维度,\(W\) 被限制为矩阵乘积,

\(W = PLU\)

其中 \(P\sim C\times C\) 是通道维度上的置换矩阵,而 \(LU\sim C\times C\) 是一个下三角矩阵和上三角矩阵的可逆乘积,这是神经网络的输出,输入为 \(z\in\mathbb{R}^{M}\),表示要调节的上下文变量。

输入 \(\mathbf{x}\) 和输出 \(\mathbf{y}\) 都具有形状 […,C,H,W],其中 C 是在初始化时设置的通道数。

此操作在[1]中为Glow归一化流引入,也被称为1x1可逆卷积。它在其他著名的工作中出现,如[2,3],并对应于TensorFlow概率中的tfp.bijectors.MatvecLU类。

示例用法:

>>> from pyro.nn.dense_nn import DenseNN
>>> context_dim = 5
>>> batch_size = 3
>>> channels = 3
>>> base_dist = dist.Normal(torch.zeros(channels, 32, 32),
... torch.ones(channels, 32, 32))
>>> hidden_dims = [context_dim*10, context_dim*10]
>>> nn = DenseNN(context_dim, hidden_dims, param_dims=[channels*channels])
>>> transform = ConditionalGeneralizedChannelPermute(nn, channels=channels)
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size])) 
Parameters
  • nn – 一个函数,输入上下文变量并输出维度为 \(C^2\) 的实值参数。

  • channels (int) – 输入中的通道维度数量。

[1] Diederik P. Kingma, Prafulla Dhariwal. Glow: 使用可逆1x1卷积的生成流. [arXiv:1807.03039]

[2] Ryan Prenger, Rafael Valle, Bryan Catanzaro. WaveGlow: 一种基于流的生成网络用于语音合成。 [arXiv:1811.00002]

[3] 康纳·德坎,阿图尔·贝卡索夫,伊恩·默里,乔治·帕帕马卡里奥斯。神经样条流。[arXiv:1906.04032]

bijective = True
codomain = IndependentConstraint(Real(), 3)
condition(context)[来源]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 3)
training: bool

条件户主

class ConditionalHouseholder(input_dim, nn, count_transforms=1)[source]

基础类:pyro.distributions.conditional.ConditionalTransformModule

表示在附加上下文条件下多次应用Householder双射变换。单个Householder变换的形式为,

\(\mathbf{y} = (I - 2*\frac{\mathbf{u}\mathbf{u}^T}{||\mathbf{u}||^2})\mathbf{x}\)

其中 \(\mathbf{x}\) 是维度为 \(D\) 的输入, \(\mathbf{y}\) 是输出,\(\mathbf{u}\in\mathbb{R}^D\) 是一个函数的输出,例如神经网络,其输入为 \(z\in\mathbb{R}^{M}\), 表示要调节的上下文变量。

变换表示\(\mathbf{x}\)通过原点且法向量为\(\mathbf{u}\)的平面的反射。

\(D\) 次应用这种变换能够将标准的独立同分布高斯噪声转换为具有任意协方差矩阵的高斯变量。使用 \(K 次变换,可以通过秩为 \(K\) 的线性变换来近似一个全秩高斯分布。

ConditionalTransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> from pyro.nn.dense_nn import DenseNN
>>> input_dim = 10
>>> context_dim = 5
>>> batch_size = 3
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [input_dim]
>>> hypernet = DenseNN(context_dim, [50, 50], param_dims)
>>> transform = ConditionalHouseholder(input_dim, hypernet)
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size])) 
Parameters
  • input_dim (int) – 输入(和输出)变量的维度。

  • nn (可调用) – 一个函数,输入上下文变量并输出一个维度为 \((1, D, D)\) 的实值参数三元组。

  • count_transforms (int) – 要应用的Householder变换的次数。

参考文献:

[1] Jakub M. Tomczak, Max Welling. 使用Householder Flow改进变分自编码器。 [arXiv:1611.09630]

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[source]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

条件矩阵指数

class ConditionalMatrixExponential(input_dim, nn, iterations=8, normalization='none', bound=None)[source]

基础类:pyro.distributions.conditional.ConditionalTransformModule

一个密集矩阵指数双射变换(Hoogeboom等,2020年),它通过方程在额外的上下文变量上进行条件化,

\(\mathbf{y} = \exp(M)\mathbf{x}\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, \(\exp(\cdot)\) 表示矩阵指数,并且 \(M\in\mathbb{R}^D\times\mathbb{R}^D\) 是神经网络在输入维度 \(D\) 上基于上下文变量 \(\mathbf{z}\) 的输出。 通常,\(M\) 不需要是可逆的。

由于矩阵指数的良好数学特性,该变换具有精确的逆变换和对数行列式-雅可比行列式,其时间复杂度为\(O(D)\)。正向和反向操作都通过截断的幂级数进行近似。为了数值稳定性,可以通过normalization关键字参数限制\(M\)的范数。

示例用法:

>>> from pyro.nn.dense_nn import DenseNN
>>> input_dim = 10
>>> context_dim = 5
>>> batch_size = 3
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [input_dim*input_dim]
>>> hypernet = DenseNN(context_dim, [50, 50], param_dims)
>>> transform = ConditionalMatrixExponential(input_dim, hypernet)
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size])) 
Parameters
  • input_dim (int) – 输入(和输出)变量的维度。

  • iterations (int) – 用于近似矩阵指数的截断幂级数中的项数。

  • normalization (string) – 选择应用于权重矩阵的归一化类型之一 [‘none’, ‘weight’, ‘spectral’]weight 对应于权重归一化(Salimans 和 Kingma,2016),而 spectral 对应于谱归一化(Miyato 等人,2018)。

  • bound (float) – 当通过 normalization 参数选择权重或谱范数正则化时,这是一个界限。此值的较低值意味着需要更少的截断幂级数项来近似矩阵指数的精确值。

参考文献:

[1] Emiel Hoogeboom, Victor Garcia Satorras, Jakub M. Tomczak, Max Welling. The

卷积指数和广义西尔维斯特流。[arXiv:2006.01910]

[2] Tim Salimans, Diederik P. Kingma. Weight Normalization: A Simple

重新参数化以加速深度神经网络的训练。 [arXiv:1602.07868]

[3] Takeru Miyato, Toshiki Kataoka, Masanori Koyama, Yuichi Yoshida. Spectral

生成对抗网络的归一化。ICLR 2018。

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[source]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

条件神经自回归

class ConditionalNeuralAutoregressive(autoregressive_nn, **kwargs)[source]

基础类:pyro.distributions.conditional.ConditionalTransformModule

深度神经自回归流(NAF)双射变换的实现,基于“IAF风格”的条件,附加一个上下文变量,可用于采样和评分从中抽取的样本(但不能用于任意样本)。

示例用法:

>>> from pyro.nn import ConditionalAutoRegressiveNN
>>> input_dim = 10
>>> context_dim = 5
>>> batch_size = 3
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> arn = ConditionalAutoRegressiveNN(input_dim, context_dim, [40],
... param_dims=[16]*3)
>>> transform = ConditionalNeuralAutoregressive(arn, hidden_units=16)
>>> pyro.module("my_transform", transform)  
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size]))  

逆操作未实现。这需要数值反演,例如使用根查找方法 - 这是未来实现的一个可能性。

Parameters
  • autoregressive_nn (nn.Module) – 一个自回归神经网络,其前向调用返回三个实值张量的元组,其最后一个维度是输入维度,倒数第二个维度等于hidden_units。

  • hidden_units (int) – 在NAF变换中使用的隐藏单元数量 (参见参考文献中的公式(8))

  • activation (string) – 使用的激活函数。可选值为‘ELU’、‘LeakyReLU’、‘sigmoid’或‘tanh’。

参考:

[1] Chin-Wei Huang, David Krueger, Alexandre Lacoste, Aaron Courville. 神经自回归流. [arXiv:1804.00779]

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[source]

对上下文变量的条件,返回类型为NeuralAutoregressive的非条件变换。

domain = IndependentConstraint(Real(), 1)
training: bool

条件平面

class ConditionalPlanar(nn)[source]

基础类:pyro.distributions.conditional.ConditionalTransformModule

使用方程的条件性‘平面’双射变换,

\(\mathbf{y} = \mathbf{x} + \mathbf{u}\tanh(\mathbf{w}^T\mathbf{z}+b)\)

其中 \(\mathbf{x}\) 是维度为 \(D\) 的输入, \(\mathbf{y}\) 是输出,伪参数 \(b\in\mathbb{R}\)\(\mathbf{u}\in\mathbb{R}^D\)\(\mathbf{w}\in\mathbb{R}^D\) 是函数的输出,例如神经网络, 输入 \(z\in\mathbb{R}^{M}\) 表示要条件化的上下文变量。 为了使这是一个可逆变换,强制执行条件 \(\mathbf{w}^T\mathbf{u}>-1\)

ConditionalTransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> from pyro.nn.dense_nn import DenseNN
>>> input_dim = 10
>>> context_dim = 5
>>> batch_size = 3
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [1, input_dim, input_dim]
>>> hypernet = DenseNN(context_dim, [50, 50], param_dims)
>>> transform = ConditionalPlanar(hypernet)
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size])) 

此变换的逆变换没有解析解,因此未实现。然而,在采样期间调用正向操作时,逆变换会被缓存,因此可以使用平面变换绘制的样本进行评分。

Parameters

nn (可调用) – 一个函数,输入上下文变量并输出一个维度为 \((1, D, D)\) 的实值参数三元组。

参考文献: [1] 变分推断与归一化流 [arXiv:1505.05770] Danilo Jimenez Rezende, Shakir Mohamed

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[source]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

条件径向

class ConditionalRadial(nn)[source]

基础类:pyro.distributions.conditional.ConditionalTransformModule

使用方程的条件性“径向”双射变换上下文,

\(\mathbf{y} = \mathbf{x} + \beta h(\alpha,r)(\mathbf{x} - \mathbf{x}_0)\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 而 \(\alpha\in\mathbb{R}^+\)\(\beta\in\mathbb{R}\)、 和 \(\mathbf{x}_0\in\mathbb{R}^D\) 是函数的输出,例如神经网络, 输入 \(z\in\mathbb{R}^{M}\) 表示条件变量。 输入维度为 \(D\)\(r=||\mathbf{x}-\mathbf{x}_0||_2\),且 \(h(\alpha,r)=1/(\alpha+r)\)。 为了使这是一个可逆变换,必须满足条件 \(\beta>-\alpha\)

示例用法:

>>> from pyro.nn.dense_nn import DenseNN
>>> input_dim = 10
>>> context_dim = 5
>>> batch_size = 3
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [input_dim, 1, 1]
>>> hypernet = DenseNN(context_dim, [50, 50], param_dims)
>>> transform = ConditionalRadial(hypernet)
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size])) 

此变换的逆变换没有解析解,因此未实现。然而,在采样期间调用正向操作时,逆变换会被缓存,因此可以使用径向变换绘制的样本进行评分。

Parameters

input_dim (int) – 输入(和输出)变量的维度。

参考文献:

[1] Danilo Jimenez Rezende, Shakir Mohamed. 使用归一化流的变分推断。 [arXiv:1505.05770]

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[source]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

条件样条

class ConditionalSpline(nn, input_dim, count_bins, bound=3.0, order='linear')[source]

基础类:pyro.distributions.conditional.ConditionalTransformModule

线性阶和二次阶元素级有理样条双射的实现(Durkan等,2019;Dolatabadi等,2020),基于额外的上下文变量进行条件化。

有理样条是由两个多项式的比率组成的函数。例如,对于样条的第\(d\)维和第\(k\)段,函数将采用以下形式,

\(y_d = \frac{\alpha^{(k)}(x_d)}{\beta^{(k)}(x_d)},\)

其中 \(\alpha^{(k)}\)\(\beta^{(k)}\) 是两个阶数为 \(d\) 的多项式,其参数是一个函数的输出,例如神经网络,输入为 \(z\\in\\mathbb{R}^{M}\),表示要条件化的上下文变量。对于 \(d=1\),我们称样条为线性的,对于 \(d=2\),则为二次的。样条在指定的边界框 \([-K,K]\times[-K,K]\) 上构建,其他地方使用恒等函数。

有理样条提供了功能灵活性的极佳组合,同时保持了数值稳定的逆运算,其计算和空间复杂度与正向操作相同。这种逐元素的变换允许精确表示复杂的单变量分布。

示例用法:

>>> from pyro.nn.dense_nn import DenseNN
>>> input_dim = 10
>>> context_dim = 5
>>> batch_size = 3
>>> count_bins = 8
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [input_dim * count_bins, input_dim * count_bins,
... input_dim * (count_bins - 1), input_dim * count_bins]
>>> hypernet = DenseNN(context_dim, [50, 50], param_dims)
>>> transform = ConditionalSpline(hypernet, input_dim, count_bins)
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size])) 
Parameters
  • input_dim (int) – 输入向量的维度。这是必需的,以便我们知道要存储多少参数。

  • count_bins (int) – 组成样条的段数。

  • bound (float) – 确定样条边界框的量 \(K\)\([-K,K]\times[-K,K]\)

  • order (string) – 其中之一是 ['linear', 'quadratic'],用于指定样条的顺序。

参考文献:

康纳·德坎,阿图尔·贝卡索夫,伊恩·默里,乔治·帕帕马卡里奥斯。神经样条流。NeurIPS 2019。

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. 使用线性有理样条的可逆生成建模。AISTATS 2020。

bijective = True
codomain = Real()
condition(context)[source]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = Real()
training: bool

条件样条自回归

class ConditionalSplineAutoregressive(input_dim, autoregressive_nn, **kwargs)[source]

基础类:pyro.distributions.conditional.ConditionalTransformModule

一种自回归层的实现,使用线性和二次阶有理样条双射(Durkan等,2019;Dolatabadi等,2020),并在额外的上下文变量上进行条件化。有理样条是由两多项式之比组成的函数(参见Spline)。

自回归层使用变换,

\(y_d = g_{\theta_d}(x_d)\ \ \ d=1,2,\ldots,D\)

其中 \(\mathbf{x}=(x_1,x_2,\ldots,x_D)\) 是输入, \(\mathbf{y}=(y_1,y_2,\ldots,y_D)\) 是输出,\(g_{\theta_d}\) 是 一个具有参数 \(\theta_d\) 的逐元素有理单调样条,并且 \(\theta=(\theta_1,\theta_2,\ldots,\theta_D)\) 是一个条件自回归神经网络的输出,该网络输入 \(\mathbf{x}\) 并以 上下文变量 \(\mathbf{z}\) 为条件。

示例用法:

>>> from pyro.nn import ConditionalAutoRegressiveNN
>>> input_dim = 10
>>> count_bins = 8
>>> context_dim = 5
>>> batch_size = 3
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> hidden_dims = [input_dim * 10, input_dim * 10]
>>> param_dims = [count_bins, count_bins, count_bins - 1, count_bins]
>>> hypernet = ConditionalAutoRegressiveNN(input_dim, context_dim, hidden_dims,
... param_dims=param_dims)
>>> transform = ConditionalSplineAutoregressive(input_dim, hypernet,
... count_bins=count_bins)
>>> pyro.module("my_transform", transform)  
>>> z = torch.rand(batch_size, context_dim)
>>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,
... [transform]).condition(z)
>>> flow_dist.sample(sample_shape=torch.Size([batch_size]))  
Parameters
  • input_dim (int) – 输入向量的维度。尽管是逐元素操作,但这是必需的,以便我们知道要存储多少参数。

  • autoregressive_nn (callable) – 一个自回归神经网络,其前向调用返回样条参数的元组

  • count_bins (int) – 组成样条的段数。

  • bound (float) – 确定样条边界框的量 \(K\)\([-K,K]\times[-K,K]\)

  • order (string) – 其中之一是 ['linear', 'quadratic'],用于指定样条的顺序。

参考文献:

康纳·德坎,阿图尔·贝卡索夫,伊恩·默里,乔治·帕帕马卡里奥斯。神经样条流。NeurIPS 2019。

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. 使用线性有理样条的可逆生成建模。AISTATS 2020。

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[source]

上下文变量的条件,返回类型为SplineAutoregressive的非条件变换。

domain = IndependentConstraint(Real(), 1)
training: bool

条件转换模块

class ConditionalTransformModule(*args, **kwargs)[源代码]

基础类:pyro.distributions.conditional.ConditionalTransform, torch.nn.modules.module.Module

具有可学习参数的条件变换,例如归一化流,应该继承自这个类,而不是ConditionalTransform,这样它们也是Module的子类,并继承该类的所有有用方法。

property inv: pyro.distributions.conditional.ConditionalTransformModule
training: bool

广义通道置换

class GeneralizedChannelPermute(channels=3, permutation=None)[source]

基础类:pyro.distributions.transforms.generalized_channel_permute.ConditionedGeneralizedChannelPermute, pyro.distributions.torch_transform.TransformModule

一种双射,它推广了对一批2D图像通道的排列,格式为\([\ldots,C,H,W]\)。具体来说,这个变换执行以下操作,

\(\mathbf{y} = \text{torch.nn.functional.conv2d}(\mathbf{x}, W)\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 而 \(W\sim C\times C\times 1\times 1\) 是用于1x1卷积的滤波器矩阵,具有 \(C\) 个输入和输出通道。

忽略最后两个维度,\(W\) 被限制为矩阵乘积,

\(W = PLU\)

其中 \(P\sim C\times C\) 是通道维度上的置换矩阵,\(L\sim C\times C\) 是对角线上为1的下三角矩阵,\(U\sim C\times C\) 是上三角矩阵。\(W\) 被初始化为一个随机正交矩阵。然后,\(P\) 被固定,可学习的参数设置为 \(L,U\)

输入 \(\mathbf{x}\) 和输出 \(\mathbf{y}\) 都具有形状 […,C,H,W],其中 C 是在初始化时设置的通道数。

此操作在[1]中为Glow归一化流引入,也被称为1x1可逆卷积。它在其他著名的工作中出现,如[2,3],并对应于TensorFlow概率中的tfp.bijectors.MatvecLU类。

示例用法:

>>> channels = 3
>>> base_dist = dist.Normal(torch.zeros(channels, 32, 32),
... torch.ones(channels, 32, 32))
>>> inv_conv = GeneralizedChannelPermute(channels=channels)
>>> flow_dist = dist.TransformedDistribution(base_dist, [inv_conv])
>>> flow_dist.sample()  
Parameters

channels (int) – 输入中的通道维度数量。

[1] Diederik P. Kingma, Prafulla Dhariwal. Glow: 使用可逆1x1卷积的生成流. [arXiv:1807.03039]

[2] Ryan Prenger, Rafael Valle, Bryan Catanzaro. WaveGlow: 一种基于流的生成网络用于语音合成。 [arXiv:1811.00002]

[3] 康纳·德坎,阿图尔·贝卡索夫,伊恩·默里,乔治·帕帕马卡里奥斯。神经样条流。[arXiv:1906.04032]

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 3)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 3)

Householder

class Householder(input_dim, count_transforms=1)[source]

基础类:pyro.distributions.transforms.householder.ConditionedHouseholder, pyro.distributions.torch_transform.TransformModule

表示Householder双射变换的多次应用。单个Householder变换的形式为,

\(\mathbf{y} = (I - 2*\frac{\mathbf{u}\mathbf{u}^T}{||\mathbf{u}||^2})\mathbf{x}\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 可学习的参数是 \(\mathbf{u}\in\mathbb{R}^D\),用于输入 维度 \(D\)

变换表示\(\mathbf{x}\)通过原点且法向量为\(\mathbf{u}\)的平面的反射。

\(D\) 次应用这种变换能够将标准的独立同分布高斯噪声转换为具有任意协方差矩阵的高斯变量。使用 \(K 次变换,可以通过秩为 \(K\) 的线性变换来近似一个全秩高斯分布。

TransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> transform = Householder(10, count_transforms=5)
>>> pyro.module("my_transform", p) 
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  
Parameters
  • input_dim (int) – 输入(和输出)变量的维度。

  • count_transforms (int) – 要应用的Householder变换的次数。

参考文献:

[1] Jakub M. Tomczak, Max Welling. 使用Householder Flow改进变分自编码器。 [arXiv:1611.09630]

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
reset_parameters()[source]
volume_preserving = True

矩阵指数

class MatrixExponential(input_dim, iterations=8, normalization='none', bound=None)[source]

基础类:pyro.distributions.transforms.matrix_exponential.ConditionedMatrixExponential, pyro.distributions.torch_transform.TransformModule

一个密集矩阵指数双射变换(Hoogeboom 等人,2020 年)具有方程,

\(\mathbf{y} = \exp(M)\mathbf{x}\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, \(\exp(\cdot)\) 表示矩阵指数,可学习的 参数是 \(M\in\mathbb{R}^D\times\mathbb{R}^D\),用于输入维度 \(D\)。通常,\(M\) 不需要是可逆的。

由于矩阵指数的良好数学特性,该变换具有精确的逆变换和对数行列式-雅可比行列式,其时间复杂度为\(O(D)\)。正向和反向操作都通过截断的幂级数进行近似。为了数值稳定性,可以通过normalization关键字参数限制\(M\)的范数。

示例用法:

>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> transform = MatrixExponential(10)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  
Parameters
  • input_dim (int) – 输入(和输出)变量的维度。

  • iterations (int) – 用于近似矩阵指数的截断幂级数中的项数。

  • normalization (string) – 选择应用于权重矩阵的归一化类型之一 [‘none’, ‘weight’, ‘spectral’]weight 对应于权重归一化(Salimans 和 Kingma,2016),而 spectral 对应于谱归一化(Miyato 等人,2018)。

  • bound (float) – 当通过 normalization 参数选择权重或谱范数正则化时,这是一个界限。此值的较低值意味着需要更少的截断幂级数项来近似矩阵指数的精确值。

参考文献:

[1] Emiel Hoogeboom, Victor Garcia Satorras, Jakub M. Tomczak, Max Welling. The

卷积指数和广义西尔维斯特流。[arXiv:2006.01910]

[2] Tim Salimans, Diederik P. Kingma. Weight Normalization: A Simple

重新参数化以加速深度神经网络的训练。 [arXiv:1602.07868]

[3] Takeru Miyato, Toshiki Kataoka, Masanori Koyama, Yuichi Yoshida. Spectral

生成对抗网络的归一化。ICLR 2018。

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
reset_parameters()[source]

神经自回归

class NeuralAutoregressive(autoregressive_nn, hidden_units=16, activation='sigmoid')[源代码]

基础类:pyro.distributions.torch_transform.TransformModule

深度神经自回归流(NAF)双射变换的“IAF风味”实现,可用于采样和评分从中抽取的样本(但不能用于任意样本)。

示例用法:

>>> from pyro.nn import AutoRegressiveNN
>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> arn = AutoRegressiveNN(10, [40], param_dims=[16]*3)
>>> transform = NeuralAutoregressive(arn, hidden_units=16)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  

逆操作未实现。这需要数值反演,例如使用根查找方法 - 这是未来实现的一个可能性。

Parameters
  • autoregressive_nn (nn.Module) – 一个自回归神经网络,其前向调用返回三个实值张量的元组,其最后一个维度是输入维度,倒数第二个维度等于hidden_units。

  • hidden_units (int) – 在NAF变换中使用的隐藏单元数量 (参见参考文献中的公式(8))

  • activation (string) – 使用的激活函数。可选值为‘ELU’、‘LeakyReLU’、‘sigmoid’或‘tanh’。

参考:

[1] Chin-Wei Huang, David Krueger, Alexandre Lacoste, Aaron Courville. 神经自回归流. [arXiv:1804.00779]

autoregressive = True
bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
eps = 1e-08
log_abs_det_jacobian(x, y)[来源]

计算对数雅可比行列式的逐元素行列式

平面

class Planar(input_dim)[source]

基础类:pyro.distributions.transforms.planar.ConditionedPlanar, pyro.distributions.torch_transform.TransformModule

一个具有方程的‘平面’双射变换,

\(\mathbf{y} = \mathbf{x} + \mathbf{u}\tanh(\mathbf{w}^T\mathbf{z}+b)\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 可学习的参数是 \(b\in\mathbb{R}\)\(\mathbf{u}\in\mathbb{R}^D\)\(\mathbf{w}\in\mathbb{R}^D\) 对于 输入维度 \(D\)。为了使这是一个可逆变换, 条件 \(\mathbf{w}^T\mathbf{u}>-1\) 被强制执行。

TransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> transform = Planar(10)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  

此变换的逆变换没有解析解,因此未实现。然而,在采样期间调用正向操作时,逆变换会被缓存,因此可以使用平面变换绘制的样本进行评分。

Parameters

input_dim (int) – 输入(和输出)变量的维度。

参考文献:

[1] Danilo Jimenez Rezende, Shakir Mohamed. 使用归一化流的变分推断。 [arXiv:1505.05770]

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
reset_parameters()[source]

多项式

class Polynomial(autoregressive_nn, input_dim, count_degree, count_sum)[source]

基础类:pyro.distributions.torch_transform.TransformModule

如Jaini等人(2019)所述的自回归双射变换,应用以下逐元素方程,

\(y_n = c_n + \int^{x_n}_0\sum^K_{k=1}\left(\sum^R_{r=0}a^{(n)}_{r,k}u^r\right)du\)

其中 \(x_n\)\(n\)\(n\)\(\left\{a^{(n)}_{r,k}\in\mathbb{R}\right\}\) 是可学习的参数, 这些参数是自回归神经网络输入 \(x_{\prec n}={x_1,x_2,\ldots,x_{n-1}}\) 的输出。

TransformedDistribution 一起,这提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> from pyro.nn import AutoRegressiveNN
>>> input_dim = 10
>>> count_degree = 4
>>> count_sum = 3
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [(count_degree + 1)*count_sum]
>>> arn = AutoRegressiveNN(input_dim, [input_dim*10], param_dims)
>>> transform = Polynomial(arn, input_dim=input_dim, count_degree=count_degree,
... count_sum=count_sum)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  

此变换的逆变换没有解析解,因此未实现。然而,在采样期间调用正向操作时,逆变换会被缓存,因此可以使用多项式变换绘制的样本进行评分。

Parameters
  • autoregressive_nn (nn.Module) – 一个自回归神经网络,其前向调用返回一个大小为 (batch_size, (count_degree+1)*count_sum, input_dim) 的实值张量

  • count_degree (int) – 用于每个元素变换的多项式的次数。

  • count_sum (int) – 在每个元素变换中要相加的多项式数量。

参考文献:

[1] Priyank Jaini, Kira A. Shelby, Yaoliang Yu. 平方和多项式流。 [arXiv:1905.02325]

autoregressive = True
bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
log_abs_det_jacobian(x, y)[来源]

计算对数雅可比行列式的逐元素行列式

reset_parameters()[来源]

径向

class Radial(input_dim)[source]

基础类:pyro.distributions.transforms.radial.ConditionedRadial, pyro.distributions.torch_transform.TransformModule

使用方程的‘径向’双射变换,

\(\mathbf{y} = \mathbf{x} + \beta h(\alpha,r)(\mathbf{x} - \mathbf{x}_0)\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 可学习的参数是 \(\alpha\in\mathbb{R}^+\)\(\beta\in\mathbb{R}\)\(\mathbf{x}_0\in\mathbb{R}^D\),对于输入 维度 \(D\)\(r=||\mathbf{x}-\mathbf{x}_0||_2\)\(h(\alpha,r)=1/(\alpha+r)\)。为了使这是一个可逆变换, 条件 \(\beta>-\alpha\) 被强制执行。

示例用法:

>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> transform = Radial(10)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  

此变换的逆变换没有解析解,因此未实现。然而,在采样期间调用正向操作时,逆变换会被缓存,因此可以使用径向变换绘制的样本进行评分。

Parameters

input_dim (int) – 输入(和输出)变量的维度。

参考文献:

[1] Danilo Jimenez Rezende, Shakir Mohamed. 使用归一化流的变分推断。 [arXiv:1505.05770]

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
reset_parameters()[source]

样条

class Spline(input_dim, count_bins=8, bound=3.0, order='linear')[源代码]

基础类:pyro.distributions.transforms.spline.ConditionedSpline, pyro.distributions.torch_transform.TransformModule

线性阶和二次阶元素级有理样条双射的实现(Durkan等,2019;Dolatabadi等,2020)。有理样条是由两多项式之比组成的函数。例如,对于样条的第\(d\)维和第\(k\)段,函数将采用以下形式,

\(y_d = \frac{\alpha^{(k)}(x_d)}{\beta^{(k)}(x_d)},\)

其中 \(\alpha^{(k)}\)\(\beta^{(k)}\) 是两个阶数为 \(d\) 的多项式。对于 \(d=1\),我们称样条为线性的,对于 \(d=2\),则为二次的。样条是在指定的边界框 \([-K,K]\times[-K,K]\) 上构建的,其他地方使用恒等函数。

有理样条提供了功能灵活性的极佳组合,同时保持了数值稳定的逆运算,其计算和空间复杂度与正向操作相同。这种逐元素的变换允许精确表示复杂的单变量分布。

示例用法:

>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> transform = Spline(10, count_bins=4, bound=3.)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  
Parameters
  • input_dim (int) – 输入向量的维度。这是必需的,以便我们知道要存储多少参数。

  • count_bins (int) – 组成样条的段数。

  • bound (float) – 确定样条边界框的量 \(K\)\([-K,K]\times[-K,K]\)

  • order (string) – 其中之一是 ['linear', 'quadratic'],用于指定样条的顺序。

参考文献:

康纳·德坎,阿图尔·贝卡索夫,伊恩·默里,乔治·帕帕马卡里奥斯。神经样条流。NeurIPS 2019。

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. 使用线性有理样条的可逆生成建模。AISTATS 2020。

bijective = True
codomain: torch.distributions.constraints.Constraint = Real()
domain: torch.distributions.constraints.Constraint = Real()

SplineAutoregressive

class SplineAutoregressive(input_dim, autoregressive_nn, count_bins=8, bound=3.0, order='linear')[source]

基础类:pyro.distributions.torch_transform.TransformModule

使用线性和二次阶有理样条双射的自回归层实现(Durkan等,2019;Dolatabadi等,2020)。有理样条是由两多项式之比组成的函数(参见Spline)。

自回归层使用变换,

\(y_d = g_{\theta_d}(x_d)\ \ \ d=1,2,\ldots,D\)

其中 \(\mathbf{x}=(x_1,x_2,\ldots,x_D)\) 是输入, \(\mathbf{y}=(y_1,y_2,\ldots,y_D)\) 是输出,\(g_{\theta_d}\) 是 一个具有参数 \(\theta_d\) 的逐元素有理单调样条,并且 \(\theta=(\theta_1,\theta_2,\ldots,\theta_D)\) 是一个自回归神经网络的输出,输入为 \(\mathbf{x}\)

示例用法:

>>> from pyro.nn import AutoRegressiveNN
>>> input_dim = 10
>>> count_bins = 8
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> hidden_dims = [input_dim * 10, input_dim * 10]
>>> param_dims = [count_bins, count_bins, count_bins - 1, count_bins]
>>> hypernet = AutoRegressiveNN(input_dim, hidden_dims, param_dims=param_dims)
>>> transform = SplineAutoregressive(input_dim, hypernet, count_bins=count_bins)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  
Parameters
  • input_dim (int) – 输入向量的维度。尽管是逐元素操作,但这是必需的,以便我们知道要存储多少参数。

  • autoregressive_nn (callable) – 一个自回归神经网络,其前向调用返回样条参数的元组

  • count_bins (int) – 组成样条的段数。

  • bound (float) – 确定样条边界框的量 \(K\)\([-K,K]\times[-K,K]\)

  • order (string) – 其中之一是 ['linear', 'quadratic'],用于指定样条的顺序。

参考文献:

康纳·德坎,阿图尔·贝卡索夫,伊恩·默里,乔治·帕帕马卡里奥斯。神经样条流。NeurIPS 2019。

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. 使用线性有理样条的可逆生成建模。AISTATS 2020。

autoregressive = True
bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
log_abs_det_jacobian(x, y)[来源]

计算对数雅可比行列式的逐元素行列式

SplineCoupling

class SplineCoupling(input_dim, split_dim, hypernet, count_bins=8, bound=3.0, order='linear', identity=False)[source]

基础类:pyro.distributions.torch_transform.TransformModule

一种使用线性和二次阶有理样条双射的耦合层实现(Durkan等,2019;Dolatabadi等,2020)。有理样条是由两多项式之比组成的函数(参见Spline)。

样条耦合层使用变换,

\(\mathbf{y}_{1:d} = g_\theta(\mathbf{x}_{1:d})\) \(\mathbf{y}_{(d+1):D} = h_\phi(\mathbf{x}_{(d+1):D};\mathbf{x}_{1:d})\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, 例如 \(\mathbf{x}_{1:d}\) 表示输入的前 \(d\) 个元素, \(g_\theta\) 是恒等函数或具有参数 \(\theta\) 的逐元素有理单调样条, 而 \(h_\phi\) 是一个条件逐元素样条,基于前 \(d\) 个元素进行条件化。

示例用法:

>>> from pyro.nn import DenseNN
>>> input_dim = 10
>>> split_dim = 6
>>> count_bins = 8
>>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))
>>> param_dims = [(input_dim - split_dim) * count_bins,
... (input_dim - split_dim) * count_bins,
... (input_dim - split_dim) * (count_bins - 1),
... (input_dim - split_dim) * count_bins]
>>> hypernet = DenseNN(split_dim, [10*input_dim], param_dims)
>>> transform = SplineCoupling(input_dim, split_dim, hypernet)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  
Parameters
  • input_dim (int) – 输入向量的维度。尽管是逐元素操作,但这是必需的,以便我们知道要存储多少参数。

  • split_dim – 从零开始索引的维度 \(d\),用于执行输入/输出分割以进行转换。

  • hypernet (可调用的) – 一个神经网络,其前向调用返回样条参数的元组(参见 ConditionalSpline)。

  • count_bins (int) – 组成样条的段数。

  • bound (float) – 确定样条边界框的量 \(K\)\([-K,K]\times[-K,K]\)

  • order (string) – 其中之一是 ['linear', 'quadratic'],用于指定样条的顺序。

参考文献:

康纳·德坎,阿图尔·贝卡索夫,伊恩·默里,乔治·帕帕马卡里奥斯。神经样条流。NeurIPS 2019。

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. 使用线性有理样条的可逆生成建模。AISTATS 2020。

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
log_abs_det_jacobian(x, y)[来源]

计算对数雅可比行列式的逐元素行列式

Sylvester

class Sylvester(input_dim, count_transforms=1)[source]

基础类:pyro.distributions.transforms.householder.Householder

Householder变体的Sylvester双射变换的实现(Van den Berg等人,2018),

\(\mathbf{y} = \mathbf{x} + QR\tanh(SQ^T\mathbf{x}+\mathbf{b})\)

其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出, \(R,S\sim D\times D\) 是输入维度 \(D\) 的上三角矩阵, \(Q\sim D\times D\) 是一个正交矩阵,而 \(\mathbf{b}\sim D\) 是可学习的偏置项。

Sylvester变换是Planar的推广。在Sylvester变换的Householder类型中,\(Q\)的正交性通过将其表示为Householder变换的乘积来强制实现。

TransformedDistribution一起,它提供了一种创建更丰富的变分近似的方法。

示例用法:

>>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))
>>> transform = Sylvester(10, count_transforms=4)
>>> pyro.module("my_transform", transform)  
>>> flow_dist = dist.TransformedDistribution(base_dist, [transform])
>>> flow_dist.sample()  
    tensor([-0.4071, -0.5030,  0.7924, -0.2366, -0.2387, -0.1417,  0.0868,
            0.1389, -0.4629,  0.0986])

此变换的逆变换没有解析解,因此未实现。然而,在采样期间调用正向操作时,逆变换会被缓存,因此可以使用Sylvester变换绘制的样本进行评分。

参考文献:

[1] Rianne van den Berg, Leonard Hasenclever, Jakub M. Tomczak, Max Welling. Sylvester 归一化流用于变分推断。UAI 2018.

Q(x)[source]
R()[source]
S()[source]
bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
dtanh_dx(x)[source]
log_abs_det_jacobian(x, y)[source]

计算对数雅可比行列式的逐元素行列式

reset_parameters2()[source]
training: bool

转换模块

class TransformModule(*args, **kwargs)[source]

基础类:torch.distributions.transforms.Transform, torch.nn.modules.module.Module

具有可学习参数的变换,例如归一化流,应该继承自这个类而不是Transform,以便它们也是nn.Module的子类,并继承该类的所有有用方法。

codomain: torch.distributions.constraints.Constraint
domain: torch.distributions.constraints.Constraint

组合变换模块

class ComposeTransformModule(parts, cache_size=0)[源代码]

基础类: torch.distributions.transforms.ComposeTransform, torch.nn.modules.container.ModuleList

这允许我们以与ComposeTransform相同的方式使用TransformModule列表。这是必要的,以便在PyroModule实例中使用时,转换参数会自动由Pyro的参数存储注册。

with_cache(cache_size=1)[source]

转换工厂

每个TransformTransformModule都包含一个相应的小写辅助函数,该函数至少输入变换的输入维度,并可能输入额外的参数以直观地自定义变换。这些辅助函数的目的是向用户隐藏变换是否需要构建超网络,如果需要,则隐藏该超网络的输入和输出维度。

迭代

iterated(repeats, base_fn, *args, **kwargs)[source]

辅助函数,用于使用ComposeTransformModule组合一系列具有潜在可学习参数的双射变换。

Parameters
  • repeats – 重复变换的次数。

  • base_fn – 用于构造双射变换的函数。

  • argsbase_fn 接受的参数。

  • kwargs – 由base_fn接收的关键字参数。

Returns

TransformModule 的实例。

仿射自回归

affine_autoregressive(input_dim, hidden_dims=None, **kwargs)[source]

一个辅助函数,用于创建一个AffineAutoregressive对象,该对象负责构建具有正确输入/输出维度的自回归网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • hidden_dims (list[int]) – 自回归网络所需的隐藏维度。 默认使用 [3*input_dim + 1]

  • log_scale_min_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最小值

  • log_scale_max_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最大值

  • sigmoid_bias (float) – 在使用稳定变换时,添加到输入的对数几率的一个项。

  • stable (bool) – 当为真时,使用转换的“稳定”版本(见上文)。

仿射耦合

affine_coupling(input_dim, hidden_dims=None, split_dim=None, dim=- 1, **kwargs)[source]

一个辅助函数,用于创建一个AffineCoupling对象,该对象负责构建具有正确输入/输出维度的密集网络。

Parameters
  • input_dim (int) – 输入变量的维度,用于置换。请注意,当dim < -1时,这必须是一个对应于事件形状的元组。

  • hidden_dims (list[int]) – 密集网络所需的隐藏维度。默认使用 [10*input_dim]

  • split_dim (int) – 用于耦合变换的输入分割维度。默认使用 input_dim // 2

  • dim (int) – 要在其上分割的张量维度。此值必须为负数,并将事件维度定义为 abs(dim)

  • log_scale_min_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最小值

  • log_scale_max_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最大值

批归一化

batchnorm(input_dim, **kwargs)[source]

一个辅助函数,用于创建一个BatchNorm对象,以与其他辅助函数保持一致。

Parameters
  • input_dim (int) – 输入变量的维度

  • momentum (float) – 用于更新移动平均值的动量参数

  • epsilon (float) – 添加到方差中的小数值,以确保数值稳定性

block_autoregressive

block_autoregressive(input_dim, **kwargs)[源代码]

一个辅助函数,用于创建一个BlockAutoregressive对象,以与其他辅助函数保持一致。

Parameters
  • input_dim (int) – 输入变量的维度

  • hidden_factors (list) – 隐藏层 i 每输入维度有 hidden_factors[i] 个隐藏单元。这对应于 De Cao 等人 (2019) 中的 \(a\)\(b\)。hidden_factors 的元素必须是整数。

  • activation (string) – 使用的激活函数。可选值为‘ELU’、‘LeakyReLU’、‘sigmoid’或‘tanh’。

  • residual (string) – 使用的残差连接类型。选项有“None”, “normal”表示\(\mathbf{y}+f(\mathbf{y})\),而“gated”表示 \(\alpha\mathbf{y} + (1 - \alpha\mathbf{y})\),其中\(\alpha\)是可学习的参数。

条件仿射自回归

conditional_affine_autoregressive(input_dim, context_dim, hidden_dims=None, **kwargs)[source]

一个辅助函数,用于创建一个ConditionalAffineAutoregressive对象,该对象负责构建具有正确输入/输出维度的密集网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 密集网络所需的隐藏维度。默认使用 [10*input_dim]

  • log_scale_min_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最小值

  • log_scale_max_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最大值

  • sigmoid_bias (float) – 在使用稳定变换时,添加到输入的对数几率的一个项。

  • stable (bool) – 当为真时,使用转换的“稳定”版本(见上文)。

条件仿射耦合

conditional_affine_coupling(input_dim, context_dim, hidden_dims=None, split_dim=None, dim=- 1, **kwargs)[源代码]

一个辅助函数,用于创建一个ConditionalAffineCoupling对象,该对象负责构建具有正确输入/输出维度的密集网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 密集网络所需的隐藏维度。默认使用 [10*input_dim]

  • split_dim (int) – 用于耦合变换的输入分割维度。默认使用 input_dim // 2

  • dim (int) – 要在其上分割的张量维度。此值必须为负数,并将事件维度定义为 abs(dim)

  • log_scale_min_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最小值

  • log_scale_max_clip (float) – 用于从自回归神经网络中裁剪log(scale)的最大值

条件广义通道置换

conditional_generalized_channel_permute(context_dim, channels=3, hidden_dims=None)[source]

一个辅助函数,用于创建一个 ConditionalGeneralizedChannelPermute 对象,以与其他辅助函数保持一致。

Parameters

channels (int) – 输入中的通道维度数量。

条件户主

conditional_householder(input_dim, context_dim, hidden_dims=None, count_transforms=1)[source]

一个辅助函数,用于创建一个ConditionalHouseholder对象,该对象负责构建具有正确输入/输出维度的密集网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 密集网络所需的隐藏维度。默认使用 [input_dim * 10, input_dim * 10]

条件矩阵指数

conditional_matrix_exponential(input_dim, context_dim, hidden_dims=None, iterations=8, normalization='none', bound=None)[source]

一个辅助函数,用于创建一个ConditionalMatrixExponential对象,以与其他辅助函数保持一致。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 密集网络所需的隐藏维度。默认使用 [input_dim * 10, input_dim * 10]

  • iterations (int) – 用于近似矩阵指数的截断幂级数中的项数。

  • normalization (string) – 选择应用于权重矩阵的归一化类型之一 [‘none’, ‘weight’, ‘spectral’]weight 对应于权重归一化(Salimans 和 Kingma,2016),而 spectral 对应于谱归一化(Miyato 等人,2018)。

  • bound (float) – 当通过 normalization 参数选择权重或谱范数正则化时,这是一个界限。此值的较低值意味着需要更少的截断幂级数项来近似矩阵指数的精确值。

条件神经自回归

conditional_neural_autoregressive(input_dim, context_dim, hidden_dims=None, activation='sigmoid', width=16)[source]

一个辅助函数,用于创建一个ConditionalNeuralAutoregressive对象,该对象负责构建具有正确输入/输出维度的自回归网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 自回归网络所需的隐藏维度。 默认使用 [3*input_dim + 1]

  • activation (string) – 使用的激活函数。可选值为‘ELU’、‘LeakyReLU’、‘sigmoid’或‘tanh’。

  • width (int) – 变换中“多层感知器”的宽度(参见论文)。默认为16

条件平面

conditional_planar(input_dim, context_dim, hidden_dims=None)[source]

一个辅助函数,用于创建一个ConditionalPlanar对象,该对象负责构建具有正确输入/输出维度的密集网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 密集网络所需的隐藏维度。默认使用 [input_dim * 10, input_dim * 10]

条件径向

conditional_radial(input_dim, context_dim, hidden_dims=None)[源代码]

一个辅助函数,用于创建一个ConditionalRadial对象,该对象负责构建具有正确输入/输出维度的密集网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 密集网络所需的隐藏维度。默认使用 [input_dim * 10, input_dim * 10]

条件样条

conditional_spline(input_dim, context_dim, hidden_dims=None, count_bins=8, bound=3.0, order='linear')[来源]

一个辅助函数,用于创建一个ConditionalSpline对象,该对象负责构建具有正确输入/输出维度的密集网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 密集网络所需的隐藏维度。默认使用 [input_dim * 10, input_dim * 10]

  • count_bins (int) – 组成样条的段数。

  • bound (float) – 确定样条边界框的量 \(K\)\([-K,K] imes[-K,K]\)

  • order (string) – 其中之一是 ['linear', 'quadratic'],用于指定样条的顺序。

条件样条自回归

conditional_spline_autoregressive(input_dim, context_dim, hidden_dims=None, count_bins=8, bound=3.0, order='linear')[source]

一个辅助函数,用于创建一个ConditionalSplineAutoregressive对象,该对象负责构建具有正确输入/输出维度的自回归网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 自回归网络所需的隐藏维度。 默认使用 [input_dim * 10, input_dim * 10]

  • count_bins (int) – 组成样条的段数。

  • bound (float) – 确定样条边界框的量 \(K\)\([-K,K]\times[-K,K]\)

  • order (string) – 其中之一是 ['linear', 'quadratic'],用于指定样条的顺序。

elu

elu()[source]

一个辅助函数,用于创建一个ELUTransform对象,以与其他辅助函数保持一致。

广义通道置换

generalized_channel_permute(**kwargs)[source]

一个辅助函数,用于创建一个GeneralizedChannelPermute对象,以保持与其他辅助函数的一致性。

Parameters

channels (int) – 输入中的通道维度数量。

户主

householder(input_dim, count_transforms=None)[source]

一个辅助函数,用于创建一个Householder对象,以保持与其他辅助函数的一致性。

Parameters
  • input_dim (int) – 输入变量的维度

  • count_transforms (int) – 要应用的Householder变换的次数。

leaky_relu

leaky_relu()[source]

一个辅助函数,用于创建一个LeakyReLUTransform对象,以保持与其他辅助函数的一致性。

矩阵指数

matrix_exponential(input_dim, iterations=8, normalization='none', bound=None)[source]

一个辅助函数,用于创建一个MatrixExponential对象,以与其他辅助函数保持一致。

Parameters
  • input_dim (int) – 输入变量的维度

  • iterations (int) – 用于近似矩阵指数的截断幂级数中的项数。

  • normalization (string) – 选择应用于权重矩阵的归一化类型之一 [‘none’, ‘weight’, ‘spectral’]weight 对应于权重归一化(Salimans 和 Kingma,2016),而 spectral 对应于谱归一化(Miyato 等人,2018)。

  • bound (float) – 当通过 normalization 参数选择权重或谱范数正则化时,这是一个界限。此值的较低值意味着需要更少的截断幂级数项来近似矩阵指数的精确值。

神经自回归

neural_autoregressive(input_dim, hidden_dims=None, activation='sigmoid', width=16)[source]

一个辅助函数,用于创建一个NeuralAutoregressive对象,该对象负责构建具有正确输入/输出维度的自回归网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • hidden_dims (list[int]) – 自回归网络所需的隐藏维度。 默认使用 [3*input_dim + 1]

  • activation (string) – 使用的激活函数。可选值为‘ELU’、‘LeakyReLU’、‘sigmoid’或‘tanh’。

  • width (int) – 变换中“多层感知器”的宽度(参见论文)。默认为16

排列

permute(input_dim, permutation=None, dim=- 1)[source]

一个辅助函数,用于创建一个Permute对象,以保持与其他辅助函数的一致性。

Parameters
  • input_dim (int) – 输入变量的维度,用于置换。请注意,当dim < -1时,这必须是一个对应于事件形状的元组。

  • permutation (torch.LongTensor) – 表示排列的整数索引的Torch张量。默认为随机排列。

  • dim (int) – 要置换的张量维度。该值必须为负数,并将事件维度定义为 abs(dim)

平面

planar(input_dim)[source]

一个辅助函数,用于创建一个Planar对象,以与其他辅助函数保持一致。

Parameters

input_dim (int) – 输入变量的维度

多项式

polynomial(input_dim, hidden_dims=None)[source]

一个辅助函数,用于创建一个Polynomial对象,该对象负责构建具有正确输入/输出维度的自回归网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • hidden_dims – 自回归网络所需的隐藏维度。默认使用 [input_dim * 10]

径向

radial(input_dim)[source]

一个辅助函数,用于创建一个Radial对象,以与其他辅助函数保持一致。

Parameters

input_dim (int) – 输入变量的维度

样条

spline(input_dim, **kwargs)[源代码]

一个辅助函数,用于创建一个Spline对象,以保持与其他辅助函数的一致性。

Parameters

input_dim (int) – 输入变量的维度

样条自回归

spline_autoregressive(input_dim, hidden_dims=None, count_bins=8, bound=3.0, order='linear')[源代码]

一个辅助函数,用于创建一个SplineAutoregressive对象,该对象负责构建具有正确输入/输出维度的自回归网络。

Parameters
  • input_dim (int) – 输入变量的维度

  • hidden_dims (list[int]) – 自回归网络所需的隐藏维度。 默认使用 [3*input_dim + 1]

  • count_bins (int) – 组成样条的段数。

  • bound (float) – 确定样条边界框的量 \(K\)\([-K,K]\times[-K,K]\)

  • order (string) – 其中之一是 ['linear', 'quadratic'],用于指定样条的顺序。

样条耦合

spline_coupling(input_dim, split_dim=None, hidden_dims=None, count_bins=8, bound=3.0)[source]

一个辅助函数,用于创建一个SplineCoupling对象,以与其他辅助函数保持一致。

Parameters

input_dim (int) – 输入变量的维度

西尔维斯特

sylvester(input_dim, count_transforms=None)[source]

一个辅助函数,用于创建一个Sylvester对象,以与其他辅助函数保持一致。

Parameters
  • input_dim (int) – 输入变量的维度

  • count_transforms – 要应用的Sylvester操作的数量。默认为 input_dim // 2 + 1。 :type count_transforms: int

约束条件

Pyro的约束库扩展了 torch.distributions.constraints.

约束条件

torch.distributions.constraints.Constraint 的别名

布尔值

torch.distributions.constraints.boolean 的别名

torch.distributions.constraints.cat 的别名

corr_cholesky

torch.distributions.constraints.corr_cholesky 的别名

corr_cholesky_constraint

torch.distributions.constraints.corr_cholesky_constraint 的别名

相关矩阵

class _CorrMatrix[源代码]

约束为相关矩阵。

依赖

torch.distributions.constraints.dependent 的别名

dependent_property

torch.distributions.constraints.dependent_property 的别名

大于

torch.distributions.constraints.greater_than 的别名

大于等于

torch.distributions.constraints.greater_than_eq 的别名

半开区间

torch.distributions.constraints.half_open_interval 的别名

独立的

torch.distributions.constraints.independent 的别名

整数

class _Integer[source]

限制为整数。

整数区间

torch.distributions.constraints.integer_interval 的别名

间隔

torch.distributions.constraints.interval 的别名

is_dependent

torch.distributions.constraints.is_dependent 的别名

小于

torch.distributions.constraints.less_than 的别名

下三角Cholesky分解

torch.distributions.constraints.lower_cholesky 的别名

下三角矩阵

torch.distributions.constraints.lower_triangular 的别名

多项式

torch.distributions.constraints.multinomial 的别名

非负

torch.distributions.constraints.nonnegative 的别名

非负整数

torch.distributions.constraints.nonnegative_integer 的别名

one_hot

torch.distributions.constraints.one_hot 的别名

有序向量

class _OrderedVector[source]

约束为一个实值张量,其中元素沿event_shape维度单调递增。

正数

torch.distributions.constraints.positive 的别名

正定

torch.distributions.constraints.positive_definite 的别名

正整数

torch.distributions.constraints.positive_integer 的别名

正序向量

class _PositiveOrderedVector[source]

约束为一个正实值张量,其中元素沿event_shape维度单调递增。

正半定

torch.distributions.constraints.positive_semidefinite 的别名

实数

torch.distributions.constraints.real 的别名

实向量

torch.distributions.constraints.real_vector 的别名

单纯形

torch.distributions.constraints.simplex 的别名

softplus_lower_cholesky

class _SoftplusLowerCholesky[source]

softplus_positive

class _SoftplusPositive[源代码]

球体

class _Sphere[source]

约束到任何维度的欧几里得球体。

平方

torch.distributions.constraints.square 的别名

堆栈

torch.distributions.constraints.stack 的别名

对称

torch.distributions.constraints.symmetric 的别名

单位区间

torch.distributions.constraints.unit_interval 的别名

单位下三角Cholesky

class _UnitLowerCholesky[source]

限制为具有全一对角线的下三角方阵。