分布

PyTorch 分布

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

伯努利

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

torch.distributions.bernoulli.Bernoulli 进行封装,并加入了 TorchDistributionMixin

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

样本是二元的(0 或 1)。样本取值 1 的概率为 p,取值 0 的概率为 1 - p

示例

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

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

Beta

class Beta(concentration1, concentration0, validate_args=None)[source]

torch.distributions.beta.Beta 进行封装,并加入了 TorchDistributionMixin

concentration1concentration0 参数化的 Beta 分布。

示例

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

  • concentration0 (floatTensor) – 分布的第2个集中度参数(通常称为 beta)

二项分布

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

torch.distributions.binomial.Binomial 进行封装,并加入了 TorchDistributionMixin

创建一个由 total_count 以及 probslogits(但不能同时使用)参数化的二项分布。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.]])
参数
  • total_count (intTensor) – 伯努利试验的次数

  • probs (Tensor) – 事件概率

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

分类分布

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

torch.distributions.categorical.Categorical 进行封装,并加入了 TorchDistributionMixin

创建一个由 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)
参数
  • probs (Tensor) – 事件概率

  • logits (Tensor) – 事件对数概率(非归一化)

柯西分布

class Cauchy(loc, scale, validate_args=None)

torch.distributions.cauchy.Cauchy 进行封装,并加入了 TorchDistributionMixin

从柯西(洛伦兹)分布中采样。均值为 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])
参数
  • loc (floatTensor) – 分布的众数或中位数。

  • scale (floatTensor) – 半高全宽的一半。

卡方分布

class Chi2(df, validate_args=None)

torch.distributions.chi2.Chi2 进行封装,并加入了 TorchDistributionMixin

创建一个由形状参数 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])
参数

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

连续伯努利分布

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

torch.distributions.continuous_bernoulli.ContinuousBernoulli 进行封装,并加入了 TorchDistributionMixin

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

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

示例

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

  • logits (数值, Tensor) – 实数值参数,其 sigmoid 匹配 'probs'

[1] The continuous Bernoulli: fixing a pervasive error in variational autoencoders, Loaiza-Ganem G and Cunningham JP, NeurIPS 2019. https://arxiv.org/abs/1907.06845

狄利克雷分布

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

torch.distributions.dirichlet.Dirichlet 进行封装,并加入了 TorchDistributionMixin

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

示例

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

concentration (Tensor) – 分布的集中度参数(通常称为 alpha)

指数分布

class Exponential(rate, validate_args=None)

torch.distributions.exponential.Exponential 进行封装,并加入了 TorchDistributionMixin

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

示例

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

rate (floatTensor) – 分布的速率 rate = 1 / scale

指数族

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

torch.distributions.exp_family.ExponentialFamily 进行封装,并加入了 TorchDistributionMixin

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 散度方法的正确性。我们使用此类来计算熵和 KL 散度,采用 AD 框架和 Bregman 散度(感谢:Frank Nielsen 和 Richard Nock,Entropies and Cross-entropies of Exponential Families)。

F分布

class FisherSnedecor(df1, df2, validate_args=None)

torch.distributions.fishersnedecor.FisherSnedecor 进行封装,并加入了 TorchDistributionMixin

创建一个由 df1df2 参数化的 F分布。

示例

>>> m = FisherSnedecor(torch.tensor([1.0]), torch.tensor([2.0]))
>>> m.sample()  # Fisher-Snedecor-distributed with df1=1 and df2=2
tensor([ 0.2453])
参数
  • df1 (floatTensor) – 自由度参数 1

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

Gamma分布

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

torch.distributions.gamma.Gamma 进行封装,并加入了 TorchDistributionMixin

创建一个由形状参数 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])
参数
  • concentration (floatTensor) – 分布的形状参数(通常称为 alpha)

  • rate (floatTensor) – 分布的速率 rate = 1 / scale(通常称为 beta)

几何分布

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

torch.distributions.geometric.Geometric 进行封装,并加入了 TorchDistributionMixin

创建一个由 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.])
参数
  • probs (数值, Tensor) – 采样为 1 的概率。必须在 (0, 1] 范围内

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

Gumbel分布

class Gumbel(loc, scale, validate_args=None)

封装了 torch.distributions.gumbel.Gumbel 并通过 TorchDistributionMixin 进行混合。

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

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

HalfCauchy

class HalfCauchy(scale, validate_args=None)

封装了 torch.distributions.half_cauchy.HalfCauchy 并通过 TorchDistributionMixin 进行混合。

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

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])
参数

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

HalfNormal

class HalfNormal(scale, validate_args=None)

封装了 torch.distributions.half_normal.HalfNormal 并通过 TorchDistributionMixin 进行混合。

创建一个由 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])
参数

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

Independent

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

封装了 torch.distributions.independent.Independent 并通过 TorchDistributionMixin 进行混合。

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

这主要用于改变 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])]
参数

Kumaraswamy

class Kumaraswamy(concentration1, concentration0, validate_args=None)

封装了 torch.distributions.kumaraswamy.Kumaraswamy 并通过 TorchDistributionMixin 进行混合。

从 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])
参数
  • concentration1 (floatTensor) – 分布的第1个集中度参数(通常称为 alpha)

  • concentration0 (floatTensor) – 分布的第2个集中度参数(通常称为 beta)

LKJCholesky

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

封装了 torch.distributions.lkj_cholesky.LKJCholesky 并通过 TorchDistributionMixin 进行混合。

相关矩阵的下 Cholesky 因子的 LKJ 分布。该分布由 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]])
参数
  • dimension (dim) – 矩阵的维度

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

参考文献

[1] 基于藤蔓和扩展洋葱法生成随机相关矩阵 (2009), Daniel Lewandowski, Dorota Kurowicka, Harry Joe. Journal of Multivariate Analysis. 100. 10.1016/j.jmva.2009.04.008

Laplace

class Laplace(loc, scale, validate_args=None)

封装了 torch.distributions.laplace.Laplace 并通过 TorchDistributionMixin 进行混合。

创建一个由 locscale 参数化的 Laplace 分布。

示例

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

  • scale (floatTensor) – 分布的尺度

LogNormal

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

封装了 torch.distributions.log_normal.LogNormal 并通过 TorchDistributionMixin 进行混合。

创建一个由 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])
参数
  • loc (floatTensor) – 分布对数的均值

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

LogisticNormal

class LogisticNormal(loc, scale, validate_args=None)

封装了 torch.distributions.logistic_normal.LogisticNormal 并通过 TorchDistributionMixin 进行混合。

创建一个由 locscale 参数化的 Logistic 正态分布,它们定义了通过 StickBreakingTransform 变换的基础 Normal 分布,使得

X ~ LogisticNormal(loc, scale)
Y = log(X / (1 - X.cumsum(-1)))[..., :-1] ~ Normal(loc, scale)
参数
  • 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])

LowRankMultivariateNormal

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

封装了 torch.distributions.lowrank_multivariate_normal.LowRankMultivariateNormal 并通过 TorchDistributionMixin 进行混合。

创建一个协方差矩阵具有低秩形式的多元正态分布,由 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])
参数
  • 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

MixtureSameFamily

class MixtureSameFamily(mixture_distribution, component_distribution, validate_args=None)

封装了 torch.distributions.mixture_same_family.MixtureSameFamily 并通过 TorchDistributionMixin 进行混合。

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

示例

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

  • component_distributiontorch.distributions.Distribution 类似实例。最右侧的批次维度索引组件。

Multinomial

class Multinomial(total_count=1, probs=None, logits=None, validate_args=None)[源代码]

封装了 torch.distributions.multinomial.Multinomial 并通过 TorchDistributionMixin 进行混合。

创建一个由 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])
参数
  • total_count (int) – 试验次数

  • probs (Tensor) – 事件概率

  • logits (Tensor) – 事件对数概率(非归一化)

MultivariateNormal

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

封装了 torch.distributions.multivariate_normal.MultivariateNormal 并通过 TorchDistributionMixin 进行混合。

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

多元正态分布可以由正定协方差矩阵 \(\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])
参数
  • loc (Tensor) – 分布的均值

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

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

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

注意

只能指定 covariance_matrixprecision_matrixscale_tril 中的一个。

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

NegativeBinomial

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

封装了 torch.distributions.negative_binomial.NegativeBinomial 并通过 TorchDistributionMixin 进行混合。

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

参数
  • total_count (floatTensor) – 非负数,表示停止时的负伯努利试验次数,尽管对于实数计数,此分布仍然有效

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

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

Normal

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

封装了 torch.distributions.normal.Normal 并通过 TorchDistributionMixin 进行混合。

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

示例

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

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

OneHotCategorical

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

封装了 torch.distributions.one_hot_categorical.OneHotCategorical 并通过 TorchDistributionMixin 进行混合。

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

样本是大小为 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.])
参数
  • probs (Tensor) – 事件概率

  • logits (Tensor) – 事件对数概率(非归一化)

OneHotCategoricalStraightThrough

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

封装了 torch.distributions.one_hot_categorical.OneHotCategoricalStraightThrough 并通过 TorchDistributionMixin 进行混合。

创建一个基于 [1] 中直通(straight-through)梯度估计器的可重参数化 OneHotCategorical 分布。

[1] Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation (Bengio et al, 2013) - 条件计算中通过随机神经元估计或传播梯度

Pareto

class Pareto(scale, alpha, validate_args=None)

封装了 torch.distributions.pareto.Pareto 并通过 TorchDistributionMixin 进行混合。

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

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

Poisson

class Poisson(rate, *, is_sparse=False, validate_args=None)[源代码]

封装了 torch.distributions.poisson.Poisson 并通过 TorchDistributionMixin 进行混合。

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

样本是非负整数,其概率质量函数(pmf)由下式给出

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

示例

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

rate (Number, Tensor) – 速率参数

RelaxedBernoulli

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

封装了 torch.distributions.relaxed_bernoulli.RelaxedBernoulli 并通过 TorchDistributionMixin 进行混合。

创建一个 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])
参数
  • temperature (Tensor) – 松弛温度

  • probs (数值, Tensor) – 采样为 1 的概率

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

RelaxedOneHotCategorical

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

封装了 torch.distributions.relaxed_categorical.RelaxedOneHotCategorical 并通过 TorchDistributionMixin 进行混合。

创建一个 RelaxedOneHotCategorical 分布,由 temperature 以及 probslogits 参数化。这是 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])
参数
  • temperature (Tensor) – 松弛温度

  • probs (Tensor) – 事件概率

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

StudentT

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

封装了 torch.distributions.studentT.StudentT 并通过 TorchDistributionMixin 进行混合。

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

示例

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

  • loc (floatTensor) – 分布的均值

  • scale (floatTensor) – 分布的尺度

TransformedDistribution

class TransformedDistribution(base_distribution, transforms, validate_args=None)

封装了 torch.distributions.transformed_distribution.TransformedDistribution 并通过 TorchDistributionMixin 进行混合。

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

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

注意,一个 TransformedDistribution.event_shape 是其基础分布和其变换的最大形状,因为变换可以在事件之间引入相关性。

TransformedDistribution 的一个使用示例如下

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

有关更多示例,请参阅以下实现 GumbelHalfCauchyHalfNormalLogNormalParetoWeibullRelaxedBernoulliRelaxedOneHotCategorical

Uniform

class Uniform(low, high, validate_args=None)[源代码]

封装了 torch.distributions.uniform.Uniform 并通过 TorchDistributionMixin 进行混合。

生成来自半开区间 [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])
参数
  • low (floatTensor) – 下限(包含)。

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

VonMises

class VonMises(loc, concentration, validate_args=None)

封装了 torch.distributions.von_mises.VonMises 并通过 TorchDistributionMixin 进行混合。

一个圆形的 von Mises 分布。

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

示例:
>>> m = VonMises(torch.tensor([1.0]), torch.tensor([1.0]))
>>> m.sample()  # von Mises distributed with loc=1 and concentration=1
tensor([1.9777])
参数

Weibull

