实用工具

PyKEEN的实用工具。

class Bias(dim: int)[source]

一个用于添加偏置的模块包装器。

初始化模块。

Parameters:

dim (int) – >0 输入的维度。

forward(x: Tensor) Tensor[源代码]

将学习到的偏差添加到输入中。

Parameters:

x (Tensor) – 形状: (n, d) 输入。

Returns:

x + b[None, :]

Return type:

Tensor

reset_parameters()[source]

重置层的参数。

class ExtraReprMixin[source]

一个用于具有层次结构extra_repr的模块的mixin。

它采用了torch.nn.Module.extra_repr()的想法,并额外提供了一种简单的组合方式来生成extra_repr()的组件,通过iter_extra_repr()

如果与torch.nn.Module结合使用,请确保将ExtraReprMixin 放在 torch.nn.Module后面,以优先使用后者的__repr__()实现。

extra_repr() str[源代码]

生成额外的 repr,参见 :meth`torch.nn.Module.extra_repr`。

Returns:

repr() 的额外部分

Return type:

str

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:

Iterable[str]

class NoRandomSeedNecessary[source]

当随机种子自动设置时,在管道中使用。

class Result[source]

可以保存到目录的结果的超类。

abstract save_to_directory(directory: str, **kwargs) None[source]

将结果保存到目录中。

Parameters:

目录 (str)

Return type:

abstract save_to_ftp(directory: str, ftp: FTP) None[source]

将结果保存到FTP服务器中的目录。

Parameters:
Return type:

abstract save_to_s3(directory: str, bucket: str, s3=None) None[源代码]

将所有工件保存到S3存储桶中的指定目录。

Parameters:
  • 目录 (str) – S3 存储桶中的目录

  • bucket (str) – S3存储桶的名称

  • s3 – 来自 boto3.client() 的客户端,如果已经实例化

Return type:

all_in_bounds(x: Tensor, low: float | None = None, high: float | None = None, a_tol: float = 0.0) bool[source]

检查张量值是否遵守下限和上限。

Parameters:
  • x (Tensor) – 张量。

  • low (float | None) – 下界。

  • high (float | None) – 上限。

  • a_tol (float) – 绝对容差。

Returns:

如果所有值都在给定的范围内

Return type:

bool

at_least_eps(x: Tensor) Tensor[source]

确保张量大于零。

Parameters:

x (Tensor)

Return type:

Tensor

batched_dot(a: Tensor, b: Tensor) Tensor[source]

计算批处理向量之间的“逐元素”点积。

Parameters:
Return type:

Tensor

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:

Sequence[Sequence[X]]

>>> 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]

确定广播元素操作返回的形状。

Parameters:
Return type:

tuple[int, …]

check_shapes(*x: tuple[Tensor | tuple[int, ...], str], raise_on_errors: bool = True) bool[source]

验证一系列张量是否具有匹配的形状。

Parameters:
  • x (tuple[Tensor | tuple[int, ...], str]) – 一个元组 (t, s),其中 t 是一个张量,或者是一个张量的实际形状(一个整数元组),而 s 是一个字符串,其中每个字符对应一个(命名的)维度。如果不同张量的形状共享一个字符,则对应的维度应具有相同的大小。

  • raise_on_errors (bool) – 是否在不匹配的情况下引发异常。

Returns:

形状是否匹配。

Raises:

ValueError – 如果形状不匹配且 raise_on_error 为 True。

Return type:

bool

示例: >>> 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]

确保张量的范数不超过某个阈值。

Parameters:
Returns:

一个向量,其\(|x| <= maxnorm\)

Return type:

Tensor

combine_complex(x_re: Tensor, x_im: Tensor) Tensor[source]

从实部和虚部组合一个复数张量。

Parameters:
Return type:

Tensor

compact_mapping(mapping: Mapping[X, int]) tuple[Mapping[X, int], Mapping[int, int]][source]

更新映射(key -> id),使得ID的范围从0到len(mappings) - 1。

