概率分布 - torch.distributions ¶
distributions
包含可参数化的概率分布和采样函数。这允许构建随机计算图和随机梯度估计器以进行优化。此包通常遵循 TensorFlow Distributions 包的设计。
无法直接通过随机样本进行反向传播。然而,有两种主要方法可以创建可以反向传播的代理函数。这些是得分函数估计器/似然比估计器/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][source]
基础:
object
分布是概率分布的抽象基类。
- 属性 arg_constraintsdict[str:torch.distributions.constraints.Constraint] ¶
返回一个从参数名称到
Constraint
对象的字典,这些对象应该满足此分布的每个参数。不是张量的参数无需出现在此字典中。
- 属性 batch_shapeSize ¶
返回参数批处理的形状。
- entropy()[来源][来源] ¶
返回分布的熵,在 batch_shape 上批处理。
- 返回:
形状为 batch_shape 的张量。
- 返回类型:
- enumerate_support(expand=True)[source][source]¶
返回包含离散分布所有值的张量。结果将在维度 0 上枚举,因此结果的形状将为(cardinality,) + batch_shape + event_shape(对于一元分布,event_shape = ())。
注意,这将锁定步长枚举所有批处理张量 [[0, 0], [1, 1], …]。当 expand=False 时,枚举发生在 dim 0 上,但剩余的批处理维度为单例维度,[[0], [1], …]。
要遍历完整的笛卡尔积,请使用 itertools.product(m.enumerate_support())。
- 参数:
扩展(布尔值)- 是否将支持扩展到批维度以匹配分布的 batch_shape。
- 返回:
张量遍历维度 0。
- 返回类型:
- 属性 event_shapeSize ¶
返回单个样本的形状(不包含批处理)。
- expand(batch_shape, _instance=None)[source][source]¶
返回一个新的分布实例(或填充由派生类提供的现有实例),将批维度扩展到 batch_shape。此方法会在分布的参数上调用
expand
。因此,此方法不会为扩展的分布实例分配新的内存。此外,此方法在__init__.py 中不会重复任何 args 检查或参数广播,当实例首次创建时。- 参数:
batch_shape (torch.Size) – 所需的扩展大小。
_instance – 需要覆盖.expand 的子类提供的新实例。
- 返回:
批量维度扩展到 batch_size 的新分布实例。
- icdf(value)[来源][来源]
返回在 value 处评估的逆累积分布/质量函数。
- 参数:
value (张量) –
- 返回类型:
- log_prob(value)[来源][来源] ¶
返回在 value 处评估的概率密度/质量函数的对数。
- 参数:
value (张量) –
- 返回类型:
- 属性 meanTensor ¶
返回分布的均值。
- 属性 modeTensor ¶
返回分布的模式。
- perplexity()[来源][来源] ¶
返回分布的困惑度,批处理在 batch_shape 上。
- 返回:
形状为 batch_shape 的张量。
- 返回类型:
- rsample(sample_shape=torch.Size([]))[source][source]¶
生成形状为 sample_shape 的样本或如果分布参数是批量的,则为 sample_shape 形状的样本批次。
- 返回类型:
- sample(sample_shape=torch.Size([]))[source][source]¶
生成形状为 sample_shape 的样本或如果分布参数是批量的,则为 sample_shape 形状的样本批次。
- 返回类型:
- 设置默认的验证参数(value)[源代码][源代码] ¶
设置是否启用或禁用验证。
默认行为模仿 Python 的
assert
语句:默认启用验证,但如果 Python 以优化模式运行(通过python -O
),则禁用验证。验证可能很昂贵,因此一旦模型工作正常,您可能希望禁用它。- 参数:
是否启用验证(布尔值)。
- 属性 stddevTensor
返回分布的标准差。
- 属性 supportOptional[Constraint]
返回表示此分布支撑的
Constraint
对象。
- 属性方差张量 ¶
返回分布的方差。
指数族
- class torch.distributions.exp_family.ExponentialFamily(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)[source][source]¶
基础:
Distribution
ExponentialFamily 是指数族概率分布的抽象基类,其概率质量/密度函数的形式如下定义
其中 表示自然参数, 表示充分统计量, 是给定族的对数规范化函数, 是载体测度。
注意
此类是 Distribution 类和属于指数族的分布之间的中介,主要用于检查 .entropy() 和解析 KL 散度方法是否正确。我们使用此类通过 AD 框架和 Bregman 散度(感谢:Frank Nielsen 和 Richard Nock,指数族熵和交叉熵)来计算熵和 KL 散度。
伯努利
- class torch.distributions.bernoulli.Bernoulli(probs=None, logits=None, validate_args=None)[source][source]¶
基类:
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.])
- 参数:
probs(数字,张量)- 采样 1 的概率
logits(数字,张量)- 采样 1 的对数几率
- arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶
- has_enumerate_support = True¶
- log_prob(value)[来源][来源] ¶
- 属性 logitsTensor
- 属性 均值张量
- 属性 modeTensor ¶
- 属性 param_shapeSize
- 属性 probsTensor
- support=布尔值()
- 属性 varianceTensor ¶
测试版
- class torch.distributions.beta.Beta(浓度 1, 浓度 0, validate_args=None)[source][source]
基类:
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])
- 参数:
浓度 1(浮点数或张量)- 分布的第 1 个浓度参数(通常称为 alpha)
浓度 0(浮点数或张量)- 分布的第 2 个浓度参数(通常称为 beta)
- 参数约束={'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)} ¶
- 属性浓度 0Tensor
- 属性浓度 1 张量 ¶
- 熵()[来源][来源] ¶
- has_rsample = True¶
- log_prob(value)[来源][来源] ¶
- 属性 均值张量
- 属性 modeTensor ¶
- rsample(sample_shape=())[来源][来源] ¶
- 返回类型:
- support=区间(下限=0.0, 上限=1.0) ¶
- 属性 varianceTensor
二项式分布
- class torch.distributions.binomial.Binomial(total_count=1, probs=None, logits=None, validate_args=None)[source][source]¶
基础:
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.]])
- 参数:
total_count(int 或 Tensor)- 伯努利试验次数
概率(张量)- 事件概率
logits(张量)- 事件对数几率
- 参数约束={'logits': 实数(), 'probs': 区间(下限=0.0, 上限=1.0), 'total_count': 整数大于(下限=0)} ¶
- entropy()[来源][来源] ¶
- has_enumerate_support = True¶
- 属性 均值张量
- 属性 modeTensor ¶
- 属性 param_shapeSize ¶
- 属性 probsTensor ¶
- 属性 support ¶
- 返回类型:
_依赖属性
- 属性 varianceTensor
分类 ¶
- class torch.distributions.categorical.Categorical(probs=None, logits=None, validate_args=None)[source][source]¶
基础:
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)
- 参数:
概率(张量)- 事件概率
logits(张量)- 事件对数概率(未归一化)
- arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶
- 熵()[来源][来源]
- enumerate_support(expand=True)[来源][来源] ¶
- expand(batch_shape, _instance=None)[来源][来源] ¶
- has_enumerate_support = True¶
- log_prob(value)[source][source]
- 属性 logitsTensor
- 属性 均值张量
- 属性 modeTensor ¶
- 属性 param_shapeSize ¶
- 属性 probsTensor ¶
- 属性 support ¶
- 返回类型:
_依赖属性
- 属性 varianceTensor ¶
库西
- class torch.distributions.cauchy.Cauchy(loc, scale, validate_args=None)[source][source] 库西
基础:
Distribution
从 Cauchy(洛伦兹)分布中抽取样本。独立正态分布随机变量的比率的分布遵循 Cauchy 分布。
示例:
>>> m = Cauchy(torch.tensor([0.0]), torch.tensor([1.0])) >>> m.sample() # sample from a Cauchy distribution with loc=0 and scale=1 tensor([ 2.3214])
- 参数:
loc(浮点数或 Tensor)- 分布的模或中位数。
scale(浮点数或张量)- 半最大值半宽度。
- 参数约束={'loc': 实数(), 'scale': 大于(lower_bound=0.0)} ¶
- cdf(value)[来源][来源] ¶
- 熵()[来源][来源]
- expand(batch_shape, _instance=None)[来源][来源] ¶
- has_rsample=True
- icdf(value) [来源][来源] ¶
- log_prob(value)[source][source]
- 属性 均值张量
- 属性 modeTensor ¶
- support=实数() ¶
- 属性 varianceTensor ¶
Chi2¶
- class torch.distributions.chi2.Chi2(df, validate_args=None)[source][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])
- 参数:
df (浮点数或张量) – 分布的形状参数
- arg_constraints={'df': 大于(lower_bound=0.0)} ¶
- 属性 dfTensor ¶
- expand(batch_shape, _instance=None) [来源][来源] ¶
ContinuousBernoulli¶
- 类 torch.distributions.continuous_bernoulli.ContinuousBernoulli(probs=None, logits=None, lims=(0.499, 0.501), validate_args=None)[source][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])
- 参数:
probs(数字,张量)- (0,1) 值参数
logits(数字,张量)- 实数值参数,其 sigmoid 函数与 'probs' 相匹配
[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)}¶
- entropy() [来源][来源] ¶
- expand(batch_shape, _instance=None) [来源][来源] ¶
- has_rsample = True¶
- icdf(value)[源][源] ¶
- log_prob(value)[source][source]
- 属性 均值张量
- 属性 param_shapeSize ¶
- 属性 probsTensor ¶
- 属性 stddevTensor ¶
- 支持区间=Interval(下限=0.0, 上限=1.0) ¶
- 属性 varianceTensor ¶
黎曼 ¶
- class torch.distributions.dirichlet.Dirichlet(浓度, validate_args=None)[source][source] ¶
Bases:
ExponentialFamily
创建一个由浓度参数化的 Dirichlet 分布
concentration
。示例:
>>> m = Dirichlet(torch.tensor([0.5, 0.5])) >>> m.sample() # Dirichlet distributed with concentration [0.5, 0.5] tensor([ 0.1046, 0.8954])
- 参数:
浓度 (Tensor) – 分布的浓度参数(通常称为 alpha)
- arg_constraints={'浓度': IndependentConstraint(大于(lower_bound=0.0), 1)} ¶
- entropy() [来源][来源] ¶
- expand(batch_shape, _instance=None) [来源][来源] ¶
- has_rsample = True¶
- log_prob(value)[source][source]
- 属性 均值张量
- 属性 modeTensor ¶
- rsample(sample_shape=())[来源][来源] ¶
- 返回类型:
- support = Simplex()¶
- 属性 varianceTensor ¶
指数
- class torch.distributions.exponential.Exponential(rate, validate_args=None)[source][source]¶
基类:
ExponentialFamily
创建一个由
rate
参数化的指数分布。示例:
>>> m = Exponential(torch.tensor([1.0])) >>> m.sample() # Exponential distributed with rate=1 tensor([ 0.1046])
- 参数:
率(浮点数或张量)- 率 = 分布的尺度倒数
- 参数约束={'rate': 大于(lower_bound=0.0)}
- cdf(value)[来源][来源]
- entropy()[来源][来源]
- has_rsample = True¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- 属性 stddevTensor ¶
- support=大于等于(lower_bound=0.0) ¶
- 属性方差张量 ¶
费舍尔-斯涅德科 ¶
- class torch.distributions.fishersnedecor.FisherSnedecor(df1, df2, validate_args=None)[source][source]¶
基础:
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])
- 参数:
df1(浮点数或张量)- 自由度参数 1
df2(浮点数或张量)- 自由度参数 2
- arg_constraints={'df1': 大于(下限=0.0), 'df2': 大于(下限=0.0)} ¶
- has_rsample = True¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- support = GreaterThan(lower_bound=0.0)¶
- 属性方差张量 ¶
伽马 ¶
- 类 torch.distributions.gamma.Gamma(浓度, 速率, validate_args=None)[source][source] ¶
基类:
ExponentialFamily
创建一个形状参数为
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])
- 参数:
浓度(浮点数或张量)- 分布的形状参数(通常称为 alpha)
速率(浮点数或张量)- 分布的速率参数(通常称为 beta),速率 = 1 / 尺度
- arg_constraints={'浓度': 大于(下限=0.0), '速率': 大于(下限=0.0)} ¶
- cdf(值)[来源][来源] ¶
- 熵()[来源][来源] ¶
- expand(batch_shape, _instance=None)[来源][来源] ¶
- has_rsample = True¶
- log_prob(值)[来源][来源] ¶
- 属性 平均张量
- 属性 模式张量
- rsample(sample_shape=torch.Size([]))[来源][来源] ¶
- 返回类型:
- support=大于等于(lower_bound=0.0) ¶
- 属性方差张量 ¶
几何的 ¶
- class torch.distributions.geometric.Geometric(probs=None, logits=None, validate_args=None)[source][source]¶
基础:
Distribution
创建一个由
probs
参数化的几何分布,其中probs
是伯努利试验成功的概率。注意
torch.distributions.geometric.Geometric()
次试验是第一次成功,因此从 中抽取样本,而torch.Tensor.geometric_()
k 次试验是第一次成功,因此从 中抽取样本。示例:
>>> m = Geometric(torch.tensor([0.3])) >>> m.sample() # underlying Bernoulli has 30% chance 1; 70% chance 0 tensor([ 2.])
- 参数:
probs(数字,张量)- 抽样 1 的概率。必须在范围(0,1] 内。
logits(数字,张量)- 采样 1 的对数几率。
- 参数约束={'logits': 实数(), 'probs': 区间(lower_bound=0.0, upper_bound=1.0)} ¶
- log_prob(值)[来源][来源] ¶
- 属性 logitsTensor
- 属性 meanTensor
- 属性 modeTensor
- 属性 probsTensor ¶
- sample(sample_shape=torch.Size([]))[来源][来源] ¶
- 支持整数大于(下界=0) ¶
- 属性 varianceTensor ¶
Gumbel¶
- class torch.distributions.gumbel.Gumbel(位置, 尺度, validate_args=None)[源代码][源代码] ¶
基类:
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])
- 参数:
loc (浮点数或张量) – 分布的位置参数
scale (浮点数或张量) – 分布的尺度参数
- arg_constraintsdict[str:torch.distributions.constraints.Constraint]={'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)} ¶
- entropy()[来源][来源] ¶
- 属性 meanTensor
- 属性 modeTensor
- 属性 stddevTensor
- 支持实数()
- 属性 varianceTensor
半柯西分布
- class torch.distributions.half_cauchy.HalfCauchy(scale, validate_args=None)[source][source]¶
基类:
TransformedDistribution
创建一个由 scale 参数化的半 Cauchy 分布,其中:
X ~ Cauchy(0, scale) Y = |X| ~ HalfCauchy(scale)
示例:
>>> m = HalfCauchy(torch.tensor([1.0])) >>> m.sample() # half-cauchy distributed with scale=1 tensor([ 2.3214])
- 参数:
scale (浮点数或 Tensor) - 全 Cauchy 分布的尺度
- arg_constraints: dict[str, torch.distributions.constraints.Constraint] = {'scale': GreaterThan(lower_bound=0.0)}¶
- 累积分布函数(value)[源代码][源代码] ¶
- 熵()[源代码][源代码] ¶
- expand(batch_shape, _instance=None)[源代码][源代码] ¶
- has_rsample=True
- icdf(prob)[source][source]
- log_prob(value)[source][source]
- property meanTensor
- 属性 modeTensor ¶
- 属性 scaleTensor ¶
- 支持大于等于(lower_bound=0.0) ¶
- 属性 varianceTensor ¶
半正态分布
- class torch.distributions.half_normal.HalfNormal(scale, validate_args=None)[source][source]¶
基类:
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])
- 参数:
scale(浮点数或张量)- 全部正态分布的缩放比例
- 参数约束 dict[str:torch.distributions.constraints.Constraint]={'scale': GreaterThan(lower_bound=0.0)} ¶
- has_rsample = True¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- 属性 scaleTensor ¶
- support = GreaterThanEq(lower_bound=0.0)¶
- 属性方差张量 ¶
独立
- 类 torch.distributions.independent.Independent(base_distribution, reinterpreted_batch_ndims, validate_args=None)[source][source] ¶
基类:
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, torch.distributions.constraints.Constraint] = {}¶
- 熵()[来源][来源] ¶
- enumerate_support(expand=True)[来源][来源] ¶
- expand(batch_shape, _instance=None)[来源][来源] ¶
- 属性支持枚举布尔值 ¶
- 属性支持重采样布尔值 ¶
- log_prob(value)[来源][来源] ¶
- 属性均值张量 ¶
- 属性模式 Tensor ¶
- 属性支持 ¶
- 返回类型:
依赖属性
- 属性方差张量 ¶
逆伽马 ¶
- class torch.distributions.inverse_gamma.InverseGamma(浓度, 速率, validate_args=None)[source][source] ¶
基础:
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])
- 参数:
浓度(浮点数或张量)- 分布的形状参数(通常称为 alpha)
速率(浮点数或张量)- 速率 = 分布的 scale 的倒数(通常称为 beta)
- arg_constraints: dict[str, torch.distributions.constraints.Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}¶
- 属性浓度张量
- 熵()[来源][来源]
- expand(batch_shape, _instance=None)[来源][来源]
- has_rsample=True
- 属性 均值张量
- 属性 模式张量
- 属性 频率张量
- support=大于(下限=0.0) ¶
- 属性方差张量 ¶
库马拉斯瓦米 ¶
- 类 torch.distributions.kumaraswamy.Kumaraswamy(浓度 1, 浓度 0, 验证参数=None)[source][source] ¶
基础:
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])
- 参数:
concentration1(浮点数或张量)- 分布的第 1 个浓度参数(通常称为 alpha)
concentration0(浮点数或张量)- 分布的第 2 个浓度参数(通常称为 beta)
- arg_constraintsdict[strtorch.distributions.constraints.Constraint]={'concentration0': 大于(lower_bound=0.0), 'concentration1': 大于(lower_bound=0.0)} ¶
- entropy()[来源][来源] ¶
- expand(batch_shape, _instance=None)[来源][来源] ¶
- has_rsample = True¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- support=区间(下限=0.0, 上限=1.0) ¶
- 属性 varianceTensor ¶
LKJCholesky¶
- class torch.distributions.lkj_cholesky.LKJCholesky(dim, concentration=1.0, validate_args=None)[source][source]¶
Bases:
Distribution
LKJ 分布用于相关矩阵的下 Cholesky 因子。该分布由
concentration
参数 控制,使得从 Cholesky 因子生成的相关矩阵 的概率与 成比例。因此,当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]])
- 参数:
矩阵的维度(dim)
浓度(浮点数或张量)- 分布的浓度/形状参数(通常称为 eta)
参考文献引用
[1] 基于 vines 和扩展洋葱方法生成随机相关矩阵(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()¶
拉普拉斯分布
- class torch.distributions.laplace.Laplace(loc, scale, validate_args=None)[source][source] 拉普拉斯分布
基类:
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])
- 参数:
loc(浮点数或张量)- 分布的均值
scale(浮点数或张量)- 分布的尺度
- arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
- entropy() [来源][来源] ¶
- expand(batch_shape, _instance=None) [来源][来源] ¶
- has_rsample = True¶
- icdf(value) [来源][来源] ¶
- log_prob(值)[来源][来源] ¶
- 属性 平均张量
- 属性 模式张量
- rsample(sample_shape=torch.Size([]))[来源][来源] ¶
- 返回类型:
- 属性 stddevTensor
- 支持实数类型()
- 属性 varianceTensor
对数正态分布
- class torch.distributions.log_normal.LogNormal(loc, scale, validate_args=None)[source][source]¶
基类:
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])
- 参数:
loc (浮点数或张量) - 分布对数的均值
scale(浮点数或张量)- 分布的对数的标准差
- 参数约束 dict[str:torch.distributions.constraints.Constraint]={'loc': 实数(), 'scale': 大于(lower_bound=0.0)} ¶
- has_rsample = True¶
- 属性 locTensor
- 属性 meanTensor
- 属性 modeTensor ¶
- 属性 scaleTensor ¶
- 支持大于(下限=0.0) ¶
- 属性 varianceTensor ¶
低秩多元正态分布 ¶
- class torch.distributions.lowrank_multivariate_normal.LowRankMultivariateNormal(loc, cov_factor, cov_diag, validate_args=None)[source][source]¶
基类:
Distribution
创建一个具有低秩形式协方差矩阵的多变量正态分布,其参数由
cov_factor
和cov_diag
参数化 :covariance_matrix = cov_factor @ cov_factor.T + cov_diag
示例
>>> m = LowRankMultivariateNormal( ... torch.zeros(2), torch.tensor([[1.0], [0.0]]), torch.ones(2) ... ) >>> m.sample() # normally distributed with mean=`[0,0]`, cov_factor=`[[1],[0]]`, cov_diag=`[1,1]` tensor([-0.2102, -0.5429])
- 参数:
loc(张量)- 形状为 batch_shape + event_shape 的分布的均值
cov_factor(张量)- 协方差矩阵低秩形式的因子部分,形状为 batch_shape + event_shape + (rank,)
cov_diag(张量)- 协方差矩阵低秩形式的对角部分,形状为 batch_shape + event_shape
注意
当 cov_factor.shape[1] << cov_factor.shape[0]时,通过 Woodbury 矩阵恒等式和矩阵行列式引理,避免了协方差矩阵的行列式和逆的计算。多亏了这些公式,我们只需要计算小尺寸的“电容”矩阵的行列式和逆:
capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor
- arg_constraints={'cov_diag': 独立约束(大于(lower_bound=0.0), 1), 'cov_factor': 独立约束(实数(), 2), 'loc': 独立约束(实数(), 1)} ¶
- 属性协方差矩阵 Tensor
- entropy()[来源][来源]
- expand(batch_shape, _instance=None)[来源][来源]
- has_rsample=True
- log_prob(value)[source][source]
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- 属性 precision_matrixTensor ¶
- 属性 scale_trilTensor
- support=IndependentConstraint(Real(), 1)
- 属性 varianceTensor
MixtureSameFamily
- class torch.distributions.mixture_same_family.MixtureSameFamily(mixture_distribution, component_distribution, validate_args=None)[source][source]¶
Bases:
Distribution
The MixtureSameFamily distribution implements a (batch of) mixture distribution where all component are from different parameterizations of the same distribution type. It is parameterized by a Categorical “selecting distribution” (over k component) and a component distribution, i.e., a Distribution with a rightmost batch shape (equal to [k]) which indexes each (batch of) component.
示例:
>>> # 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)
- 参数:
混合分布(分类)- 类似于 torch.distributions.Categorical 的实例。管理选择组件的概率。类别数量必须与 component_distribution 的最后一个批次维度匹配。必须有标量 batch_shape 或与 component_distribution.batch_shape[:-1]匹配的 batch_shape
component_distribution(分布)- 类似于 torch.distributions.Distribution 的实例。最右侧的批次维度索引组件
- arg_constraints: dict[str, torch.distributions.constraints.Constraint] = {}¶
- 属性 组件分布分布 ¶
- expand(batch_shape, _instance=None)[来源][来源] ¶
- has_rsample = False¶
- 属性 均值张量
- 属性 混合分布 Categorical
- 属性支持 ¶
- 返回类型:
_依赖属性
- 属性方差张量 ¶
多项分布 ¶
- class torch.distributions.multinomial.Multinomial(total_count=1, probs=None, logits=None, validate_args=None)[source][source]¶
基类:
Distribution
创建一个由
total_count
参数化,并由probs
或logits
(但不能同时使用)定义的多项分布。probs
的最内层维度索引类别,其他所有维度索引批次。注意,如果只调用
log_prob()
,则不需要指定total_count
(见下例)注意
probs 参数必须是非负、有限且总和不为零的,它将被归一化到最后一维的总和为 1。
probs
将返回这个归一化的值。logits 参数将被解释为未归一化的对数概率,因此可以是任何实数。它也将被归一化,使得结果概率在最后一维上求和为 1。logits
将返回这个归一化的值。sample()
要求所有参数和样本共享一个单独的总计数。log_prob()
允许每个参数和样本有不同的总计数。
示例:
>>> 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])
- 参数:
总数(整数)- 试验次数
概率(张量)- 事件概率
logits(张量)- 事件对数概率(未归一化)
- arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶
- entropy()()[source][source] ¶
- property logitsTensor
- 属性 meanTensor ¶
- 属性 param_shapeSize ¶
- 属性 probsTensor ¶
- 属性支持 ¶
- 返回类型:
_依赖属性
- 总计数量 int ¶
- 属性方差张量 ¶
多元正态分布 ¶
- class torch.distributions.multivariate_normal.MultivariateNormal(loc, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[source][source]¶
基类:
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])
- 参数:
loc(张量)- 分布的均值
covariance_matrix(张量)- 正定协方差矩阵
precision_matrix(张量)- 正定精度矩阵
scale_tril(张量)- 协方差的下三角因子,对角线为正值
注意
只能指定
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()}¶
- 属性 covariance_matrixTensor ¶
- entropy() [来源][来源] ¶
- expand(batch_shape, _instance=None) [来源][来源] ¶
- has_rsample = True¶
- log_prob(value) [来源][来源] ¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- 属性 precision_matrixTensor ¶
- 属性 scale_trilTensor
- support=IndependentConstraint(Real(), 1)
- 属性 varianceTensor
负二项式分布
-
torch.distributions.negative_binomial.NegativeBinomial(total_count, probs=None, logits=None, validate_args=None)[source][source] ¶ torch.distributions.negative_binomial.NegativeBinomial(总计数, probs=None, logits=None, validate_args=None)[source][source] ¶ 基础:
Distribution
创建负二项分布,即达到
total_count
次失败之前成功独立且相同的伯努利试验的分布。每次伯努利试验成功的概率为probs
。- 参数:
total_count(浮点数或张量)- 非负数,表示负伯努利试验的总次数以停止,尽管对于实值计数分布仍然有效
probs(张量)- 在半开区间[0, 1)内的成功事件概率
logits(张量)- 成功概率的事件对数比
- 参数约束={'logits': 实数(), 'probs': 半开区间(下限=0.0, 上限=1.0), 'total_count': 大于等于(下限=0)}
- expand(batch_shape, _instance=None)[source][source]
- log_prob(value)[source][source]
- 属性 logitsTensor ¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- 属性 param_shapeSize ¶
- 属性 probsTensor ¶
- sample(sample_shape=torch.Size([]))[来源][来源] ¶
- 支持整数大于(下界=0) ¶
- 属性 varianceTensor ¶
正常 ¶
- class torch.distributions.normal.Normal(loc, scale, validate_args=None)[source][source]¶
基类:
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])
- 参数:
loc(浮点数或张量)- 分布的均值(通常称为 mu)
scale(浮点数或张量)- 分布的标准差(通常称为 sigma)
- arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
- entropy() [来源][来源] ¶
- expand(batch_shape, _instance=None) [来源][来源] ¶
- has_rsample = True¶
- icdf(value) [来源][来源] ¶
- log_prob(值)[来源][来源] ¶
- 属性 平均张量
- 属性 模式张量
- rsample(sample_shape=torch.Size([]))[来源][来源] ¶
- 返回类型:
- sample(sample_shape=torch.Size([]))[来源][来源] ¶
- 属性 标准差张量
- 支持实数()
- 属性 方差张量
OneHotCategorical¶
- class torch.distributions.one_hot_categorical.OneHotCategorical(probs=None, logits=None, validate_args=None)[source][source]¶
基类:
Distribution
创建一个由
probs
或logits
参数化的 one-hot 分类分布。样本是一组大小为
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.])
- 参数:
probs(张量)- 事件概率
logits(张量)- 事件日志概率(未归一化)
- 参数约束={'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()} ¶
- entropy()[来源][来源] ¶
- enumerate_support(expand=True)[来源][来源] ¶
- has_enumerate_support = True¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- 属性 param_shapeSize ¶
- 属性 probsTensor ¶
- sample(sample_shape=torch.Size([]))[来源][来源] ¶
- support = OneHot()¶
- 属性 varianceTensor ¶
帕累托 ¶
- class torch.distributions.pareto.Pareto(scale, alpha, validate_args=None)[source][source]¶
基类:
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])
- 参数:
scale(浮点数或张量)- 分布的缩放参数
alpha(浮点数或张量)- 分布的形状参数
- arg_constraintsdict[str:torch.distributions.constraints.Constraint]={'alpha': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)} ¶
- 属性 均值张量
- 属性 模式张量
- 属性支持约束 ¶
- 返回类型:
依赖属性
- 属性方差张量 ¶
普朗克 ¶
- class torch.distributions.poisson.Poisson(rate, validate_args=None)[source][source]¶
Bases:
ExponentialFamily
创建一个参数化的泊松分布,参数为
rate
,即速率参数。样本为非负整数,其概率质量函数(pmf)为
示例:
>>> m = Poisson(torch.tensor([4])) >>> m.sample() tensor([ 3.])
- 参数:
速率(数字,张量)- 速率参数
- 参数约束={'rate': 大于等于(lower_bound=0.0)} ¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- 支持=整数大于(下限=0) ¶
- 属性方差张量 ¶
RelaxedBernoulli¶
- class torch.distributions.relaxed_bernoulli.RelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)[source][source]¶
Bases:
TransformedDistribution
创建一个由
temperature
参数化,并使用probs
或logits
(但不能同时使用)的 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])
- 参数:
温度(张量)- 松弛温度
probs(数字,张量)- 采样 1 的概率
logits(数字,张量)- 采样 1 的对数几率
- arg_constraints: dict[str, torch.distributions.constraints.Constraint] = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶
- has_rsample=True
- 属性 logitsTensor
- 属性 probsTensor
- support=区间(下限=0.0,上限=1.0) ¶
- 属性 温度张量 ¶
LogitRelaxedBernoulli¶
- class torch.distributions.relaxed_bernoulli.LogitRelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)[source][source]¶
Bases:
Distribution
创建一个由
probs
或logits
(但不能同时使用)参数化的 LogitRelaxedBernoulli 分布,它是 RelaxedBernoulli 分布的对数。样本是对 (0, 1) 区间内值的对数。更多详情请参阅 [1]。
- 参数:
温度(张量)- 松弛温度
probs(数字,张量)- 采样 1 的概率
logits(数字,张量)- 采样 1 的对数几率
[1] 《连续分布:离散随机变量的连续松弛》(Maddison 等人,2017 年)
[2] 基于 Gumbel-Softmax 的类别重参数化(Jang 等人,2017 年)
- arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶
- 属性 logitsTensor ¶
- 属性 param_shapeSize ¶
- 属性 probsTensor ¶
-
support=Real() ¶ 支持=Real() ¶
RelaxedOneHotCategorical
- torch.distributions.relaxed_categorical.RelaxedOneHotCategorical(temperature, probs=None, logits=None, validate_args=None)[source][source] ¶
基础:
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])
- 参数:
温度(Tensor)- 松弛温度
probs(Tensor)- 事件概率
logits(Tensor)- 每个事件的未归一化对数概率
- arg_constraintsdict[strtorch.distributions.constraints.Constraint]={'logits': 独立约束(实数(), 1), 'probs': 单形约束()} ¶
- has_rsample = True¶
- 属性 logitsTensor ¶
- 属性 probsTensor ¶
- 支持简单形() ¶
- 属性 temperatureTensor ¶
学生 t 分布
- class torch.distributions.studentT.StudentT(df, loc=0.0, scale=1.0, validate_args=None)[source][source]¶
Bases:
Distribution
创建由自由度
df
、均值loc
和尺度scale
参数化的 Student t 分布。示例:
>>> m = StudentT(torch.tensor([2.0])) >>> m.sample() # Student's t-distributed with degrees of freedom=2 tensor([ 0.1046])
- 参数:
df (浮点数或张量) – 自由度
loc(浮点数或张量)- 分布的均值
scale(浮点数或张量)- 分布的尺度
- arg_constraints = {'df': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶
-
expand(batch_shape, _instance=None)[source][source] ¶ 扩展 batch_shape,_instance=None[源][源] ¶
- has_rsample=True
- log_prob(value)[source][source]
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- support = Real()¶
- 属性方差张量 ¶
转换分布 ¶
- 类 torch.distributions.transformed_distribution.TransformedDistribution(基本分布, 转换, validate_args=None)[source][source] ¶
基类:
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 = 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_constraintsdict[strtorch.distributions.constraints.Constraint]={}
-
expand(batch_shape, _instance=None)[source][source] ¶ 扩展 batch_shape,_instance=None[源][源] ¶
- 属性 has_rsamplebool ¶
- icdf(value)[来源][来源] ¶
使用变换(s)和计算基本分布的得分来计算逆累积分布函数。
- log_prob(value)[来源][来源] ¶
通过反转变换并使用基本分布的得分和 log abs det jacobian 来计算得分。
- rsample(sample_shape=torch.Size([]))[source][source]¶
生成形状为 sample_shape 的重新参数化样本或如果分布参数是批量的,则生成形状为 sample_shape 的重新参数化样本批次。首先从基本分布中采样,然后对列表中的每个变换应用 transform()。
- 返回类型:
- sample(sample_shape=torch.Size([]))[source][source]
生成形状为 sample_shape 的样本或如果分布参数是批量的,则生成形状为 sample_shape 的样本批次。首先从基本分布中采样,然后对列表中的每个变换应用 transform()。
- 属性支持 ¶
- 返回类型:
_依赖属性
均匀 ¶
- 类 torch.distributions.uniform.Uniform(低, 高, validate_args=None)[source][source] ¶
基础:
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 ¶ 具有_rsample=True
- icdf(value)[源][源] ¶
- log_prob(值)[来源][来源] ¶
- 属性 meanTensor ¶
- 属性 modeTensor ¶
- 属性 stddevTensor
- 属性 support
- 返回类型:
_依赖属性
- 属性方差张量 ¶
VonMises¶
- class torch.distributions.von_mises.VonMises(loc, concentration, validate_args=None)[source][source]¶
基础:
Distribution
圆形冯·米塞斯分布。
此实现使用极坐标。
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()}¶
- has_rsample=False
- log_prob(value)[source][source]
- 属性 meanTensor
提供的均值是循环均值。
- 属性 modeTensor ¶
- sample(sample_shape=torch.Size([]))[source][source]¶
基于以下论文的采样算法用于冯·米塞斯分布:D.J. Best 和 N.I. Fisher,“冯·米塞斯分布的高效模拟。”应用统计学(1979):152-157。
为了避免在 _rejection_sample() 中因浓度值较小而导致的挂起,内部采样始终以双精度进行,这在单精度下大约从 1e-4 开始出现(见问题 #88443)。
- support=Real()
- 属性方差张量 ¶
提供的方差是圆形方差。
Weibull¶
- class torch.distributions.weibull.Weibull(尺度, 浓度, validate_args=None)[source][source] ¶
基础:
TransformedDistribution
来自双参数威布尔分布的样本。
示例
>>> m = Weibull(torch.tensor([1.0]), torch.tensor([1.0])) >>> m.sample() # sample from a Weibull distribution with scale=1, concentration=1 tensor([ 0.4784])
- 参数:
scale(浮点数或张量)- 分布的尺度参数(λ)。
concentration(浮点数或张量)- 分布的浓度参数(k/形状)。
- arg_constraints: dict[str, torch.distributions.constraints.Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)}¶
- 属性 meanTensor
- 属性 modeTensor ¶
- support = GreaterThan(lower_bound=0.0)¶
- 属性 varianceTensor ¶
Wishart
- class torch.distributions.wishart.Wishart(df, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)[source][source]¶
基类:
ExponentialFamily
创建一个参数化的 Wishart 分布,该分布由一个对称正定矩阵 或其 Cholesky 分解 决定
示例
>>> 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
- 参数:
df(浮点数或张量)- 大于(方阵维度)- 1 的实值参数
协方差矩阵(张量)- 正定协方差矩阵
精度矩阵(张量)- 正定精度矩阵
scale_tril (Tensor) – 协方差下三角因子,对角线值为正
注意
只能指定
covariance_matrix
或precision_matrix
或scale_tril
中的一个。使用scale_tril
将更高效:所有内部计算都基于scale_tril
。如果传递covariance_matrix
或precision_matrix
,则仅用于通过 Cholesky 分解计算相应的下三角矩阵。‘torch.distributions.LKJCholesky’ 是一个受限的 Wishart 分布。[1]参考文献引用
[1] 王峥,吴宇,褚浩,2018. LKJ 分布与限制 Wishart 分布的等价性。[2] 萨瓦耶,2007. Wishart 分布与逆 Wishart 抽样。[3] 安德森,2003. 多元统计分析导论(第 3 版)。[4] 奥德尔,P. L. 和费夫森,A. H.,1966. 生成样本协方差矩阵的数值方法。JASA,61(313):199-203。[5] 库,Y.-C. 和布卢门菲尔德,P.,2010. 在 OX 中生成具有分数自由度的随机 Wishart 矩阵。
- arg_constraints={'covariance_matrix': PositiveDefinite(), 'df': GreaterThan(lower_bound=0), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}
- property covariance_matrixTensor
- entropy()[source][source]
- has_rsample = True¶
- log_prob(value)[来源][来源] ¶
- 属性 meanTensor
- 属性 modeTensor ¶
- 属性 precision_matrixTensor ¶
- rsample(sample_shape=torch.Size([]), max_try_correction=None)[来源][来源] ¶
警告
在某些情况下,基于 Bartlett 分解的采样算法可能会返回奇异矩阵样本。默认情况下会尝试纠正奇异样本,但最终可能仍然返回奇异矩阵样本。奇异样本可能在.log_prob()中返回-∞值。在这种情况下,用户应验证样本,并相应地调整 df 的值或.max_try_correction 参数的值。
- 返回类型:
- 属性 scale_trilTensor
- support=正定矩阵() ¶
- 属性方差张量 ¶
KL 散度
- torch.distributions.kl.kl_divergence(p, q)[source][source]¶
计算两个分布之间的 Kullback-Leibler 散度 。
- 参数:
p(分布)- 一个
Distribution
对象。q(分布)- 一个
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
和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)[source][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.
- 参数:
type_p(类型)–
Distribution
的子类。type_q(类型)–
Distribution
的子类。
转换
- 通过映射 @0# 进行转换的 torch.distributions.transforms.AbsTransform(cache_size=0)[源][源]
通过映射 进行转换。
- class torch.distributions.transforms.AffineTransform(loc, scale, event_dim=0, cache_size=0)[source][source]¶
通过点对点仿射映射进行变换 .
- 参数:
loc (Tensor 或 float) – 位置参数。
scale (Tensor 或 float) – 缩放参数。
event_dim(int)- 可选的事件_shape 大小。对于一元随机变量,应为 0,对于向量分布,应为 1,对于矩阵分布,应为 2,等等。
- class torch.distributions.transforms.CatTransform(tseq, dim=0, lengths=None, cache_size=0)[source][source]¶
将变换序列 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)
- class torch.distributions.transforms.ComposeTransform(parts, cache_size=0)[source][source]¶
将多个变换组合成链。组合的变换负责缓存。
- 参数:
parts(列表
Transform
)- 要组合的变换列表。cache_size(整数)- 缓存大小。如果为零,则不进行缓存。如果为 1,则缓存最新的单个值。仅支持 0 和 1。
- 类 torch.distributions.transforms.CorrCholeskyTransform(cache_size=0)[source][source]
将长度为 的无约束实向量 转换为 D 维相关矩阵的 Cholesky 因子。这个 Cholesky 因子是一个下三角矩阵,对角线为正,并且每行具有单位欧几里得范数。转换过程如下:
首先将 x 转换为按行顺序排列的下三角矩阵。
对于下三角部分的每一行 ,我们应用类StickBreakingTransform
的有符号版本,将 转换为单位欧几里得长度向量,步骤如下:- 按照区间 的域进行缩放: 。- 转换为无符号域: 。- 应用 。- 转换回有符号域: 。
- class torch.distributions.transforms.CumulativeDistributionTransform(distribution, cache_size=0)[source][source]¶
通过概率分布的累积分布函数进行转换。
- 参数:
分布(分布)- 用于转换的累积分布函数的分布。
示例:
# 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][source]¶
包装另一个转换,将最右侧的
reinterpreted_batch_ndims
个额外维度视为依赖。这不会对前向或反向转换产生影响,但在log_abs_det_jacobian()
中会求和出reinterpreted_batch_ndims
个最右侧的维度。- 参数:
base_transform (
Transform
) – 基础转换。reinterpreted_batch_ndims (int) – 将额外视为依赖的最右侧维度数量。
- class torch.distributions.transforms.LowerCholeskyTransform(cache_size=0)[source][source]¶
将非约束矩阵转换为具有非负对角线的下三角矩阵的转换。
这对于用 Cholesky 分解来参数化正定矩阵非常有用。
- class torch.distributions.transforms.PositiveDefiniteTransform(cache_size=0)[source][source]¶
将非约束矩阵转换为正定矩阵。
- class torch.distributions.transforms.PowerTransform(指数, 缓存大小=0)[source][source] ¶
通过映射 进行转换。
- class torch.distributions.transforms.ReshapeTransform(输入形状, 输出形状, 缓存大小=0)[source][source] ¶
单元雅可比变换用于重塑张量最右侧的部分。
注意
in_shape
和out_shape
必须具有相同数量的元素,就像torch.Tensor.reshape()
一样。- 参数:
in_shape(torch.Size)- 输入事件形状。
out_shape(torch.Size)- 输出事件形状。
缓存大小(int)- 缓存的大小。如果为零,则不进行缓存。如果为 1,则缓存最新的单个值。仅支持 0 和 1。(默认 0。)
- 类 torch.distributions.transforms.SigmoidTransform(cache_size=0)[source][source]
通过映射 和 进行转换。
- 类 torch.distributions.transforms.SoftplusTransform(cache_size=0)[source][source]
通过映射 进行转换。当 时,实现将恢复为线性函数。
- class torch.distributions.transforms.TanhTransform(cache_size=0)[source][source]¶
通过映射 进行转换。
这等价于
ComposeTransform( [ AffineTransform(0.0, 2.0), SigmoidTransform(), AffineTransform(-1.0, 2.0), ] )
然而,这可能在数值上不稳定,因此建议使用 TanhTransform。
注意,当涉及到 NaN/Inf 值时,应使用 cache_size=1。
- class torch.distributions.transforms.SoftmaxTransform(缓存大小=0)[source][source] ¶
将非约束空间转换为单纯形,然后进行归一化。
这不是双射,不能用于 HMC。然而,它主要按坐标方式操作(除了最后的归一化),因此适用于按坐标优化的算法。
- class torch.distributions.transforms.StackTransform(tseq, dim=0, 缓存大小=0)[source][source] ¶
将变换算子应用于每个子矩阵的 dim 维度,执行一系列变换 tseq,与
torch.stack()
兼容。示例:
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][source]
通过 stick-breaking 过程将非约束空间转换为额外维度单纯形。
该变换在 Dirichlet 分布的 stick-breaking 构造中作为迭代 sigmoid 变换出现:第一个 logit 通过 sigmoid 变换为第一个概率,然后是其他所有概率,然后过程递归。
这是对 HMC 使用来说是双射且合适的;然而,它将坐标混合在一起,在优化方面不太合适。
- class torch.distributions.transforms.Transform(cache_size=0)[source][source]
可逆变换的抽象类,具有可计算的 log det jacobian。它们主要用于
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)- 缓存大小。如果为零,则不进行缓存。如果为 1,则缓存最新的单个值。仅支持 0 和 1。
- 变量:
领域(
Constraint
)- 表示此变换有效输入的约束。值域(
Constraint
)- 表示此变换有效输出(也是逆变换的输入)的约束。双射(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)
。符号(int 或 Tensor)- 对于双射的单变量变换,这应该是+1 或-1,取决于变换是单调递增还是递减。
- 属性 invTransform ¶
返回此变换的逆变换
Transform
。这应该满足t.inv.inv is t
。
- 属性 signint ¶
如果适用,返回雅可比矩阵行列式的符号。通常,这仅适用于双射变换。
约束
- class torch.distributions.constraints.Constraint[source][source]¶
约束的抽象基类。
约束对象表示变量有效的区域,例如变量可以在此区域内进行优化。
- 变量:
is_discrete(布尔值)- 约束空间是否为离散。默认为 False。
event_dim(int)- 定义事件的右端维度数量。
check()
方法将在计算有效性时移除这么多维度。
- check(value)[source][source]
返回一个字节张量,表示 value 中的每个事件是否满足此约束。
- torch.distributions.constraints.cat[source]
_Cat
的别名
- torch.distributions.constraints.is_dependent(constraint)[source][source]¶
检查
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
的别名
约束注册表 ¶
PyTorch 提供了两个全局 ConstraintRegistry
对象,它们将 Constraint
对象与 Transform
对象链接。这两个对象都输入约束并返回转换,但它们对双射性的保证不同。
biject_to(constraint)
从给定的constraint
查找双射的Transform
。返回的转换保证具有.bijective = True
并且应该实现.log_abs_det_jacobian()
。查找从
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][source]
将约束与变换链接的注册表。
- register(constraint, factory=None)[source][source]¶
在此注册表中注册一个
Constraint
子类。用法:@my_registry.register(MyConstraintClass) def construct_transform(constraint): assert isinstance(constraint, MyConstraint) return MyTransform(constraint.arg_constraints)
- 参数:
constraint (子类
Constraint
) –Constraint
的子类,或所需类的单例对象。工厂(可调用)- 输入约束对象并返回
Transform
对象的可调用。