class Weibull(scale, concentration, validate_args=None)

封装了 torch.distributions.weibull.Weibull 并通过 TorchDistributionMixin 进行混合。

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

  • concentration (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.Wishart 并通过 TorchDistributionMixin 进行混合。

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

示例

>>> 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
参数
  • 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] Wang, Z., Wu, Y. and Chu, H., 2018. On equivalence of the LKJ distribution and the restricted Wishart distribution - 关于 LKJ 分布和受限 Wishart 分布的等价性. [2] Sawyer, S., 2007. Wishart Distributions and Inverse-Wishart Sampling - Wishart 分布和逆 Wishart 抽样. [3] Anderson, T. W., 2003. An Introduction to Multivariate Statistical Analysis (3rd ed.) - 多元统计分析导论(第三版). [4] Odell, P. L. & Feiveson, A. H., 1966. A Numerical Procedure to Generate a SampleCovariance Matrix - 生成样本协方差矩阵的数值过程. JASA, 61(313):199-203. [5] Ku, Y.-C. & Bloomfield, P., 2010. Generating Random Wishart Matrices with Fractional Degrees of Freedom in OX - 在 OX 中生成具有分数自由度的随机 Wishart 矩阵。

Pyro 分布

抽象分布

class Distribution(*args, **kwargs)[源代码]

基类: 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)[源代码]

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

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

返回

一个随机值。

返回类型

torch.Tensor

abstract sample(*args, **kwargs)[源代码]

采样一个随机值。

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

参数

sample_shape (torch.Size) – 要从分布中抽取的 iid 批次的大小。

返回

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

返回类型

torch.Tensor

abstract log_prob(x, *args, **kwargs)[源代码]

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

参数

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

返回

作为一维 Tensor 的对数概率密度,与 value 和 params 具有相同的批次大小。结果的形状应为 self.batch_size

返回类型

torch.Tensor

score_parts(x, *args, **kwargs)[源代码]

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

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

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

参数

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

返回

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

返回类型

ScoreParts

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

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

请注意,这会一次返回所有批处理随机变量 (RV) 的支持集值,而非完整的笛卡尔积。

参数

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

返回

分布离散支持集上的迭代器。

返回类型

迭代器

conjugate_update(other)[source]

EXPERIMENTAL 创建一个更新后的分布,融合了来自另一个兼容分布的信息。仅部分共轭分布支持此操作。

这应满足以下方程

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,但由于 PyTorch 分布必须归一化,我们返回一个延迟求和 (updated, log_normalizer)。因此,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)
参数

other – 一个分布,表示 p(data|latent),但它是在 latent 而非 data 上归一化的。此处,latent 是来自 self 的候选样本,而 data 是不相关类型的观测值。

返回

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

has_rsample_(value)[source]

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

这有助于指示推断算法避免对那些不连续地决定下游控制流的变量使用可重参数化梯度。

参数

value (bool) – 样本是否具有路径可微性。

返回

self

返回类型

Distribution

property rv

EXPERIMENTAL 切换到随机变量 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
返回

一个 :class: ~pyro.contrib.randomvariable.random_variable.RandomVariable 类对象,包装了此分布。

返回类型

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[source]

采样一个随机值。

在可能的情况下,此方法是可重参数化的,对可重参数化分布调用 rsample(),对不可重参数化分布调用 sample()

参数

sample_shape (torch.Size) – 要从分布中抽取的 iid 批次的大小。

返回

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

返回类型

torch.Tensor

property batch_shape: torch.Size

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

类型

返回值

property event_shape: torch.Size

分布中单个样本的形状(不含批处理)。 :rtype: torch.Size

类型

返回值

property event_dim: int

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

类型

返回值

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

从此分布中采样的张量形状。

样本形状为

d.shape(sample_shape) == sample_shape + d.batch_shape + d.event_shape
参数

sample_shape (torch.Size) – 要从分布中抽取的 iid 批次的大小。

返回

样本的张量形状。

返回类型

torch.Size

classmethod infer_shapes(**arg_shapes)[source]

根据传递给 __init__() 的参数形状推断 batch_shapeevent_shape

注意

这假设分布形状仅依赖于张量输入的形状,而不依赖于输入中包含的数据。

参数

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

返回

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

返回类型

元组

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

返回一个新的 ExpandedDistribution 实例,其批处理维度展开到 batch_shape

参数
  • batch_shape (tuple) – 要展开到的批处理形状。

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

返回

ExpandedDistribution 的一个实例。

返回类型

ExpandedDistribution

expand_by(sample_shape)[source]

通过将 sample_shape 添加到其 batch_shape 的左侧来展开分布。

要将 self.batch_shape 的内部维度从 1 展开到更大的值,请改用 expand()

参数

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

返回

此分布的展开版本。

返回类型

ExpandedDistribution

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

将此分布 batch_shape 的最右侧 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])]
参数

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

返回

此分布的重塑版本。

返回类型

pyro.distributions.torch.Independent

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

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

参数

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

返回

此分布的掩码副本。

返回类型

屏蔽分布

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 类型。

张量形状:

TorchDistribution 提供了用于获取样本张量形状的 .shape() 方法。

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

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

  • 样本形状 对应于从分布中抽取的 iid 样本的形状。这被用作分布的 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() 方法(如果 .has_rsample == True,则实现 rsample())和 log_prob() 方法,并且必须实现 batch_shapeevent_shape 属性。离散分布类还可以实现 enumerate_support() 方法来改进梯度估计并设置 .has_enumerate_support = True

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

返回一个新的 ExpandedDistribution 实例,其批处理维度展开到 batch_shape

参数
  • batch_shape (tuple) – 要展开到的批处理形状。

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

返回

ExpandedDistribution 的一个实例。

返回类型

ExpandedDistribution

AffineBeta

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

AsymmetricLaplace

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

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

Laplace 分布的非对称版本。

loc 的左侧,它表现得像 -Exponential(1/(asymmetry*scale));在 loc 的右侧,它表现得像 Exponential(asymmetry/scale)。密度是连续的,因此 loc 处的左侧和右侧密度一致。

参数
  • loc – 位置参数,即众数。

  • scale – 尺度参数 = 左侧和右侧尺度的几何平均。

  • asymmetry – 左侧与右侧尺度的比值的平方。

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([]))[source]
support = Real()
property variance

AVFMultivariateNormal

class AVFMultivariateNormal(loc, scale_tril, control_var)[source]

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

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

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

参数
  • 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]

BetaBinomial

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

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

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

参数
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)[source]
expand(batch_shape, _instance=None)[source]
has_enumerate_support = True
log_prob(value)[source]
property mean
sample(sample_shape=())[source]
property support
property variance

CoalescentTimes

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

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

在给定不规则采样 leaf_times 和恒定种群大小的情况下,排序后 coalescent 时间上的分布。

样本值将是二元 coalescent 时间的 排序后 集合。每个样本 value 的基数将为 value.size(-1) = leaf_times.size(-1) - 1,这样系统发育树就是完整的二叉树。因此,给定固定的叶节点时间(数量),可以在系统发育树的多个样本上进行批处理,例如来自 BEAST 或 MrBayes 的系统发育树样本。

参考文献

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

“On the Genealogy of Large Populations” 《应用概率杂志》

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

“The Coalescent” 《随机过程及其应用》

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

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

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

CoalescentTimesWithRate

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

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

在给定不规则采样 leaf_times 和在正则时间网格上定义的分段常数 coalescent 速率的情况下,coalescent 时间上的分布。

这假设基本 coalescent 速率在时间间隔 (-inf,1], [1,2], …, [T-1,inf) 上是分段常数,其中 T = rate_grid.size(-1)。叶节点可以在任意实数时间被采样,但通常在间隔 [0, T] 内采样。

样本值将是二元 coalescent 时间的排序后集合。每个样本 value 的基数将为 value.size(-1) = leaf_times.size(-1) - 1,这样系统发育树就是完整的二叉树。因此,给定固定的叶节点时间(数量),可以在系统发育树的多个样本上进行批处理,例如来自 BEAST 或 MrBayes 的系统发育树样本。

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

另请参阅 CoalescentRateLikelihood

参考文献

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

“On the Genealogy of Large Populations” 《应用概率杂志》

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

“The Coalescent” 《随机过程及其应用》

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

“Inferring epidemiological dynamics with Bayesian coalescent inference: The merits of deterministic and stochastic models” https://arxiv.org/pdf/1407.1792.pdf

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

  • rate_grid (torch.Tensor) – 基本 coalescent 速率(配对合并速率)的张量。例如,在一个简单的 SIR 模型中,这可能是 beta S / I。最右侧的维度是时间,此张量表示在时间上是分段常数的一批速率。

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

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

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

参数

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

返回

似然 p(coal_times | leaf_times, rate_grid)

返回类型

torch.Tensor

property support

ConditionalDistribution

class ConditionalDistribution[source]

基类:abc.ABC

abstract condition(context)[source]
返回类型

torch.distributions.Distribution

ConditionalTransformedDistribution

class ConditionalTransformedDistribution(base_dist, transforms)[source]

基类: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 的推断,因为这样做会产生不正确的结果。

参数
  • 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

由 dirichlet-多项 对组成的复合分布。Multinomial 分布的类别概率 (probs) 未知,并在给定 total_count 次 Categorical 试验之前,从 Dirichlet 分布中随机抽取。

参数
  • concentration (floattorch.Tensor) – Dirichlet 分布的集中度参数 (alpha)。

  • total_count (inttorch.Tensor) – Categorical 试验次数。

  • 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)[source]
property mean
sample(sample_shape=())[source]
property support
property variance

DiscreteHMM

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

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

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

这使用 [1] 对时间进行并行化,从而为计算 log_prob()filter()sample() 实现了 O(log(time)) 的并行复杂度。

此分布的 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)

“Temporal Parallelization of Bayesian Filters and Smoothers” https://arxiv.org/pdf/1905.13002.pdf

参数
  • initial_logits (Tensor) – 用于潜在状态初始分类分布的 logits 张量。其最右侧维度应为 state_dim,且可广播到 batch_shape + (state_dim,)

  • transition_logits (Tensor) – 用于潜在状态之间转移条件分布的 logits 张量。其最右侧形状应为 (state_dim, state_dim) (旧状态,新状态),且可广播到 batch_shape + (num_steps, state_dim, state_dim)

  • observation_dist (Distribution) – 观测数据以潜在状态为条件的条件分布。其 .batch_shape 的最右侧维度应为 state_dim,且可广播到 batch_shape + (num_steps, state_dim)。其 .event_shape 可以是任意的。

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

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

给定观测序列,计算最终状态的后验分布。

参数

value (Tensor) – 观测序列。

返回

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

返回类型

分类

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

EmpiricalDistribution

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])
参数
  • samples (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 的值进行评分。

参数

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

property log_weights
property mean

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

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

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

property sample_size

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

返回 int

收集到的样本数量。

support = Real()
property variance

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

ExtendedBetaBinomial

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

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

EXPERIMENTAL 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

ExtendedBinomial

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

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

EXPERIMENTAL 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

FoldedDistribution

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

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

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

参数

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

expand(batch_shape, _instance=None)[source]
log_prob(value)[source]
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

隐马尔可夫模型,其初始状态、隐状态和观测状态的联合分布是遵循参考 [2] 和 [3] 的 MultivariateStudentT 分布。此模型适应 [1] 中的方法,通过时间并行化实现 O(log(time)) 的并行复杂度。

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

“Temporal Parallelization of Bayesian Filters and Smoothers” https://arxiv.org/pdf/1905.13002.pdf

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

“Bayesian Kalman filtering with elliptically contoured errors”

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

“Student’s t-filters for noise scale estimation” https://users.aalto.fi/~ssarkka/pub/SPL2019.pdf

变量
  • hidden_dim (int) – 隐状态的维度。

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

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

  • initial_dist (MultivariateNormal) – 具有单位尺度混合的初始状态分布。其 batch_shape 应可广播到 self.batch_shape。其 event_shape 应为 (hidden_dim,)

  • transition_matrix (Tensor) – 隐状态的线性变换。其形状应可广播到 self.batch_shape + (num_steps, hidden_dim, hidden_dim),其中最右侧维度顺序为 (旧状态, 新状态)

  • transition_dist (MultivariateNormal) – 具有单位尺度混合的过程噪声分布。其 batch_shape 应可广播到 self.batch_shape + (num_steps,)。其 event_shape 应为 (hidden_dim,)

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

  • observation_dist (MultivariateNormal) – 具有单位尺度混合的观测噪声分布。其 batch_shape 应可广播到 self.batch_shape + (num_steps,)。其 event_shape 应为 (obs_dim,)

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

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

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

参数

value (Tensor) – 观测序列。

返回

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

返回类型

一个包含 ~pyro.distributions.Gamma 和 ~pyro.distributions.MultivariateNormal 的元组

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

GammaPoisson

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

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

由 gamma-poisson 对组成的复合分布,也称为 gamma-poisson 混合分布。Poisson 分布的 rate 参数是未知的,并从 Gamma 分布中随机抽取。

注意

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

参数
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)[source]
property mean
property rate
sample(sample_shape=())[source]
support = IntegerGreaterThan(lower_bound=0)
property variance

