概率分布 - torch.distributions¶
该包包含可参数化的概率分布
和采样函数。这允许构建随机计算
用于优化的图形和随机梯度估计器。此软件包
通常遵循 TensorFlow Distributions 软件包的设计。distributions
无法直接通过随机样本进行反向传播。然而 创建代理函数有两种主要方法,可以是 反向传播通过。这些是分数函数估计量/似然比 estimator/REINFORCE 和 pathwise 导数估计器。REINFORCE 通常 被视为强化学习中策略梯度方法的基础,而 Pathwise Derivative Estimator 常见于 reparameterization 技巧 在变分自动编码器中。而 score 函数只需要 样本数量,路径导数需要.接下来的章节将讨论强化学习中的这两者 例。有关更多详细信息,请参阅 Gradient Estimation Using Stochastic Computation Graphs 。
Score 函数¶
当概率密度函数相对于其
parameters 中,我们只需要 和 实现 REINFORCE:sample()
log_prob()
哪里是参数,是学习率,是奖励,而是 采取行动在状态给定策略.
在实践中,我们会从网络的输出中采样一个操作,应用这个
action 中,然后使用 API 来构造等效的
loss 函数。请注意,我们使用负数,因为优化器使用 gradient
descent,而上述规则假定 Gradient Ascent。使用分类
policy,则实施 REINFORCE 的代码如下:log_prob
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()
Pathwise 导数¶
实现这些随机/策略梯度的另一种方法是使用
reparameterization 技巧,其中
parameterized random variable 可以通过 parameterized
无参数随机变量的确定性函数。重新参数化的
因此,样本变得可微分。用于实现 pathwise 的代码
衍生数将如下所示: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()
分配¶
-
类 (batch_shape=Torch.Size([]), event_shape=Torch。Size([]), validate_args=无)[来源]
torch.distributions.distribution.
Distribution
¶ -
Distribution 是概率分布的抽象基类。
-
财产
arg_constraints
¶ 返回从参数名称到
对象的字典,这些对象 应该由此 distribution 的每个参数满足。Args 的 不是张量,不需要出现在这个 dict 中。
-
财产
batch_shape
¶ 返回对其参数进行批处理的形状。
-
enumerate_support
(expand=True)[来源]¶ 返回包含 discrete 支持的所有值的张量 分配。结果将在维度 0 上枚举,因此形状 的结果将是 (cardinality,) + batch_shape + event_shape (其中 event_shape = () 对于单变量分布)。
请注意,这将枚举锁步 [[0, 0], [1, 1], ...] 中的所有批处理张量。使用 expand=False 时,将发生枚举 沿 Dim 0,但其余批次维度为 单例维度, [[0], [1], ...
要迭代完整的笛卡尔积,请使用 itertools.product(m.enumerate_support())。
- 参数
expand (bool) – 是否扩展对 批量变暗以匹配分配的batch_shape。
- 返回
Tensor 迭代维度 0。
-
财产
event_shape
¶ 返回单个样本的形状(无批处理)。
-
expand
(batch_shape,_instance=无)[来源]¶ 返回新的分发实例(或填充现有实例 由派生类提供),并将批次维度扩展为 batch_shape。此方法调用
分配的参数。因此,这不会分配新的 memory 的 memory 进行扩展的分发实例。此外 这不会在首次创建实例时在 __init__.py 中重复任何 ARGS 检查或参数广播。
- 参数
batch_shape(Torch。Size) – 所需的扩展大小。
_instance – 由子类提供的新实例 需要覆盖 .expand。
- 返回
批次维度扩展为 batch_size 的新分配实例。
-
财产
mean
¶ 返回分布的平均值。
-
财产
mode
¶ 返回分布的模式。
-
sample
(sample_shape=Torch。Size([]))[来源]¶ 生成 sample_shape 形样品或 sample_shape 形批次 samples (如果分布参数是批处理的)。
-
static (值)[来源]
set_default_validate_args
¶ 设置是启用还是禁用验证。
默认行为模仿 Python 的语句:validation 默认为 on,但如果 Python 以优化模式运行,则将其禁用 (通过 )。验证可能很昂贵,因此您可能需要 一旦模型开始工作,就禁用它。
assert
python -O
- 参数
value (bool) – 是否启用验证。
-
财产
stddev
¶ 返回分布的标准差。
-
财产
support
¶
-
财产
variance
¶ 返回分布的方差。
-
财产
指数系列¶
-
类 (batch_shape=Torch.Size([]), event_shape=Torch。Size([]), validate_args=无)[来源]
torch.distributions.exp_family.
ExponentialFamily
¶ -
ExponentialFamily 是属于 指数族,其概率质量/密度函数的形式定义如下
哪里表示自然参数,表示足够的统计数据,是给定系列的对数归一化器函数,是运维 量。
注意
这个类是 Distribution 类和属于 到指数族,主要是为了检查 .entropy() 和解析 KL 的正确性 Divergence 方法。我们使用这个类来计算使用 AD 的熵和 KL 散度 框架和 Bregman 散度(由:Frank Nielsen 和 Richard Nock、Entropies 和 指数族的交叉熵)。
伯努利¶
-
class (probs=None, logits=None, validate_args=None)[来源]
torch.distributions.bernoulli.
Bernoulli
¶ -
样本是二进制的(0 或 1)。他们取值 1 的概率 p,取值 0 的概率 1 - p。
例:
>>> m = Bernoulli(torch.tensor([0.3])) >>> m.sample() # 30% chance 1; 70% chance 0 tensor([ 0.])
-
arg_constraints
= {'logits': Real(), 'probs': 区间(lower_bound=0.0, upper_bound=1.0)}¶
-
has_enumerate_support
= 真¶
-
财产
logits
¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
param_shape
¶
-
财产
probs
¶
-
support
= 布尔值 ()¶
-
财产
variance
¶
-
试用版¶
-
类别(浓度 1,浓度 0,validate_args=无)[来源]
torch.distributions.beta.
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': 大于(lower_bound=0.0), 'concentration1': 大于(lower_bound=0.0)}¶
-
财产
concentration0
¶
-
财产
concentration1
¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= 区间(lower_bound=0.0, upper_bound=1.0)¶
-
财产
variance
¶
二项式¶
-
class (total_count=1, probs=None, logits=None, validate_args=None)[来源]
torch.distributions.binomial.
Binomial
¶ -
创建参数化为 和 的二项分布 要么
or
(但不能同时) 。 必须是 可通过
/
进行广播。
total_count
total_count
例:
>>> 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
= 真¶
-
财产
logits
¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
param_shape
¶
-
财产
probs
¶
-
财产
support
¶
-
财产
variance
¶
-
分类¶
-
class (probs=None, logits=None, validate_args=None)[来源]
torch.distributions.categorical.
Categorical
¶ -
样本是来自其中 K 是 。
probs.size(-1)
如果 probs 是长度为 K 的一维,则每个元素都是相对概率 的 Sampling of the Class.
如果 probs 是 N 维的,则前 N-1 维将被视为一批 相对概率向量。
注意
probs 参数必须是非负的、有限的,并且具有非零和, 并且它将沿最后一个维度归一化为 sum 为 1。
将返回此标准化值。 logits 参数将被解释为非规范化对数概率 ,因此可以是任何实数。它同样将被标准化,以便 结果概率沿最后一个维度总和 1。
将返回此标准化值。
例:
>>> 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': 单纯形法()}¶
-
has_enumerate_support
= 真¶
-
财产
logits
¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
param_shape
¶
-
财产
probs
¶
-
财产
support
¶
-
财产
variance
¶
-
柯 西¶
-
class (loc, scale, validate_args=None)[来源]
torch.distributions.cauchy.
Cauchy
¶ -
来自 Cauchy (Lorentz) 分布的样本。比率的分布 均值为 0 的独立正态分布随机变量遵循 a 柯西分布。
例:
>>> 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
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= 实数()¶
-
财产
variance
¶
-
气2¶
连续式伯努利¶
-
类 (probs=None, logits=None, lims=(0.499, 0.501), validate_args=None)[来源]
torch.distributions.continuous_bernoulli.
ContinuousBernoulli
¶ -
该分布在 [0, 1] 中受支持,并由 'probs' 参数化(在 (0,1)) 或 'logits' (实值)。请注意,与伯努利不同,“probs” 不对应于概率,并且 'logits' 不对应于 log-odds,但由于与 伯努利。有关详细信息,请参见 [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': 区间(lower_bound=0.0, upper_bound=1.0)}¶
-
has_rsample
= 真¶
-
财产
logits
¶
-
财产
mean
¶
-
财产
param_shape
¶
-
财产
probs
¶
-
财产
stddev
¶
-
support
= 区间(lower_bound=0.0, upper_bound=1.0)¶
-
财产
variance
¶
-
狄里克莱¶
-
等级(浓度,validate_args=无)[来源]
torch.distributions.dirichlet.
Dirichlet
¶ -
创建按浓度参数化的狄利克雷分布。
concentration
例:
>>> m = Dirichlet(torch.tensor([0.5, 0.5])) >>> m.sample() # Dirichlet distributed with concentrarion concentration tensor([ 0.1046, 0.8954])
- 参数
concentration (Tensor) – 分布的浓度参数 (通常称为 Alpha)
-
arg_constraints
= {'concentration': IndependentConstraint(GreaterThan(lower_bound=0.0), 1)}¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= 单纯形 ()¶
-
财产
variance
¶
指数¶
-
class (rate, validate_args=None)[来源]
torch.distributions.exponential.
Exponential
¶ -
创建一个参数化为 的指数分布。
rate
例:
>>> m = Exponential(torch.tensor([1.0])) >>> m.sample() # Exponential distributed with rate=1 tensor([ 0.1046])
-
arg_constraints
= {'rate': 大于(lower_bound=0.0)}¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
stddev
¶
-
support
= GreaterThanEq(lower_bound=0.0)¶
-
财产
variance
¶
-
费舍尔斯内德科¶
-
class (df1, df2, validate_args=None)[来源]
torch.distributions.fishersnedecor.
FisherSnedecor
¶ -
创建由 和 参数化的 Fisher-Snedecor 分布。
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': 大于(lower_bound=0.0), 'df2': 大于(lower_bound=0.0)}¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= 大于 (lower_bound=0.0)¶
-
财产
variance
¶
-
伽马¶
-
等级(浓度、率、validate_args=无)[来源]
torch.distributions.gamma.
Gamma
¶ -
创建由 shape 和 参数化的 Gamma 分布。
concentration
rate
例:
>>> 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
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= GreaterThanEq(lower_bound=0.0)¶
-
财产
variance
¶
几何¶
-
class (probs=None, logits=None, validate_args=None)[来源]
torch.distributions.geometric.
Geometric
¶ -
创建由
参数化的 Geometric 分布 。 其中
是伯努利试验成功的概率。 它表示在伯努利试验、 第一试验失败了,然后才看到成功。
样本是非负整数 [0,).
例:
>>> m = Geometric(torch.tensor([0.3])) >>> m.sample() # underlying Bernoulli has 30% chance 1; 70% chance 0 tensor([ 2.])
-
arg_constraints
= {'logits': Real(), 'probs': 区间(lower_bound=0.0, upper_bound=1.0)}¶
-
财产
logits
¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
probs
¶
-
support
= IntegerGreaterThan(lower_bound=0)¶
-
财产
variance
¶
-
甘贝¶
-
class (loc, scale, validate_args=None)[来源]
torch.distributions.gumbel.
Gumbel
¶ -
来自 Gumbel 分布的样本。
例子:
>>> m = Gumbel(torch.tensor([1.0]), torch.tensor([2.0])) >>> m.sample() # sample from Gumbel distribution with loc=1, scale=2 tensor([ 1.0124])
-
arg_constraints
: dict[str, torch.distributions.constraints.Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
stddev
¶
-
support
= 实数()¶
-
财产
variance
¶
-
半柯西¶
-
class (scale, validate_args=None)[来源]
torch.distributions.half_cauchy.
HalfCauchy
¶ -
创建按尺度参数化的半柯西分布,其中:
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, torch.distributions.constraints.Constraint] = {'scale': GreaterThan(lower_bound=0.0)}¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
scale
¶
-
support
= GreaterThanEq(lower_bound=0.0)¶
-
财产
variance
¶
-
半法线¶
-
class (scale, validate_args=None)[来源]
torch.distributions.half_normal.
HalfNormal
¶ -
创建按尺度参数化的半正态分布,其中:
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, torch.distributions.constraints.Constraint] = {'scale': GreaterThan(lower_bound=0.0)}¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
scale
¶
-
support
= GreaterThanEq(lower_bound=0.0)¶
-
财产
variance
¶
-
独立¶
-
class (base_distribution, reinterpreted_batch_ndims, validate_args=None)[来源]
torch.distributions.independent.
Independent
¶ -
将分布的某些批次维度重新解释为事件维度。
这主要用于更改 的结果的形状
。例如,要创建对角线正态分布 的形状与多元正态分布相同(因此它们是 可互换),您可以:
>>> 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, torch.distributions.constraints.Constraint] = {}¶
-
财产
has_enumerate_support
¶
-
财产
has_rsample
¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
support
¶
-
财产
variance
¶
库马拉斯瓦米¶
-
类别(浓度 1,浓度 0,validate_args=无)[来源]
torch.distributions.kumaraswamy.
Kumaraswamy
¶ -
来自 Kumaraswamy 分布的样本。
例:
>>> m = Kumaraswamy(torch.tensor([1.0]), torch.tensor([1.0])) >>> m.sample() # sample from a Kumaraswamy distribution with concentration alpha=1 and beta=1 tensor([ 0.1729])
- 参数
-
arg_constraints
: dict[str, torch.distributions.constraints.Constraint] = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)}¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= 区间(lower_bound=0.0, upper_bound=1.0)¶
-
财产
variance
¶
LKJCholesky¶
-
类别(dim,浓度=1.0,validate_args=无)[来源]
torch.distributions.lkj_cholesky.
LKJCholesky
¶ -
相关矩阵的较低 Cholesky 因子的 LKJ 分布。 分布由参数控制
concentration
制作相关矩阵的概率生成自 一个 Cholesky 因子 propotional to.正因为如此, 当 时,我们在 Cholesky 上呈均匀分布 相关矩阵的因子。请注意,此发行版对 相关矩阵的 Cholesky 因子,而不是相关矩阵 本身,因此与 [1] 中的推导略有不同,因为 LKJCorr 发行版。对于采样,这将使用 Onion 方法从 [1] 第 3 节。concentration == 1
L ~ LKJCholesky(昏暗,浓度) X = L @ L' ~ LKJCorr(dim, concentration)
例:
>>> 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] 基于 vines 和扩展洋葱法生成随机相关矩阵, 丹尼尔·莱万多夫斯基、多罗塔·库罗维卡、哈里·乔。
-
arg_constraints
= {'concentration': 大于(lower_bound=0.0)}¶
-
support
= CorrCholesky()¶
-
拉普拉斯¶
-
class (loc, scale, validate_args=None)[来源]
torch.distributions.laplace.
Laplace
¶ -
创建由 和 参数化的拉普拉斯分布。
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
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
stddev
¶
-
support
= 实数()¶
-
财产
variance
¶
-
对数¶
-
class (loc, scale, validate_args=None)[来源]
torch.distributions.log_normal.
LogNormal
¶ -
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, torch.distributions.constraints.Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
-
has_rsample
= 真¶
-
财产
loc
¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
scale
¶
-
support
= 大于 (lower_bound=0.0)¶
-
财产
variance
¶
-
LowRankMultivariateNormal¶
-
class (loc, cov_factor, cov_diag, validate_args=None)[来源]
torch.distributions.lowrank_multivariate_normal.
LowRankMultivariateNormal
¶ -
创建协方差矩阵具有低秩形式的多元正态分布 参数化为 和 :
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])
- 参数
注意
由于 Woodbury 矩阵恒等式和矩阵行列式引理,当 cov_factor.shape[1] << cov_factor.shape[0] 时,避免了行列式和协方差矩阵逆矩阵的计算。 多亏了这些公式,我们只需要计算 小尺寸 “电容” 矩阵:
capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor
-
arg_constraints
= {'cov_diag': IndependentConstraint(GreaterThan(lower_bound=0.0), 1), 'cov_factor': IndependentConstraint(Real(), 2), 'loc': IndependentConstraint(Real(), 1)}¶
-
财产
covariance_matrix
¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
precision_matrix
¶
-
财产
scale_tril
¶
-
support
= IndependentConstraint(Real(), 1)¶
-
财产
variance
¶
MixtureSameFamily¶
-
class (mixture_distribution, component_distribution, validate_args=None)[来源]
torch.distributions.mixture_same_family.
MixtureSameFamily
¶ -
MixtureSameFamily 分布实现一个(批次的)混合物 分布,其中所有组件都来自不同的参数化 相同的分发类型。它由一个分类 “选择分布” (超过 k 个分量) 和一个分量参数化 Distribution,即具有最右侧 Batch 形状的 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_distribution – torch.distributions.Categorical-like 实例。管理选择零部件的概率。 类别数必须与最右侧的批次匹配 维度的 component_distribution。必须具有 标量batch_shape或匹配batch_shape component_distribution.batch_shape[:-1]
component_distribution – 类似 torch.distributions.Distribution 实例。最右侧的批处理维度索引组件。
-
arg_constraints
: Dict[str, torch.distributions.constraints.Constraint] = {}¶
-
财产
component_distribution
¶
-
has_rsample
= 假¶
-
财产
mean
¶
-
财产
mixture_distribution
¶
-
财产
support
¶
-
财产
variance
¶
多项式¶
-
class (total_count=1, probs=None, logits=None, validate_args=None)[来源]
torch.distributions.multinomial.
Multinomial
¶ -
创建参数化为
和 的多项式分布 要么
or
(但不能同时) 。类别索引的最内层维度
。所有其他维度对批次进行索引。
请注意,
如果只有
is ,则无需指定 called(见下面的示例)
注意
probs 参数必须是非负的、有限的,并且具有非零和, 并且它将沿最后一个维度归一化为 sum 为 1。
将返回此标准化值。 logits 参数将被解释为非规范化对数概率 ,因此可以是任何实数。它同样将被标准化,以便 结果概率沿最后一个维度总和 1。
将返回此标准化值。
例:
>>> 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': 单纯形法()}¶
-
财产
logits
¶
-
财产
mean
¶
-
财产
param_shape
¶
-
财产
probs
¶
-
财产
support
¶
-
财产
variance
¶
-
MultivariateNormal¶
-
class (loc, covariance_matrix=无, precision_matrix=无, scale_tril=无, validate_args=无)[来源]
torch.distributions.multivariate_normal.
MultivariateNormal
¶ -
创建多元正态(也称为高斯)分布 由均值向量和协方差矩阵参数化。
多元正态分布可以参数化 就正定协方差矩阵而言或正定精度矩阵或下三角矩阵为正值 对角线条目,使得.这个三角矩阵 可以通过例如协方差的 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])
- 参数
-
arg_constraints
= {'covariance_matrix': PositiveDefinite(), 'loc': IndependentConstraint(Real(), 1), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}¶
-
财产
covariance_matrix
¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
precision_matrix
¶
-
财产
scale_tril
¶
-
support
= IndependentConstraint(Real(), 1)¶
-
财产
variance
¶
负双项式¶
-
class (total_count, probs=None, logits=None, validate_args=None)[来源]
torch.distributions.negative_binomial.
NegativeBinomial
¶ -
创建负二项式分布,即分布 成功的独立和相同的伯努利试验的数量 在实现失败之前。概率 每个伯努利试验的成功率为
。
total_count
- 参数
-
arg_constraints
= {'logits': Real(), 'probs': HalfOpenInterval(lower_bound=0.0, upper_bound=1.0), 'total_count': GreaterThanEq(lower_bound=0)}¶
-
财产
logits
¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
param_shape
¶
-
财产
probs
¶
-
support
= IntegerGreaterThan(lower_bound=0)¶
-
财产
variance
¶
正常¶
-
class (loc, scale, validate_args=None)[来源]
torch.distributions.normal.
Normal
¶ -
创建由 和 参数化的正态(也称为高斯)分布。
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
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
stddev
¶
-
support
= 实数()¶
-
财产
variance
¶
-
OneHotCategorical 餐厅¶
-
class (probs=None, logits=None, validate_args=None)[来源]
torch.distributions.one_hot_categorical.
OneHotCategorical
¶ -
样本是大小为 的 one-hot 编码向量。
probs.size(-1)
注意
probs 参数必须是非负的、有限的,并且具有非零和, 并且它将沿最后一个维度归一化为 sum 为 1。
将返回此标准化值。 logits 参数将被解释为非规范化对数概率 ,因此可以是任何实数。它同样将被标准化,以便 结果概率沿最后一个维度总和 1。
将返回此标准化值。
另请参阅:有关 和 的
规范。
torch.distributions.Categorical()
例:
>>> 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': 单纯形法()}¶
-
has_enumerate_support
= 真¶
-
财产
logits
¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
param_shape
¶
-
财产
probs
¶
-
support
= OneHot() (英语)¶
-
财产
variance
¶
-
帕 累 托¶
-
class (scale, alpha, validate_args=None)[来源]
torch.distributions.pareto.
Pareto
¶ -
来自 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])
-
arg_constraints
: dict[str, torch.distributions.constraints.Constraint] = {'alpha': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)}¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
support
¶
-
财产
variance
¶
-
泊 松¶
-
class (rate, validate_args=None)[来源]
torch.distributions.poisson.
Poisson
¶ -
创建由 rate 参数参数化的泊松分布。
rate
样本是非负整数,其中 pmf 由下式给出
例:
>>> m = Poisson(torch.tensor([4])) >>> m.sample() tensor([ 3.])
- 参数
rate (Number, Tensor) – rate 参数
-
arg_constraints
= {'rate': GreaterThanEq(lower_bound=0.0)}¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= IntegerGreaterThan(lower_bound=0)¶
-
财产
variance
¶
松弛伯努利¶
-
class (temperature, probs=None, logits=None, validate_args=None)[来源]
torch.distributions.relaxed_bernoulli.
RelaxedBernoulli
¶ -
创建一个 RelaxedBernoulli 分布,由
、 和
或
(但不能同时用两者) 参数化。这是伯努利分布的简化版本, 所以值在 (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, torch.distributions.constraints.Constraint] = {'logits': real(), 'probs': interval(lower_bound=0.0, upper_bound=1.0)}¶
-
has_rsample
= 真¶
-
财产
logits
¶
-
财产
probs
¶
-
support
= 区间(lower_bound=0.0, upper_bound=1.0)¶
-
财产
temperature
¶
-
LogitRelaxedBernoulli¶
-
class (temperature, probs=None, logits=None, validate_args=None)[来源]
torch.distributions.relaxed_bernoulli.
LogitRelaxedBernoulli
¶ -
创建由
或
(但不能同时由两者) 参数化的 LogitRelaxedBernoulli 分布,该分布是 RelaxedBernoulli 的 Logit 分配。
样本是 (0, 1) 中值的对数。有关详细信息,请参见 [1]。
[1] 具体分布:离散随机的连续松弛 变量 (Maddison et al, 2017)
[2] 使用 Gumbel-Softmax 进行分类参数化 (Jang 等人,2017 年)
-
arg_constraints
= {'logits': Real(), 'probs': 区间(lower_bound=0.0, upper_bound=1.0)}¶
-
财产
logits
¶
-
财产
param_shape
¶
-
财产
probs
¶
-
support
= 实数()¶
-
RelaxedOneHotCategorical¶
-
class (temperature, probs=None, logits=None, validate_args=None)[来源]
torch.distributions.relaxed_categorical.
RelaxedOneHotCategorical
¶ -
创建一个 RelaxedOneHotCategorical 分布,该分布由
、 和
或 参数
化。 这是发行版的轻松版本,因此 它的样本是单纯形法,并且可以重新参数化。
OneHotCategorical
例:
>>> m = RelaxedOneHotCategorical(torch.tensor([2.2]), torch.tensor([0.1, 0.2, 0.3, 0.4])) >>> m.sample() tensor([ 0.1294, 0.2324, 0.3859, 0.2523])
-
arg_constraints
: dict[str, torch.distributions.constraints.Constraint] = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶
-
has_rsample
= 真¶
-
财产
logits
¶
-
财产
probs
¶
-
support
= 单纯形 ()¶
-
财产
temperature
¶
-
学生T¶
-
类(df,loc=0.0,scale=1.0,validate_args=None)[来源]
torch.distributions.studentT.
StudentT
¶ -
创建按度数参数化的 Student t 分布 自由 、 中庸 和 规模 。
df
loc
scale
例:
>>> 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
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= 实数()¶
-
财产
variance
¶
-
TransformedDistribution¶
-
class (base_distribution, transforms, validate_args=None)[来源]
torch.distributions.transformed_distribution.
TransformedDistribution
¶ -
Distribution 类的扩展,它应用一系列 Transform 添加到基本分配。设 f 为应用的转换的组合:
X ~ BaseDistribution Y = f(X) ~ TransformedDistribution(BaseDistribution, f) log p(Y) = log p(X) + log |det (dX/dY)|
请注意,a
的 是 其 base 分布及其转换的最大形状,因为 Transforms 可以引入事件之间的关联。
.event_shape
# 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)
-
arg_constraints
: Dict[str, torch.distributions.constraints.Constraint] = {}¶
-
财产
has_rsample
¶
-
rsample
(sample_shape=Torch。Size([]))[来源]¶ 生成 sample_shape 形状的重新参数化样品或sample_shape 如果分布参数 进行批处理。首先从基本分布中采样,然后对列表中的每个转换应用 transform()。
-
sample
(sample_shape=Torch。Size([]))[来源]¶ 生成 sample_shape 形样品或 sample_shape 形批次 samples (如果分布参数是批处理的)。样本 first from base 分布,并对 列表。
-
财产
support
¶
-
均匀¶
-
class (low, high, validate_args=None)[来源]
torch.distributions.uniform.
Uniform
¶ -
从半开区间 生成均匀分布的随机样本。
[low, high)
例:
>>> m = Uniform(torch.tensor([0.0]), torch.tensor([5.0])) >>> m.sample() # uniformly distributed in the range [0.0, 5.0) tensor([ 2.3418])
-
arg_constraints
= {'high': dependent(), 'low': dependent()}¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
stddev
¶
-
财产
support
¶
-
财产
variance
¶
-
冯米塞斯¶
-
class (loc, concentration, validate_args=None)[来源]
torch.distributions.von_mises.
VonMises
¶ -
循环 von Mises 分布。
此实现使用极坐标。和 args 可以是任何实数(以便于不受约束的优化),但 解释为 angles modulo 2 pi。
loc
value
- 例::
>>> m = dist.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) – 以弧度为单位的角度。
浓度(Torch。Tensor) – 浓度参数
-
arg_constraints
= {'concentration': GreaterThan(lower_bound=0.0), 'loc': Real()}¶
-
has_rsample
= 假¶
-
财产
mean
¶ 提供的平均值是循环平均值。
-
财产
mode
¶
-
sample
(sample_shape=Torch。Size([]))[来源]¶ von Mises 分布的抽样算法基于以下论文: Best, DJ 和 Nicholas I. Fisher。 “von Mises 分布的高效模拟。”应用统计学 (1979):152-157。
-
support
= 实数()¶
-
财产
variance
¶ 提供的差异是循环的差异。
威布尔¶
-
class (scale, concentration, validate_args=None)[来源]
torch.distributions.weibull.
Weibull
¶ -
来自双参数 Weibull 分布的样本。
例
>>> m = Weibull(torch.tensor([1.0]), torch.tensor([1.0])) >>> m.sample() # sample from a Weibull distribution with scale=1, concentration=1 tensor([ 0.4784])
- 参数
-
arg_constraints
: dict[str, torch.distributions.constraints.Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)}¶
-
财产
mean
¶
-
财产
mode
¶
-
support
= 大于 (lower_bound=0.0)¶
-
财产
variance
¶
威沙特¶
-
class (df, covariance_matrix=无, precision_matrix=无, scale_tril=无, validate_args=无)[来源]
torch.distributions.wishart.
Wishart
¶ -
创建由对称正定矩阵参数化的 Wishart 分布, 或其 Cholesky 分解
例
>>> 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
- 参数
注意
只能指定 or
中的
一个。 使用
会更有效率:所有计算都在内部进行 基于
。如果
传递 or
,则它仅用于计算 使用 Cholesky 分解的相应下三角矩阵。 'torch.distributions.LKJCholesky' 是受限制的 Wishart 发行版。[1]
引用
[1] 关于 LKJ 分销和受限 Wishart 分销的等效性, 王振勋, 吴云楠, 楚海涛.
-
arg_constraints
= {'covariance_matrix': PositiveDefinite(), 'df': GreaterThan(lower_bound=0), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}¶
-
财产
covariance_matrix
¶
-
has_rsample
= 真¶
-
财产
mean
¶
-
财产
mode
¶
-
财产
precision_matrix
¶
-
rsample
(sample_shape=Torch。Size([]), max_try_correction=无)[来源]¶ 警告
在某些情况下,基于 Bartlett 分解的 algorithn 采样可能会返回奇异矩阵样本。 默认情况下,会执行多次尝试更正奇异样本,但最终可能会返回 奇异矩阵样本。Sigular 样本可能会在 .log_prob() 中返回 -inf 值。 在这些情况下,用户应验证样本,并相应地修复 df 的值或调整 .rsample 中参数max_try_correction值。
-
财产
scale_tril
¶
-
support
= PositiveDefinite()¶
-
财产
variance
¶
KL Divergence¶
-
torch.distributions.kl.
kl_divergence
(p, q)[来源]¶ Compute Kullback-Leibler divergence在两个分配之间。
- 参数
p (Distribution) (分配) – 对象。
Distribution
q (Distribution) (分配) – 对象。
Distribution
- 返回
形状为 batch_shape 的一批 KL 发散。
- 返回类型
- 提高
NotImplementedError – 如果尚未通过
.
- 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
和Exponential
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)[来源]¶ -
@register_kl(Normal, Normal) def kl_normal_normal(p, q): # insert implementation here
Lookup 返回按子类排序的最具体的 (type,type) 匹配项。如果 匹配项不明确,则会引发 RuntimeWarning。例如,将 解决模棱两可的情况:
@register_kl(BaseP, DerivedQ) def kl_version1(p, q): ... @register_kl(DerivedP, BaseQ) def kl_version2(p, q): ...
您应该注册第三个最具体的 implementation,例如:
register_kl(DerivedP, DerivedQ)(kl_version1) # Break the tie.
变换¶
-
类 (loc, scale, event_dim=0, cache_size=0)[来源]
torch.distributions.transforms.
AffineTransform
¶ 通过逐点仿射映射进行变换.
-
class (tseq, dim=0, lengths=None, cache_size=0)[来源]
torch.distributions.transforms.
CatTransform
¶ Transform functor,它按组件将一系列转换 tseq 应用于 dim 处的每个子矩阵,长度为 lengths[dim], 以兼容
的方式。
- 例::
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 (parts, cache_size=0)[来源]
torch.distributions.transforms.
ComposeTransform
¶ 在一个链中组合多个转换。 正在组合的转换负责缓存。
- 参数
cache_size (int) – 缓存的大小。如果为零,则不执行缓存。如果 1 个,则 缓存最新的单个值。仅支持 0 和 1。
-
类 (cache_size=0)[来源]
torch.distributions.transforms.
CorrCholeskyTransform
¶ 变换一个未约束的实向量带 length到 D 维相关矩阵的 Cholesky 因子。这个 Cholesky 因子较低 具有正对角线的三角形矩阵,每行的单位为欧几里得范数。 转换的处理方式如下:
-
类(分布,cache_size=0)[来源]
torch.distributions.transforms.
CumulativeDistributionTransform
¶ 通过概率分布的累积分布函数进行变换。
- 参数
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])
-
类 (base_transform, reinterpreted_batch_ndims, cache_size=0)[来源]
torch.distributions.transforms.
IndependentTransform
¶ 包装另一个转换,将 -many extra 的右侧最维度视为 依靠。这对向前或向后转换没有影响,但 求和 - 许多最右边的维度 在。
reinterpreted_batch_ndims
reinterpreted_batch_ndims
log_abs_det_jacobian()
- 参数
reinterpreted_batch_ndims (int) – 最右边的额外数量 要视为从属的维度。
-
类 (cache_size=0)[来源]
torch.distributions.transforms.
LowerCholeskyTransform
¶ 从无约束矩阵变换为下三角矩阵 非负对角线条目。
这对于根据 他们的 Cholesky 因式分解。
-
类 (in_shape, out_shape, cache_size=0)[来源]
torch.distributions.transforms.
ReshapeTransform
¶ Unit Jacobian 变换来重塑张量的最右侧部分。
请注意,和 必须具有相同的 元素,就像
.
in_shape
out_shape
- 参数
in_shape(Torch。Size) – 输入事件形状。
out_shape(Torch。Size) – 输出事件形状。
-
类 (cache_size=0)[来源]
torch.distributions.transforms.
TanhTransform
¶ 通过映射进行变换.
它等效于但是,这可能在数值上不稳定,因此建议使用 TanhTransform。
` ComposeTransform([AffineTransform(0., 2.), SigmoidTransform(), AffineTransform(-1., 2.)]) `
请注意,当涉及到 NaN/Inf 值时,应使用 cache_size=1。
-
类 (cache_size=0)[来源]
torch.distributions.transforms.
SoftmaxTransform
¶ 通过从无约束空间变换为单纯形然后 正火。
这不是双射的,不能用于 HMC。然而,这主要起作用 坐标方向(最终归一化除外),因此 适用于坐标优化算法。
-
类 (tseq, dim=0, cache_size=0)[来源]
torch.distributions.transforms.
StackTransform
¶ Transform functor,它以兼容的方式将一系列转换 tseq 按组件应用于 dim 处的每个子矩阵。
- 例::
x = torch.stack([torch.range(1, 10), torch.range(1, 10)], dim=1) t = StackTransform([ExpTransform(), identity_transform], dim=1) y = t(x)
-
类 (cache_size=0)[来源]
torch.distributions.transforms.
StickBreakingTransform
¶ 从不受约束的空间变换到一个附加空间的单纯形 尺寸。
此转换作为折杆中的迭代 sigmoid 转换出现 狄利克雷分布的构造:第一个 logit 是 通过 sigmoid 转换为第一个概率和 其他所有内容,然后进程递归。
这是双射的,适合在 HMC 中使用;然而,它混合在一起 坐标在一起,不太适合进行优化。
-
类 (cache_size=0)[来源]
torch.distributions.transforms.
Transform
¶ 具有可计算对数的可逆转换的抽象类 雅各布人。它们主要用于 。
torch.distributions.TransformedDistribution
缓存对于其 inverse 为 cost 或 数值不稳定。请注意,必须注意记忆值 因为 autograd 图表可能是相反的。例如,虽然以下 使用或不使用缓存:
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
派生类应实现 或 中的一个或两个。设置 bijective=True 的派生类也应 实施
.
_call()
_inverse()
- 参数
cache_size (int) – 缓存的大小。如果为零,则不执行缓存。如果 1 个,则 缓存最新的单个值。仅支持 0 和 1。
- 变量
-
财产
sign
¶ 返回雅可比行列式的行列式的符号(如果适用)。 通常,这仅对 bijective 转换有意义。
约束¶
实施了以下约束:
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_integer
constraints.one_hot
constraints.positive_integer
constraints.positive
constraints.positive_semidefinite
constraints.positive_definite
constraints.real_vector
constraints.real
constraints.simplex
constraints.symmetric
constraints.stack
constraints.square
constraints.symmetric
constraints.unit_interval
-
torch.distributions.constraints.
cat
¶ 别名为
torch.distributions.constraints._Cat
-
torch.distributions.constraints.
dependent_property
¶ 别名为
torch.distributions.constraints._DependentProperty
-
torch.distributions.constraints.
greater_than
¶ 别名为
torch.distributions.constraints._GreaterThan
-
torch.distributions.constraints.
greater_than_eq
¶ 别名为
torch.distributions.constraints._GreaterThanEq
-
torch.distributions.constraints.
independent
¶ 别名为
torch.distributions.constraints._IndependentConstraint
-
torch.distributions.constraints.
integer_interval
¶ 别名为
torch.distributions.constraints._IntegerInterval
-
torch.distributions.constraints.
interval
¶ 别名为
torch.distributions.constraints._Interval
-
torch.distributions.constraints.
half_open_interval
¶ 别名为
torch.distributions.constraints._HalfOpenInterval
-
torch.distributions.constraints.
less_than
¶ 别名为
torch.distributions.constraints._LessThan
-
torch.distributions.constraints.
multinomial
¶ 别名为
torch.distributions.constraints._Multinomial
-
torch.distributions.constraints.
stack
¶ 别名为
torch.distributions.constraints._Stack
约束注册表¶
PyTorch 提供了两个全局对象,用于将对象链接到
对象。这些对象都
input constraints 和 return 转换,但它们对
双射度。
biject_to(constraint)
查找 bijectivefrom 到 given .返回的转换保证具有并且应该实现 。
constraints.real
constraint
.bijective = True
.log_abs_det_jacobian()
transform_to(constraint)
查找一个不一定的双射from 到给定的 。返回的转换不能保证 实现。
constraints.real
constraint
.log_abs_det_jacobian()
注册表可用于执行 unconstrained
对概率分布的约束参数进行优化,这些参数是
由每个分配的 dict 指示。这些转换通常
过度参数化 space 以避免旋转;因此,他们是
适用于像 Adam 这样的坐标优化算法:transform_to()
.arg_constraints
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()
注意
其中 和 differ 的示例是 : 返回一个
对其输入进行指数化和归一化;这是一个便宜且大部分
适合 SVI 等算法的坐标运算。在
contrast 的 Sample,返回一个
将其输入向下喷射到少一维的空间;这个更多
成本高昂、数值稳定性较低但算法需要的变换
就像 HMC 一样。
transform_to
biject_to
constraints.simplex
transform_to(constraints.simplex)
biject_to(constraints.simplex)
和 对象可以通过用户定义的
constraints 和 transform,使用它们的方法作为
函数 on singleton constraints: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)