Parameters:

mapping (Mapping[X, int]) – 要压缩的映射。

Returns:

一对(translated, translation) 其中 translated 是更新后的映射,而 translation 是从旧ID到新ID的字典。

Return type:

tuple[Mapping[X, int], Mapping[int, int]]

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}\)复数的模

Parameters:

x (Tensor) – 一个表示复数的张量

Returns:

一个逐元素归一化的向量。

Return type:

Tensor

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到其头/尾实体集合的映射。

Parameters:

triples (Iterable[tuple[int, int, int]]) – 三元组。

Returns:

一对字典,每个字典将关系ID映射到实体ID集合。

Return type:

tuple[Mapping[int, set[int]], Mapping[int, set[int]]]

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]])
Parameters:

args (Any)

Return type:

Tensor

ensure_complex(*xs: Tensor) Iterable[Tensor][source]

确保所有张量都是复数类型。

如有必要,进行重塑和转换。

Parameters:

xs (Tensor) – 张量

Yields:

复数张量。

Return type:

Iterable[Tensor]

ensure_ftp_directory(*, ftp: FTP, directory: str) None[source]

确保目录存在于FTP服务器上。

Parameters:
Return type:

ensure_torch_random_state(random_state: None | int | Generator) Generator[source]

为PyTorch准备一个随机状态。

Parameters:

random_state (None | int | Generator)

Return type:

Generator

ensure_tuple(*x: X | Sequence[X]) Sequence[Sequence[X]][源代码]

确保序列中的所有元素都升级为序列。

Parameters:

x (X | Sequence[X]) – 一个序列的序列或字面量

Returns:

一个升级的序列序列

Return type:

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]

给定张量的形状,计算一系列广播元素级操作的成本。

Parameters:
Return type:

int

extend_batch(batch: Tensor, max_id: int, dim: int, ids: Tensor | None = None) Tensor[source]

通过显式枚举扩展1对多评分的批次。

Parameters:
  • batch (Tensor) – 形状: (batch_size, 2) 批次。

  • max_id (int) – 要枚举的最大ID。

  • ids (Tensor | None) – 形状: (num_ids,) | (batch_size, num_ids) 显式ID

  • dim (int) – 在 {0,1,2} 中 插入枚举ID的列。

Returns:

形状: (batch_size * num_choices, 3) 一个大批次,其中原始批次中的每一对都与每个ID组合。

Return type:

Tensor

fix_dataclass_init_docs(cls: type) type[source]

修复__init__的文档,用于dataclasses.dataclass

Parameters:

cls (type) – 需要修复文档字符串的类

Returns:

传递的类,以便此函数可以用作装饰器

Return type:

type

flatten_dictionary(dictionary: Mapping[str, Any], prefix: str | None = None, sep: str = '.') dict[str, Any][source]

展平一个嵌套的字典。

Parameters:
Return type:

dict[str, Any]

format_relative_comparison(part: int, total: int) str[source]

格式化相对比较。

Parameters:
Return type:

str

get_batchnorm_modules(module: Module) list[Module][source]

返回所有作为批量归一化层的子模块。

Parameters:

模块 (Module)

Return type:

list[Module]

get_benchmark(name: str) Path[source]

获取此版本的基准目录。

Parameters:

name (str)

Return type:

Path

get_connected_components(pairs: Iterable[tuple[X, X]]) Collection[Collection[X]][source]

计算给定为边列表的图的连通组件。

实现使用了带有路径压缩的union-find数据结构。

Parameters:

pairs (Iterable[tuple[X, X]]) – 边列表,即节点ID的对。

Returns:

一组连接的组件,即一组不相交的节点ID集合。

Return type:

Collection[Collection[X]]

get_devices(module: Module) Collection[device][source]

返回模型中每个组件的设备。

Parameters:

模块 (Module)

Return type:

Collection[device]

get_df_io(df: DataFrame) BytesIO[source]

获取数据框为字节。

Parameters:

df (数据框)

Return type:

BytesIO