GaussianHMM

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)

“Temporal Parallelization of Bayesian Filters and Smoothers” https://arxiv.org/pdf/1905.13002.pdf

变量
  • hidden_dim (int) – 隐状态的维度。

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

参数
  • initial_dist (MultivariateNormal) – 初始状态的分布。其 batch_shape 应可广播到 self.batch_shape。其 event_shape 应为 (hidden_dim,)

  • transition_matrix (Tensor) – 隐状态的线性变换。其形状应可广播到 self.batch_shape + (num_steps, hidden_dim, hidden_dim),其中最右侧维度顺序为 (旧状态, 新状态)

  • transition_dist (MultivariateNormal) – 过程噪声分布。其 batch_shape 应可广播到 self.batch_shape + (num_steps,)。其 event_shape 应为 (hidden_dim,)

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

  • observation_dist (MultivariateNormal or Normal) – 观测噪声分布。其 batch_shape 应可广播到 self.batch_shape + (num_steps,)。其 event_shape 应为 (obs_dim,)

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

arg_constraints = {}
conjugate_update(other)[source]

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

这应该满足

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

other (MultivariateNormal or Normal) – 表示 p(data|self.probs) 但按 self.probs 而非 data 归一化的分布。

返回

一个包含 (updated,log_normalizer) 的对,其中 updated 是一个更新的 GaussianHMMlog_normalizer 是一个表示归一化因子的 Tensor

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

给定观测序列,计算最终状态的后验分布。

参数

value (Tensor) – 观测序列。

返回

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

返回类型

多元正态

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

EXPERIMENTAL 假设自身具有 event_shape == (t+f, d),且数据 x 的形状为 batch_shape + (t, d),计算 event_shape 为 (f, d) 的条件分布。通常,t 是训练时间步数,f 是预测时间步数,d 是数据维度。

参数

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

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

EXPERIMENTAL 从以观测为条件的潜在状态中采样。

support = IndependentConstraint(Real(), 2)

GaussianMRF

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

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

时间马尔可夫随机场,其初始分布、转移分布和观测分布均采用高斯因子。此模型适应 [1] 中的方法,通过时间并行化实现 O(log(time)) 的并行复杂度,但不同之处在于它跟踪对数归一化因子以确保 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)

“Temporal Parallelization of Bayesian Filters and Smoothers” https://arxiv.org/pdf/1905.13002.pdf

变量
  • hidden_dim (int) – 隐状态的维度。

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

参数
  • initial_dist (MultivariateNormal) – 初始状态的分布。其 batch_shape 应可广播到 self.batch_shape。其 event_shape 应为 (hidden_dim,)

  • transition_dist (MultivariateNormal) – 一对连续时间步的联合分布因子。其 batch_shape 应可广播到 self.batch_shape + (num_steps,)。其 event_shape 应为 (hidden_dim + hidden_dim,) (旧状态+新状态)。

  • observation_dist (MultivariateNormal) – 隐状态和观测状态的联合分布因子。其 batch_shape 应可广播到 self.batch_shape + (num_steps,)。其 event_shape 应为 (hidden_dim + obs_dim,)

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

GaussianScaleMixture

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 logits 向量 component_logits 控制。此分布实现了来自该分布的样本的路径微分。此分布目前不支持批量参数。

有关路径微分实现的详细信息,请参见参考 [1]。如果您在研究中使用路径微分,请考虑引用此参考文献。

[1] Pathwise Derivatives for Multivariate Distributions, Martin Jankowiak & Theofanis Karaletsos. arXiv:1806.01856

请注意,此分布支持偶数和奇数维度,但前者精度应稍高一些,因为它在反向传播调用中不使用任何 erf 函数。另请注意,此分布不支持 D=1。

参数
  • 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([]))[source]

GroupedNormalNormal

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 指定的组之一。

有关标量 obs_scale 更简单情况下的相关表达式,请参见参考 [1] 中的公式 (55) 等。

示例

>>> 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] “Conjugate Bayesian analysis of the Gaussian distribution,” Kevin P. Murphy.

参数
  • 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)[source]
sample(sample_shape=())[source]
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() 时此分布会出错。要创建 instead 从指定分布采样的类似分布,请考虑使用 .mask(False),如下所示:

xyz = dist.Normal(0, 1).expand([3]).to_event(1).mask(False)
参数
  • support (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

IndependentHMM

class IndependentHMM(base_dist)[source]

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

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

.batch_shape

.event_shape

base_dist

shape + (obs_dim,)

(duration, 1)

result

shape

(duration, obs_dim)

参数

base_dist (HiddenMarkovModel) – 基本隐马尔可夫模型实例。

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

InverseGamma

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

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

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

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

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

LinearHMM

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

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

具有线性动态和观测以及任意噪声的隐马尔可夫模型,用于初始、转移和观测分布。这些分布可以是例如 MultivariateNormalIndependentNormalStudentTStable。此外,观测分布可以受约束,例如 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 的任意组合的齐次/异构时间依赖性。然而,至少一个分布或矩阵必须扩展以包含时间维度。

变量
  • hidden_dim (int) – 隐状态的维度。

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

参数
  • initial_dist – 关于初始状态的分布。其 batch_shape 必须可广播到 self.batch_shape。其 event_shape 应为 (hidden_dim,)

  • transition_matrix (Tensor) – 隐状态的线性变换。其形状应可广播到 self.batch_shape + (num_steps, hidden_dim, hidden_dim),其中最右侧维度顺序为 (旧状态, 新状态)

  • transition_dist – 关于过程噪声的分布。其 batch_shape 必须可广播到 self.batch_shape + (num_steps,)。其 event_shape 应为 (hidden_dim,)

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

  • observation_dist – 观测噪声分布。其 batch_shape 必须可广播到 self.batch_shape + (num_steps,)。其 event_shape 应为 (obs_dim,)

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

arg_constraints = {}
expand(batch_shape, _instance=None)[source]
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 时,分布偏向于具有小行列式的样本。当我们先验地知道某些底层变量相关时,这很有用。

参数
  • dimension (int) – 矩阵的维度

  • concentration (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

LogNormalNegativeBinomial

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

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

负二项分布的三参数泛化 [1]。它可以理解为负二项分布的连续混合,我们在负二项分布的 logits 中注入服从正态分布的噪声:

\[\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] “Lognormal and Gamma Mixed Negative Binomial Regression,”Mingyuan Zhou, Lingbo Li, David Dunson, and Lawrence Carin.

参数
  • total_count (float or torch.Tensor) – 负伯努利试验的非负次数。方差随着 total_count 的增加而减小。

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

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

  • 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)[source]
property mean
sample(sample_shape=torch.Size([]))[source]
support = IntegerGreaterThan(lower_bound=0)
property variance

Logistic

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

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

Logistic 分布。

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

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

Laplace 密度一样,此密度具有最重的可能尾部(渐近意义上),同时仍然是对数凸的。与 Laplace 分布不同,此分布处处无限可微,因此适用于构建拉普拉斯近似。

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

MaskedDistribution

class MaskedDistribution(base_dist, mask)[source]

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

通过一个布尔张量屏蔽一个分布,该张量可以广播到该分布的 batch_shape

在特殊情况下 mask is False,跳过 log_prob()score_parts()kl_divergence() 的计算,并返回常数零值。这对于具有缺失数据的似然非常有用。

参数

mask (torch.Tensor or bool) – 一个布尔值或布尔值张量。

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)[source]
property support
property variance

MaskedMixture

class MaskedMixture(mask, component0, component1, validate_args=None)[source]

基类: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)
参数
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

MixtureOfDiagNormals

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

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

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

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

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

[1] Pathwise Derivatives for Multivariate Distributions, Martin Jankowiak & Theofanis Karaletsos. arXiv:1806.01856

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

MixtureOfDiagNormalsSharedCovariance

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] Pathwise Derivatives for Multivariate Distributions, Martin Jankowiak & Theofanis Karaletsos. arXiv:1806.01856

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

MultivariateStudentT

class MultivariateStudentT(df, loc, scale_tril, validate_args=None)[source]

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

创建由自由度 df、均值 loc 和尺度 scale_tril 参数化的多元 Student's t 分布。

参数
  • 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)[source]
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)[source]

基类: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)[source]

基类: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

OMTMultivariateNormal

class OMTMultivariateNormal(loc, scale_tril)[source]

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

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

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

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

OneOneMatching

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

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

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

样本表示为形状为 (N,) 的长张量,取值为 {0,...,N-1} 并满足上述一对一约束。样本 v 的对数概率是边 logits 的总和,直到对数配分函数 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)

“非负矩阵的Bethe永久式” https://arxiv.org/pdf/1107.4196.pdf

[4] M Chertkov, AB Yedidia (2013)

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

参数
  • logits (Tensor) – (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

OneTwoMatching

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

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

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

样本表示为形状为 (2*N,) 的 long tensor,取值范围为 {0,...,N-1} 并满足上述一对二约束。样本 v 的对数概率是边 logits 之和,直至对数配分函数 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)

“非负矩阵的Bethe永久式” https://arxiv.org/pdf/1107.4196.pdf

[4] M Chertkov, AB Yedidia (2013)

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

参数
  • 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

OrderedLogistic

class OrderedLogistic(predictor, cutpoints, validate_args=None)[source]

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

分类变量分布的另一种参数化。

这提供了一种替代分类变量典型参数化(即个体类别的概率质量 p)的方法,对于指定有序分类模型非常有用。它接受一个 cutpoints 向量,这是一个有序的实数向量,表示个体类别的基线累积 log-odds,以及一个模型向量 predictor,它修改每个样本的基线。

然后将这些累积 log-odds 转换为离散的累积概率分布,最后通过求差得到指定分类分布的概率质量矩阵 p

参数
  • predictor (Tensor) – 任意形状的预测变量张量。此分布的非批量样本的输出形状将与 predictor 的形状相同。

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

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

ProjectedNormal

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

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

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

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

要将此分布与自动引导一起使用,请在模型中使用 poutine.reparam,并将 ProjectedNormalReparam 重新参数化器,例如

@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

参数

concentration (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

实现了带有 Straight-Through 梯度估计器的 RelaxedBernoulli

此分布具有以下属性:

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

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

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

参考文献

[1] Concrete 分布:离散随机变量的连续松弛,

Chris J. Maddison, Andriy Mnih, Yee Whye Teh

[2] 使用 Gumbel-Softmax 的分类变量重新参数化,

Eric Jang, Shixiang Gu, Ben Poole

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)[source]

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

实现了带有 Straight-Through 梯度估计器的 RelaxedOneHotCategorical

此分布具有以下属性:

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

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

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

参考文献

[1] Concrete 分布:离散随机变量的连续松弛,

Chris J. Maddison, Andriy Mnih, Yee Whye Teh

