概率分布 - torch.distributions¶
The distributions 包含可参数化的概率分布和采样函数。 这允许构建随机计算图和随机梯度估计器以进行优化。 此包通常遵循 TensorFlow 分布 包的设计。
无法直接通过随机样本进行反向传播。 但是,有两种主要方法可以创建可以反向传播的代理函数。 它们是分数函数估计器/似然比估计器/REINFORCE 和路径导数估计器。 REINFORCE 通常被视为强化学习中策略梯度方法的基础,而路径导数估计器通常在变分自动编码器中的重新参数化技巧中被看到。 虽然分数函数只需要样本的值 ,路径导数需要导数 。 以下部分将讨论强化学习示例中的这两个方面。 有关更多详细信息,请参阅 使用随机计算图的梯度估计。
分数函数¶
当概率密度函数关于其参数可微时,我们只需要 sample() 和 log_prob() 来实现 REINFORCE
其中 是参数, 是学习率, 是奖励, 是在策略 下,在状态 中采取动作 的概率。
在实践中,我们会从网络输出中采样一个动作,在环境中应用这个动作,然后使用 log_prob 来构建等效的损失函数。需要注意的是,我们使用负号是因为优化器使用梯度下降,而上面的规则假设梯度上升。对于分类策略,实现 REINFORCE 的代码如下:
probs = policy_network(state)
# Note that this is equivalent to what used to be called multinomial
m = Categorical(probs)
action = m.sample()
next_state, reward = env.step(action)
loss = -m.log_prob(action) * reward
loss.backward()
路径导数¶
实现这些随机/策略梯度的另一种方法是使用来自 rsample() 方法的重新参数化技巧,其中参数化的随机变量可以通过无参数随机变量的参数化确定性函数来构建。因此,重新参数化的样本变得可微。实现路径导数的代码如下:
params = policy_network(state)
m = Normal(*params)
# Any distribution with .has_rsample == True could work based on the application
action = m.rsample()
next_state, reward = env.step(action) # Assuming that reward is differentiable
loss = -reward
loss.backward()
分布¶
- class torch.distributions.distribution.Distribution(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)[source]¶
基类:
objectDistribution 是概率分布的抽象基类。
- property arg_constraints: Dict[str, Constraint]¶
返回一个字典,从参数名称映射到
Constraint对象,这些对象应该由该分布的每个参数满足。非张量参数不需要出现在此字典中。
- enumerate_support(expand=True)[source]¶
返回包含离散分布支持的所有值的张量。结果将枚举维度 0,因此结果的形状将为 (cardinality,) + batch_shape + event_shape(其中对于单变量分布 event_shape = ())。
请注意,这会同步枚举所有批处理张量 [[0, 0], [1, 1], …]。使用 expand=False,枚举发生在 dim 0 处,但其余批处理维度是单例维度,[[0], [1], ...
要迭代完整的笛卡尔积,请使用 itertools.product(m.enumerate_support())。
- expand(batch_shape, _instance=None)[source]¶
返回一个新的分布实例(或填充由派生类提供的现有实例),其批处理维度扩展到 batch_shape。此方法在分布的参数上调用
expand。因此,这不会为扩展的分布实例分配新的内存。此外,这不会在创建实例时重复 __init__.py 中的任何参数检查或参数广播。- 参数
batch_shape (torch.Size) – 期望的扩展大小。
_instance – 由需要覆盖 .expand 的子类提供的新的实例。
- 返回值
批处理维度扩展到 batch_size 的新的分布实例。
- rsample(sample_shape=torch.Size([]))[source]¶
如果分布参数是批处理的,则生成一个 sample_shape 形状的重新参数化样本,或者一个 sample_shape 形状的重新参数化样本批。
- 返回类型
- sample(sample_shape=torch.Size([]))[source]¶
如果分布参数是批处理的,则生成一个 sample_shape 形状的样本,或者一个 sample_shape 形状的样本批。
- 返回类型
- static set_default_validate_args(value)[source]¶
设置是否启用或禁用验证。
默认行为模仿 Python 的
assert语句:验证默认情况下处于启用状态,但如果 Python 在优化模式下运行(通过python -O),则被禁用。验证可能很昂贵,因此您可能希望在模型正常工作后将其禁用。- 参数
value (bool) – 是否启用验证。
- property support: Optional[Any]¶
返回一个
Constraint对象,表示该分布的支持。
指数族¶
- class torch.distributions.exp_family.ExponentialFamily(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)[source]¶
Bases:
DistributionExponentialFamily 是概率分布的抽象基类,这些概率分布属于指数族,其概率质量/密度函数的形式定义如下
其中 表示自然参数, 表示充分统计量, 是给定族对数归一化函数, 是载体测度。
注意
此类是 Distribution 类和属于指数族的分布之间的中介,主要用于检查 .entropy() 和解析 KL 散度方法的正确性。我们使用此类使用 AD 框架和 Bregman 散度(由 Frank Nielsen 和 Richard Nock 提供:指数族的熵和交叉熵)来计算熵和 KL 散度。
伯努利¶
- class torch.distributions.bernoulli.Bernoulli(probs=None, logits=None, validate_args=None)[source]¶
Bases:
ExponentialFamily创建一个由
probs或logits(但不是两者)参数化的伯努利分布。样本是二进制的(0 或 1)。它们以概率 p 接受值 1,以概率 1 - p 接受值 0。
示例
>>> m = Bernoulli(torch.tensor([0.3])) >>> m.sample() # 30% chance 1; 70% chance 0 tensor([ 0.])
- arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶
- has_enumerate_support = True¶
- property logits¶
- property mean¶
- property mode¶
- property param_shape¶
- property probs¶
- support = Boolean()¶
- property variance¶
Beta¶
- class torch.distributions.beta.Beta(concentration1, concentration0, validate_args=None)[source]¶
Bases:
ExponentialFamilyBeta 分布,由
concentration1和concentration0参数化。示例
>>> m = Beta(torch.tensor([0.5]), torch.tensor([0.5])) >>> m.sample() # Beta distributed with concentration concentration1 and concentration0 tensor([ 0.1046])
- 参数
- arg_constraints = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)}¶
- property concentration0¶
- property concentration1¶
- has_rsample = True¶
- property mean¶
- property mode¶
- support = Interval(lower_bound=0.0, upper_bound=1.0)¶
- property variance¶
Binomial¶
- class torch.distributions.binomial.Binomial(total_count=1, probs=None, logits=None, validate_args=None)[source]¶
Bases:
Distribution创建一个由
total_count和probs或logits(但不是两者)参数化的二项式分布。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.]])
- arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0), 'total_count': IntegerGreaterThan(lower_bound=0)}¶
- has_enumerate_support = True¶
- property logits¶
- property mean¶
- property mode¶
- property param_shape¶
- property probs¶
- property support¶
- property variance¶
Categorical¶
- class torch.distributions.categorical.Categorical(probs=None, logits=None, validate_args=None)[source]¶
Bases:
Distribution创建一个由
probs或logits参数化(但不能同时使用)的分类分布。注意
它等效于
torch.multinomial()从中采样的分布。样本是来自 的整数,其中 K 是
probs.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)
- arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶
- has_enumerate_support = True¶
- property logits¶
- property mean¶
- property mode¶
- property param_shape¶
- property probs¶
- property support¶
- property variance¶
Cauchy¶
- class torch.distributions.cauchy.Cauchy(loc, scale, validate_args=None)[source]¶
Bases:
Distribution从柯西(洛伦兹)分布中采样。独立正态分布随机变量的比率分布(均值为 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])
- arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- support = Real()¶
- property variance¶
Chi2¶
- class torch.distributions.chi2.Chi2(df, validate_args=None)[source]¶
Bases:
Gamma创建由形状参数
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])
- arg_constraints = {'df': GreaterThan(lower_bound=0.0)}¶
- property df¶
ContinuousBernoulli¶
- class torch.distributions.continuous_bernoulli.ContinuousBernoulli(probs=None, logits=None, lims=(0.499, 0.501), validate_args=None)[source]¶
Bases:
ExponentialFamily创建一个由
probs或logits(但不是两者)参数化的连续伯努利分布。该分布在 [0, 1] 中受支持,并由“probs”(在(0,1)中)或“logits”(实值)参数化。请注意,与伯努利不同,“probs”不对应于概率,“logits”不对应于对数几率,但由于与伯努利的相似性,使用相同的名称。有关更多详细信息,请参见 [1]。
示例
>>> m = ContinuousBernoulli(torch.tensor([0.3])) >>> m.sample() tensor([ 0.2538])
[1] 连续伯努利:修复变分自动编码器中的普遍错误,Loaiza-Ganem G 和 Cunningham JP,NeurIPS 2019。 https://arxiv.org/abs/1907.06845
- arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶
- has_rsample = True¶
- property logits¶
- property mean¶
- property param_shape¶
- property probs¶
- property stddev¶
- support = Interval(lower_bound=0.0, upper_bound=1.0)¶
- property variance¶
Dirichlet¶
- class torch.distributions.dirichlet.Dirichlet(concentration, validate_args=None)[source]¶
Bases:
ExponentialFamily创建以浓度
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)
- arg_constraints = {'concentration': IndependentConstraint(GreaterThan(lower_bound=0.0), 1)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- support = Simplex()¶
- property variance¶
Exponential¶
- class torch.distributions.exponential.Exponential(rate, validate_args=None)[source]¶
Bases:
ExponentialFamily创建以
rate为参数的指数分布。示例
>>> m = Exponential(torch.tensor([1.0])) >>> m.sample() # Exponential distributed with rate=1 tensor([ 0.1046])
- arg_constraints = {'rate': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property stddev¶
- support = GreaterThanEq(lower_bound=0.0)¶
- property variance¶
FisherSnedecor¶
- class torch.distributions.fishersnedecor.FisherSnedecor(df1, df2, validate_args=None)[source]¶
Bases:
Distribution创建以
df1和df2为参数的费希尔-斯尼德科分布。示例
>>> m = FisherSnedecor(torch.tensor([1.0]), torch.tensor([2.0])) >>> m.sample() # Fisher-Snedecor-distributed with df1=1 and df2=2 tensor([ 0.2453])
- arg_constraints = {'df1': GreaterThan(lower_bound=0.0), 'df2': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- support = GreaterThan(lower_bound=0.0)¶
- property variance¶
Gamma¶
- class torch.distributions.gamma.Gamma(concentration, rate, validate_args=None)[source]¶
Bases:
ExponentialFamily创建一个由形状
concentration和rate参数化的 Gamma 分布。示例
>>> m = Gamma(torch.tensor([1.0]), torch.tensor([1.0])) >>> m.sample() # Gamma distributed with concentration=1 and rate=1 tensor([ 0.1046])
- 参数
- arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- support = GreaterThanEq(lower_bound=0.0)¶
- property variance¶
Geometric¶
- class torch.distributions.geometric.Geometric(probs=None, logits=None, validate_args=None)[source]¶
Bases:
Distribution创建一个由
probs参数化的几何分布,其中probs是伯努利试验成功的概率。注意
torch.distributions.geometric.Geometric()-th trial is the first success hence draws samples in , whereastorch.Tensor.geometric_()k-th trial is the first success hence draws samples in .示例
>>> m = Geometric(torch.tensor([0.3])) >>> m.sample() # underlying Bernoulli has 30% chance 1; 70% chance 0 tensor([ 2.])
- arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶
- property logits¶
- property mean¶
- property mode¶
- property probs¶
- support = IntegerGreaterThan(lower_bound=0)¶
- property variance¶
Gumbel¶
- class torch.distributions.gumbel.Gumbel(loc, scale, validate_args=None)[source]¶
Bases:
TransformedDistribution从 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])
- arg_constraints: Dict[str, Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
- property mean¶
- property mode¶
- property stddev¶
- support = Real()¶
- property variance¶
HalfCauchy¶
- class torch.distributions.half_cauchy.HalfCauchy(scale, validate_args=None)[source]¶
Bases:
TransformedDistribution创建一个由 scale 参数化的半柯西分布,其中
X ~ Cauchy(0, scale) Y = |X| ~ HalfCauchy(scale)
示例
>>> m = HalfCauchy(torch.tensor([1.0])) >>> m.sample() # half-cauchy distributed with scale=1 tensor([ 2.3214])
- arg_constraints: Dict[str, Constraint] = {'scale': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property scale¶
- support = GreaterThanEq(lower_bound=0.0)¶
- property variance¶
HalfNormal¶
- class torch.distributions.half_normal.HalfNormal(scale, validate_args=None)[source]¶
Bases:
TransformedDistribution创建一个由 scale 参数化的半正态分布,其中
X ~ Normal(0, scale) Y = |X| ~ HalfNormal(scale)
示例
>>> m = HalfNormal(torch.tensor([1.0])) >>> m.sample() # half-normal distributed with scale=1 tensor([ 0.1046])
- arg_constraints: Dict[str, Constraint] = {'scale': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property scale¶
- support = GreaterThanEq(lower_bound=0.0)¶
- property variance¶
Independent¶
- class torch.distributions.independent.Independent(base_distribution, reinterpreted_batch_ndims, validate_args=None)[source]¶
Bases:
Distribution将分布的某些批次维度重新解释为事件维度。
这主要用于更改
log_prob()的结果形状。例如,要创建与多元正态分布形状相同的对角正态分布(因此它们是可互换的),您可以>>> from torch.distributions.multivariate_normal import MultivariateNormal >>> from torch.distributions.normal import Normal >>> loc = torch.zeros(3) >>> scale = torch.ones(3) >>> mvn = MultivariateNormal(loc, scale_tril=torch.diag(scale)) >>> [mvn.batch_shape, mvn.event_shape] [torch.Size([]), torch.Size([3])] >>> normal = Normal(loc, scale) >>> [normal.batch_shape, normal.event_shape] [torch.Size([3]), torch.Size([])] >>> diagn = Independent(normal, 1) >>> [diagn.batch_shape, diagn.event_shape] [torch.Size([]), torch.Size([3])]
- 参数
base_distribution (torch.distributions.distribution.Distribution) – 基础分布
reinterpreted_batch_ndims (int) – 要重新解释为事件维度的批次维度的数量
- arg_constraints: Dict[str, Constraint] = {}¶
- property has_enumerate_support¶
- property has_rsample¶
- property mean¶
- property mode¶
- property support¶
- property variance¶
InverseGamma¶
- class torch.distributions.inverse_gamma.InverseGamma(concentration, rate, validate_args=None)[source]¶
Bases:
TransformedDistribution创建一个由
concentration和rate参数化的逆伽马分布,其中X ~ Gamma(concentration, rate) Y = 1 / X ~ InverseGamma(concentration, rate)
示例
>>> m = InverseGamma(torch.tensor([2.0]), torch.tensor([3.0])) >>> m.sample() tensor([ 1.2953])
- 参数
- arg_constraints: Dict[str, Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}¶
- property concentration¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property rate¶
- support = GreaterThan(lower_bound=0.0)¶
- property variance¶
Kumaraswamy¶
- class torch.distributions.kumaraswamy.Kumaraswamy(concentration1, concentration0, validate_args=None)[source]¶
Bases:
TransformedDistribution从 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])
- 参数
- arg_constraints: Dict[str, Constraint] = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- support = Interval(lower_bound=0.0, upper_bound=1.0)¶
- property variance¶
LKJCholesky¶
- class torch.distributions.lkj_cholesky.LKJCholesky(dim, concentration=1.0, validate_args=None)[source]¶
Bases:
Distribution用于相关矩阵的下三角矩阵的 LKJ 分布。该分布由
concentration参数 控制,以使相关矩阵 的概率(从下三角矩阵生成)与 成比例。因此,当concentration == 1时,我们在相关矩阵的下三角矩阵上有一个均匀分布。L ~ LKJCholesky(dim, concentration) X = L @ L' ~ LKJCorr(dim, concentration)
注意,该分布对相关矩阵的下三角矩阵进行采样,而不是相关矩阵本身,因此与 [1] 中关于 LKJCorr 分布的推导略有不同。为了采样,这使用了 [1] 第 3 节中的洋葱法。
示例
>>> 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]])
参考文献
[1] 基于藤和扩展洋葱法的随机相关矩阵生成 (2009),Daniel Lewandowski,Dorota Kurowicka,Harry Joe。多元分析杂志。100. 10.1016/j.jmva.2009.04.008
- arg_constraints = {'concentration': GreaterThan(lower_bound=0.0)}¶
- support = CorrCholesky()¶
Laplace¶
- class torch.distributions.laplace.Laplace(loc, scale, validate_args=None)[source]¶
Bases:
Distribution创建一个由
loc和scale参数化的拉普拉斯分布。示例
>>> m = Laplace(torch.tensor([0.0]), torch.tensor([1.0])) >>> m.sample() # Laplace distributed with loc=0, scale=1 tensor([ 0.1046])
- arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property stddev¶
- support = Real()¶
- property variance¶
LogNormal¶
- class torch.distributions.log_normal.LogNormal(loc, scale, validate_args=None)[source]¶
Bases:
TransformedDistribution创建一个对数正态分布,该分布由
loc和scale参数化,其中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])
- arg_constraints: Dict[str, Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property loc¶
- property mean¶
- property mode¶
- property scale¶
- support = GreaterThan(lower_bound=0.0)¶
- property variance¶
LowRankMultivariateNormal¶
- class torch.distributions.lowrank_multivariate_normal.LowRankMultivariateNormal(loc, cov_factor, cov_diag, validate_args=None)[source]¶
Bases:
Distribution创建一个具有低秩形式协方差矩阵的多元正态分布,该分布由
cov_factor和cov_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])
- 参数
注意
当 cov_factor.shape[1] << cov_factor.shape[0] 时,由于 Woodbury 矩阵恒等式 和 矩阵行列式引理,避免了对协方差矩阵的行列式和逆的计算。由于这些公式,我们只需要计算小尺寸“电容”矩阵的行列式和逆
capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor
- arg_constraints = {'cov_diag': IndependentConstraint(GreaterThan(lower_bound=0.0), 1), 'cov_factor': IndependentConstraint(Real(), 2), 'loc': IndependentConstraint(Real(), 1)}¶
- property covariance_matrix¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property precision_matrix¶
- property scale_tril¶
- support = IndependentConstraint(Real(), 1)¶
- property variance¶
MixtureSameFamily¶
- class torch.distributions.mixture_same_family.MixtureSameFamily(mixture_distribution, component_distribution, validate_args=None)[source]¶
Bases:
DistributionMixtureSameFamily 分布实现了一个(一批)混合分布,其中所有分量都来自同一分布类型的不同参数化。 它由一个 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 Model in 2D consisting of 5 equally >>> # weighted bivariate normal distributions >>> mix = D.Categorical(torch.ones(5,)) >>> comp = D.Independent(D.Normal( ... torch.randn(5,2), torch.rand(5,2)), 1) >>> gmm = MixtureSameFamily(mix, comp) >>> # Construct a batch of 3 Gaussian Mixture Models in 2D each >>> # consisting of 5 random weighted bivariate normal distributions >>> mix = D.Categorical(torch.rand(3,5)) >>> comp = D.Independent(D.Normal( ... torch.randn(3,5,2), torch.rand(3,5,2)), 1) >>> gmm = MixtureSameFamily(mix, comp)
- 参数
mixture_distribution – torch.distributions.Categorical 类实例。 管理选择分量的概率。 类别数量必须与 component_distribution 的最右边的批处理维度匹配。 必须具有标量 batch_shape 或与 component_distribution.batch_shape[:-1] 匹配的 batch_shape
component_distribution – torch.distributions.Distribution 类实例。 最右边的批处理维度索引分量。
- arg_constraints: Dict[str, Constraint] = {}¶
- property component_distribution¶
- has_rsample = False¶
- property mean¶
- property mixture_distribution¶
- property support¶
- property variance¶
Multinomial¶
- class torch.distributions.multinomial.Multinomial(total_count=1, probs=None, logits=None, validate_args=None)[source]¶
Bases:
Distribution创建一个由
total_count参数化的多项式分布,或者由probs或logits参数化(但不能同时参数化)。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])
- arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶
- property logits¶
- property mean¶
- property param_shape¶
- property probs¶
- property support¶
- property variance¶
MultivariateNormal¶
- class torch.distributions.multivariate_normal.MultivariateNormal(loc, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[source]¶
Bases:
Distribution创建多元正态(也称为高斯)分布,由均值向量和协方差矩阵参数化。
多元正态分布可以通过正定协方差矩阵 或正定精度矩阵 或下三角矩阵 (对角线元素为正值),使得 参数化。此三角矩阵可通过例如协方差的 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])
- 参数
注意
只能指定
covariance_matrix或precision_matrix或scale_tril之一。使用
scale_tril将更高效:所有内部计算都基于scale_tril。如果传递了covariance_matrix或precision_matrix,它仅用于使用 Cholesky 分解计算相应的下三角矩阵。- arg_constraints = {'covariance_matrix': PositiveDefinite(), 'loc': IndependentConstraint(Real(), 1), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}¶
- property covariance_matrix¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property precision_matrix¶
- property scale_tril¶
- support = IndependentConstraint(Real(), 1)¶
- property variance¶
负二项分布¶
- class torch.distributions.negative_binomial.NegativeBinomial(total_count, probs=None, logits=None, validate_args=None)[source]¶
Bases:
Distribution创建负二项分布,即在获得
total_count次失败之前成功的独立同分布伯努利试验次数的分布。每次伯努利试验成功的概率为probs。- 参数
- arg_constraints = {'logits': Real(), 'probs': HalfOpenInterval(lower_bound=0.0, upper_bound=1.0), 'total_count': GreaterThanEq(lower_bound=0)}¶
- property logits¶
- property mean¶
- property mode¶
- property param_shape¶
- property probs¶
- support = IntegerGreaterThan(lower_bound=0)¶
- property variance¶
正态分布¶
- class torch.distributions.normal.Normal(loc, scale, validate_args=None)[source]¶
Bases:
ExponentialFamily创建正态分布(也称为高斯分布),由
loc和scale参数化。示例
>>> m = Normal(torch.tensor([0.0]), torch.tensor([1.0])) >>> m.sample() # normally distributed with loc=0 and scale=1 tensor([ 0.1046])
- arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property stddev¶
- support = Real()¶
- property variance¶
独热分类分布¶
- class torch.distributions.one_hot_categorical.OneHotCategorical(probs=None, logits=None, validate_args=None)[source]¶
Bases:
Distribution样本是大小为
probs.size(-1)的独热编码向量。注意
probs 参数必须是非负、有限的并且具有非零和,并且它将在最后一个维度上被归一化为和为 1。
probs将返回此归一化值。 logits 参数将被解释为未归一化的对数概率,因此可以是任何实数。 它也将被归一化,以便得到的概率沿最后一个维度之和为 1。logits将返回此归一化值。另见:
torch.distributions.Categorical()用于probs和logits的规范。示例
>>> 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.])
- arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶
- has_enumerate_support = True¶
- property logits¶
- property mean¶
- property mode¶
- property param_shape¶
- property probs¶
- support = OneHot()¶
- property variance¶
帕累托¶
- class torch.distributions.pareto.Pareto(scale, alpha, validate_args=None)[source]¶
Bases:
TransformedDistribution从帕累托类型 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])
- arg_constraints: Dict[str, Constraint] = {'alpha': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)}¶
- property mean¶
- property mode¶
- property support¶
- property variance¶
泊松¶
- class torch.distributions.poisson.Poisson(rate, validate_args=None)[source]¶
Bases:
ExponentialFamily创建一个由
rate参数化的泊松分布,它是速率参数。样本是非负整数,其 pmf 由下式给出
示例
>>> m = Poisson(torch.tensor([4])) >>> m.sample() tensor([ 3.])
- 参数
rate (Number, Tensor) – 速率参数
- arg_constraints = {'rate': GreaterThanEq(lower_bound=0.0)}¶
- property mean¶
- property mode¶
- support = IntegerGreaterThan(lower_bound=0)¶
- property variance¶
RelaxedBernoulli¶
- class torch.distributions.relaxed_bernoulli.RelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)[source]¶
Bases:
TransformedDistribution创建 RelaxedBernoulli 分布,由
temperature参数化,并使用probs或logits(但不能同时使用)参数化。 这是一个 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])
- 参数
- arg_constraints: Dict[str, Constraint] = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶
- has_rsample = True¶
- property logits¶
- property probs¶
- support = Interval(lower_bound=0.0, upper_bound=1.0)¶
- property temperature¶
LogitRelaxedBernoulli¶
- class torch.distributions.relaxed_bernoulli.LogitRelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)[source]¶
Bases:
Distribution创建 LogitRelaxedBernoulli 分布,由
probs或logits(但不能同时使用)参数化,它是 RelaxedBernoulli 分布的 logit。样本是 (0, 1) 中值的 logit。有关详细信息,请参阅 [1]。
- 参数
[1] The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables (Maddison et al., 2017)
[2] Categorical Reparametrization with Gumbel-Softmax (Jang et al., 2017)
- arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶
- property logits¶
- property param_shape¶
- property probs¶
- support = Real()¶
RelaxedOneHotCategorical¶
- class torch.distributions.relaxed_categorical.RelaxedOneHotCategorical(temperature, probs=None, logits=None, validate_args=None)[source]¶
Bases:
TransformedDistribution创建一个由
temperature参数化的 RelaxedOneHotCategorical 分布,以及probs或logits。 这是一个对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])
- arg_constraints: Dict[str, Constraint] = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶
- has_rsample = True¶
- property logits¶
- property probs¶
- support = Simplex()¶
- property temperature¶
学生t分布¶
- class torch.distributions.studentT.StudentT(df, loc=0.0, scale=1.0, validate_args=None)[source]¶
Bases:
Distribution创建一个由自由度
df、均值loc和尺度scale参数化的学生t分布。示例
>>> m = StudentT(torch.tensor([2.0])) >>> m.sample() # Student's t-distributed with degrees of freedom=2 tensor([ 0.1046])
- arg_constraints = {'df': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- support = Real()¶
- property variance¶
变换分布¶
- class torch.distributions.transformed_distribution.TransformedDistribution(base_distribution, transforms, validate_args=None)[source]¶
Bases:
DistributionDistribution 类的扩展,它将一系列变换应用于基本分布。 令 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)
有关更多示例,请查看
Gumbel、HalfCauchy、HalfNormal、LogNormal、Pareto、Weibull、RelaxedBernoulli和RelaxedOneHotCategorical的实现。- arg_constraints: Dict[str, Constraint] = {}¶
- property has_rsample¶
- rsample(sample_shape=torch.Size([]))[source]¶
如果分布参数是批量的,则生成一个 sample_shape 形状的重新参数化样本或 sample_shape 形状的重新参数化样本批次。首先从基本分布中采样,然后对列表中的每个转换应用 transform()。
- 返回类型
- sample(sample_shape=torch.Size([]))[source]¶
如果分布参数是批量的,则生成一个 sample_shape 形状的样本或 sample_shape 形状的样本批次。首先从基本分布中采样,然后对列表中的每个转换应用 transform()。
- property support¶
Uniform¶
- class torch.distributions.uniform.Uniform(low, high, validate_args=None)[source]¶
Bases:
Distribution从半开区间
[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])
- arg_constraints = {'high': Dependent(), 'low': Dependent()}¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property stddev¶
- property support¶
- property variance¶
VonMises¶
- class torch.distributions.von_mises.VonMises(loc, concentration, validate_args=None)[source]¶
Bases:
Distribution循环 von Mises 分布。
此实现使用极坐标。
loc和value参数可以是任何实数(便于无约束优化),但被解释为模 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])
- 参数
loc (torch.Tensor) – 以弧度表示的角度。
concentration (torch.Tensor) – 集中参数
- arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'loc': Real()}¶
- has_rsample = False¶
- property mean¶
提供的平均值是循环的。
- property mode¶
- sample(sample_shape=torch.Size([]))[source]¶
von Mises 分布的采样算法基于以下论文:D.J. Best 和 N.I. Fisher,“von Mises 分布的有效模拟”。应用统计 (1979): 152-157。
采样始终在内部以双精度进行,以避免在浓度值较小时,_rejection_sample() 中出现挂起,对于单精度,这种情况大约在 1e-4 时开始发生(参见问题 #88443)。
- support = Real()¶
- property variance¶
提供的方差是循环的。
Weibull¶
- class torch.distributions.weibull.Weibull(scale, concentration, validate_args=None)[source]¶
Bases:
TransformedDistribution从双参数 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])
- arg_constraints : Dict[str, Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)}¶
- property mean¶
- property mode¶
- support = GreaterThan(lower_bound=0.0)¶
- property variance¶
Wishart¶
- class torch.distributions.wishart.Wishart(df, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[source]¶
Bases:
ExponentialFamily创建由对称正定矩阵 或其 Cholesky 分解 参数化的 Wishart 分布。
示例
>>> m = Wishart(torch.Tensor([2]), covariance_matrix=torch.eye(2)) >>> m.sample() # Wishart distributed with mean=`df * I` and >>> # variance(x_ij)=`df` for i != j and variance(x_ij)=`2 * df` for i == j
- 参数
注意
只能指定
covariance_matrix或precision_matrix或scale_tril之一。使用scale_tril将更有效率:所有内部计算都是基于scale_tril的。如果传递covariance_matrix或precision_matrix,则它仅用于使用 Cholesky 分解计算相应的下三角矩阵。‘torch.distributions.LKJCholesky’ 是一个受限的 Wishart 分布。[1]参考文献
[1] Wang, Z., Wu, Y. 和 Chu, H., 2018. 关于 LKJ 分布与受限 Wishart 分布的等价性。[2] Sawyer, S., 2007. Wishart 分布和逆 Wishart 采样。[3] Anderson, T. W., 2003. 多元统计分析导论 (第 3 版)。[4] Odell, P. L. & Feiveson, A. H., 1966. 生成样本协方差矩阵的数值过程。JASA, 61(313):199-203。[5] Ku, Y.-C. & Bloomfield, P., 2010. 在 OX 中生成具有分数自由度的随机 Wishart 矩阵.
- arg_constraints = {'covariance_matrix': PositiveDefinite(), 'df': GreaterThan(lower_bound=0), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}¶
- property covariance_matrix¶
- has_rsample = True¶
- property mean¶
- property mode¶
- property precision_matrix¶
- rsample(sample_shape=torch.Size([]), max_try_correction=None)[source]¶
警告
在某些情况下,基于 Bartlett 分解的采样算法可能会返回奇异矩阵样本。默认情况下,会进行多次尝试以更正奇异样本,但最终可能仍会返回奇异矩阵样本。奇异样本可能会在 .log_prob() 中返回 -inf 值。在这种情况下,用户应验证样本,并相应地修复 df 的值或调整 .rsample 中参数的 max_try_correction 值。
- 返回类型
- property scale_tril¶
- support = PositiveDefinite()¶
- property variance¶
KL 散度¶
- torch.distributions.kl.kl_divergence(p, q)[source]¶
计算两个分布之间的 Kullback-Leibler 散度 .
- 参数
p (Distribution) – 一个
Distribution对象。q (Distribution) – 一个
Distribution对象。
- 返回值
形状为 batch_shape 的 KL 散度批次。
- 返回类型
- 异常情况
NotImplementedError – 如果分布类型尚未通过
register_kl()注册。
- 目前已为以下分布对实现了 KL 散度
Bernoulli和BernoulliBernoulli和PoissonBeta和BetaBeta和ContinuousBernoulliBeta和ExponentialBeta和GammaBeta和NormalBeta和ParetoBeta和UniformBinomial和BinomialCategorical和CategoricalCauchy和CauchyContinuousBernoulli和ContinuousBernoulliContinuousBernoulli和ExponentialContinuousBernoulli和NormalContinuousBernoulli和ParetoContinuousBernoulli和UniformDirichlet和DirichletExponential和BetaExponential和ContinuousBernoulliExponential和ExponentialExponential和GammaExponential和GumbelExponential和NormalExponential和ParetoExponential和UniformExponentialFamily和ExponentialFamilyGamma和BetaGamma和ContinuousBernoulliGamma和ExponentialGamma和GammaGamma和GumbelGamma和NormalGamma和ParetoGamma和UniformGeometric和GeometricGumbel和BetaGumbel和ContinuousBernoulliGumbel和ExponentialGumbel和GammaGumbel和GumbelGumbel和NormalGumbel和ParetoGumbel和UniformHalfNormal和HalfNormalIndependent和IndependentLaplace和BetaLaplace和ContinuousBernoulliLaplace和ExponentialLaplace和GammaLaplace和LaplaceLaplace和NormalLaplace和ParetoLaplace和UniformLowRankMultivariateNormal和LowRankMultivariateNormalLowRankMultivariateNormal和MultivariateNormalMultivariateNormal和LowRankMultivariateNormalMultivariateNormal和MultivariateNormalNormal和BetaNormal和ContinuousBernoulliNormal和ExponentialNormal和GammaNormal和GumbelNormal和LaplaceNormal和NormalNormal和ParetoNormal和UniformOneHotCategorical和OneHotCategoricalPareto和BetaPareto和ContinuousBernoulliPareto和ExponentialPareto和GammaPareto和NormalPareto和ParetoPareto和UniformPoisson和BernoulliPoisson和BinomialPoisson和PoissonTransformedDistribution和TransformedDistributionUniform和BetaUniform和ContinuousBernoulliUniform和ExponentialUniform和GammaUniform和GumbelUniform和NormalUniform和ParetoUniform和Uniform
- torch.distributions.kl.register_kl(type_p, type_q)[source]¶
装饰器,用于向
kl_divergence()注册成对函数。用法@register_kl(Normal, Normal) def kl_normal_normal(p, q): # insert implementation here
查找返回最具体的(类型,类型)匹配,按子类排序。如果匹配不明确,则会引发 RuntimeWarning。例如,要解决不明确的情况
@register_kl(BaseP, DerivedQ) def kl_version1(p, q): ... @register_kl(DerivedP, BaseQ) def kl_version2(p, q): ...
你应该注册第三个最具体的实现,例如
register_kl(DerivedP, DerivedQ)(kl_version1) # Break the tie.
Transforms¶
- class torch.distributions.transforms.AffineTransform(loc, scale, event_dim=0, cache_size=0)[source]¶
通过逐点仿射映射 进行变换。
- class torch.distributions.transforms.CatTransform(tseq, dim=0, lengths=None, cache_size=0)[source]¶
Transform functor,它以与
torch.cat()兼容的方式,对 dim 上的每个子矩阵,长度为 lengths[dim],逐个应用变换序列 tseq。示例
x0 = torch.cat([torch.range(1, 10), torch.range(1, 10)], dim=0) x = torch.cat([x0, x0], dim=0) t0 = CatTransform([ExpTransform(), identity_transform], dim=0, lengths=[10, 10]) t = CatTransform([t0, t0], dim=0, lengths=[20, 20]) y = t(x)
- class torch.distributions.transforms.ComposeTransform(parts, cache_size=0)[source]¶
将多个变换组合成一个链。组合的变换负责缓存。
- class torch.distributions.transforms.CorrCholeskyTransform(cache_size=0)[source]¶
将长度为 的无约束实向量 转换为 D 维相关矩阵的 Cholesky 分解因子。该 Cholesky 分解因子是一个下三角矩阵,其对角线为正,每行的欧几里得范数为 1。变换过程如下
首先,我们将 x 转换为按行排列的下三角矩阵。
对于下三角部分的每一行 ,我们使用类
StickBreakingTransform的带符号版本,使用以下步骤将 转换为单位欧几里得长度向量: - 缩放至 域: . - 转换为无符号域: . - 应用 . - 转换为带符号域: .
- class torch.distributions.transforms.CumulativeDistributionTransform(distribution, cache_size=0)[source]¶
通过概率分布的累积分布函数进行变换。
- 参数
distribution (Distribution) – 用于变换的累积分布函数的分布。
示例
# Construct a Gaussian copula from a multivariate normal. base_dist = MultivariateNormal( loc=torch.zeros(2), scale_tril=LKJCholesky(2).sample(), ) transform = CumulativeDistributionTransform(Normal(0, 1)) copula = TransformedDistribution(base_dist, [transform])
- class torch.distributions.transforms.IndependentTransform(base_transform, reinterpreted_batch_ndims, cache_size=0)[source]¶
另一个变换的包装器,将
reinterpreted_batch_ndims个额外最右侧的维度视为依赖项。这对正向或反向变换没有影响,但确实在log_abs_det_jacobian()中将最右侧reinterpreted_batch_ndims个维度加起来。
- class torch.distributions.transforms.LowerCholeskyTransform(cache_size=0)[source]¶
从无约束矩阵到具有非负对角线元素的下三角矩阵的变换。
这对于根据其 Cholesky 分解来参数化正定矩阵很有用。
- class torch.distributions.transforms.PositiveDefiniteTransform(cache_size=0)[source]¶
从无约束矩阵到正定矩阵的变换。
- class torch.distributions.transforms.ReshapeTransform(in_shape, out_shape, cache_size=0)[source]¶
单元雅可比变换,用于重塑张量的最右侧部分。
请注意,
in_shape和out_shape必须具有相同数量的元素,就像torch.Tensor.reshape()一样。- 参数
in_shape (torch.Size) – 输入事件形状。
out_shape (torch.Size) – 输出事件形状。
- class torch.distributions.transforms.SoftplusTransform(cache_size=0)[source]¶
通过映射 进行变换。当 时,该实现会恢复到线性函数。
- class torch.distributions.transforms.TanhTransform(cache_size=0)[source]¶
通过映射 进行变换。
它等价于
` ComposeTransform([AffineTransform(0., 2.), SigmoidTransform(), AffineTransform(-1., 2.)]) `但是这在数值上可能不稳定,因此建议使用 TanhTransform 而不是它。注意,对于 NaN/Inf 值,应该使用 cache_size=1。
- class torch.distributions.transforms.SoftmaxTransform(cache_size=0)[source]¶
通过 然后归一化,将无约束空间转换为单纯形。
这不是双射的,不能用于 HMC。但是它主要按坐标进行操作(除了最终的归一化),因此适用于按坐标进行的优化算法。
- class torch.distributions.transforms.StackTransform(tseq, dim=0, cache_size=0)[source]¶
变换函数,它以与
torch.stack()兼容的方式,对 dim 中的每个子矩阵以分量的方式应用一系列变换 tseq。示例
x = torch.stack([torch.range(1, 10), torch.range(1, 10)], dim=1) t = StackTransform([ExpTransform(), identity_transform], dim=1) y = t(x)
- class torch.distributions.transforms.StickBreakingTransform(cache_size=0)[source]¶
通过折棍过程,将无约束空间转换为具有一个额外维度的单纯形。
这种变换出现在 Dirichlet 分布的折棍构造中,作为迭代 sigmoid 变换:第一个 logit 通过 sigmoid 变换为第一个概率和所有其他概率的概率,然后递归地进行该过程。
这是双射的,适合用于 HMC;但是它将坐标混合在一起,不太适合优化。
- class torch.distributions.transforms.Transform(cache_size=0)[source]¶
可逆变换的抽象类,具有可计算的对数行列式雅可比矩阵。它们主要用于
torch.distributions.TransformedDistribution。缓存对于逆运算很昂贵或数值不稳定的变换很有用。注意,在使用记忆值时,必须谨慎,因为自动梯度图可能会被反转。例如,虽然以下代码在使用或不使用缓存的情况下都能工作
y = t(x) t.log_abs_det_jacobian(x, y).backward() # x will receive gradients.
但是,由于依赖关系反转,以下代码在使用缓存时会出错
y = t(x) z = t.inv(y) grad(z.sum(), [y]) # error because z is x
派生类应该实现
_call()或_inverse()之一或两者。将 bijective=True 设置为 True 的派生类也应该实现log_abs_det_jacobian()。- 参数
cache_size (int) – 缓存大小。如果为零,则不进行缓存。如果为一,则缓存最新的单个值。仅支持 0 和 1。
- 变量
domain (
Constraint) – 表示此变换有效输入的约束。codomain (
Constraint) – 表示此变换有效输出的约束,这些输出是逆变换的输入。bijective (bool) – 此变换是否为双射的。变换
t为双射的当且仅当对域中的每个x和陪域中的每个y满足t.inv(t(x)) == x以及t(t.inv(y)) == y。非双射的变换至少应满足较弱的伪逆属性t(t.inv(t(x)) == t(x)以及t.inv(t(t.inv(y))) == t.inv(y)。sign (int or Tensor) – 对于双射的一元变换,这应为 +1 或 -1,具体取决于变换是单调递增还是递减。
- property sign¶
如果适用,返回雅可比矩阵行列式的符号。通常情况下,这仅对双射变换有意义。
约束¶
实现了以下约束
constraints.booleanconstraints.catconstraints.corr_choleskyconstraints.dependentconstraints.greater_than(lower_bound)constraints.greater_than_eq(lower_bound)constraints.independent(constraint, reinterpreted_batch_ndims)constraints.integer_interval(lower_bound, upper_bound)constraints.interval(lower_bound, upper_bound)constraints.less_than(upper_bound)constraints.lower_choleskyconstraints.lower_triangularconstraints.multinomialconstraints.nonnegativeconstraints.nonnegative_integerconstraints.one_hotconstraints.positive_integerconstraints.positiveconstraints.positive_semidefiniteconstraints.positive_definiteconstraints.real_vectorconstraints.realconstraints.simplexconstraints.symmetricconstraints.stackconstraints.squareconstraints.symmetricconstraints.unit_interval
- torch.distributions.constraints.cat¶
_Cat的别名。
- torch.distributions.constraints.dependent_property¶
_DependentProperty的别名。
- torch.distributions.constraints.greater_than¶
_GreaterThan的别名。
- torch.distributions.constraints.greater_than_eq¶
_GreaterThanEq的别名。
- torch.distributions.constraints.independent¶
_IndependentConstraint的别名。
- torch.distributions.constraints.integer_interval¶
_IntegerInterval的别名。
- torch.distributions.constraints.interval¶
_Interval的别名。
- torch.distributions.constraints.half_open_interval¶
_HalfOpenInterval的别名。
- torch.distributions.constraints.is_dependent(constraint)[source]¶
检查
constraint是否为_Dependent对象。- 参数
constraint – 一个
Constraint对象。- 返回值
如果
constraint可以细化为_Dependent类型,则为 True,否则为 False。- 返回类型
bool
示例
>>> import torch >>> from torch.distributions import Bernoulli >>> from torch.distributions.constraints import is_dependent
>>> dist = Bernoulli(probs = torch.tensor([0.6], requires_grad=True)) >>> constraint1 = dist.arg_constraints["probs"] >>> constraint2 = dist.arg_constraints["logits"]
>>> for constraint in [constraint1, constraint2]: >>> if is_dependent(constraint): >>> continue
- torch.distributions.constraints.less_than¶
_LessThan的别名。
- torch.distributions.constraints.multinomial¶
_Multinomial的别名。
- torch.distributions.constraints.stack¶
_Stack的别名。
Constraint Registry¶
PyTorch 提供了两个全局 ConstraintRegistry 对象,它们将 Constraint 对象链接到 Transform 对象。这两个对象都输入约束并返回变换,但它们对双射性的保证不同。
biject_to(constraint)会查找从constraints.real到给定constraint的双射Transform。返回的变换保证具有.bijective = True,并且应该实现.log_abs_det_jacobian()。transform_to(constraint)会查找从constraints.real到给定constraint的非双射Transform。返回的变换不保证实现.log_abs_det_jacobian()。
transform_to() 注册表对于对概率分布的受限参数执行无约束优化很有用,这些参数由每个分布的 .arg_constraints 字典指示。这些变换通常会对空间进行过度参数化以避免旋转;因此,它们更适合像 Adam 这样的逐坐标优化算法。
loc = torch.zeros(100, requires_grad=True)
unconstrained = torch.zeros(100, requires_grad=True)
scale = transform_to(Normal.arg_constraints['scale'])(unconstrained)
loss = -Normal(loc, scale).log_prob(data).sum()
biject_to() 注册表对于哈密顿蒙特卡罗很有用,其中受限 .support 概率分布的样本在无约束空间中传播,并且算法通常是旋转不变的。
dist = Exponential(rate)
unconstrained = torch.zeros(100, requires_grad=True)
sample = biject_to(dist.support)(unconstrained)
potential_energy = -dist.log_prob(sample).sum()
注意
例如,transform_to 和 biject_to 不同的情况是 constraints.simplex:transform_to(constraints.simplex) 返回一个 SoftmaxTransform,它只是对输入进行指数化和归一化;这是一个廉价且大部分是逐坐标的操作,适合像 SVI 这样的算法。相反,biject_to(constraints.simplex) 返回一个 StickBreakingTransform,它将输入双射到低一个维度的空间;这是一个更昂贵、数值稳定性较差的变换,但对于像 HMC 这样的算法是必需的。
biject_to 和 transform_to 对象可以通过用户定义的约束和变换来扩展,使用它们的 .register() 方法,可以作为单例约束上的函数
transform_to.register(my_constraint, my_transform)
或者作为参数化约束上的装饰器
@transform_to.register(MyConstraintClass)
def my_factory(constraint):
assert isinstance(constraint, MyConstraintClass)
return MyTransform(constraint.param1, constraint.param2)
您可以通过创建一个新的 ConstraintRegistry 对象来创建自己的注册表。
- class torch.distributions.constraint_registry.ConstraintRegistry[source]¶
将约束链接到变换的注册表。
- register(constraint, factory=None)[source]¶
在这个注册表中注册一个
Constraint子类。用法@my_registry.register(MyConstraintClass) def construct_transform(constraint): assert isinstance(constraint, MyConstraint) return MyTransform(constraint.arg_constraints)
- 参数
constraint (
Constraint的子类) –Constraint的子类,或所需类的单例对象。factory (Callable) – 一个可调用对象,它输入一个约束对象并返回一个
Transform对象。