get_dropout_modules(module: Module) list[Module][source]

返回所有作为 dropout 层的子模块。

Parameters:

模块 (Module)

Return type:

list[Module]

get_edge_index(*, triples_factory: Any | None = None, mapped_triples: Tensor | None = None, edge_index: Tensor | None = None) Tensor[source]

从多个不同的来源获取边缘索引。

Parameters:
  • triples_factory (Any | None) – 三元组工厂

  • mapped_triples (Tensor | None) – 形状: (m, 3) 基于ID的三元组

  • edge_index (Tensor | None) – 形状: (2, m) 边索引

Raises:

ValueError – 如果没有任何源与 None 不同

Returns:

形状: (2, m) 边缘索引

Return type:

Tensor

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}\]
Parameters:
  • p (int | float | str) – 范数的参数 p。

  • d (int) – 向量的维度。

Returns:

期望值。

Raises:
Return type:

float

get_json_bytes_io(obj) BytesIO[source]

获取JSON为字节。

Return type:

BytesIO

get_model_io(model) BytesIO[source]

获取模型的字节形式。

Return type:

BytesIO

get_optimal_sequence(*shapes: tuple[int, ...]) tuple[int, tuple[int, ...]][源代码]

根据形状找到最佳序列,以按元素方式组合张量。

Parameters:

shapes (tuple[int, ...]) – 要组合的张量的形状。

Returns:

最佳执行顺序(作为索引),以及成本。

Return type:

tuple[int, tuple[int, …]]

get_preferred_device(module: Module, allow_ambiguity: bool = True) device[source]

返回首选设备。

Parameters:
Return type:

device

get_until_first_blank(s: str) str[source]

总结字符串中的所有行,直到第一个空行。

Parameters:

s (str)

Return type:

str

invert_mapping(mapping: Mapping[K, V]) Mapping[V, K][source]

反转一个映射。

Parameters:

mapping (Mapping[K, V]) – 映射,键 -> 值。

Returns:

逆映射,值 -> 键。

Raises:

ValueError – 如果映射不是双射的

Return type:

Mapping[V, K]

is_triple_tensor_subset(a: Tensor, b: Tensor) bool[source]

检查一个三元组张量是否是另一个张量的子集。

Parameters:
Return type:

bool

isin_many_dim(elements: Tensor, test_elements: Tensor, dim: int = 0) Tensor[source]

返回元素是否包含在测试元素中。

Parameters:
Return type:

Tensor

logcumsumexp(a: ndarray) ndarray[source]

计算 log(cumsum(exp(a)))

Parameters:

a (ndarray) – 形状: s 数组

Returns:

形状 s 数组的对数累积和指数

Return type:

ndarray

另请参阅

scipy.special.logsumexp()torch.logcumsumexp()

lp_norm(x: Tensor, p: float, dim: int | None, normalize: bool) Tensor[source]

返回 \(L_p\) 范数。

Parameters:
Return type:

Tensor

negative_norm(x: Tensor, p: str | int | float = 2, power_norm: bool = False) Tensor[source]

评估向量的负范数。

Parameters:
Returns:

形状: (batch_size, num_heads, num_relations, num_tails) 分数。

Return type:

Tensor

negative_norm_of_sum(*x: Tensor, p: str | int | float = 2, power_norm: bool = False) Tensor[source]

评估在已经广播的表示上向量和的负范数。

Parameters:
Returns:

形状: (batch_size, num_heads, num_relations, num_tails) 分数。

Return type:

Tensor

nested_get(d: Mapping[str, Any], *key: str, default=None) Any[source]

从嵌套字典中获取。

Parameters:
  • d (Mapping[str, Any]) – (嵌套的)字典

  • key (str) – 一个键的序列

  • default – 默认值

Returns:

值或默认值

Return type:

Any

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:
  • path (str | Path | TextIO | None) – 以任何有效形式表示的路径。

  • 其他 (str | Path) – 要连接到路径的附加部分

  • mkdir (bool) – 是否通过创建路径来确保路径指向一个已存在的目录(如果需要的话)

  • is_file (bool) – 路径是否意图为文件 - 仅与创建目录相关

  • 默认 (str | Path | TextIO | None) – 如果路径为None时使用的默认值

Raises:
  • TypeError – 如果 path 的类型不合适

  • ValueError – 如果 pathdefault 都为 None

Returns:

绝对路径和解析路径

Return type:

Path

normalize_string(s: str, *, suffix: str | None = None) str[source]

为查找规范化字符串。

Parameters:
Return type:

str

powersum_norm(x: Tensor, p: float, dim: int | None, normalize: bool) Tensor[source]

返回幂和范数。

Parameters:
Return type:

Tensor

prepare_filter_triples(mapped_triples: Tensor, additional_filter_triples: None | Tensor | list[Tensor] = None, warn: bool = True) Tensor[source]

从评估三元组和额外的过滤三元组中准备过滤三元组。

Parameters:
Return type:

Tensor

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\]
Parameters:
  • e (Tensor) – 形状: (…, d_e) 实体嵌入。

  • e_p (Tensor) – 形状: (…, d_e) 实体投影。

  • r_p (Tensor) – 形状: (…, d_r) 关系投影。

Returns:

形状: (…, d_r)

Return type:

Tensor

random_non_negative_int() int[source]

生成一个随机的正整数。

Return type:

int

rate_limited(xs: Iterable[X], min_avg_time: float = 1.0) Iterable[X][源代码]

以速率限制迭代可迭代对象。

Parameters:
  • xs (Iterable[X]) – 可迭代对象

  • min_avg_time (float) – 每个元素的最小平均时间

Yields:

可迭代对象的元素

Return type:

Iterable[X]

resolve_device(device: str | device | None = None) device[source]

解析给定的期望设备(字符串)为torch.device。

Parameters:

设备 (str | device | None)

Return type:

device

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:

tuple[None, Generator, None]

split_complex(x: Tensor) tuple[Tensor, Tensor][源代码]

将一个复数张量分割为实部和虚部。

Parameters:

x (Tensor)

Return type:

tuple[Tensor, Tensor]

split_workload(n: int) range[source]

为多进程分割工作负载。

Parameters:

n (int)

Return type:

range

tensor_product(*tensors: Tensor) Tensor[源代码]

计算广播形状中张量的逐元素乘积。

Parameters:

张量 (Tensor)

Return type:

Tensor

tensor_sum(*tensors: Tensor) Tensor[source]

计算可广播形状的张量的逐元素和。

Parameters:

张量 (Tensor)

Return type:

Tensor

triple_tensor_to_set(tensor: Tensor) set[tuple[int, ...]][source]

将三元组的张量转换为一组整数元组。

Parameters:

张量 (Tensor)

Return type:

set[tuple[int, …]]

unpack_singletons(*xs: tuple[X]) Sequence[X | tuple[X]][source]

解包长度为1的序列。

Parameters:

xs (tuple[X]) – 一个长度为1或更多的元组序列

Returns:

一个未打包的序列序列

Return type:

Sequence[X | tuple[X]]

>>> 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')
view_complex(x: Tensor) Tensor[source]

将PyKEEN复杂张量表示转换为torch表示。

Parameters:

x (Tensor)

Return type:

Tensor

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 | 无

get_git_hash(terse: bool = True) str[source]

获取PyKEEN的git哈希值。

Parameters:

简洁 (bool) – 哈希值是否应截断为8个字符?

Returns:

git哈希值,如果遇到CalledProcessError则等于'UNHASHED',表示代码未以开发模式安装。

Return type:

str

get_version(with_git_hash: bool = False) str[source]

获取PyKEEN版本字符串,包括git哈希值。

Parameters:

with_git_hash (bool) – 如果设置为True,git哈希值将附加到版本中。

Returns:

PyKEEN版本以及git哈希值,如果参数with_git_hash设置为true。

Return type:

str