[2] 使用 Gumbel-Softmax 的分类变量重新参数化,

Eric Jang, Shixiang Gu, Ben Poole

log_prob(value)[source]

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

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

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

Rejector

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

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

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

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

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

  • log_scale – 总对数接受概率。

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

SineBivariateVonMises

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

基类: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) 是第一类修正贝塞尔函数,μ 是分布的位置,κ 是集中度,ρ 表示角度 x_1 和 x_2 之间的相关性。

此分布是双变量 von Mises 分布的一个子模型,在方向统计中称为 Sine 分布 [2]。

此分布有助于对肽链中的扭转角等耦合角度进行建模。要推断参数,请使用 NUTSHMC,并使用避免分布变为双峰的先验;参见下面的注释。

注意

采样效率随着

\[\frac{\rho}{\kappa_1\kappa_2} \rightarrow 1\] 的增加而下降,因为分布越来越呈双峰。为避免双峰性,请使用 weighted_correlation 参数,并使其偏离 1(例如,Beta(1,3))。weighted_correlation 应在 [0,1] 范围内。

采样效率随着

注意

correlationweighted_correlation 参数是互斥的。

注意

SVI 的上下文中,此分布可用作似然函数,但不能用作隐变量。

** 参考文献: **
  1. 两个相关圆变量的概率模型 Singh, H., Hnizdo, V., and Demchuck, E. (2002)

  2. 蛋白质生物信息学和角度数据的双变量 von Mises 混合分布,Mardia, K. V, Taylor, T. C., and Subramaniam, G. (2007)

参数
  • 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]
** 参考文献: **
  1. 一类广泛方向分布模拟的新统一方法 John T. Kent, Asaad M. Ganeiber & Kanti V. Mardia (2018)

support = IndependentConstraint(Real(), 1)

SineSkewed

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

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

Sine 偏斜 [1] 是一种生成打破环面分布点对称性的分布的程序。新的分布称为 Sine Skewed X 分布,其中 X 是 (对称) 基分布的名称。

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

Sine Skewed X 分布通过 X 事件的每个维度的权重参数化。例如,对于圆上的 von Mises 分布(1-环面),Sine Skewed 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)

为了确保偏斜不改变 (Sine Bivaraite von Mises) 基分布的归一化常数,偏斜参数受到约束。该约束要求偏斜的绝对值之和小于或等于一。因此,对于上面的代码片段,必须满足

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-环面上,因此 event_shape 必须是 (d,)。

注意

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

** 参考文献: **
  1. Sine-skewed 环面分布及其在蛋白质生物信息学中的应用 Ameijeiras-Alonso, J., Ley, C. (2019)

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

SkewLogistic

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] 广义 Logistic 分布

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

参数
  • 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)[source]
expand(batch_shape, _instance=None)[source]
has_rsample = True
icdf(value)[source]
log_prob(value)[source]
rsample(sample_shape=torch.Size([]))[source]
support = Real()

SoftAsymmetricLaplace

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

基类: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)
参数
  • 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)[source]
property mean
property right_scale
rsample(sample_shape=torch.Size([]))[source]
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)

像拉普拉斯密度一样,此密度具有最重的可能尾部(渐近),同时仍然是对数凸的。与拉普拉斯分布不同,此分布处处无穷可微,因此适合构建拉普拉斯近似。

参数
  • 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

SpanningTree

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

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

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

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

  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) 的秩。要将边 logits 矩阵转换为此处使用的线性表示形式:

assert my_matrix.shape == (V, V)
i, j = make_complete_graph(V)
edge_logits = my_matrix[i, j]
参数
  • edge_logits (torch.Tensor) – 一个长度为 V*(V-1)//2 的张量,包含完全图上 V 个顶点所有边的 logits (aka 负能量)。边顺序参见上述注释。

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

arg_constraints = {'edge_logits': Real()}
property edge_mean

计算每条边处于活跃状态的边际概率。

注意

这类似于其他分布的 .mean() 方法,但形状不同,因为此分布的值未编码为二进制矩阵。

返回

一个形状为 (V,V) 的对称方阵,值在 [0,1] 范围内,表示每个边在采样值中的边际概率。

返回类型

Tensor

enumerate_support(expand=True)[source]

此方法实现了多达 6 个顶点(和 5 条边)的树。

has_enumerate_support = True
property log_partition_function
log_prob(edges)[source]
property mode

最大权重生成树。 :rtype: Tensor

类型

返回

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

此采样器是使用 MCMC 实现的,在廉价的近似采样器初始化后运行少量步骤。此采样器是近似的,时间复杂度为 O(V^3)。这比经典的 Aldous-Broder 采样器 [1,2] 更快,尤其对于混合时间较大的图。最近的研究 [3,4] 提出了运行时间低于矩阵乘法时间的采样器,但实现更复杂。

参考文献

[1] 生成随机生成树

Andrei Broder (1989)

[2] 均匀生成树和均匀标记树的随机游走构造

David J. Aldous (1990)

[3] 采样随机生成树的速度快于矩阵乘法

David Durfee, Rasmus Kyng, John Peebles, Anup B. Rao, Sushant Sachdeva (2017) https://arxiv.org/abs/1611.07451

[4] 一种用于均匀随机生成树生成的接近线性的时间算法

Aaron Schild (2017) https://arxiv.org/abs/1711.06455

support = IntegerGreaterThan(lower_bound=0)
validate_edges(edges)[source]

验证一批 edges 张量,这些张量由 sample()enumerate_support() 返回,或作为 log_prob() 的输入。

参数

edges (torch.LongTensor) – 一批边。

引发

ValueError

返回

None

Stable

class Stable(stability, skew, scale=1.0, loc=0.0, coords='S0', validate_args=None)[source]

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

Levy \(\alpha\)-稳定分布。参见 [1] 获取综述。

这使用了 Nolan 对 loc 参数的参数化 [2],这是连续性和可微性所必需的。这对应于 [1] 中的符号 \(S^0_\alpha(\beta,\sigma,\mu_0)\),其中 \(\alpha\) = stability(稳定度),\(\beta\) = skew(偏斜度),\(\sigma\) = scale(尺度),\(\mu_0\) = loc(位置)。要改为使用 scipy 中的 S 参数化,请传递 coords="S",但 注意stability=1 处此参数化是不连续的,并且对于推断而言几何形状较差。

这实现了重参数化的采样器 rsample(),以及通过数值积分进行的相对昂贵的 log_prob() 计算,这使得推理速度较慢(相对于其他分布),但具有更好的收敛特性,尤其是对于偏态的 \(\alpha\)-stable 分布(参见下面的 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

参数
  • stability (Tensor) – Levy 稳定参数 \(\alpha\in(0,2]\)

  • skew (Tensor) – 偏度 \(\beta\in[-1,1]\)

  • scale (Tensor) – 尺度 \(\sigma > 0\)。默认为 1。

  • loc (Tensor) – 使用 Nolan 的 S0 参数化 [2] 时的位置参数 \(\mu_0\),或使用 S 参数化时的 \(\mu\)。默认为 0。

  • coords (str) – 使用 Nolan 的连续 S0 参数化时为 “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)[源代码]
has_rsample = True
log_prob(value)[源代码]

通过数值积分实现,该数值积分基于 Chambers, Mallows 和 Stuck (CMS) 提出的用于模拟 Levy \(\alpha\)-stable 分布的算法。CMS 算法涉及将两个独立的随机变量非线性转换为一个 stable 随机变量。第一个随机变量服从均匀分布,而第二个服从指数分布。数值积分是在第一个服从均匀分布的随机变量上进行的。

property mean
rsample(sample_shape=torch.Size([]))[源代码]
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 拒绝重参数化。

TruncatedPolyaGamma

class TruncatedPolyaGamma(prototype, validate_args=None)[源代码]

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

这是一个截断在区间 (0, 2.5) 内具有有限支持的 PolyaGamma(1, 0) 分布。详细信息请参见 [1]。截断的结果是 log_prob 方法的精度仅约为小数点后六位。此外,提供的采样器是一个粗略的近似,仅适用于采样精度不重要的场景(例如初始化)。总的来说,此实现仅适用于对 log_prob 的良好近似就足够的情况,例如 HMC。

参数

prototype (tensor) – 一个具有任意形状的原型张量,用于确定 samplelog_prob 返回的 dtypedevice

参考文献

[1] ‘使用 Polya-Gamma 潜在变量对逻辑模型进行贝叶斯推断’

Nicholas G. Polson, James G. Scott, Jesse Windle。

arg_constraints = {}
expand(batch_shape, _instance=None)[源代码]
has_rsample = False
log_prob(value)[源代码]
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

Unit

class Unit(log_factor, *, has_rsample=None, validate_args=None)[源代码]

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

表示单位类型的微不足道的非归一化分布。

单位类型只有一个没有数据的数值,即 value.numel() == 0

这用于 pyro.factor() 语句。

arg_constraints = {'log_factor': Real()}
expand(batch_shape, _instance=None)[源代码]
log_prob(value)[源代码]
rsample(sample_shape=torch.Size([]))[源代码]
sample(sample_shape=torch.Size([]))[源代码]
support = Real()

VonMises3D

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

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

球面 von Mises 分布。

此实现将方向参数和集中参数组合为一个包含方向和幅度的单一组合参数。value 参数以笛卡尔坐标表示:它必须是位于二维球面上的归一化三维向量。

参见 VonMises,它是此分布的二维极坐标表亲。参见 projected_normal,它是一个性质相似但实现了更多功能的分布。

目前仅实现了 log_prob()

参数

concentration (torch.Tensor) – 位置和集中度合并向量。该向量的方向是位置,其大小是集中度。

arg_constraints = {'concentration': Real()}
expand(batch_shape)[源代码]
log_prob(value)[源代码]
support = Sphere

ZeroInflatedDistribution

class ZeroInflatedDistribution(base_dist, *, gate=None, gate_logits=None, validate_args=None)[源代码]

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

通用零膨胀分布。

这可以直接使用,也可以用作基类,例如 ZeroInflatedPoissonZeroInflatedNegativeBinomial

参数
  • base_dist (TorchDistribution) – 基础分布。

  • gate (torch.Tensor) – 通过伯努利分布给出的额外零的概率。

  • gate_logits (torch.Tensor) – 通过伯努利分布给出的额外零的对数几率。

arg_constraints = {'gate': Interval(lower_bound=0.0, upper_bound=1.0), 'gate_logits': Real()}
expand(batch_shape, _instance=None)[源代码]
property gate
property gate_logits
log_prob(value)[源代码]
property mean
sample(sample_shape=torch.Size([]))[源代码]
property support
property variance

ZeroInflatedNegativeBinomial

class ZeroInflatedNegativeBinomial(total_count, *, probs=None, logits=None, gate=None, gate_logits=None, validate_args=None)[源代码]

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

零膨胀负二项分布。

参数
  • total_count (float or torch.Tensor) – 非负的负伯努利试验次数。

  • probs (torch.Tensor) – 成功事件的概率,取值范围为半开区间 [0, 1)。

  • logits (torch.Tensor) – 成功概率的对数几率。

  • gate (torch.Tensor) – 额外零的概率。

  • gate_logits (torch.Tensor) – 额外零的对数几率。

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

ZeroInflatedPoisson

class ZeroInflatedPoisson(rate, *, gate=None, gate_logits=None, validate_args=None)[源代码]

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

零膨胀泊松分布。

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

Transforms

ConditionalTransform

class ConditionalTransform[源代码]

基类:abc.ABC

abstract condition(context)[源代码]
返回类型

torch.distributions.Transform

CholeskyTransform

class CholeskyTransform(cache_size=0)[源代码]

基类: 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)[源代码]

CorrMatrixCholeskyTransform

class CorrMatrixCholeskyTransform(cache_size=0)[源代码]

基类: 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)[源代码]

DiscreteCosineTransform

class DiscreteCosineTransform(dim=- 1, smooth=0.0, cache_size=0)[源代码]

基类: torch.distributions.transforms.Transform

