实用工具
PyKEEN的实用工具。
- class Bias(dim: int)[source]
一个用于添加偏置的模块包装器。
初始化模块。
- Parameters:
dim (int) – >0 输入的维度。
- class ExtraReprMixin[source]
一个用于具有层次结构extra_repr的模块的mixin。
它采用了
torch.nn.Module.extra_repr()
的想法,并额外提供了一种简单的组合方式来生成extra_repr()
的组件,通过iter_extra_repr()
。如果与torch.nn.Module结合使用,请确保将
ExtraReprMixin
放在torch.nn.Module
后面,以优先使用后者的__repr__()
实现。- iter_extra_repr() Iterable[str] [来源]
遍历
extra_repr()
的组件。此方法通常被重写。一个常见的模式是
def iter_extra_repr(self) -> Iterable[str]: yield from super().iter_extra_repr() yield "<key1>=<value1>" yield "<key2>=<value2>"
- Returns:
一个可迭代的
extra_repr()
的各个组件- Return type:
- class Result[source]
可以保存到目录的结果的超类。
- abstract save_to_directory(directory: str, **kwargs) None [source]
将结果保存到目录中。
- Parameters:
目录 (str)
- Return type:
无
- all_in_bounds(x: Tensor, low: float | None = None, high: float | None = None, a_tol: float = 0.0) bool [source]
检查张量值是否遵守下限和上限。
- broadcast_upgrade_to_sequences(*xs: X | Sequence[X]) Sequence[Sequence[X]] [source]
对每个输入应用upgrade_to_sequence,然后重复单例以匹配最大长度。
- Parameters:
xs (X | Sequence[X]) – 长度: m 输入。
- Returns:
一个长度为m的序列,其中每个元素都是一个序列,并且所有元素的长度相同。
- Raises:
ValueError – 如果存在长度与最大序列长度不同的非单一序列输入。
- Return type:
>>> broadcast_upgrade_to_sequences(1) ((1,),) >>> broadcast_upgrade_to_sequences(1, 2) ((1,), (2,)) >>> broadcast_upgrade_to_sequences(1, (2, 3)) ((1, 1), (2, 3))
- calculate_broadcasted_elementwise_result_shape(first: tuple[int, ...], second: tuple[int, ...]) tuple[int, ...] [source]
确定广播元素操作返回的形状。
- check_shapes(*x: tuple[Tensor | tuple[int, ...], str], raise_on_errors: bool = True) bool [source]
验证一系列张量是否具有匹配的形状。
- Parameters:
- Returns:
形状是否匹配。
- Raises:
ValueError – 如果形状不匹配且 raise_on_error 为 True。
- Return type:
示例: >>> check_shapes(((10, 20), “bd”), ((10, 20, 20), “bdd”)) True >>> check_shapes(((10, 20), “bd”), ((10, 30, 20), “bdd”), raise_on_errors=False) False
- clamp_norm(x: Tensor, maxnorm: float, p: str | int = 'fro', dim: None | int | Iterable[int] = None) Tensor [source]
确保张量的范数不超过某个阈值。
- compact_mapping(mapping: Mapping[X, int]) tuple[Mapping[X, int], Mapping[int, int]] [source]
更新映射(key -> id),使得ID的范围从0到len(mappings) - 1。
- complex_normalize(x: Tensor) Tensor [source]
将复数向量归一化,使得每个元素都是单位长度。
让 \(x \in \mathbb{C}^d\) 表示一个复数向量。然后,操作计算
\[x_i' = \frac{x_i}{|x_i|}\]其中 \(|x_i| = \sqrt{Re(x_i)^2 + Im(x_i)^2}\) 是 复数的模
- class compose(*operations: Callable[[X], X], name: str)[source]
一个表示多个函数组合的类。
使用一系列操作初始化组合。
- Parameters:
操作 (可调用[[X], X]) – 将依次应用的一元操作
name (str) – 组合函数的名称。
- create_relation_to_entity_set_mapping(triples: Iterable[tuple[int, int, int]]) tuple[Mapping[int, set[int]], Mapping[int, set[int]]] [源代码]
创建从关系ID到其头/尾实体集合的映射。
- einsum(equation, *operands) Tensor [source]
对输入
operands
的元素沿使用爱因斯坦求和约定指定的维度进行乘积求和。Einsum 允许通过基于爱因斯坦求和约定的简写格式来表示和计算许多常见的多维线性代数数组操作,该格式由
equation
给出。此格式的详细信息如下所述,但总体思路是用一些下标标记输入operands
的每个维度,并定义哪些下标是输出的一部分。然后通过沿不属于输出的维度的下标对operands
的元素乘积求和来计算输出。例如,矩阵乘法可以使用 einsum 计算为 torch.einsum("ij,jk->ik", A, B)。在这里,j 是求和下标,i 和 k 是输出下标(有关原因的更多详细信息,请参见下面的部分)。方程:
equation
字符串指定了输入operands
每个维度的下标([a-zA-Z] 中的字母),顺序与维度相同,每个操作数的下标用逗号(‘,’)分隔,例如 ‘ij,jk’ 指定了两个二维操作数的下标。用相同下标标记的维度必须是可广播的,即它们的大小必须匹配或为 1。例外情况是如果同一个输入操作数的下标重复出现,在这种情况下,该操作数用此下标标记的维度必须大小匹配,并且该操作数将沿这些维度替换为其对角线。在equation
中只出现一次的下标将成为输出的一部分,按字母顺序递增排序。输出是通过将输入operands
按元素相乘,并根据下标对齐它们的维度,然后对不属于输出的维度的下标进行求和来计算的。可选地,可以通过在方程末尾添加箭头('->')来显式定义输出下标,后跟输出的下标。例如,以下方程计算矩阵乘法的转置:'ij,jk->ki'。输出下标必须至少出现在某个输入操作数中一次,并且最多出现在输出中一次。
省略号('...')可以用来代替下标,以广播省略号所覆盖的维度。 每个输入操作数最多可以包含一个省略号,它将覆盖未被下标覆盖的维度, 例如,对于一个具有5个维度的输入操作数,方程‘ab…c’中的省略号覆盖第三和第四 维度。省略号不需要在
operands
中覆盖相同数量的维度,但 省略号的“形状”(它们覆盖的维度的大小)必须一起广播。如果输出没有 用箭头('->')符号明确定义,省略号将首先出现在输出中(最左边的维度), 在输入操作数中只出现一次的下标标签之前。例如,以下方程实现了 批量矩阵乘法‘…ij,…jk’。最后几点注意事项:方程中不同元素(下标、省略号、箭头和逗号)之间可能包含空格,但像‘…’这样的内容无效。对于标量操作数,空字符串‘’是有效的。
注意
torch.einsum
处理省略号(’…’)的方式与 NumPy 不同,它允许省略号覆盖的维度被求和,也就是说,省略号不一定是输出的一部分。注意
此函数使用opt_einsum(https://optimized-einsum.readthedocs.io/en/stable/)来通过优化收缩顺序来加速计算或减少内存消耗。当至少有三个输入时,这种优化会发生,因为否则顺序无关紧要。请注意,找到_最优_路径是一个NP难问题,因此,opt_einsum依赖于不同的启发式方法来实现接近最优的结果。如果opt_einsum不可用,默认顺序是从左到右进行收缩。
要绕过此默认行为,请添加以下行以禁用opt_einsum的使用并跳过路径计算:torch.backends.opt_einsum.enabled = False
要指定您希望opt_einsum用于计算收缩路径的策略,请添加以下行: torch.backends.opt_einsum.strategy = ‘auto’。默认策略是‘auto’,我们还支持‘greedy’和 ‘optimal’。请注意,‘optimal’的运行时间是输入数量的阶乘!更多详情请参见 opt_einsum文档 (https://optimized-einsum.readthedocs.io/en/stable/path_finding.html)。
注意
截至 PyTorch 1.10,
torch.einsum()
也支持子列表格式(见下面的示例)。在此格式中,每个操作数的下标由子列表指定,子列表是 [0, 52) 范围内的整数列表。这些子列表跟随它们的操作数,并且可以在输入的末尾出现一个额外的子列表来指定输出的下标,例如 torch.einsum(op1, sublist1, op2, sublist2, …, [subslist_out])。可以在子列表中提供 Python 的 Ellipsis 对象,以启用如上文公式部分所述的广播。- Args:
equation (str): 爱因斯坦求和的子标。 operands (List[Tensor]): 用于计算爱因斯坦求和的张量。
示例:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> # trace >>> torch.einsum('ii', torch.randn(4, 4)) tensor(-1.2104) >>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> # diagonal >>> torch.einsum('ii->i', torch.randn(4, 4)) tensor([-0.1034, 0.7952, -0.2433, 0.4545]) >>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> # outer product >>> x = torch.randn(5) >>> y = torch.randn(4) >>> torch.einsum('i,j->ij', x, y) tensor([[ 0.1156, -0.2897, -0.3918, 0.4963], [-0.3744, 0.9381, 1.2685, -1.6070], [ 0.7208, -1.8058, -2.4419, 3.0936], [ 0.1713, -0.4291, -0.5802, 0.7350], [ 0.5704, -1.4290, -1.9323, 2.4480]]) >>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> # batch matrix multiplication >>> As = torch.randn(3, 2, 5) >>> Bs = torch.randn(3, 5, 4) >>> torch.einsum('bij,bjk->bik', As, Bs) tensor([[[-1.0564, -1.5904, 3.2023, 3.1271], [-1.6706, -0.8097, -0.8025, -2.1183]], [[ 4.2239, 0.3107, -0.5756, -0.2354], [-1.4558, -0.3460, 1.5087, -0.8530]], [[ 2.8153, 1.8787, -4.3839, -1.2112], [ 0.3728, -2.1131, 0.0921, 0.8305]]]) >>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> # with sublist format and ellipsis >>> torch.einsum(As, [..., 0, 1], Bs, [..., 1, 2], [..., 0, 2]) tensor([[[-1.0564, -1.5904, 3.2023, 3.1271], [-1.6706, -0.8097, -0.8025, -2.1183]], [[ 4.2239, 0.3107, -0.5756, -0.2354], [-1.4558, -0.3460, 1.5087, -0.8530]], [[ 2.8153, 1.8787, -4.3839, -1.2112], [ 0.3728, -2.1131, 0.0921, 0.8305]]]) >>> # batch permute >>> A = torch.randn(2, 3, 4, 5) >>> torch.einsum('...ij->...ji', A).shape torch.Size([2, 3, 5, 4]) >>> # equivalent to torch.nn.functional.bilinear >>> A = torch.randn(3, 5, 4) >>> l = torch.randn(2, 5) >>> r = torch.randn(2, 4) >>> torch.einsum('bn,anm,bm->ba', l, A, r) tensor([[-0.3430, -5.2405, 0.4494], [ 0.3311, 5.5201, -3.0356]])
- ensure_torch_random_state(random_state: None | int | Generator) Generator [source]
为PyTorch准备一个随机状态。
- ensure_tuple(*x: X | Sequence[X]) Sequence[Sequence[X]] [源代码]
确保序列中的所有元素都升级为序列。
>>> ensure_tuple(1, (1,), (1, 2)) ((1,), (1,), (1, 2))
- estimate_cost_of_sequence(shape: tuple[int, ...], *other_shapes: tuple[int, ...]) int [source]
给定张量的形状,计算一系列广播元素级操作的成本。
- extend_batch(batch: Tensor, max_id: int, dim: int, ids: Tensor | None = None) Tensor [source]
通过显式枚举扩展1对多评分的批次。
- flatten_dictionary(dictionary: Mapping[str, Any], prefix: str | None = None, sep: str = '.') dict[str, Any] [source]
展平一个嵌套的字典。
- get_connected_components(pairs: Iterable[tuple[X, X]]) Collection[Collection[X]] [source]
计算给定为边列表的图的连通组件。
实现使用了带有路径压缩的union-find数据结构。
- Parameters:
- Returns:
一组连接的组件,即一组不相交的节点ID集合。
- Return type:
Collection[Collection[X]]
- get_devices(module: Module) Collection[device] [source]
返回模型中每个组件的设备。
- Parameters:
模块 (Module)
- Return type:
- get_edge_index(*, triples_factory: Any | None = None, mapped_triples: Tensor | None = None, edge_index: Tensor | None = None) Tensor [source]
从多个不同的来源获取边缘索引。
- Parameters:
- Raises:
ValueError – 如果没有任何源与 None 不同
- Returns:
形状: (2, m) 边缘索引
- Return type:
- get_expected_norm(p: int | float | str, d: int) float [source]
计算L_p范数的期望值。
\[E[\|x\|_p] = d^{1/p} E[|x_1|^p]^{1/p}\]在假设\(x_i \sim N(0, 1)\)下,即
\[E[|x_1|^p] = 2^{p/2} \cdot \Gamma(\frac{p+1}{2} \cdot \pi^{-1/2}\]
- get_optimal_sequence(*shapes: tuple[int, ...]) tuple[int, tuple[int, ...]] [源代码]
根据形状找到最佳序列,以按元素方式组合张量。
- invert_mapping(mapping: Mapping[K, V]) Mapping[V, K] [source]
反转一个映射。
- Parameters:
mapping (Mapping[K, V]) – 映射,键 -> 值。
- Returns:
逆映射,值 -> 键。
- Raises:
ValueError – 如果映射不是双射的
- Return type:
Mapping[V, K]
- isin_many_dim(elements: Tensor, test_elements: Tensor, dim: int = 0) Tensor [source]
返回元素是否包含在测试元素中。
- logcumsumexp(a: ndarray) ndarray [source]
计算
log(cumsum(exp(a)))
。另请参阅
scipy.special.logsumexp()
和torch.logcumsumexp()
- negative_norm(x: Tensor, p: str | int | float = 2, power_norm: bool = False) Tensor [source]
评估向量的负范数。
- Parameters:
x (Tensor) – 形状: (batch_size, num_heads, num_relations, num_tails, dim) 向量。
p (str | int | float) – 范数的p值。参见
torch.linalg.vector_norm()
。power_norm (bool) – 是否返回 \(|x-y|_p^p\),参见 https://github.com/pytorch/pytorch/issues/28119
- Returns:
形状: (batch_size, num_heads, num_relations, num_tails) 分数。
- Return type:
- negative_norm_of_sum(*x: Tensor, p: str | int | float = 2, power_norm: bool = False) Tensor [source]
评估在已经广播的表示上向量和的负范数。
- Parameters:
x (Tensor) – 形状: (batch_size, num_heads, num_relations, num_tails, dim) 表示。
p (str | int | float) – 范数的p值。参见
torch.linalg.vector_norm()
。power_norm (bool) – 是否返回 \(|x-y|_p^p\),参见 https://github.com/pytorch/pytorch/issues/28119
- Returns:
形状: (batch_size, num_heads, num_relations, num_tails) 分数。
- Return type:
- normalize_path(path: str | Path | TextIO | None, *other: str | Path, mkdir: bool = False, is_file: bool = False, default: str | Path | TextIO | None = None) Path [源代码]
规范化路径。
- Parameters:
- Raises:
TypeError – 如果 path 的类型不合适
ValueError – 如果 path 和 default 都为 None
- Returns:
绝对路径和解析路径
- Return type:
- prepare_filter_triples(mapped_triples: Tensor, additional_filter_triples: None | Tensor | list[Tensor] = None, warn: bool = True) Tensor [source]
从评估三元组和额外的过滤三元组中准备过滤三元组。
- project_entity(e: Tensor, e_p: Tensor, r_p: Tensor) Tensor [源代码]
项目实体关系特定。
\[e_{\bot} = M_{re} e = (r_p e_p^T + I^{d_r \times d_e}) e = r_p e_p^T e + I^{d_r \times d_e} e = r_p (e_p^T e) + e'\]并且另外强制执行
\[\|e_{\bot}\|_2 \leq 1\]
- set_random_seed(seed: int) tuple[None, Generator, None] [source]
设置numpy、torch和python的随机种子。
- Parameters:
seed (int) – 将用于
np.random.seed()
,torch.manual_seed()
, 和random.seed()
的种子。- Returns:
一个包含None、torch生成器和None的三元组。
- Return type:
- unpack_singletons(*xs: tuple[X]) Sequence[X | tuple[X]] [source]
解包长度为1的序列。
>>> unpack_singletons((1,), (1, 2), (1, 2, 3)) (1, (1, 2), (1, 2, 3))
- upgrade_to_sequence(x: X | Sequence[X]) Sequence[X] [source]
确保输入是一个序列。
注意
虽然字符串在技术上也是一个序列,即,
isinstance("test", typing.Sequence) is True
这可能在调用upgrade_to_sequence(“test”)时导致意外行为。 因此,我们将字符串视为非序列。要恢复其他行为,可以使用以下方法:
upgrade_to_sequence(tuple("test"))
- Parameters:
x (X | Sequence[X]) – 一个字面量或字面量的序列
- Returns:
如果给出了一个字面量,则返回包含它的单元素元组。否则,返回给定的值。
- Return type:
Sequence[X]
>>> upgrade_to_sequence(1) (1,) >>> upgrade_to_sequence((1, 2, 3)) (1, 2, 3) >>> upgrade_to_sequence("test") ('test',) >>> upgrade_to_sequence(tuple("test")) ('t', 'e', 's', 't')
- env(file=None)[source]
如果在Jupyter中,打印环境或输出为HTML。
- Parameters:
file – 如果不在Jupyter环境中,要打印到的文件。默认为sys.stdout
- Returns:
如果在Jupyter笔记本环境中,则为
IPython.display.HTML
,否则为无。
PyKEEN的版本信息。
- get_git_branch() str | None [source]
获取PyKEEN分支,如果以可编辑模式从git安装。
- Returns:
返回当前分支的名称,如果未以开发模式安装则返回 None。
- Return type:
str | 无