torch.distributions 概率分布
distributions 包含可参数化的概率分布和采样函数,允许构建随机计算图并进行优化的随机梯度估计。此包的设计通常遵循TensorFlow Distributions包的设计。
无法直接通过随机样本进行反向传播。然而,有两种主要的方法可以创建替代函数来进行反向传播:得分函数估计器(也称为似然比估计器或REINFORCE)和路径导数估计器。REINFORCE通常被视为强化学习中策略梯度方法的基础,而路径导数估计器则常用于变分自编码器中的重参数化技巧。虽然得分函数只需要样本的值 $f(x)$,但路径导数需要计算导数值 $f'(x)$。接下来的部分将在一个强化学习示例中讨论这两种方法。更多详情请参阅使用随机计算图进行梯度估计。
评分函数
当概率密度函数对参数可微时,我们只需使用sample()和log_prob()来实现REINFORCE算法。
其中,$\theta$ 是参数,$\alpha$ 是学习率,$r$ 是奖励,$p(a|\pi^\theta(s))$ 表示在给定策略$\pi^\theta$ 的情况下,在状态$s$ 采取动作$a$ 的概率。
实际上,我们会从网络输出中采样一个动作,在环境中应用该动作,并使用 log_prob 来构建等效的损失函数。需要注意的是,优化器使用梯度下降方法,而上述规则假设使用梯度上升。对于分类策略,实现 REINFORCE 的代码如下:
probs = policy_network(state) # Note that this is equivalent to what used to be called multinomial m = 类别(probs) action = m.sample() next_state, reward = env.step(action) loss = -m.log_prob(action) * reward loss.backward()
路径导数
另一种实现这些随机/策略梯度的方法是使用rsample() 方法中的重参数化技巧。通过这种方法,参数化的随机变量可以通过无参数随机变量和一个确定性函数来构造。这样,重参数化的样本就变得可微分了。实现路径导数的代码如下所示:
params = policy_network(state) m = 正常(*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()
分布
- classtorch.distributions.distribution.Distribution(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)[源代码]
-
继承自:
object分布是概率分布抽象基类。
- 属性arg_constraints:Dict[str, Constraint]
-
返回一个字典,将参数名映射到相应的约束条件(
Constraint)对象,这些约束条件应由分布的每个参数满足。非张量类型的参数无需出现在该字典中。
- 属性batch_shape:Size
-
返回批处理参数的形状。
- enumerate_support(expand=True)[源代码]
-
返回一个张量,包含离散分布支持的所有值。结果将在第 0 维度上进行枚举,因此结果的形状将是 (cardinality,) + batch_shape + event_shape(对于一元分布,event_shape = ())。
请注意,这会同步遍历所有批处理张量[[0, 0], [1, 1], …]。当设置expand=False时,遍历会在维度0上进行,而其余的批处理维度将是单例维度[[0], [1], ..。
要遍历完整的笛卡尔积,可以使用 itertools.product(m.enumerate_support())。
- 属性event_shape:Size
-
返回单个样本的形状(未进行批处理)。
- expand(batch_shape, _instance=None)[源代码]
-
返回一个新的分布实例(或者填充派生类提供的现有实例),并将批量维度扩展到batch_shape。此方法调用
expand来扩展分布的参数,因此不会为扩展示例分配新的内存。此外,在首次创建实例时,__init__.py中不会重复任何参数检查或参数广播。- 参数
-
-
batch_shape (torch.Size) – 表示所需的批处理形状的扩展大小。
-
_instance — 由需要重写.expand方法的子类提供的新实例。
-
- 返回值
-
一个新的分布实例,其批处理维度扩展到了batch_size。
- 属性mean:Tensor
-
返回该分布的平均值。
- 属性 模式 : Tensor
-
返回该分布的众数。
- rsample(sample_shape=torch.Size([]))[源代码]
-
根据 sample_shape 生成重参数化的样本。如果分布参数是批量处理的,则生成一批形状为 sample_shape 的重参数化样本。
- 返回类型
- sample(sample_shape=torch.Size([]))[源代码]
-
生成一个形状为 sample_shape 的样本,或者如果分布参数是批量的,则生成一批形状为 sample_shape 的样本。
- 返回类型
- staticset_default_validate_args(value)[源代码]
-
设置验证是启用还是禁用。
默认行为模仿了Python的
assert语句:验证默认是开启的,但在使用python -O命令以优化模式运行Python时会禁用验证。由于验证可能会比较耗资源,因此在模型正常工作后你可能希望将其关闭。- 参数
-
value (bool) – 是否开启验证。
- 属性stddev: Tensor
-
返回该分布的标准偏差。
- property支持:Optional[Any]
-
返回一个表示该分布支持范围的
Constraint对象。
- 属性 方差 : Tensor
-
返回该分布的方差。
指数分布族
- classtorch.distributions.exp_family.ExponentialFamily(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)[源代码]
-
继承自:
DistributionExponentialFamily 是指数族概率分布的抽象基类,其概率质量或密度函数的形式如下定义。
$p_{F}(x; \theta) = \exp(\langle t(x), \theta\rangle - F(\theta) + k(x))$其中 $\theta$ 表示自然参数,$t(x)$ 表示充分统计量,$F(\theta)$ 是给定族的对数规范化函数,$k(x)$ 则是承载测度。
注意
此类作为Distribution类与属于指数族分布之间的中介,主要用于验证.entropy() 和解析KL散度方法的正确性。我们利用此类通过自动微分框架及Bregman散度(由Frank Nielsen和Richard Nock提供:关于指数族的熵和交叉熵)来计算熵和KL散度。
- 熵()[源代码]
-
使用对数归一化项的Bregman散度来计算熵的方法。
伯努利
- 类torch.distributions.bernoulli.Bernoulli(probs=None, logits=None, validate_args=None)[源代码]
-
继承自:
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)}
- 熵()[源代码]
- enumerate_support(expand=True)[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_enumerate_support=True
- log_prob(value)[源代码]
- 属性 logits
- 属性平均值
- 属性 模式
- 属性param_shape
- 属性 probs
- sample(sample_shape=torch.Size([]))[源代码]
- 支持= Boolean()
- 属性方差
测试版
- classtorch.distributions.beta.Beta(concentration1, concentration0, validate_args=None)[源代码]
-
继承自:
ExponentialFamily由
concentration1和concentration0参数化的 Beta 分布。示例:
>>> 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)}
- 属性 concentration0
- 属性 concentration1
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 支持的范围= Interval(lower_bound=0.0, upper_bound=1.0)
- 属性方差
二项式
- classtorch.distributions.binomial.Binomial(total_count=1, probs=None, logits=None, validate_args=None)[源代码]
-
继承自:
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)}
- 熵()[源代码]
- enumerate_support(expand=True)[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_enumerate_support=True
- log_prob(value)[源代码]
- 属性 logits
- 属性平均值
- 属性 模式
- 属性param_shape
- 属性 probs
- sample(sample_shape=torch.Size([]))[源代码]
- 属性支持
- 属性方差
Categorical
- 类torch.distributions.categorical.Categorical(probs=None, logits=None, validate_args=None)[源代码]
-
继承自:
Distribution创建一个由
probs或logits(但不会同时使用两者) 参数化的分类分布。注意
它等同于
torch.multinomial()函数所采样的分布。样本是整数,取自集合$\{0, \ldots, K-1\}$,其中K的值为
probs.size(-1)。如果 probs 是一维的,长度为 K,那么每个元素表示该索引位置类别样本的相对概率。
如果 probs 是 N 维的,那么前 N-1 维将被视为一组相对概率向量。
注意
参数 probs 必须是非负的、有限的,并且总和不为零。它将在最后一个维度上被归一化,使其总和为1。
probs将返回这个归一化的值。logits 参数将被视为未归一化的对数概率,因此可以是任何实数。它也将被归一化以使最后一个维度上的概率总和为1。logits将返回这个归一化的值。示例:
>>> 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()}
- 熵()[源代码]
- enumerate_support(expand=True)[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_enumerate_support=True
- log_prob(value)[源代码]
- 属性 logits
- 属性平均值
- 属性 模式
- 属性param_shape
- 属性 probs
- sample(sample_shape=torch.Size([]))[源代码]
- 属性支持
- 属性方差
柯西
- classtorch.distributions.cauchy.Cauchy(loc, scale, validate_args=None)[源代码]
-
继承自:
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)}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- icdf(value)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 支持=Real()
- 属性方差
Chi2
- classtorch.distributions.chi2.Chi2(df, validate_args=None)[源代码]
-
继承自:
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)}
- 属性 df
- expand(batch_shape, _instance=None)[源代码]
连续伯努利分布
- classtorch.distributions.continuous_bernoulli.ContinuousBernoulli(probs=None, logits=None, lims=(0.499, 0.501), validate_args=None)[源代码]
-
继承自:
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)}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- icdf(value)[源代码]
- log_prob(value)[源代码]
- 属性 logits
- 属性平均值
- 属性param_shape
- 属性 probs
- sample(sample_shape=torch.Size([]))[源代码]
- 属性stddev
- 支持的范围= Interval(lower_bound=0.0, upper_bound=1.0)
- 属性方差
狄利克雷
- classtorch.distributions.dirichlet.Dirichlet(concentration, validate_args=None)[源代码]
-
继承自:
ExponentialFamily创建一个由浓度参数 concentration 参数化的 Dirichlet 分布。
示例:
>>> 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(大于下界为0.0的GreaterThan约束, 1)}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 支持=Simplex()
- 属性方差
指数
- classtorch.distributions.exponential.Exponential(rate, validate_args=None)[源代码]
-
继承自:
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)}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- icdf(value)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性stddev
- 支持大于等于0.0
- 属性方差
- classtorch.distributions.fishersnedecor.FisherSnedecor(df1, df2, validate_args=None)[源代码]
-
继承自:
Distribution创建一个由
df1和df2参数化的Fisher-Snedecor分布。示例:
>>> m = FisherSnedecor(torch.tensor([1.0]), torch.tensor([2.0])) >>> m.sample() # Fisher-Snedecor-distributed with df1=1 and df2=2 tensor([ 0.2453])
- arg_constraints={'df1': >0.0, 'df2': >0.0}
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 支持>0.0
- 属性方差
伽马
- classtorch.distributions.gamma.Gamma(concentration, rate, validate_args=None)[源代码]
-
继承自:
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)}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 支持大于等于0.0
- 属性方差
几何
- 类torch.distributions.geometric.Geometric(probs=None, logits=None, validate_args=None)[源代码]
-
继承自:
Distribution创建一个由
probs参数化的几何分布,其中probs表示伯努利试验中成功的概率。$P(X=k) = (1-p)^{k} p, k = 0, 1, ...$注意
torch.distributions.geometric.Geometric()中第 $(k+1)$ 次试验是第一次成功,因此在$\{0, 1, \ldots\}$中抽取样本;而torch.Tensor.geometric_()中第 k 次试验是第一次成功,因此在$\{1, 2, \ldots\}$中抽取样本。示例:
>>> 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)}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- log_prob(value)[源代码]
- 属性 logits
- 属性平均值
- 属性 模式
- 属性 probs
- sample(sample_shape=torch.Size([]))[源代码]
- 支持:IntegerGreaterThan(lower_bound=0)
- 属性方差
耿贝尔
- classtorch.distributions.gumbel.Gumbel(loc, scale, validate_args=None)[源代码]
-
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)}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性stddev
- 支持=Real()
- 属性方差
HalfCauchy
- classtorch.distributions.half_cauchy.HalfCauchy(scale, validate_args=None)[源代码]
-
创建一个以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)}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- icdf(prob)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性scale
- 支持大于等于0.0
- 属性方差
半正态分布
- classtorch.distributions.half_normal.HalfNormal(scale, validate_args=None)[源代码]
-
根据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)}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- icdf(prob)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性scale
- 支持大于等于0.0
- 属性方差
独立
- classtorch.distributions.independent.Independent(base_distribution, reinterpreted_batch_ndims, validate_args=None)[源代码]
-
继承自:
Distribution将分布的部分批处理维度重新解释为事件维度。
这主要用来改变
log_prob()的结果形状。例如,为了创建一个与多元正态分布具有相同形状的对角线正态分布(以便它们可以互换),你可以:>>> from torch.distributions.multivariate_normal import 多元正态分布 >>> 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]={}
- 熵()[源代码]
- enumerate_support(expand=True)[源代码]
- expand(batch_shape, _instance=None)[源代码]
- 属性enumerate支持
- 属性has_rsample
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- sample(sample_shape=torch.Size([]))[源代码]
- 属性支持
- 属性方差
逆伽玛分布
- classtorch.distributions.inverse_gamma.InverseGamma(concentration, rate, validate_args=None)[源代码]
-
创建一个由
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)}
- 属性浓度
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- 属性平均值
- 属性 模式
- 属性利率
- 支持>0.0
- 属性方差
Kumaraswamy
- classtorch.distributions.kumaraswamy.Kumaraswamy(concentration1, concentration0, validate_args=None)[源代码]
-
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)}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- 属性平均值
- 属性 模式
- 支持的范围= Interval(lower_bound=0.0, upper_bound=1.0)
- 属性方差
LKJCholesky
- classtorch.distributions.lkj_cholesky.LKJCholesky(dim, concentration=1.0, validate_args=None)[源代码]
-
继承自:
DistributionLKJ分布用于相关矩阵的下三角Cholesky因子。该分布通过
concentration参数$\eta$控制,使得从Cholesky因子生成的相关矩阵$M$的概率与$\det(M)^{\eta - 1}$成正比。因此,当concentration == 1时,我们得到的是相关矩阵Cholesky因子上的均匀分布:L ~ LKJCholesky(dim, concentration) X = L @ L' ~ LKJCorr(dim, concentration)
请注意,此分布采样的是相关矩阵的 Cholesky 因子,而不是相关矩阵本身,因此与文献 [1] 中对 LKJCorr 分布的推导略有不同。在进行采样时,使用了文献 [1] 第 3 节中的 Onion 方法。
示例:
>>> l = LKJCholesky(3, 0.5) >>> l.sample() # l @ l.T is a sample of a correlation 3x3 matrix tensor([[ 1.0000, 0.0000, 0.0000], [ 0.3516, 0.9361, 0.0000], [-0.1899, 0.4748, 0.8593]])
参考资料
[1] 基于藤和扩展洋葱法生成随机相关矩阵 (2009), Daniel Lewandowski, Dorota Kurowicka, Harry Joe. 《多元分析杂志》. 100. 10.1016/j.jmva.2009.04.008
- arg_constraints={'concentration':GreaterThan(lower_bound=0.0)}
- expand(batch_shape, _instance=None)[源代码]
- log_prob(value)[源代码]
- sample(sample_shape=torch.Size([]))[源代码]
- 支持(CorrCholesky())
拉普拉斯
- classtorch.distributions.laplace.Laplace(loc, scale, validate_args=None)[源代码]
-
继承自:
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)}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- icdf(value)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性stddev
- 支持=Real()
- 属性方差
对数正态
- classtorch.distributions.log_normal.LogNormal(loc, scale, validate_args=None)[源代码]
-
创建一个以
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)}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- 属性 位置
- 属性平均值
- 属性 模式
- 属性scale
- 支持>0.0
- 属性方差
低秩多元正态分布
- 类torch.distributions.lowrank_multivariate_normal.LowRankMultivariateNormal(loc, cov_factor, cov_diag, validate_args=None)[源代码]
-
继承自:
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)}
- 属性协方差矩阵
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性precision_matrix
- 属性 scale_tril
- 支持= IndependentConstraint(Real(), 1)
- 属性方差
MixtureSameFamily
- classtorch.distributions.mixture_same_family.MixtureSameFamily(mixture_distribution, component_distribution, validate_args=None)[源代码]
-
继承自:
DistributionMixtureSameFamily 分布实现了一个或多个混合分布,其中所有组件都来自同一分布类型的不同的参数化。它通过一个 Categorical “选择分布”(覆盖 k 个组件)和一个具有右most批处理形状(等于 [k])的 Distribution 组件进行参数化,该形状用于索引每个(批量)组件。
示例:
>>> # Construct Gaussian Mixture Model in 1D consisting of 5 equally >>> # weighted normal distributions >>> mix = D.Categorical(torch.ones(5,)) >>> comp = D.Normal(torch.randn(5,), torch.rand(5,)) >>> gmm = MixtureSameFamily(mix, comp) >>> # Construct Gaussian Mixture 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] 匹配。
-
component_distribution – 类似torch.distributions.Distribution的实例。最右侧的批次维度表示组件。
注:这里的"right-most batch dimension indexes component."可能需要根据上下文进一步确认,更合适的翻译可能是“最右侧的批次维度表示组件”。请根据具体文档内容调整。
-
- arg_constraints:Dict[str, Constraint]={}
- cdf(x)[源代码]
- 属性 组件分布
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=False
- log_prob(x)[源代码]
- 属性平均值
- 属性混合分布
- sample(sample_shape=torch.Size([]))[源代码]
- 属性支持
- 属性方差
多项式
- 类torch.distributions.multinomial.Multinomial(total_count=1, probs=None, logits=None, validate_args=None)[源代码]
-
继承自:
Distribution创建一个由
total_count参数化,并通过probs或者logits(但不是两者)定义的 Multinomial 分布。其中,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()}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- log_prob(value)[源代码]
- 属性 logits
- 属性平均值
- 属性param_shape
- 属性 probs
- sample(sample_shape=torch.Size([]))[源代码]
- 属性支持
- total_count: int
- 属性方差
-
MultivariateNormal
- 类torch.distributions.multivariate_normal.MultivariateNormal(loc, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[源代码]
-
继承自:
Distribution创建一个由均值向量和协方差矩阵参数化的多元正态分布(也称为高斯分布)。
多元正态分布可以用几种方式来定义参数:一个正定的协方差矩阵$\mathbf{\Sigma}$、一个正定的精度矩阵$\mathbf{\Sigma}^{-1}$,或者一个具有正值对角线元素的下三角矩阵$\mathbf{L}$,满足关系式$\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top$。这个下三角矩阵可以通过协方差的乔莱斯基分解等方法得到。
示例
>>> m = MultivariateNormal(torch.zeros(2), torch.eye(2)) >>> m.sample() # normally distributed with mean=`[0,0]` and covariance_matrix=`I` tensor([-0.2102, -0.5429])
- 参数
注意
只能指定以下之一:
covariance_matrix、precision_matrix或scale_tril。使用
scale_tril会更高效:所有内部计算都基于scale_tril。如果传递的是covariance_matrix或precision_matrix,则仅用于通过Cholesky分解计算相应的下三角矩阵。更自然的版本:
使用
scale_tril会更加高效:所有的内部计算都是基于scale_tril进行的。如果传递的是covariance_matrix或precision_matrix,则它们仅用于通过Cholesky分解来计算相应的下三角矩阵。- arg_constraints={'covariance_matrix': PositiveDefinite(), 'loc': IndependentConstraint(Real(), 1), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}
- 属性协方差矩阵
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性precision_matrix
- 属性 scale_tril
- 支持= IndependentConstraint(Real(), 1)
- 属性方差
负二项分布
- classtorch.distributions.negative_binomial.NegativeBinomial(total_count, probs=None, logits=None, validate_args=None)[源代码]
-
继承自:
Distribution创建一个负二项式分布,表示在达到
total_count次失败之前成功独立且相同的伯努利试验的次数。每次伯努利试验成功的概率是probs。- 参数
- arg_constraints={'logits': Real(), 'probs': HalfOpenInterval(lower_bound=0.0, upper_bound=1.0), 'total_count': GreaterThanEq(lower_bound=0)}
- expand(batch_shape, _instance=None)[源代码]
- log_prob(value)[源代码]
- 属性 logits
- 属性平均值
- 属性 模式
- 属性param_shape
- 属性 probs
- sample(sample_shape=torch.Size([]))[源代码]
- 支持:IntegerGreaterThan(lower_bound=0)
- 属性方差
Normal
- classtorch.distributions.normal.Normal(loc, scale, validate_args=None)[源代码]
-
继承自:
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)}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- icdf(value)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- sample(sample_shape=torch.Size([]))[源代码]
- 属性stddev
- 支持=Real()
- 属性方差
独热分类
- classtorch.distributions.one_hot_categorical.OneHotCategorical(probs=None, logits=None, validate_args=None)[源代码]
-
继承自:
Distribution创建一个由
probs或logits参数化的 one-hot 分类分布。样本是大小为
probs.size(-1)的一-hot编码向量。注意
参数 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()}
- 熵()[源代码]
- enumerate_support(expand=True)[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_enumerate_support=True
- log_prob(value)[源代码]
- 属性 logits
- 属性平均值
- 属性 模式
- 属性param_shape
- 属性 probs
- sample(sample_shape=torch.Size([]))[源代码]
- 支持=OneHot()
- 属性方差
Pareto
- classtorch.distributions.pareto.Pareto(scale, alpha, validate_args=None)[源代码]
-
帕累托分布类型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)}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- 属性平均值
- 属性 模式
- 属性支持
- 属性方差
泊松
- classtorch.distributions.poisson.Poisson(rate, validate_args=None)[源代码]
-
继承自:
ExponentialFamily根据
rate(速率参数)创建一个泊松分布。样本为非负整数,其概率质量函数如下所示:
$\mathrm{rate}^k \frac{e^{-\mathrm{rate}}}{k!}$示例:
>>> m = Poisson(torch.tensor([4])) >>> m.sample() tensor([ 3.])
- 参数
-
rate (Number, Tensor) – 指数分布的率参数
- arg_constraints={'rate': GreaterThanEq(lower_bound=0.0)}
- expand(batch_shape, _instance=None)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- sample(sample_shape=torch.Size([]))[源代码]
- 支持:IntegerGreaterThan(lower_bound=0)
- 属性方差
RelaxedBernoulli
- classtorch.distributions.relaxed_bernoulli.RelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)[源代码]
-
创建一个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)}
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- 属性 logits
- 属性 probs
- 支持的范围= Interval(lower_bound=0.0, upper_bound=1.0)
- 属性温度
LogitRelaxedBernoulli
- 类torch.distributions.relaxed_bernoulli.LogitRelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)[源代码]
-
继承自:
Distribution创建一个由
probs或logits(但不是同时使用两者)参数化的 LogitRelaxedBernoulli 分布,它是 RelaxedBernoulli 分布的对数几率形式。样本是对数几率值,范围在(0, 1)之间。更多细节请参见[1]
[1] The Concrete Distribution: 离散随机变量的连续近似(Maddison等人,2017)
[2] 使用Gumbel-Softmax的分类重新参数化(Jang等人,2017年)
- arg_constraints={'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}
- expand(batch_shape, _instance=None)[源代码]
- log_prob(value)[源代码]
- 属性 logits
- 属性param_shape
- 属性 probs
- 支持=Real()
RelaxedOneHotCategorical
- classtorch.distributions.relaxed_categorical.RelaxedOneHotCategorical(temperature, probs=None, logits=None, validate_args=None)[源代码]
-
创建一个由
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()}
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- 属性 logits
- 属性 probs
- 支持=Simplex()
- 属性温度
StudentT
- classtorch.distributions.studentT.StudentT(df, loc=0.0, scale=1.0, validate_args=None)[源代码]
-
继承自:
Distribution根据自由度
df、均值loc和尺度scale创建一个 Student's 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)}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 支持=Real()
- 属性方差
变换分布
- classtorch.distributions.transformed_distribution.TransformedDistribution(base_distribution, transforms, validate_args=None)[源代码]
-
继承自:
Distribution分布类的一个扩展,通过一系列变换来处理基础分布。设 f 表示这些变换的组合效果:
X ~ BaseDistribution Y = f(X) ~ TransformedDistribution(BaseDistribution, f) log p(Y) = log p(X) + log |det (dX/dY)|
注意,
.event_shape的值对于TransformedDistribution是其基础分布和变换的最大形状,因为变换可以引入事件间的相关性。使用
TransformedDistribution的一个示例如下:# Building a Logistic Distribution # X ~ Uniform(0, 1) # f = a + b * logit(X) # Y ~ f(X) ~ Logistic(a, b) base_distribution = 统一的(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]={}
- cdf(value)[源代码]
-
通过反转变换计算基础分布的得分,从而得出累积分布函数。
- expand(batch_shape, _instance=None)[源代码]
- 属性has_rsample
- icdf(value)[源代码]
-
使用变换计算逆累积分布函数,并计算基础分布的得分。
- log_prob(value)[源代码]
-
通过逆向变换,并利用基础分布的得分和对数绝对值雅可比行列式的值,来计算样本的得分。
- rsample(sample_shape=torch.Size([]))[源代码]
-
生成一个形状为 sample_shape 的重参数化样本。如果分布参数是批量的,则生成一批形状为 sample_shape 的重参数化样本。首先从基础分布中抽取样本,然后对列表中的每个变换应用 transform()。
- 返回类型
- sample(sample_shape=torch.Size([]))[源代码]
-
生成一个形状为 sample_shape 的样本,或者如果分布参数是批量的,则生成一批形状为 sample_shape 的样本。具体来说,先从基础分布中抽取样本,然后依次对每个变换应用 transform() 方法。
- 属性支持
Uniform
- classtorch.distributions.uniform.Uniform(low, high, validate_args=None)[源代码]
-
继承自:
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()}
- cdf(value)[源代码]
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- icdf(value)[源代码]
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性stddev
- 属性支持
- 属性方差
冯·米塞斯
- classtorch.distributions.von_mises.VonMises(loc, concentration, validate_args=None)[源代码]
-
继承自:
DistributionVon Mises分布的一种圆形表示。
此实现采用极坐标系统。参数
loc和value可以是任意实数(便于进行无约束优化),但实际上它们表示的是模2π的角度值。- 示例:
-
>>> 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()}
- expand(batch_shape)[源代码]
- has_rsample=False
- log_prob(value)[源代码]
- 属性平均值
-
提供的平均值是指圆的。
- 属性 模式
- sample(sample_shape=torch.Size([]))[源代码]
-
von Mises分布的采样算法参考了以下论文:D.J. Best和N.I. Fisher的“von Mises分布的有效模拟”(Applied Statistics,1979年,第152-157页)。
采样始终在内部以双精度进行,以避免在低浓度值时出现 _rejection_sample() 挂起的问题。单精度情况下,大约在 1e-4 时开始出现问题(参见问题 #88443)。
- 支持=Real()
- 属性方差
-
提供的方差是指圆型方差。
威布尔
- classtorch.distributions.weibull.Weibull(scale, concentration, validate_args=None)[源代码]
-
两个参数威布尔分布的样本。
示例
>>> 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)}
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- 属性平均值
- 属性 模式
- 支持>0.0
- 属性方差
Wishart
- classtorch.distributions.wishart.Wishart(df, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[源代码]
-
继承自:
ExponentialFamily创建一个由对称正定矩阵$\Sigma$或其Cholesky分解$\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top$参数化的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] 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()}
- 属性协方差矩阵
- 熵()[源代码]
- expand(batch_shape, _instance=None)[源代码]
- has_rsample=True
- log_prob(value)[源代码]
- 属性平均值
- 属性 模式
- 属性precision_matrix
- rsample(sample_shape=torch.Size([]), max_try_correction=None)[源代码]
-
警告
在某些情况下,基于 Bartlett 分解的采样算法可能会生成奇异矩阵样本。默认会尝试几次来纠正这些奇异样本,但最终仍可能返回奇异矩阵样本。对于奇异样本,在.log_prob()中可能会出现-inf值。在这种情况下,用户应验证样本,并根据需要调整df的值或.rsample参数中的max_try_correction值。
- 返回类型
- 属性 scale_tril
- 支持= PositiveDefinite()
- 属性方差
KL 散度
- torch.distributions.kl.kl_divergence(p, q)[源代码]
-
计算两个分布之间的Kullback-Leibler散度$KL(p \| q)$。
$KL(p \| q) = \int p(x) \log\frac {p(x)} {q(x)} \,dx$- 参数
-
-
p (分布) – 一个表示
分布的对象。 -
q (Distribution) – 表示一个
Distribution类型的对象。
-
- 返回值
-
一批形状为 batch_shape 的 KL 散度值。
- 返回类型
- 异常
-
NotImplementedError – 如果分布类型未通过
register_kl()注册。
- 目前实现的KL散度包括以下分布对:
-
-
Bernoulli和Bernoulli -
Bernoulli和Poisson -
Beta和Beta -
Beta和ContinuousBernoulli -
Beta和Exponential -
Beta和Gamma -
Beta和Normal -
Beta和Pareto -
Beta和Uniform -
Binomial和Binomial -
Categorical和Categorical -
Cauchy和Cauchy -
ContinuousBernoulli和ContinuousBernoulli -
ContinuousBernoulli和Exponential -
ContinuousBernoulli和Normal -
ContinuousBernoulli和Pareto -
ContinuousBernoulli和Uniform -
Dirichlet和Dirichlet -
Exponential和Beta -
Exponential和ContinuousBernoulli -
Exponential和Exponential -
Exponential和Gamma -
Exponential和Gumbel -
Exponential和Normal -
Exponential和Pareto -
Exponential和Uniform -
ExponentialFamily和ExponentialFamily -
Gamma和Beta -
Gamma和ContinuousBernoulli -
Gamma和指数 -
Gamma和Gamma -
Gamma和Gumbel -
Gamma和Normal -
Gamma和Pareto -
Gamma和Uniform -
Geometric和Geometric -
Gumbel和Beta -
Gumbel和ContinuousBernoulli -
Gumbel和Exponential -
Gumbel和Gamma -
Gumbel和Gumbel -
Gumbel和Normal -
Gumbel和Pareto -
Gumbel和Uniform -
HalfNormal和HalfNormal -
Independent和Independent -
Laplace和Beta -
Laplace和ContinuousBernoulli -
Laplace和Exponential -
Laplace和Gamma -
Laplace和Laplace -
Laplace和Normal -
Laplace和Pareto -
Laplace和Uniform -
LowRankMultivariateNormal和LowRankMultivariateNormal -
LowRankMultivariateNormal和MultivariateNormal -
MultivariateNormal和LowRankMultivariateNormal -
MultivariateNormal和MultivariateNormal -
Normal和Beta -
Normal和ContinuousBernoulli -
Normal和Exponential -
Normal和Gamma -
Normal和Gumbel -
Normal和Laplace -
Normal和Normal -
Normal和Pareto -
Normal和Uniform -
OneHotCategorical和OneHotCategorical -
Pareto和Beta -
Pareto和ContinuousBernoulli -
Pareto和Exponential -
Pareto和Gamma -
Pareto和Normal -
Pareto和Pareto -
Pareto和Uniform -
Poisson和Bernoulli -
Poisson和Binomial -
Poisson和Poisson -
TransformedDistribution和TransformedDistribution -
Uniform和Beta -
Uniform和ContinuousBernoulli -
Uniform和Exponential -
Uniform和Gamma -
Uniform和Gumbel -
Uniform和Normal -
Uniform和Pareto -
Uniform和Uniform
-
- torch.distributions.kl.register_kl(type_p, type_q)[源代码]
-
一个装饰器,用于将成对函数与
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.
变换
- 类torch.distributions.transforms.AbsTransform(cache_size=0)[源代码]
-
使用映射 $y = |x| 进行变换。
- 类torch.distributions.transforms.AffineTransform(loc, scale, event_dim=0, cache_size=0)[源代码]
-
通过公式 $y = \text{loc} + \text{scale} \times x$ 进行逐点仿射变换。
- 类torch.distributions.transforms.CatTransform(tseq, dim=0, lengths=None, cache_size=0)[源代码]
-
变换函子,它以逐元素的方式将一系列变换 tseq 应用于在维度 dim 上的每个子矩阵(长度为 lengths[dim]),这种方式与
torch.cat()兼容。示例:
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)
- 类torch.distributions.transforms.ComposeTransform(parts, cache_size=0)[源代码]
-
将以链式方式组合多个转换。每个转换都负责自己的缓存。
- 类torch.distributions.transforms.CorrCholeskyTransform(cache_size=0)[源代码]
-
将一个长度为$D*(D-1)/2$的无约束实数向量$x$转换为D维相关矩阵的Cholesky因子。该Cholesky因子是一个具有正对角线元素和每行单位欧几里得范数的下三角矩阵。转换过程如下:
-
首先,我们将 x 转换为按行顺序的下三角矩阵。
-
对于下三角部分的每一行$X_i$,我们使用带有符号版本的
StickBreakingTransform类来将其转换为单位欧几里得长度向量。具体步骤如下:
- 将$X_i$缩放到区间$(-1, 1)$: $r_i = \tanh(X_i)$
- 转换到无符号域:$z_i = r_i^2$
- 应用$s_i = StickBreakingTransform(z_i)$
- 回转到带符号的域:$y_i = sign(r_i) * \sqrt{s_i}$
-
- classtorch.distributions.transforms.CumulativeDistributionTransform(distribution, cache_size=0)[源代码]
-
根据概率分布的累积分布函数进行转换。
- 参数
-
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])
- 类torch.distributions.transforms.ExpTransform(cache_size=0)[源代码]
-
根据映射$y = \exp(x)$进行转换。
- classtorch.distributions.transforms.IndependentTransform(base_transform, reinterpreted_batch_ndims, cache_size=0)[源代码]
-
这是一个围绕另一个变换的包装器,将
reinterpreted_batch_ndims个最右侧维度视为依赖维度。这不会影响正向或反向变换,但在计算log_abs_det_jacobian()时会求和这些维度。
- 类torch.distributions.transforms.LowerCholeskyTransform(cache_size=0)[源代码]
-
将无约束矩阵转换为具有非负对角线元素的下三角矩阵。
这有助于通过它们的乔莱斯基分解来参数化正定矩阵。
- 类torch.distributions.transforms.PositiveDefiniteTransform(cache_size=0)[源代码]
-
将非约束矩阵转换为正定矩阵。
- 类torch.distributions.transforms.PowerTransform(exponent, cache_size=0)[源代码]
-
使用映射 $y = x^{\text{exponent}}$ 进行转换。
- 类torch.distributions.transforms.ReshapeTransform(in_shape, out_shape, cache_size=0)[源代码]
-
使用单元雅可比变换来重塑张量的最右部分。
注意,
in_shape和out_shape必须包含相同数量的元素,就像在torch.Tensor.reshape()中一样。- 参数
-
-
in_shape (torch.Size) – 表示输入事件形状的大小。
-
out_shape (torch.Size) – 表示输出事件形状的 torch.Size 对象。
-
- 类torch.distributions.transforms.SigmoidTransform(cache_size=0)[源代码]
-
使用映射 $y = \frac{1}{1 + \exp(-x)}$ 和 $x = \text{logit}(y)$ 进行转换。
- 类torch.distributions.transforms.SoftplusTransform(cache_size=0)[源代码]
-
通过映射$\text{Softplus}(x) = \log(1 + \exp(x))$进行转换。当$x > 20$时,该实现会退化为线性函数。
- 类torch.distributions.transforms.TanhTransform(cache_size=0)[源代码]
-
根据映射$y = \tanh(x)$进行转换。
它等同于
`ComposeTransform([AffineTransform(0., 2.), SigmoidTransform(), AffineTransform(-1., 2.)])`。然而这种方法在数值稳定性方面可能存在一些问题,因此建议使用TanhTransform代替。在处理NaN/Inf值时,应注意使用cache_size=1。
- 类torch.distributions.transforms.SoftmaxTransform(cache_size=0)[源代码]
-
首先通过$y = \exp(x)$将无约束空间转换为单纯形,然后再进行归一化处理。
这不是一个双射函数,不适合用于HMC。但是,它的大部分操作都是在坐标级别上进行的(除了最后的归一化步骤),所以它适用于坐标级别的优化算法。
- 类torch.distributions.transforms.StackTransform(tseq, dim=0, cache_size=0)[源代码]
-
这是一个变换函子,它以与
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)
- 类torch.distributions.transforms.StickBreakingTransform(cache_size=0)[源代码]
-
通过棒劈裂过程,将无约束空间转换为高一维度的单纯形。
此变换在构建狄利克雷分布的 stick-breaking 构造中作为迭代 sigmoid 变换出现:第一个 logit 通过 sigmoid 转换为第一个概率和剩余所有事件的概率,然后该过程递归进行。
这是一种双射方法,适用于HMC;然而,它会将坐标混在一起,因此不太适合优化。
- 类torch.distributions.transforms.Transform(cache_size=0)[源代码]
-
表示可逆变换的抽象基类,这些变换具有可计算的日志行列式雅可比矩阵。它们主要用于
torch.distributions.TransformedDistribution。缓存对那些逆运算成本高或数值不稳定的转换非常有用。需要注意的是,因为自动求导图可能被反转,所以要小心处理缓存的值。例如,下面的代码无论是使用还是不使用缓存都可以正常运行:
y = t(x) t.log_abs_det_jacobian(x, y).backward() # x will receive gradients.
然而,由于依赖关系反转,以下代码在进行缓存时会报错。
y = t(x) z = t.inv(y) grad(z.sum(), [y]) # error because z is x
派生类应该实现一个或两个方法:
_call()或_inverse()。如果设置了 bijective=True,还需要实现log_abs_det_jacobian()。- 参数
-
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 或 Tensor) – 对于双射单变量变换,此参数应根据变换是单调递增还是递减来取值为 +1 或 -1。
-
- property inv
-
返回此转换的逆
Transform。这应该满足t.inv.inv 是 t。
- 属性符号
-
返回雅可比矩阵的行列式的符号(如果适用)。通常情况下,这仅在双射变换时有意义。
- log_abs_det_jacobian(x, y)[源代码]
-
根据输入和输出,计算对数雅可比行列式 log |dy/dx|。
- forward_shape(shape)[源代码]
-
根据输入形状推断前向计算的形状,默认情况下保持形状不变。
- inverse_shape(shape)[源代码]
-
根据输出形状来推断逆运算的形状,默认情况下保持形状不变。
约束条件
实施了以下约束条件:
-
constraints.boolean -
constraints.cat -
constraints.corr_cholesky -
constraints.dependent -
constraints.greater_than(lower_bound) -
constraints.greater_than_eq(lower_bound) -
constraints.independent(constraint, reinterpreted_batch_ndims) -
constraints.integer_interval(lower_bound, upper_bound) -
constraints.interval(lower_bound, upper_bound) -
constraints.less_than(upper_bound) -
constraints.lower_cholesky -
constraints.lower_triangular -
constraints.multinomial -
constraints.nonnegative -
constraints.nonnegative_integer -
constraints.one_hot -
constraints.positive_integer -
constraints.positive -
constraints.positive_semidefinite -
positive_definite约束 -
constraints.real_vector -
constraints.real -
constraints.simplex -
symmetric constraints -
constraints.stack -
constraints.square -
symmetric constraints -
constraints.unit_interval
- 类torch.distributions.constraints.Constraint[源代码]
-
约束的抽象基础类。
约束对象表示变量的有效范围,例如,在此范围内可以对变量进行优化。
- 变量
- check(value)[源代码]
-
返回一个形状为
sample_shape + batch_shape的字节张量,表示值中的每个事件是否满足该约束条件。
- torch.distributions.constraints.cat
-
_Cat的别名
- torch.distributions.constraints.dependent_property
-
别名:
_DependentProperty
- torch.distributions.constraints.greater_than
-
_GreaterThan的别名
- torch.distributions.constraints.greater_than_or_equal
-
_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)[源代码]
-
判断
constraint是否为_Dependent对象。- 参数
-
约束 —— 一个
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.multinomial
-
_Multinomial的别名
- torch.distributions.constraints.stack
-
_Stack的别名
约束注册表
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()
The biject_to() registry is useful for Hamiltonian Monte Carlo, where samples from a probability distribution with constrained .support are propagated in an unconstrained space, and algorithms typically remain invariant to rotations:
dist = Exponential(rate) unconstrained = torch.zeros(100, requires_grad=True) sample = biject_to(dist.support)(unconstrained) potential_energy = -dist.log_prob(sample).sum()
注意
一个例子是constraints.simplex,在这个例子中,transform_to 和 biject_to 的行为不同:transform_to(constraints.simplex) 返回一个SoftmaxTransform,它简单地对输入进行指数运算并归一化;这是一个成本较低且主要按坐标操作的转换,适用于SVI等算法。相比之下,biject_to(constraints.simplex) 返回一个StickBreakingTransform,它将输入映射到维度少一的空间;这是一个成本更高且数值稳定性较差的转换,但HMC等算法需要使用。
可以通过在.register()方法中使用用户定义的约束和变换来扩展biject_to 和 transform_to 对象,这些约束可以作为单例约束上的函数。
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 对象来创建自己的注册表。
- 类torch.distributions.constraint_registry.ConstraintRegistry[源代码]
-
用于将约束链接到转换的注册表。
- 注册(约束条件, 工厂=None)[源代码]
-
将
Constraint的子类注册到该注册表中。用法:@my_registry.register(MyConstraintClass) def construct_transform(constraint): assert isinstance(constraint, MyConstraint) return MyTransform(constraint.arg_constraints)
- 参数
-
-
constraint (
Constraint的子类) – 一个Constraint子类,或者所需类的单例对象。 -
factory (Callable) – 一个可调用对象,它以约束对象作为输入,并返回
Transform对象。
-