II 型离散余弦变换。

这使用 dct()idct() 来计算正交 DCT 和逆 DCT 变换。雅可比行列式为 1。

参数
  • dim (int) – 要进行转换的维度。必须是负数。这是从右边计算的绝对维度。

  • smooth (float) – 平滑参数。当为 0 时,将白噪声转换为白噪声;当为 1 时,将布朗噪声转换为白噪声;当为 -1 时,将紫噪声转换为白噪声;等等。允许任何实数。https://en.wikipedia.org/wiki/Colors_of_noise

bijective = True
property codomain
property domain
forward_shape(shape)[源代码]
inverse_shape(shape)[源代码]
log_abs_det_jacobian(x, y)[源代码]
with_cache(cache_size=1)[源代码]

ELUTransform

class ELUTransform(cache_size=0)[源代码]

基类: 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)[源代码]
sign = 1

HaarTransform

class HaarTransform(dim=- 1, flip=False, cache_size=0)[源代码]

基类: torch.distributions.transforms.Transform

离散 Haar 变换。

这使用 haar_transform()inverse_haar_transform() 来计算(正交的)Haar 和逆 Haar 变换。雅可比行列式为 1。对于长度 T 不是二的幂的序列,此实现等效于一种块结构 Haar 变换,其中块大小从左到右减半。

参数
  • dim (int) – 要进行转换的维度。必须是负数。这是从右边计算的绝对维度。

  • flip (bool) – 是否在应用 Haar 变换之前翻转时间轴。默认为 False。

bijective = True
property codomain
property domain
forward_shape(shape)[源代码]
inverse_shape(shape)[源代码]
log_abs_det_jacobian(x, y)[源代码]
with_cache(cache_size=1)[源代码]

LeakyReLUTransform

class LeakyReLUTransform(cache_size=0)[源代码]

基类: 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)[源代码]
sign = 1

LowerCholeskyAffine

class LowerCholeskyAffine(loc, scale_tril, cache_size=0)[源代码]

基类: torch.distributions.transforms.Transform

形式为以下公式的双射:

\(\mathbf{y} = \mathbf{L} \mathbf{x} + \mathbf{r}\)

其中 \(\mathbf{L}\) 是一个下三角矩阵,\(\mathbf{r}\) 是一个向量。

参数
  • 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)[源代码]

计算对数雅可比行列式的元素级绝对值,即 log(abs(dy/dx))。

volume_preserving = False
with_cache(cache_size=1)[源代码]

Normalize

class Normalize(p=2, cache_size=0)[源代码]

基类: 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)[源代码]

OrderedTransform

class OrderedTransform(cache_size=0)[源代码]

基类: 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)[源代码]

Permute

class Permute(permutation, *, dim=- 1, cache_size=1)[源代码]

基类: 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()  
参数
  • permutation (torch.LongTensor) – 应用于输入的排列顺序。

  • dim (int) – 要置换的张量维度。此值必须为负数,并将事件维度定义为 abs(dim)

bijective = True
property codomain
property domain
property inv_permutation
log_abs_det_jacobian(x, y)[源代码]

计算对数雅可比行列式的元素级绝对值,即 log(abs([dy_0/dx_0, …, dy_{N-1}/dx_{N-1}]))。注意,这种类型的变换不是自回归的,因此对数雅可比行列式不是上述表达式的和。然而,它总是 0(因为行列式是 -1 或 +1),所以返回一个零向量是可行的。

volume_preserving = True
with_cache(cache_size=1)[源代码]

PositivePowerTransform

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)[源代码]
log_abs_det_jacobian(x, y)[源代码]
sign = 1
with_cache(cache_size=1)[源代码]

SimplexToOrderedTransform

class SimplexToOrderedTransform(anchor_point=None)[源代码]

基类: torch.distributions.transforms.Transform

将单形体转换为有序向量(通过分界点之间 Logistic CDF 的差值)。用于 [1] 中,通过转换有序类别概率来引入潜在分界点上的先验。

参数

anchor_point – 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)[源代码]
inverse_shape(shape)[源代码]
log_abs_det_jacobian(x, y)[源代码]

SoftplusLowerCholeskyTransform

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)[源代码]

基类: 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

UnitLowerCholeskyTransform

class UnitLowerCholeskyTransform(cache_size=0)[源代码]

基类: torch.distributions.transforms.Transform

将无约束矩阵转换为对角线元素全为一的下三角矩阵。

codomain: torch.distributions.constraints.Constraint = UnitLowerCholesky()
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 2)

TransformModules

AffineAutoregressive

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 Et Al., 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 的逆变换。这个实现会在其前向操作被调用时(例如,从 TransformedDistribution 中采样时)缓存 Bijector 的逆变换。然而,如果缓存的值不可用,无论是由于采样新值时被覆盖,还是正在对任意值进行评分,它都会手动计算。请注意,这是一个复杂度为 O(D) 的操作,其中 D 是输入维度,因此应避免在高维中使用。所以总的来说,从 IAF 采样并对 IAF 采样的值进行评分是廉价的,但对任意值进行评分是昂贵的。

参数
  • autoregressive_nn (callable) – 一个自回归神经网络,其前向调用返回一个实值均值和 logit 尺度的元组

  • log_scale_min_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最小值

  • log_scale_max_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最大值

  • sigmoid_bias (float) – 在使用 stable 变换时添加到输入 logit 的项。

  • stable (bool) – 当为 True 时,使用备选的“stable”版本变换(见上文)。

参考文献

[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

AffineCoupling

class AffineCoupling(split_dim, hypernet, *, dim=- 1, log_scale_min_clip=- 5.0, log_scale_max_clip=3.0)[源代码]

基类: pyro.distributions.torch_transform.TransformModule

RealNVP (Dinh et al., 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\) 个分量由前 \(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 的逆变换。这个实现会在其前向操作被调用时(例如,从 TransformedDistribution 中采样时)缓存 Bijector 的逆变换。然而,如果缓存的值不可用,无论是由于采样新值时被覆盖,还是正在对任意值进行评分,它都会手动计算。

这是一个复杂度为 O(1) 的操作,即与输入维度无关。因此,总的来说,从 AffineCoupling 中采样和评分(任意值)都是廉价的。

参数
  • split_dim (int) – 进行变换的输入/输出分割的零索引维度 \(d\)。

  • hypernet (callable) – 一个神经网络,其前向调用返回一个实值均值和 logit 尺度的元组。输入的最终维度应为 split_dim,元组中每个成员的输出最终维度应为 input_dim-split_dim。

  • dim (int) – 进行分割的张量维度。此值必须为负,并将事件维度定义为 abs(dim)

  • log_scale_min_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最小值

  • log_scale_max_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最大值

参考文献

[1] Laurent Dinh, Jascha Sohl-Dickstein, and Samy Bengio. 使用 Real NVP 进行密度估计。ICLR 2017。

bijective = True
property codomain
property domain
log_abs_det_jacobian(x, y)[源代码]

计算对数雅可比行列式的逐元素值

BatchNorm

class BatchNorm(input_dim, momentum=0.1, epsilon=1e-05)[源代码]

基类: pyro.distributions.torch_transform.TransformModule

一种可用于稳定归一化流训练的批量归一化类型。逆操作定义为

\(x = (y - \hat{\mu}) \oslash \sqrt{\hat{\sigma^2}} \otimes \gamma + \beta\)

即标准的批量归一化方程,其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出,\(\gamma,\beta\) 是可学习参数,而 \(\hat{\mu}\)/\(\hat{\sigma^2}\) 分别是样本均值和方差的平滑移动平均。强制执行约束 \(\gamma>0\) 以简化 log-det-Jacobian 项的计算。

这是一个逐元素变换,当应用于向量时,为输入的每个维度学习两个参数(\(\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()  
参数
  • input_dim (int) – 输入的维度

  • momentum (float) – 用于更新移动平均的动量参数

  • epsilon (float) – 添加到方差中的小数值,以确保数值稳定性

参考文献

[1] Sergey Ioffe and Christian Szegedy. 批量归一化:通过减少内部协变量偏移加速深度网络训练。In International Conference on Machine Learning, 2015. https://arxiv.org/abs/1502.03167

[2] Laurent Dinh, Jascha Sohl-Dickstein, and Samy Bengio. 使用 Real NVP 进行密度估计。In International Conference on Learning Representations, 2017. https://arxiv.org/abs/1605.08803

[3] George Papamakarios, Theo Pavlakou, and Iain Murray. 用于密度估计的掩码自回归流。In Neural Information Processing Systems, 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

BlockAutoregressive

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 et al., 2019) 双射变换的一种实现。Block-NAF 使用类似于深度稠密 NAF 的变换,在某种程度上将自回归 NN 构建到变换的结构中。

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

逆操作尚未实现。这需要数值求逆,例如使用求根方法——这是未来实现的一种可能性。

参数
  • input_dim (int) – 输入和输出变量的维度。

  • hidden_factors (list) – 第 i 个隐藏层在每个输入维度上有 hidden_factors[i] 个隐藏单元。这对应于 De Cao et al. (2019) 中的 \(a\) 和 \(b\)。hidden_factors 的元素必须是整数。

  • activation (string) – 使用的激活函数。选项包括 ‘ELU’, ‘LeakyReLU’, ‘sigmoid’, 或 ‘tanh’。

  • residual (string) – 使用的残差连接类型。选项包括 “None”,对于 \(\mathbf{y}+f(\mathbf{y})\) 使用 “normal”,以及对于可学习参数 \(\alpha\),对于 \(\alpha\mathbf{y} + (1 - \alpha\mathbf{y})\) 使用 “gated”。

参考文献

[1] Nicola De Cao, Ivan Titov, Wilker Aziz. Block Neural Autoregressive Flow。 [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)[源代码]

计算对数雅可比行列式的逐元素值

ConditionalAffineAutoregressive

class ConditionalAffineAutoregressive(autoregressive_nn, **kwargs)[源代码]

基类: pyro.distributions.conditional.ConditionalTransformModule

逆自回归流 (IAF) 双射变换的一种实现,该变换以附加上下文变量为条件,默认使用 Kingma Et Al., 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 的逆变换。这个实现会在其前向操作被调用时(例如,从 TransformedDistribution 中采样时)缓存 Bijector 的逆变换。然而,如果缓存的值不可用,无论是由于采样新值时被覆盖,还是正在对任意值进行评分,它都会手动计算。请注意,这是一个复杂度为 O(D) 的操作,其中 D 是输入维度,因此应避免在高维中使用。所以总的来说,从 IAF 采样并对 IAF 采样的值进行评分是廉价的,但对任意值进行评分是昂贵的。

参数
  • autoregressive_nn (nn.Module) – 一个自回归神经网络,其前向调用返回一个实值均值和 logit 尺度的元组

  • log_scale_min_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最小值

  • log_scale_max_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最大值

  • sigmoid_bias (float) – 在使用 stable 变换时添加到输入 logit 的项。

  • stable (bool) – 当为 True 时,使用备选的“stable”版本变换(见上文)。

参考文献

[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)[源代码]

以上下文变量为条件,返回一个非条件变换,类型为 AffineAutoregressive

domain = IndependentConstraint(Real(), 1)
training: bool

ConditionalAffineCoupling

class ConditionalAffineCoupling(split_dim, hypernet, **kwargs)[源代码]

基类: pyro.distributions.conditional.ConditionalTransformModule

RealNVP (Dinh et al., 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\) 个分量由前 \(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 的逆变换。这个实现会在其前向操作被调用时(例如,从 ConditionalTransformedDistribution 中采样时)缓存 Bijector 的逆变换。然而,如果缓存的值不可用,无论是由于采样新值时被覆盖,还是正在对任意值进行评分,它都会手动计算。

这是一个复杂度为 O(1) 的操作,即与输入维度无关。因此,总的来说,从 ConditionalAffineCoupling 中采样和评分(任意值)都是廉价的。

参数
  • split_dim (int) – 进行变换的输入/输出分割的零索引维度 \(d\)。

  • hypernet (callable) – 一个神经网络,其前向调用返回一个实值均值和 logit 尺度的元组。输入的最终维度应为 split_dim,元组中每个成员的输出最终维度应为 input_dim-split_dim。该网络还接收一个上下文变量作为关键字参数,以便根据它来条件化输出。

  • log_scale_min_clip (float) – 用于裁剪 NN 的 log(scale) 的最小值

  • log_scale_max_clip (float) – 用于裁剪 NN 的 log(scale) 的最大值

参考文献

Laurent Dinh, Jascha Sohl-Dickstein, and Samy Bengio. 使用 Real NVP 进行密度估计。ICLR 2017。

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[源代码]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

ConditionalGeneralizedChannelPermute

class ConditionalGeneralizedChannelPermute(nn, channels=3, permutation=None)[源代码]

基类: pyro.distributions.conditional.ConditionalTransformModule

一种双射变换,它推广了对 […,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\) 是一个输入和输出通道均为 \(C\) 的 1x1 卷积的滤波器矩阵。

忽略最后两个维度,\(W\) 被限制为矩阵乘积,

\(W = PLU\)

其中 \(P\sim C\times C\) 是通道维度上的置换矩阵,而 \(LU\sim C\times C\) 是一个可逆的下三角矩阵和上三角矩阵的乘积,它是以代表条件上下文变量 \(z\in\mathbb{R}^{M}\) 为输入的 NN 的输出。

输入 \(\mathbf{x}\) 和输出 \(\mathbf{y}\) 的形状均为 […,C,H,W],其中 C 是初始化时设置的通道数。

此操作在 [1] 中为 Glow 归一化流引入,也称为 1x1 可逆卷积。它出现在 [2,3] 等其他著名工作中,对应于 TensorFlow Probability 中的 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])) 
参数
  • 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] Conor Durkan, Artur Bekasov, Iain Murray, George Papamakarios. 神经样条流。 [arXiv:1906.04032]

bijective = True
codomain = IndependentConstraint(Real(), 3)
condition(context)[源代码]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 3)
training: bool

ConditionalHouseholder

class ConditionalHouseholder(input_dim, nn, count_transforms=1)[源代码]

基类: 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\) 是一个函数(例如 NN)的输出,该函数的输入为 \(z\in\mathbb{R}^{M}\),代表要作为条件的上下文变量。

此变换表示 \(\mathbf{x}\) 经过原点且法向量为 \(\mathbf{u}\) 的平面进行的反射。

此变换应用 \(D\) 次后,能够将标准独立同分布的高斯噪声转换为具有任意协方差矩阵的高斯变量。使用 \(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])) 
参数
  • input_dim (int) – 输入(和输出)变量的维度。

  • nn (callable) – 一个接收上下文变量并输出维度为 \((1, D, D)\) 的实值参数三元组的函数。

  • count_transforms (int) – 应用 Householder 变换的次数。

参考文献

[1] Jakub M. Tomczak, Max Welling. 使用 Householder 流改进变分自编码器。 [arXiv:1611.09630]

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[源代码]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

ConditionalMatrixExponential

class ConditionalMatrixExponential(input_dim, nn, iterations=8, normalization='none', bound=None)[源代码]

基类: pyro.distributions.conditional.ConditionalTransformModule

一种稠密矩阵指数双射变换 (Hoogeboom et al., 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])) 
参数
  • input_dim (int) – 输入(和输出)变量的维度。

  • iterations (int) – 用于近似矩阵指数的截断幂级数中的项数。

  • normalization (string) – 选择应用于权重矩阵的归一化类型,选项为 [‘none’, ‘weight’, ‘spectral’]weight 对应于权重归一化 (Salimans and Kingma, 2016),spectral 对应于谱归一化 (Miyato et al, 2018)。

  • bound (float) – 当 normalization 参数选择权重或谱归一化时,对权重或谱范数的约束。较低的值会使截断幂级数需要更少的项来紧密近似矩阵指数的精确值。

参考文献

[1] Emiel Hoogeboom, Victor Garcia Satorras, Jakub M. Tomczak, Max Welling. 卷积指数和广义 Sylvester 流。 [arXiv:2006.01910]

[2] Tim Salimans, Diederik P. Kingma. 权重归一化:一种加速深度神经网络训练的简单重参数化方法。 [arXiv:1602.07868]

[3] Takeru Miyato, Toshiki Kataoka, Masanori Koyama, Yuichi Yoshida. 生成对抗网络的谱归一化。ICLR 2018。

bijective = True

codomain = IndependentConstraint(Real(), 1)

condition(context)[源代码]

domain = IndependentConstraint(Real(), 1)
training: bool
ConditionalNeuralAutoregressive

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

class ConditionalNeuralAutoregressive(autoregressive_nn, **kwargs)[源代码]
深度 Neural Autoregressive Flow (NAF) 双射变换的一种实现,具有“IAF 特点”,该变换以附加上下文变量为条件,可用于从中采样和对采样结果进行评分(但不能对任意值进行评分)。

autoregressive_nn (nn.Module) – 一个自回归神经网络,其前向调用返回一个包含三个实值张量的元组,这些张量的最后一个维度是输入维度,倒数第二个维度等于 hidden_units。

hidden_units (int) – 在 NAF 变换中使用的隐藏单元数量(参见参考文献中的公式 (8))

基类: pyro.distributions.conditional.ConditionalTransformModule

参考文献

示例用法

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

逆操作尚未实现。这需要数值求逆,例如使用求根方法——这是未来实现的一种可能性。

参数
  • [1] Chin-Wei Huang, David Krueger, Alexandre Lacoste, Aaron Courville. 神经自回归流。 [arXiv:1804.00779]

  • bijective = True

  • activation (string) – 使用的激活函数。选项包括 ‘ELU’, ‘LeakyReLU’, ‘sigmoid’, 或 ‘tanh’。

codomain = IndependentConstraint(Real(), 1)

condition(context)[源代码]

以上下文变量为条件,返回一个非条件变换,类型为 NeuralAutoregressive
domain = IndependentConstraint(Real(), 1)
training: bool

ConditionalPlanar

class ConditionalPlanar(nn)[源代码]
一种条件‘平面’双射变换,使用了方程,

\(\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\) 是一个函数(例如 NN)的输出,该函数的输入为 \(z\in\mathbb{R}^{M}\),代表要作为条件的上下文变量。为了使其成为可逆变换,需要强制执行条件 \(\mathbf{w}^T\mathbf{u}>-1\)。

基类: pyro.distributions.conditional.ConditionalTransformModule

此变换的逆变换没有解析解,因此未实现。然而,当在采样期间调用前向操作时,逆变换会被缓存,因此可以使用平面变换采样的样本进行评分。

参考文献:[1] 使用归一化流进行变分推断 [arXiv:1505.05770] Danilo Jimenez Rezende, Shakir Mohamed

bijective = True

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

codomain = IndependentConstraint(Real(), 1)

参数

nn (callable) – 一个接收上下文变量并输出维度为 \((1, D, D)\) 的实值参数三元组的函数。

参考文献:[1] 使用归一化流的变分推断 [arXiv:1505.05770] Danilo Jimenez Rezende, Shakir Mohamed

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[源]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

ConditionalRadial

class ConditionalRadial(nn)[源]

基类: 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])) 

此变换的逆没有解析解,因此未实现。但是,在采样期间调用前向操作时,逆会被缓存,因此可以使用径向变换抽取的样本进行评分。

参数

input_dim (int) – 输入(和输出)变量的维度。

参考文献

[1] Danilo Jimenez Rezende, Shakir Mohamed. Variational Inference with Normalizing Flows. [arXiv:1505.05770]

bijective = True
codomain = IndependentConstraint(Real(), 1)
condition(context)[源]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = IndependentConstraint(Real(), 1)
training: bool

ConditionalSpline

class ConditionalSpline(nn, input_dim, count_bins, bound=3.0, order='linear')[源]

基类: pyro.distributions.conditional.ConditionalTransformModule

“线性”和“二次”阶元素级有理样条双射的实现 (Durkan et al., 2019; Dolatabadi et al., 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])) 
参数
  • input_dim (int) – 输入向量的维度。这是必需的,以便我们知道需要存储多少个参数。

  • count_bins (int) – 构成样条的段数。

  • bound (float) – 确定样条边界框 \([-K,K]\times[-K,K]\) 的量 \(K\)

  • order (string) – [‘linear’, ‘quadratic’] 之一,指定样条的阶数。

参考文献

Conor Durkan, Artur Bekasov, Iain Murray, George Papamakarios. Neural Spline Flows. NeurIPS 2019.

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. Invertible Generative Modeling using Linear Rational Splines. AISTATS 2020.

bijective = True
codomain = Real()
condition(context)[源]

参见 pyro.distributions.conditional.ConditionalTransformModule.condition()

domain = Real()
training: bool

ConditionalSplineAutoregressive

class ConditionalSplineAutoregressive(input_dim, autoregressive_nn, **kwargs)[源]

基类: pyro.distributions.conditional.ConditionalTransformModule

“线性”和“二次”阶有理样条双射的自回归层实现 (Durkan et al., 2019; Dolatabadi et al., 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]))  
参数
  • input_dim (int) – 输入向量的维度。尽管是元素级操作,但这是必需的,以便我们知道需要存储多少个参数。

  • autoregressive_nn (callable) – 一个自回归神经网络,其前向调用返回一个样条参数的元组。

  • count_bins (int) – 构成样条的段数。

  • bound (float) – 确定样条边界框 \([-K,K]\times[-K,K]\) 的量 \(K\)

  • order (string) – [‘linear’, ‘quadratic’] 之一,指定样条的阶数。

参考文献

Conor Durkan, Artur Bekasov, Iain Murray, George Papamakarios. Neural Spline Flows. NeurIPS 2019.

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. Invertible Generative Modeling using Linear Rational Splines. AISTATS 2020.

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
condition(context)[源]

基于上下文变量进行条件化,返回一个类型为 SplineAutoregressive 的非条件变换。

domain = IndependentConstraint(Real(), 1)
training: bool

ConditionalTransformModule

class ConditionalTransformModule(*args, **kwargs)[源]

父类:pyro.distributions.conditional.ConditionalTransform, torch.nn.modules.module.Module

带有可学习参数的条件变换,例如归一化流,应该继承此类而不是 ConditionalTransform,以便它们也是 Module 的子类,并继承该类的所有有用方法。

property inv: pyro.distributions.conditional.ConditionalTransformModule
training: bool

GeneralizedChannelPermute

class GeneralizedChannelPermute(channels=3, permutation=None)[源]

父类:pyro.distributions.transforms.generalized_channel_permute.ConditionedGeneralizedChannelPermute, pyro.distributions.torch_transform.TransformModule

一种双射,它推广了 \([\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\) 是一个输入和输出通道均为 \(C\) 的 1x1 卷积的滤波器矩阵。

忽略最后两个维度,\(W\) 被限制为矩阵乘积,

\(W = PLU\)

其中,\(P\sim C\times C\) 是通道维度上的置换矩阵,\(L\sim C\times C\) 是对角线上为一的下三角矩阵,\(U\sim C\times C\) 是上三角矩阵。\(W\) 被初始化为一个随机正交矩阵。然后,\(P\) 被固定,可学习参数设置为\(L,U\)

输入 \(\mathbf{x}\) 和输出 \(\mathbf{y}\) 的形状均为 […,C,H,W],其中 C 是初始化时设置的通道数。

此操作在 [1] 中为 Glow 归一化流引入,也称为 1x1 可逆卷积。它出现在 [2,3] 等其他著名工作中,对应于 TensorFlow Probability 中的 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()  
参数

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] Conor Durkan, Artur Bekasov, Iain Murray, George Papamakarios. 神经样条流。 [arXiv:1906.04032]

其中 \(P\sim C\times C\) 是通道维度上的置换矩阵,\(L\sim C\times C\) 是对角线上为一的下三角矩阵,\(U\sim C\times C\) 是上三角矩阵。\(W\) 初始化为随机正交矩阵。然后,\(P\) 被固定,可学习参数设置为 \(L,U\)
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)[源]

父类:pyro.distributions.transforms.householder.ConditionedHouseholder, pyro.distributions.torch_transform.TransformModule

\(\mathbf{y} = (I - 2*\frac{\mathbf{u}\mathbf{u}^T}{||\mathbf{u}||^2})\mathbf{x}\)

表示 Householder 双射变换的多次应用。单次 Householder 变换的形式为:

此变换表示 \(\mathbf{x}\) 经过原点且法向量为 \(\mathbf{u}\) 的平面进行的反射。

此变换应用 \(D\) 次后,能够将标准独立同分布的高斯噪声转换为具有任意协方差矩阵的高斯变量。使用 \(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()  
参数
  • input_dim (int) – 输入(和输出)变量的维度。

  • count_transforms (int) – 应用 Householder 变换的次数。

参考文献

[1] Jakub M. Tomczak, Max Welling. 使用 Householder 流改进变分自编码器。 [arXiv:1611.09630]

bijective = True
其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出,对于输入维度 \(D\),可学习参数是 \(\mathbf{u}\in\mathbb{R}^D\)
bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)

reset_parameters()[源]

volume_preserving = True

MatrixExponential

class MatrixExponential(input_dim, iterations=8, normalization='none', bound=None)[源]

\(\mathbf{y} = \exp(M)\mathbf{x}\)

父类:pyro.distributions.transforms.matrix_exponential.ConditionedMatrixExponential, pyro.distributions.torch_transform.TransformModule

由于矩阵指数有利的数学特性,该变换具有精确的逆变换和复杂度为 \(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()  
参数
  • input_dim (int) – 输入(和输出)变量的维度。

  • iterations (int) – 用于近似矩阵指数的截断幂级数中的项数。

  • normalization (string) – 选择应用于权重矩阵的归一化类型,选项为 [‘none’, ‘weight’, ‘spectral’]weight 对应于权重归一化 (Salimans and Kingma, 2016),spectral 对应于谱归一化 (Miyato et al, 2018)。

  • bound (float) – 当 normalization 参数选择权重或谱归一化时,对权重或谱范数的约束。较低的值会使截断幂级数需要更少的项来紧密近似矩阵指数的精确值。

参考文献

[1] Emiel Hoogeboom, Victor Garcia Satorras, Jakub M. Tomczak, Max Welling. 卷积指数和广义 Sylvester 流。 [arXiv:2006.01910]

[2] Tim Salimans, Diederik P. Kingma. 权重归一化:一种加速深度神经网络训练的简单重参数化方法。 [arXiv:1602.07868]

[3] Takeru Miyato, Toshiki Kataoka, Masanori Koyama, Yuichi Yoshida. 生成对抗网络的谱归一化。ICLR 2018。

bijective = True

codomain = IndependentConstraint(Real(), 1)

condition(context)[源代码]

一种密集矩阵指数双射变换 (Hoogeboom et al., 2020),使用以下公式:
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出,\(\exp(\cdot)\) 表示矩阵指数,对于输入维度 \(D\),可学习参数是 \(M\in\mathbb{R}^D\times\mathbb{R}^D\)。通常,\(M\) 不需要是可逆的。
bijective = True

codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)

domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)

基类: pyro.distributions.torch_transform.TransformModule

reset_parameters()[源]

示例用法

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

逆操作尚未实现。这需要数值求逆,例如使用求根方法——这是未来实现的一种可能性。

参数
  • [1] Chin-Wei Huang, David Krueger, Alexandre Lacoste, Aaron Courville. 神经自回归流。 [arXiv:1804.00779]

  • bijective = True

  • activation (string) – 使用的激活函数。选项包括 ‘ELU’, ‘LeakyReLU’, ‘sigmoid’, 或 ‘tanh’。

codomain = IndependentConstraint(Real(), 1)

condition(context)[源代码]

NeuralAutoregressive
class NeuralAutoregressive(autoregressive_nn, hidden_units=16, activation='sigmoid')[源]
一种深度神经网络自回归流 (NAF) 双射变换的实现,属于“IAF 风格”,可用于从其中抽取样本并对这些样本进行评分(但不能对任意样本进行评分)。
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)[源]

Planar

参考文献:[1] 使用归一化流进行变分推断 [arXiv:1505.05770] Danilo Jimenez Rezende, Shakir Mohamed

class Planar(input_dim)[源]

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

codomain = IndependentConstraint(Real(), 1)

参数

input_dim (int) – 输入(和输出)变量的维度。

参考文献

[1] Danilo Jimenez Rezende, Shakir Mohamed. Variational Inference with Normalizing Flows. [arXiv:1505.05770]

父类:pyro.distributions.transforms.planar.ConditionedPlanar, pyro.distributions.torch_transform.TransformModule
一种“平面”双射变换,使用以下公式:
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
其中 \(\mathbf{x}\) 是输入,\(\mathbf{y}\) 是输出,对于输入维度 \(D\),可学习参数是 \(b\in\mathbb{R}\), \(\mathbf{u}\in\mathbb{R}^D\), \(\mathbf{w}\in\mathbb{R}^D\)。为了使这是一个可逆变换,必须满足条件 \(\mathbf{w}^T\mathbf{u}>-1\)

bijective = True

codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)

基类: pyro.distributions.torch_transform.TransformModule

domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)

reset_parameters()[源]

Polynomial

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

class Polynomial(autoregressive_nn, input_dim, count_degree, count_sum)[源]

参数
  • 一种自回归双射变换,如 Jaini et al. (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\) 个元素,\(\left\{a^{(n)}_{r,k}\in\mathbb{R}\right\}\) 是可学习参数,它们是一个自回归神经网络的输出,该网络输入 \(x_{\prec n}={x_1,x_2,\ldots,x_{n-1}}\)

参考文献

此变换的逆没有解析解,因此未实现。但是,在采样期间调用前向操作时,逆会被缓存,因此可以使用多项式变换抽取的样本进行评分。

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]

计算对数雅可比行列式的逐元素值

reset_parameters()[source]

Radial

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

此变换的逆没有解析解,因此未实现。但是,在采样期间调用前向操作时,逆会被缓存,因此可以使用径向变换抽取的样本进行评分。

参数

input_dim (int) – 输入(和输出)变量的维度。

参考文献

[1] Danilo Jimenez Rezende, Shakir Mohamed. Variational Inference with Normalizing Flows. [arXiv:1505.05770]

bijective = True
codomain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
domain: torch.distributions.constraints.Constraint = IndependentConstraint(Real(), 1)
reset_parameters()[source]

Spline

class Spline(input_dim, count_bins=8, bound=3.0, order='linear')[source]

基类: pyro.distributions.transforms.spline.ConditionedSpline, pyro.distributions.torch_transform.TransformModule

一种元素级有理样条双射的实现,支持线性和二次阶(Durkan et al., 2019; Dolatabadi et al., 2020)。有理样条是由两个多项式之比构成的分段函数。

\(y_d = \frac{\alpha^{(k)}(x_d)}{\beta^{(k)}(x_d)},\)

例如,对于样条上的第\(d\)维和第\(k\)段,函数形式如下:其中\(\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()  
参数
  • input_dim (int) – 输入向量的维度。这是必需的,以便我们知道需要存储多少个参数。

  • count_bins (int) – 构成样条的段数。

  • bound (float) – 确定样条边界框 \([-K,K]\times[-K,K]\) 的量 \(K\)

  • order (string) – [‘linear’, ‘quadratic’] 之一,指定样条的阶数。

参考文献

Conor Durkan, Artur Bekasov, Iain Murray, George Papamakarios. Neural Spline Flows. NeurIPS 2019.

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. Invertible Generative Modeling using Linear Rational Splines. 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 et al., 2019; Dolatabadi et al., 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}\)的自回归NN的输出。

示例用法

>>> 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()  
参数
  • input_dim (int) – 输入向量的维度。尽管是元素级操作,但这是必需的,以便我们知道需要存储多少个参数。

  • autoregressive_nn (callable) – 一个自回归神经网络,其前向调用返回一个样条参数的元组。

  • count_bins (int) – 构成样条的段数。

  • bound (float) – 确定样条边界框 \([-K,K]\times[-K,K]\) 的量 \(K\)

  • order (string) – [‘linear’, ‘quadratic’] 之一,指定样条的阶数。

参考文献

Conor Durkan, Artur Bekasov, Iain Murray, George Papamakarios. Neural Spline Flows. NeurIPS 2019.

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. Invertible Generative Modeling using Linear Rational Splines. 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)[source]

计算对数雅可比行列式的逐元素值

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 et al., 2019; Dolatabadi et al., 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()  
参数
  • input_dim (int) – 输入向量的维度。尽管是元素级操作,但这是必需的,以便我们知道需要存储多少个参数。

  • split_dim – 零索引维度\(d\),用于对输入/输出进行分割以进行变换。

  • hypernet (可调用) – 一个神经网络,其前向调用返回一个样条参数元组(参见 ConditionalSpline)。

  • count_bins (int) – 构成样条的段数。

  • bound (float) – 确定样条边界框 \([-K,K]\times[-K,K]\) 的量 \(K\)

  • order (string) – [‘linear’, ‘quadratic’] 之一,指定样条的阶数。

参考文献

Conor Durkan, Artur Bekasov, Iain Murray, George Papamakarios. Neural Spline Flows. NeurIPS 2019.

Hadi M. Dolatabadi, Sarah Erfani, Christopher Leckie. Invertible Generative Modeling using Linear Rational Splines. 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)[source]

计算对数雅可比行列式的逐元素值

Sylvester

class Sylvester(input_dim, count_transforms=1)[source]

基类: pyro.distributions.transforms.householder.Householder

Householder 变体的 Sylvester 双射变换实现(Van den Berg Et Al., 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 的泛化。在 Householder 类型的 Sylvester 变换中,\(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 Normalizing Flows for Variational Inference. 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

TransformModule

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

ComposeTransformModule

class ComposeTransformModule(parts, cache_size=0)[source]

基类: torch.distributions.transforms.ComposeTransform, torch.nn.modules.container.ModuleList

这允许我们以与 ComposeTransform 相同的方式使用 TransformModule 列表。这是必要的,以便在使用 PyroModule 实例时,变换参数能被 Pyro 的参数存储自动注册。

with_cache(cache_size=1)[source]

变换工厂

每个 TransformTransformModule 都包含一个对应的小写字母辅助函数,它至少接受变换的输入维度,并可能接受附加参数,以直观的方式自定义变换。这些辅助函数的目的是向用户隐藏变换是否需要构造 hypernet,以及如果需要,该 hypernet 的输入和输出维度。

iterated

iterated(repeats, base_fn, *args, **kwargs)[source]

辅助函数,使用 ComposeTransformModule 组合一系列可能具有可学习参数的双射变换。

参数
  • repeats – 重复变换的次数。

  • base_fn – 用于构造双射变换的函数。

  • argsbase_fn 接受的参数。

  • kwargsbase_fn 接受的关键字参数。

返回

TransformModule 的实例。

affine_autoregressive

affine_autoregressive(input_dim, hidden_dims=None, **kwargs)[source]

一个辅助函数,用于创建 AffineAutoregressive 对象,负责构建具有正确输入/输出维度的自回归网络。

参数
  • input_dim (int) – 输入变量的维度

  • hidden_dims (list[int]) – 所需的自回归网络的隐藏维度。默认为使用 [3*input_dim + 1]

  • log_scale_min_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最小值

  • log_scale_max_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最大值

  • sigmoid_bias (float) – 在使用 stable 变换时添加到输入 logit 的项。

  • stable (bool) – 当为 True 时,使用备选的“stable”版本变换(见上文)。

affine_coupling

affine_coupling(input_dim, hidden_dims=None, split_dim=None, dim=- 1, **kwargs)[source]

一个辅助函数,用于创建 AffineCoupling 对象,负责构建具有正确输入/输出维度的密集网络。

参数
  • 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) – 用于裁剪自回归 NN 的 log(scale) 的最小值

  • log_scale_max_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最大值

batchnorm

batchnorm(input_dim, **kwargs)[source]

一个辅助函数,用于创建 BatchNorm 对象,与其他辅助函数保持一致性。

参数
  • input_dim (int) – 输入变量的维度

  • momentum (float) – 用于更新移动平均的动量参数

  • epsilon (float) – 添加到方差中的小数值,以确保数值稳定性

block_autoregressive

block_autoregressive(input_dim, **kwargs)[source]

一个辅助函数,用于创建 BlockAutoregressive 对象,与其他辅助函数保持一致性。

参数
  • input_dim (int) – 输入变量的维度

  • hidden_factors (list) – 第 i 个隐藏层在每个输入维度上有 hidden_factors[i] 个隐藏单元。这对应于 De Cao et al. (2019) 中的 \(a\) 和 \(b\)。hidden_factors 的元素必须是整数。

  • activation (string) – 使用的激活函数。选项包括 ‘ELU’, ‘LeakyReLU’, ‘sigmoid’, 或 ‘tanh’。

  • residual (string) – 使用的残差连接类型。选项包括 “None”,对于 \(\mathbf{y}+f(\mathbf{y})\) 使用 “normal”,以及对于可学习参数 \(\alpha\),对于 \(\alpha\mathbf{y} + (1 - \alpha\mathbf{y})\) 使用 “gated”。

conditional_affine_autoregressive

conditional_affine_autoregressive(input_dim, context_dim, hidden_dims=None, **kwargs)[source]

一个辅助函数,用于创建 ConditionalAffineAutoregressive 对象,负责构建具有正确输入/输出维度的密集网络。

参数
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 所需的密集网络的隐藏维度。默认为使用 [10*input_dim]

  • log_scale_min_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最小值

  • log_scale_max_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最大值

  • sigmoid_bias (float) – 在使用 stable 变换时添加到输入 logit 的项。

  • stable (bool) – 当为 True 时,使用备选的“stable”版本变换(见上文)。

conditional_affine_coupling

conditional_affine_coupling(input_dim, context_dim, hidden_dims=None, split_dim=None, dim=- 1, **kwargs)

一个辅助函数,用于创建 ConditionalAffineCoupling 对象,负责构建具有正确输入/输出维度的密集网络。

参数
  • 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) – 用于裁剪自回归 NN 的 log(scale) 的最小值

  • log_scale_max_clip (float) – 用于裁剪自回归 NN 的 log(scale) 的最大值

conditional_generalized_channel_permute

conditional_generalized_channel_permute(context_dim, channels=3, hidden_dims=None)[source]

一个辅助函数,用于创建 ConditionalGeneralizedChannelPermute 对象,与其他辅助函数保持一致性。

参数

channels (int) – 输入中的通道维度数量。

conditional_householder

conditional_householder(input_dim, context_dim, hidden_dims=None, count_transforms=1)[source]

一个辅助函数,用于创建 ConditionalHouseholder 对象,负责构建具有正确输入/输出维度的密集网络。

参数
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 所需的密集网络的隐藏维度。默认为使用 [input_dim * 10, input_dim * 10]

conditional_matrix_exponential

conditional_matrix_exponential(input_dim, context_dim, hidden_dims=None, iterations=8, normalization='none', bound=None)[source]

一个辅助函数,用于创建 ConditionalMatrixExponential 对象,与其他辅助函数保持一致性。

参数
  • 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 and Kingma, 2016),spectral 对应于谱归一化 (Miyato et al, 2018)。

  • bound (float) – 当 normalization 参数选择权重或谱归一化时,对权重或谱范数的约束。较低的值会使截断幂级数需要更少的项来紧密近似矩阵指数的精确值。

conditional_neural_autoregressive

conditional_neural_autoregressive(input_dim, context_dim, hidden_dims=None, activation='sigmoid', width=16)[source]

一个辅助函数,用于创建 ConditionalNeuralAutoregressive 对象,负责构建具有正确输入/输出维度的自回归网络。

参数
  • 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

conditional_planar(input_dim, context_dim, hidden_dims=None)[source]

一个辅助函数,用于创建 ConditionalPlanar 对象,负责构建具有正确输入/输出维度的密集网络。

参数
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 所需的密集网络的隐藏维度。默认为使用 [input_dim * 10, input_dim * 10]

conditional_radial

conditional_radial(input_dim, context_dim, hidden_dims=None)[source]

一个辅助函数,用于创建 ConditionalRadial 对象,负责构建具有正确输入/输出维度的密集网络。

参数
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 所需的密集网络的隐藏维度。默认为使用 [input_dim * 10, input_dim * 10]

conditional_spline

conditional_spline(input_dim, context_dim, hidden_dims=None, count_bins=8, bound=3.0, order='linear')[source]

一个辅助函数,用于创建 ConditionalSpline 对象,负责构建具有正确输入/输出维度的密集网络。

参数
  • 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

conditional_spline_autoregressive(input_dim, context_dim, hidden_dims=None, count_bins=8, bound=3.0, order='linear')[source]

一个辅助函数,用于创建 ConditionalSplineAutoregressive 对象,负责构建具有正确输入/输出维度的自回归网络。

参数
  • input_dim (int) – 输入变量的维度

  • context_dim (int) – 上下文变量的维度

  • hidden_dims (list[int]) – 所需的自回归网络的隐藏维度。默认为使用 [input_dim * 10, input_dim * 10]

  • count_bins (int) – 构成样条的段数。

  • bound (float) – 确定样条边界框 \([-K,K]\times[-K,K]\) 的量 \(K\)

  • order (string) – [‘linear’, ‘quadratic’] 之一,指定样条的阶数。

elu

elu()[source]

一个辅助函数,用于创建 ELUTransform 对象,与其他辅助函数保持一致性。

generalized_channel_permute

generalized_channel_permute(**kwargs)[source]

一个辅助函数,用于创建 GeneralizedChannelPermute 对象,与其他辅助函数保持一致性。

参数

channels (int) – 输入中的通道维度数量。

householder

householder(input_dim, count_transforms=None)[source]

一个辅助函数,用于创建 Householder 对象,与其他辅助函数保持一致性。

参数
  • input_dim (int) – 输入变量的维度

  • count_transforms (int) – 应用 Householder 变换的次数。

leaky_relu

leaky_relu()[source]

一个辅助函数,用于创建 LeakyReLUTransform 对象,与其他辅助函数保持一致性。

matrix_exponential

matrix_exponential(input_dim, iterations=8, normalization='none', bound=None)[source]

一个辅助函数,用于创建 MatrixExponential 对象,与其他辅助函数保持一致性。

参数
  • input_dim (int) – 输入变量的维度

  • iterations (int) – 用于近似矩阵指数的截断幂级数中的项数。

  • normalization (string) – 选择应用于权重矩阵的归一化类型,选项为 [‘none’, ‘weight’, ‘spectral’]weight 对应于权重归一化 (Salimans and Kingma, 2016),spectral 对应于谱归一化 (Miyato et al, 2018)。

  • bound (float) – 当 normalization 参数选择权重或谱归一化时,对权重或谱范数的约束。较低的值会使截断幂级数需要更少的项来紧密近似矩阵指数的精确值。

neural_autoregressive

neural_autoregressive(input_dim, hidden_dims=None, activation='sigmoid', width=16)[source]

一个辅助函数,用于创建 NeuralAutoregressive 对象,负责构建具有正确输入/输出维度的自回归网络。

参数
  • input_dim (int) – 输入变量的维度

  • hidden_dims (list[int]) – 所需的自回归网络的隐藏维度。默认为使用 [3*input_dim + 1]

  • activation (string) – 使用的激活函数。选项包括 ‘ELU’, ‘LeakyReLU’, ‘sigmoid’, 或 ‘tanh’。

  • width (int) – 变换中“多层感知机”的宽度(参见论文)。默认为 16

permute

permute(input_dim, permutation=None, dim=- 1)[source]

一个辅助函数,用于创建 Permute 对象,与其他辅助函数保持一致性。

参数
  • input_dim (int) – 要置换的输入变量的维度。注意,当 dim < -1 时,这必须是对应于事件形状的元组。

  • permutation (torch.LongTensor) – 表示置换的整数索引的 Torch 张量。默认为随机置换。

  • dim (int) – 要置换的张量维度。此值必须为负数,并将事件维度定义为 abs(dim)

planar

planar(input_dim)[source]

一个辅助函数,用于创建 Planar 对象,与其他辅助函数保持一致性。

参数

input_dim (int) – 输入变量的维度

polynomial

polynomial(input_dim, hidden_dims=None)[source]

一个辅助函数,用于创建 Polynomial 对象,负责构建具有正确输入/输出维度的自回归网络。

参数
  • input_dim (int) – 输入变量的维度

  • hidden_dims – 所需的自回归网络的隐藏维度。默认为使用 [input_dim * 10]

radial

radial(input_dim)[source]

一个辅助函数,用于创建 Radial 对象,与其他辅助函数保持一致性。

参数

input_dim (int) – 输入变量的维度

spline

spline(input_dim, **kwargs)[source]

一个辅助函数,用于创建 Spline 对象,与其他辅助函数保持一致性。

参数

input_dim (int) – 输入变量的维度

spline_autoregressive

spline_autoregressive(input_dim, hidden_dims=None, count_bins=8, bound=3.0, order='linear')[source]

一个辅助函数,用于创建 SplineAutoregressive 对象,负责构建具有正确输入/输出维度的自回归网络。

参数
  • input_dim (int) – 输入变量的维度

  • hidden_dims (list[int]) – 所需的自回归网络的隐藏维度。默认为使用 [3*input_dim + 1]

  • count_bins (int) – 构成样条的段数。

  • bound (float) – 确定样条边界框 \([-K,K]\times[-K,K]\) 的量 \(K\)

  • order (string) – [‘linear’, ‘quadratic’] 之一,指定样条的阶数。

spline_coupling

spline_coupling(input_dim, split_dim=None, hidden_dims=None, count_bins=8, bound=3.0)[source]

一个辅助函数,用于创建 SplineCoupling 对象,与其他辅助函数保持一致性。

参数

input_dim (int) – 输入变量的维度

sylvester

sylvester(input_dim, count_transforms=None)[source]

一个辅助函数,用于创建 Sylvester 对象,与其他辅助函数保持一致性。

参数
  • 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

cat

别名:torch.distributions.constraints.cat

corr_cholesky

别名:torch.distributions.constraints.corr_cholesky

corr_cholesky_constraint

别名:torch.distributions.constraints.corr_cholesky_constraint

corr_matrix

class _CorrMatrix[source]

约束为相关矩阵。

dependent

别名:torch.distributions.constraints.dependent

dependent_property

别名:torch.distributions.constraints.dependent_property

greater_than

别名:torch.distributions.constraints.greater_than

greater_than_eq

别名:torch.distributions.constraints.greater_than_eq

半开区间

别名:torch.distributions.constraints.half_open_interval

independent

别名:torch.distributions.constraints.independent

整数

class _Integer[source]

约束为整数。

整数区间

别名:torch.distributions.constraints.integer_interval

区间

别名:torch.distributions.constraints.interval

is_dependent

别名:torch.distributions.constraints.is_dependent

less_than

别名:torch.distributions.constraints.less_than

lower_cholesky

别名:torch.distributions.constraints.lower_cholesky

lower_triangular

别名:torch.distributions.constraints.lower_triangular

multinomial

别名: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[source]

球面

class _Sphere[source]

约束为任意维度的欧几里得球面。

方阵

别名:torch.distributions.constraints.square

堆叠

别名:torch.distributions.constraints.stack

对称阵

别名:torch.distributions.constraints.symmetric

单位区间

别名:torch.distributions.constraints.unit_interval

单位下三角Cholesky

class _UnitLowerCholesky[source]

约束为对角线全为1的下三角方阵。