torch_geometric.utils

scatter

src张量中,沿着给定的维度dim,减少在index张量中指定的索引处的所有值。

group_argsort

返回按值沿给定维度升序排序张量 src 的索引。

group_cat

在给定的维度 dim 上连接给定的张量序列 tensors

segment

减少src张量第一维度中所有值,范围由ptr指定。

index_sort

inputs张量的元素按升序排序。

cumsum

返回x元素的累积和。

degree

计算给定一维索引张量的(未加权)度数。

softmax

计算稀疏评估的softmax。

lexsort

使用一系列键执行间接稳定排序。

sort_edge_index

按行排序 edge_index

coalesce

按行排序 edge_index 并删除其重复条目。

is_undirected

如果由edge_index给出的图是无向的,则返回True

to_undirected

edge_index给出的图转换为无向图,使得对于每条边\((i,j) \in \mathcal{E}\),都有\((j,i) \in \mathcal{E}\)

contains_self_loops

如果由edge_index给出的图包含自环,则返回True

remove_self_loops

移除由edge_index给出的图中的每个自环,使得对于每个\(i \in \mathcal{V}\)\((i,i) \not\in \mathcal{E}\)

segregate_self_loops

将自循环从图中分离出来。

add_self_loops

向由edge_index给出的图中的每个节点\(i \in \mathcal{V}\)添加一个自环\((i,i) \in \mathcal{E}\)

add_remaining_self_loops

将剩余的自环 \((i,i) \in \mathcal{E}\) 添加到由 edge_index 给出的图中的每个节点 \(i \in \mathcal{V}\)

get_self_loop_attr

返回由edge_index给出的图中每个节点\(i \in \mathcal{V}\)的自环\((i, i)\)的边特征或权重。

contains_isolated_nodes

如果由edge_index给出的图包含孤立节点,则返回True

remove_isolated_nodes

从由edge_index给出的图中移除孤立的节点,并带有可选的边属性edge_attr

get_num_hops

返回模型聚合信息的跳数。

subgraph

返回包含subset中节点的(edge_index, edge_attr)的诱导子图。

bipartite_subgraph

返回包含subset中节点的二分图的诱导子图(edge_index, edge_attr)

k_hop_subgraph

计算在edge_index中,所有在node_idx中的节点在\(k\)跳内可达的诱导子图。

dropout_node

从邻接矩阵 edge_index 中随机删除节点,使用伯努利分布的样本,概率为 p

dropout_edge

从邻接矩阵 edge_index 中随机删除边,使用伯努利分布的样本,概率为 p

dropout_path

从邻接矩阵 edge_index 中基于随机游走删除边。

dropout_adj

从邻接矩阵 (edge_index, edge_attr) 中随机删除边,使用伯努利分布的样本,概率为 p

homophily

图的同质性描述了图中具有相同标签的节点彼此接近的可能性。

assortativity

来自"网络中的混合模式"论文的度同配系数。

normalize_edge_index

对图的边缘应用归一化。

get_laplacian

计算由edge_index和可选的edge_weight给出的图的拉普拉斯图。

get_mesh_laplacian

计算由posface给出的网格的拉普拉斯算子。

mask_select

返回一个新的张量,该张量根据布尔掩码 mask 在维度 dim 上对 src 张量进行掩码操作。

index_to_mask

将索引转换为掩码表示。

mask_to_index

将掩码转换为索引表示。

select

根据给定的索引或掩码向量选择输入张量或输入列表。

narrow

将输入张量或输入列表缩小到指定范围。

to_dense_batch

给定一个稀疏的节点特征批次 \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\)(其中 \(N_i\) 表示图 \(i\) 中的节点数量),创建一个密集的节点特征张量 \(\mathbf{X} \in \mathbb{R}^{B \times N_{\max} \times F}\)(其中 \(N_{\max} = \max_i^B N_i\))。

to_dense_adj

将由边索引和边属性给出的批量稀疏邻接矩阵转换为单个密集的批量邻接矩阵。

to_nested_tensor

给定一个连续的张量批次 \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times *}\)(其中 \(N_i\) 表示示例 \(i\) 中的元素数量),创建一个 嵌套的 PyTorch 张量

from_nested_tensor

给定一个嵌套的PyTorch张量,创建一个连续的张量批次\(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times *}\),并可选地创建一个批次向量,将每个元素分配给特定的示例。

dense_to_sparse

将密集的邻接矩阵转换为由边索引和边属性定义的稀疏邻接矩阵。

is_torch_sparse_tensor

如果输入 srctorch.sparse.Tensor(在任何稀疏布局中),则返回 True

is_sparse

如果输入的 src 是类型 torch.sparse.Tensor(在任何稀疏布局中)或类型 torch_sparse.SparseTensor,则返回 True

to_torch_coo_tensor

将由边索引和边属性定义的稀疏邻接矩阵转换为具有布局torch.sparse_cootorch.sparse.Tensor

to_torch_csr_tensor

将由边索引和边属性定义的稀疏邻接矩阵转换为具有布局torch.sparse_csrtorch.sparse.Tensor

to_torch_csc_tensor

将由边索引和边属性定义的稀疏邻接矩阵转换为具有布局torch.sparse_csctorch.sparse.Tensor

to_torch_sparse_tensor

将由边索引和边属性定义的稀疏邻接矩阵转换为具有自定义layouttorch.sparse.Tensor

to_edge_index

torch.sparse.Tensortorch_sparse.SparseTensor转换为边索引和边属性。

spmm

稀疏矩阵与密集矩阵的矩阵乘积。

unbatch

根据batch向量沿dim维度拆分src

unbatch_edge_index

根据batch向量分割edge_index

one_hot

接受一个一维的index张量,并返回其形状为[*, num_classes]的独热编码表示,其中除了最后一个维度的索引与输入张量的对应值匹配的位置为1外,其余位置均为零。

normalized_cut

计算由边索引和边属性给出的加权图的归一化割 \(\mathbf{e}_{i,j} \cdot \left( \frac{1}{\deg(i)} + \frac{1}{\deg(j)} \right)\)

grid

返回一个具有高度height和宽度width的二维网格图的边索引及其节点位置。

geodesic_distance

计算由posface给出的网格的(归一化)测地距离。

to_scipy_sparse_matrix

将给定的边索引和边属性转换为scipy稀疏矩阵。

from_scipy_sparse_matrix

将scipy稀疏矩阵转换为边索引和边属性。

to_networkx

torch_geometric.data.Data实例转换为networkx.Graph,如果to_undirected设置为True,否则转换为有向的networkx.DiGraph

from_networkx

networkx.Graphnetworkx.DiGraph 转换为 torch_geometric.data.Data 实例。

to_networkit

(edge_index, edge_weight)元组转换为networkit.Graph

from_networkit

networkit.Graph转换为(edge_index, edge_weight)元组。

to_trimesh

torch_geometric.data.Data实例转换为trimesh.Trimesh

from_trimesh

trimesh.Trimesh 转换为 torch_geometric.data.Data 实例。

to_cugraph

将由edge_index和可选的edge_weight给出的图转换为cugraph图对象。

from_cugraph

cugraph图对象转换为edge_index和可选的edge_weight张量。

to_dgl

torch_geometric.data.Datatorch_geometric.data.HeteroData实例转换为dgl图对象。

from_dgl

dgl图对象转换为torch_geometric.data.Datatorch_geometric.data.HeteroData实例。

from_rdmol

rdkit.Chem.Mol实例转换为torch_geometric.data.Data实例。

to_rdmol

torch_geometric.data.Data实例转换为rdkit.Chem.Mol实例。

from_smiles

将SMILES字符串转换为torch_geometric.data.Data实例。

to_smiles

torch_geometric.data.Data实例转换为SMILES字符串。

erdos_renyi_graph

返回一个随机Erdos-Renyi图的edge_index

stochastic_blockmodel_graph

返回一个随机块模型图的edge_index

barabasi_albert_graph

返回一个Barabasi-Albert优先连接模型的edge_index,其中包含num_nodes个节点的图通过附加具有num_edges条边的新节点来增长,这些边优先连接到具有高度数的现有节点。

negative_sampling

从由edge_index给出的图中随机抽取负边样本。

batched_negative_sampling

对由edge_indexbatch给出的多个图进行随机负边采样。

structured_negative_sampling

对于图中由edge_index给出的每个正边(i,j),采样一个负边(i,k),并将其作为形式为(i,j,k)的元组返回。

shuffle_node

随机打乱特征矩阵 x 的第一个维度。

mask_feature

使用伯努利分布的样本,以概率 p 随机屏蔽特征矩阵 x 中的特征。

add_random_edge

随机向edge_index添加边。

tree_decomposition

分子树分解算法来自"Junction Tree Variational Autoencoder for Molecular Graph Generation"论文。

get_embeddings

返回model中所有MessagePassing层的输出嵌入。

trim_to_layer

修剪edge_index表示、节点特征x和边特征edge_attr,使其在当前GNN层layer的有向NeighborLoader场景中达到最小大小的表示。

get_ppr

使用Andersen算法的变体计算所有或部分节点的个性化PageRank(PPR)向量。

train_test_split_edges

torch_geometric.data.Data对象的边分割为正负训练/验证/测试边。

实用工具包。

scatter(src: Tensor, index: Tensor, dim: int = 0, dim_size: Optional[int] = None, reduce: str = 'sum') Tensor[source]

src张量中减少所有值,这些值位于index张量中指定的索引处,沿着给定的维度dim。有关更多信息,请参阅文档中的torch_scatter包。

Parameters:
  • src (torch.Tensor) – 源张量。

  • 索引 (torch.Tensor) – 索引张量。

  • dim (int, optional) – 指定索引的维度。 (default: 0)

  • dim_size (int, optional) – 输出张量在维度 dim 的大小。如果设置为 None,将根据 index.max() + 1 创建一个最小大小的输出张量。(默认值:None

  • reduce (str, 可选) – 归约操作 ("sum", "mean", "mul", "min""max", "any"). (默认: "sum")

Return type:

Tensor

group_argsort(src: Tensor, index: Tensor, dim: int = 0, num_groups: Optional[int] = None, descending: bool = False, return_consecutive: bool = False, stable: bool = False) Tensor[source]

返回按值升序排列张量 src 沿给定维度的索引。 与 torch.argsort() 不同,排序是根据 index 中的值分组进行的。

Parameters:
  • src (torch.Tensor) – 源张量。

  • 索引 (torch.Tensor) – 索引张量。

  • dim (int, optional) – 指定索引的维度。 (默认: 0)

  • num_groups (int, optional) – 组的数量。 (默认: None)

  • 降序 (bool, 可选) – 控制排序顺序(升序或降序)。(默认: False)

  • return_consecutive (bool, 可选) – 如果设置为 True,将不会 将输出偏移为从 0 开始每个组。 (默认: False)

  • stable (bool, optional) – 控制等价元素的相对顺序。(默认: False)

示例

>>> src = torch.tensor([0, 1, 5, 4, 3, 2, 6, 7, 8])
>>> index = torch.tensor([0, 0, 1, 1, 1, 1, 2, 2, 2])
>>> group_argsort(src, index)
tensor([0, 1, 3, 2, 1, 0, 0, 1, 2])
Return type:

Tensor

group_cat(tensors: Union[List[Tensor], Tuple[Tensor, ...]], indices: Union[List[Tensor], Tuple[Tensor, ...]], dim: int = 0, return_index: bool = False) Union[Tensor, Tuple[Tensor, Tensor]][source]

在给定的维度 dim 上连接给定的张量序列 tensors。 与 torch.cat() 不同,沿着连接维度的值根据 index 张量中定义的索引进行分组。 所有张量必须具有相同的形状(除了连接维度)。

Parameters:
  • tensors ([Tensor]) – 张量序列。

  • indices ([Tensor]) – 索引张量的序列。

  • dim (int, optional) – 张量沿此维度进行连接。(默认值:0

  • return_index (bool, 可选) – 如果设置为 True,将返回新的索引张量。(默认值:False

示例

>>> x1 = torch.tensor([[0.2716, 0.4233],
...                    [0.3166, 0.0142],
...                    [0.2371, 0.3839],
...                    [0.4100, 0.0012]])
>>> x2 = torch.tensor([[0.3752, 0.5782],
...                    [0.7757, 0.5999]])
>>> index1 = torch.tensor([0, 0, 1, 2])
>>> index2 = torch.tensor([0, 2])
>>> scatter_concat([x1,x2], [index1, index2], dim=0)
tensor([[0.2716, 0.4233],
        [0.3166, 0.0142],
        [0.3752, 0.5782],
        [0.2371, 0.3839],
        [0.4100, 0.0012],
        [0.7757, 0.5999]])
Return type:

Union[Tensor, Tuple[Tensor, Tensor]]

segment(src: Tensor, ptr: Tensor, reduce: str = 'sum') Tensor[source]

减少src张量第一维度中的所有值,范围由ptr指定。有关更多信息,请参阅文档中的torch_scatter包。

Parameters:
  • src (torch.Tensor) – The source tensor.

  • ptr (torch.Tensor) – 一个单调递增的指针张量,它指向段的边界,使得 ptr[0] = 0 并且 ptr[-1] = src.size(0)

  • reduce (str, 可选) – 归约操作 ("sum", "mean", "min""max"). (默认: "sum")

Return type:

Tensor

index_sort(inputs: Tensor, max_value: Optional[int] = None, stable: bool = False) Tuple[Tensor, Tensor][source]

inputs张量的元素按升序排序。 预期inputs是一维的,并且只包含正整数。如果给出了max_value,底层算法可以使用它来提高性能。

Parameters:
  • inputs (torch.Tensor) – 一个包含正整数值的向量。

  • max_value (int, optional) – 存储在 inputs 中的最大值。这个值可以是一个估计值,但需要大于或等于实际的最大值。 (默认值: None)

  • stable (bool, optional) – Makes the sorting routine stable, which guarantees that the order of equivalent elements is preserved. (default: False)

Return type:

Tuple[Tensor, Tensor]

cumsum(x: Tensor, dim: int = 0) Tensor[source]

返回x元素的累积和。 与torch.cumsum()不同,它在输出前添加零。

Parameters:
  • x (torch.Tensor) – 输入张量。

  • dim (int, optional) – 进行操作所在的维度。 (default: 0)

示例

>>> x = torch.tensor([2, 4, 1])
>>> cumsum(x)
tensor([0, 2, 6, 7])
Return type:

Tensor

degree(index: Tensor, num_nodes: Optional[int] = None, dtype: Optional[dtype] = None) Tensor[source]

计算给定一维索引张量的(未加权)度数。

Parameters:
  • index (LongTensor) – 索引张量。

  • num_nodes (int, optional) – 节点的数量, max_val + 1index。(默认值:None

  • dtype (torch.dtype, 可选) – 返回张量的期望数据类型。

Return type:

Tensor

示例

>>> row = torch.tensor([0, 1, 0, 2, 0])
>>> degree(row, dtype=torch.long)
tensor([3, 1, 1])
softmax(src: Tensor, index: Optional[Tensor] = None, ptr: Optional[Tensor] = None, num_nodes: Optional[int] = None, dim: int = 0) Tensor[source]

计算稀疏评估的softmax。 给定一个值张量 src,此函数首先根据 index 中指定的索引沿第一维度对值进行分组, 然后分别计算每个组的softmax。

Parameters:
  • src (Tensor) – 源张量。

  • index (LongTensor, optional) – 用于应用softmax的元素的索引。(默认值:None

  • ptr (LongTensor, optional) – 如果提供,将基于CSR表示中的排序输入计算softmax。(默认值:None

  • num_nodes (int, optional) – 节点的数量, max_val + 1index。(默认值:None

  • dim (int, optional) – 归一化的维度。 (default: 0)

Return type:

Tensor

示例

>>> src = torch.tensor([1., 1., 1., 1.])
>>> index = torch.tensor([0, 0, 1, 2])
>>> ptr = torch.tensor([0, 2, 3, 4])
>>> softmax(src, index)
tensor([0.5000, 0.5000, 1.0000, 1.0000])
>>> softmax(src, None, ptr)
tensor([0.5000, 0.5000, 1.0000, 1.0000])
>>> src = torch.randn(4, 4)
>>> ptr = torch.tensor([0, 4])
>>> softmax(src, index, dim=-1)
tensor([[0.7404, 0.2596, 1.0000, 1.0000],
        [0.1702, 0.8298, 1.0000, 1.0000],
        [0.7607, 0.2393, 1.0000, 1.0000],
        [0.8062, 0.1938, 1.0000, 1.0000]])
lexsort(keys: List[Tensor], dim: int = -1, descending: bool = False) Tensor[source]

使用一系列键执行间接稳定排序。

给定多个排序键,返回一个整数索引数组,描述它们的排序顺序。 序列中的最后一个键用于主要排序顺序,倒数第二个键用于次要排序顺序,依此类推。

Parameters:
  • keys ([torch.Tensor]) – 要排序的 \(k\) 个不同列。 最后一个键是主要的排序键。

  • dim (int, optional) – 要排序的维度。(默认: -1)

  • descending (bool, optional) – Controls the sorting order (ascending or descending). (default: False)

Return type:

Tensor

sort_edge_index(edge_index: Tensor, edge_attr: Union[Tensor, None, List[Tensor], str] = '???', num_nodes: Optional[int] = None, sort_by_row: bool = True) Union[Tensor, Tuple[Tensor, Optional[Tensor]], Tuple[Tensor, List[Tensor]]][source]

Row-wise sorts edge_index.

Parameters:
  • edge_index (torch.Tensor) – The edge indices.

  • edge_attr (torch.TensorList[torch.Tensor], 可选) – 边的权重 或多维边特征。 如果以列表形式给出,将重新洗牌并删除所有 条目中的重复项。(默认值:None

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

  • sort_by_row (bool, 可选) – 如果设置为 False,将会按列/目标节点排序 edge_index。 (默认: True)

Return type:

LongTensor 如果未传递 edge_attr,否则 (LongTensor, Optional[Tensor]List[Tensor]])

警告

开始,每当 edge_attr 作为参数传递时,此函数将始终返回一个元组(即使它被设置为 None)。

示例

>>> edge_index = torch.tensor([[2, 1, 1, 0],
                        [1, 2, 0, 1]])
>>> edge_attr = torch.tensor([[1], [2], [3], [4]])
>>> sort_edge_index(edge_index)
tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]])
>>> sort_edge_index(edge_index, edge_attr)
(tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]]),
tensor([[4],
        [3],
        [2],
        [1]]))
coalesce(edge_index: Tensor, edge_attr: Union[Tensor, None, List[Tensor], str] = '???', num_nodes: Optional[int] = None, reduce: str = 'sum', is_sorted: bool = False, sort_by_row: bool = True) Union[Tensor, Tuple[Tensor, Optional[Tensor]], Tuple[Tensor, List[Tensor]]][source]

按行排序 edge_index 并删除其重复条目。 edge_attr 中的重复条目通过根据给定的 reduce 选项将它们分散在一起进行合并。

Parameters:
  • edge_index (torch.Tensor) – The edge indices.

  • edge_attr (torch.TensorList[torch.Tensor], 可选) – 边的权重 或多维边特征。 如果以列表形式给出,将重新洗牌并删除所有 条目中的重复项。(默认值:None

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

  • reduce (str, optional) – 用于合并边特征的reduce操作 ("sum", "mean", "min", "max", "mul", "any"). (默认: "sum")

  • is_sorted (bool, 可选) – 如果设置为 True,将期望 edge_index 已经按行排序。

  • sort_by_row (bool, 可选) – 如果设置为 False,将会按列排序 edge_index

Return type:

LongTensor 如果未传递 edge_attr,否则 (LongTensor, Optional[Tensor]List[Tensor]])

警告

开始,只要 edge_attr 作为参数传递,此函数将始终返回一个元组(即使它被设置为 None)。

示例

>>> edge_index = torch.tensor([[1, 1, 2, 3],
...                            [3, 3, 1, 2]])
>>> edge_attr = torch.tensor([1., 1., 1., 1.])
>>> coalesce(edge_index)
tensor([[1, 2, 3],
        [3, 1, 2]])
>>> # Sort `edge_index` column-wise
>>> coalesce(edge_index, sort_by_row=False)
tensor([[2, 3, 1],
        [1, 2, 3]])
>>> coalesce(edge_index, edge_attr)
(tensor([[1, 2, 3],
        [3, 1, 2]]),
tensor([2., 1., 1.]))
>>> # Use 'mean' operation to merge edge features
>>> coalesce(edge_index, edge_attr, reduce='mean')
(tensor([[1, 2, 3],
        [3, 1, 2]]),
tensor([1., 1., 1.]))
is_undirected(edge_index: Tensor, edge_attr: Union[Tensor, None, List[Tensor]] = None, num_nodes: Optional[int] = None) bool[source]

如果由edge_index给出的图是无向的,则返回True

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (TensorList[Tensor], 可选) – 边的权重或多维边特征。 如果以列表形式给出,将检查其所有条目中的等价性。 (默认: None)

  • num_nodes (int, optional) – 节点数量, max(edge_index) + 1。 (默认: None)

Return type:

bool 翻译后的内容: bool 在这个例子中,`bool` 是一个Python函数名称,根据翻译规则1,不需要翻译。因此,翻译后的内容保持不变。

示例

>>> edge_index = torch.tensor([[0, 1, 0],
...                         [1, 0, 0]])
>>> weight = torch.tensor([0, 0, 1])
>>> is_undirected(edge_index, weight)
True
>>> weight = torch.tensor([0, 1, 1])
>>> is_undirected(edge_index, weight)
False
to_undirected(edge_index: Tensor, edge_attr: Union[Tensor, None, List[Tensor], str] = '???', num_nodes: Optional[int] = None, reduce: str = 'add') Union[Tensor, Tuple[Tensor, Optional[Tensor]], Tuple[Tensor, List[Tensor]]][source]

edge_index给出的图转换为无向图,使得对于每一条边\((i,j) \in \mathcal{E}\),都有\((j,i) \in \mathcal{E}\)

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (TensorList[Tensor], 可选) – 边的权重或多维边特征。 如果以列表形式给出,将为其所有条目删除重复项。 (默认: None)

  • num_nodes (int, optional) – 节点数量, max(edge_index) + 1。 (默认: None)

  • reduce (str, optional) – The reduce operation to use for merging edge features ("add", "mean", "min", "max", "mul"). (default: "add")

Return type:

LongTensor if edge_attr is not passed, else (LongTensor, Optional[Tensor] or List[Tensor]])

警告

From onwards, this function will always return a tuple whenever edge_attr is passed as an argument (even in case it is set to None).

示例

>>> edge_index = torch.tensor([[0, 1, 1],
...                            [1, 0, 2]])
>>> to_undirected(edge_index)
tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]])
>>> edge_index = torch.tensor([[0, 1, 1],
...                            [1, 0, 2]])
>>> edge_weight = torch.tensor([1., 1., 1.])
>>> to_undirected(edge_index, edge_weight)
(tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]]),
tensor([2., 2., 1., 1.]))
>>> # Use 'mean' operation to merge edge features
>>>  to_undirected(edge_index, edge_weight, reduce='mean')
(tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]]),
tensor([1., 1., 1., 1.]))
contains_self_loops(edge_index: Tensor) bool[source]

如果由edge_index给出的图包含自环,则返回True

Parameters:

edge_index (LongTensor) – The edge indices.

Return type:

bool 翻译后的内容: bool 在这个例子中,`bool` 是一个Python函数名称,根据翻译规则1,不需要翻译。因此,翻译后的内容保持不变。

示例

>>> edge_index = torch.tensor([[0, 1, 0],
...                            [1, 0, 0]])
>>> contains_self_loops(edge_index)
True
>>> edge_index = torch.tensor([[0, 1, 1],
...                            [1, 0, 2]])
>>> contains_self_loops(edge_index)
False
remove_self_loops(edge_index: Tensor, edge_attr: Optional[Tensor] = None) Tuple[Tensor, Optional[Tensor]][source]

移除由edge_index给出的图中的每个自环,使得对于每个\(i \in \mathcal{V}\)\((i,i) \not\in \mathcal{E}\)

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – 边的权重或多维边的特征。(默认值:None

Return type:

(LongTensor, Tensor)

示例

>>> edge_index = torch.tensor([[0, 1, 0],
...                            [1, 0, 0]])
>>> edge_attr = [[1, 2], [3, 4], [5, 6]]
>>> edge_attr = torch.tensor(edge_attr)
>>> remove_self_loops(edge_index, edge_attr)
(tensor([[0, 1],
        [1, 0]]),
tensor([[1, 2],
        [3, 4]]))
segregate_self_loops(edge_index: Tensor, edge_attr: Optional[Tensor] = None) Tuple[Tensor, Optional[Tensor], Tensor, Optional[Tensor]][source]

将自循环从图中分离出来。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – 边的权重或多维边的特征。(默认值:None

Return type:

(LongTensor, Tensor, LongTensor, Tensor)

示例

>>> edge_index = torch.tensor([[0, 0, 1],
...                            [0, 1, 0]])
>>> (edge_index, edge_attr,
...  loop_edge_index,
...  loop_edge_attr) = segregate_self_loops(edge_index)
>>>  loop_edge_index
tensor([[0],
        [0]])
add_self_loops(edge_index: Tensor, edge_attr: Optional[Tensor] = None, fill_value: Optional[Union[float, Tensor, str]] = None, num_nodes: Optional[Union[int, Tuple[int, int]]] = None) Tuple[Tensor, Optional[Tensor]][source]

向由edge_index给出的图中的每个节点\(i \in \mathcal{V}\)添加一个自环\((i,i) \in \mathcal{E}\)。如果图是加权的或具有多维边特征(edge_attr != None),则自环的边特征将根据fill_value添加。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – 边的权重或多维边特征。(默认值:None

  • fill_value (floatTensorstr, 可选) – 生成自环边特征的方式(在 edge_attr != None 的情况下)。 如果给定为 floattorch.Tensor,自环的边特征将直接由 fill_value 给出。 如果给定为 str,自环的边特征将通过聚合指向特定节点的所有边的特征来计算,根据一个归约操作("add", "mean", "min", "max", "mul")。(默认值:1.

  • num_nodes (intTuple[int, int], 可选) – 节点的数量, max_val + 1edge_index。 如果以元组形式给出,则 edge_index 被解释为 具有形状 (num_src_nodes, num_dst_nodes) 的二部图。 (默认: None)

Return type:

(LongTensor, Tensor)

示例

>>> edge_index = torch.tensor([[0, 1, 0],
...                            [1, 0, 0]])
>>> edge_weight = torch.tensor([0.5, 0.5, 0.5])
>>> add_self_loops(edge_index)
(tensor([[0, 1, 0, 0, 1],
        [1, 0, 0, 0, 1]]),
None)
>>> add_self_loops(edge_index, edge_weight)
(tensor([[0, 1, 0, 0, 1],
        [1, 0, 0, 0, 1]]),
tensor([0.5000, 0.5000, 0.5000, 1.0000, 1.0000]))
>>> # edge features of self-loops are filled by constant `2.0`
>>> add_self_loops(edge_index, edge_weight,
...                fill_value=2.)
(tensor([[0, 1, 0, 0, 1],
        [1, 0, 0, 0, 1]]),
tensor([0.5000, 0.5000, 0.5000, 2.0000, 2.0000]))
>>> # Use 'add' operation to merge edge features for self-loops
>>> add_self_loops(edge_index, edge_weight,
...                fill_value='add')
(tensor([[0, 1, 0, 0, 1],
        [1, 0, 0, 0, 1]]),
tensor([0.5000, 0.5000, 0.5000, 1.0000, 0.5000]))
add_remaining_self_loops(edge_index: Tensor, edge_attr: Optional[Tensor] = None, fill_value: Optional[Union[float, Tensor, str]] = None, num_nodes: Optional[int] = None) Tuple[Tensor, Optional[Tensor]][source]

将剩余的自环 \((i,i) \in \mathcal{E}\) 添加到由 edge_index 给出的图中的每个节点 \(i \in \mathcal{V}\)。如果图是加权的或具有多维边特征 (edge_attr != None),则根据 fill_value 添加不存在的自环的边特征。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – 边的权重或多维边特征。(默认: None)

  • fill_value (floatTensorstr, 可选) – 生成自环边特征的方式(在 edge_attr != None 的情况下)。 如果给定为 floattorch.Tensor,自环的边特征将直接由 fill_value 给出。 如果给定为 str,自环的边特征将通过聚合指向特定节点的所有边的特征来计算, 根据一个归约操作。("add", "mean", "min", "max", "mul")。(默认值:1.

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

Return type:

(LongTensor, Tensor)

示例

>>> edge_index = torch.tensor([[0, 1],
...                            [1, 0]])
>>> edge_weight = torch.tensor([0.5, 0.5])
>>> add_remaining_self_loops(edge_index, edge_weight)
(tensor([[0, 1, 0, 1],
        [1, 0, 0, 1]]),
tensor([0.5000, 0.5000, 1.0000, 1.0000]))
get_self_loop_attr(edge_index: Tensor, edge_attr: Optional[Tensor] = None, num_nodes: Optional[int] = None) Tensor[source]

返回图中每个节点 \(i \in \mathcal{V}\) 的自环边特征或权重 \((i, i)\),这些自环边由 edge_index 给出。如果 edge_index 中缺少某些自环边,则这些缺失的自环边特征将被填充为零。如果未提供 edge_attr,则默认为全1向量。

注意

此操作类似于获取密集邻接矩阵的对角线元素。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – 边的权重或多维边特征。(默认值:None

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

Return type:

Tensor

示例

>>> edge_index = torch.tensor([[0, 1, 0],
...                            [1, 0, 0]])
>>> edge_weight = torch.tensor([0.2, 0.3, 0.5])
>>> get_self_loop_attr(edge_index, edge_weight)
tensor([0.5000, 0.0000])
>>> get_self_loop_attr(edge_index, edge_weight, num_nodes=4)
tensor([0.5000, 0.0000, 0.0000, 0.0000])
contains_isolated_nodes(edge_index: Tensor, num_nodes: Optional[int] = None) bool[source]

如果由edge_index给出的图包含孤立节点,则返回True

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

Return type:

bool 翻译后的内容: bool 在这个例子中,`bool` 是一个Python函数名称,根据翻译规则1,不需要翻译。因此,翻译后的内容保持不变。

示例

>>> edge_index = torch.tensor([[0, 1, 0],
...                            [1, 0, 0]])
>>> contains_isolated_nodes(edge_index)
False
>>> contains_isolated_nodes(edge_index, num_nodes=3)
True
remove_isolated_nodes(edge_index: Tensor, edge_attr: Optional[Tensor] = None, num_nodes: Optional[int] = None) Tuple[Tensor, Optional[Tensor], Tensor][source]

从由edge_index给出的图中移除孤立的节点, 并带有可选的边属性edge_attr。 此外,返回一个形状为[num_nodes]的掩码,以便稍后手动过滤掉孤立的节点特征。 非孤立节点的自环将被保留。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – Edge weights or multi-dimensional edge features. (default: None)

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

Return type:

(LongTensor, Tensor, BoolTensor)

示例

>>> edge_index = torch.tensor([[0, 1, 0],
...                            [1, 0, 0]])
>>> edge_index, edge_attr, mask = remove_isolated_nodes(edge_index)
>>> mask # node mask (2 nodes)
tensor([True, True])
>>> edge_index, edge_attr, mask = remove_isolated_nodes(edge_index,
...                                                     num_nodes=3)
>>> mask # node mask (3 nodes)
tensor([True, True, False])
get_num_hops(model: Module) int[source]

返回模型聚合信息的跳数。

注意

此函数计算消息传递层的数量,作为模型覆盖的总跳数的近似值。在消息传递层执行多跳聚合的情况下,其输出可能不一定正确,例如,如ChebConv中所示。

示例

>>> class GNN(torch.nn.Module):
...     def __init__(self):
...         super().__init__()
...         self.conv1 = GCNConv(3, 16)
...         self.conv2 = GCNConv(16, 16)
...         self.lin = Linear(16, 2)
...
...     def forward(self, x, edge_index):
...         x = self.conv1(x, edge_index).relu()
...         x = self.conv2(x, edge_index).relu()
...         return self.lin(x)
>>> get_num_hops(GNN())
2
Return type:

int

subgraph(subset: Union[Tensor, List[int]], edge_index: Tensor, edge_attr: Optional[Tensor] = None, relabel_nodes: bool = False, num_nodes: Optional[int] = None, *, return_edge_mask: bool = False) Union[Tuple[Tensor, Optional[Tensor]], Tuple[Tensor, Optional[Tensor], Tensor]][source]

返回包含subset中节点的(edge_index, edge_attr)的诱导子图。

Parameters:
  • subset (LongTensor, BoolTensor[int]) – 要保留的节点。

  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – Edge weights or multi-dimensional edge features. (default: None)

  • relabel_nodes (bool, 可选) – 如果设置为 True,生成的 edge_index 将被重新标记为从零开始的连续索引。(默认值:False

  • num_nodes (int, optional) – The number of nodes, i.e. max(edge_index) + 1. (default: None)

  • return_edge_mask (bool, 可选) – 如果设置为 True,将返回 边缘掩码以过滤掉额外的边缘特征。 (默认: False)

Return type:

(LongTensor, Tensor)

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6],
...                            [1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5]])
>>> edge_attr = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> subset = torch.tensor([3, 4, 5])
>>> subgraph(subset, edge_index, edge_attr)
(tensor([[3, 4, 4, 5],
        [4, 3, 5, 4]]),
tensor([ 7.,  8.,  9., 10.]))
>>> subgraph(subset, edge_index, edge_attr, return_edge_mask=True)
(tensor([[3, 4, 4, 5],
        [4, 3, 5, 4]]),
tensor([ 7.,  8.,  9., 10.]),
tensor([False, False, False, False, False, False,  True,
        True,  True,  True,  False, False]))
bipartite_subgraph(subset: Union[Tuple[Tensor, Tensor], Tuple[List[int], List[int]]], edge_index: Tensor, edge_attr: Optional[Tensor] = None, relabel_nodes: bool = False, size: Optional[Tuple[int, int]] = None, return_edge_mask: bool = False) Union[Tuple[Tensor, Optional[Tensor]], Tuple[Tensor, Optional[Tensor], Optional[Tensor]]][source]

返回包含subset中节点的二分图的诱导子图 (edge_index, edge_attr)

Parameters:
  • subset (Tuple[Tensor, Tensor] 或 tuple([int],[int])) – 要保留的节点。

  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – Edge weights or multi-dimensional edge features. (default: None)

  • relabel_nodes (bool, 可选) – 如果设置为 True,生成的 edge_index 将被重新标记为从零开始的连续索引。(默认值:False

  • size (tuple, optional) – 节点的数量。 (默认值: None)

  • return_edge_mask (bool, 可选) – 如果设置为 True,将返回 边缘掩码以过滤掉额外的边缘特征。 (默认: False)

Return type:

(LongTensor, Tensor)

示例

>>> edge_index = torch.tensor([[0, 5, 2, 3, 3, 4, 4, 3, 5, 5, 6],
...                            [0, 0, 3, 2, 0, 0, 2, 1, 2, 3, 1]])
>>> edge_attr = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> subset = (torch.tensor([2, 3, 5]), torch.tensor([2, 3]))
>>> bipartite_subgraph(subset, edge_index, edge_attr)
(tensor([[2, 3, 5, 5],
        [3, 2, 2, 3]]),
tensor([ 3,  4,  9, 10]))
>>> bipartite_subgraph(subset, edge_index, edge_attr,
...                    return_edge_mask=True)
(tensor([[2, 3, 5, 5],
        [3, 2, 2, 3]]),
tensor([ 3,  4,  9, 10]),
tensor([False, False,  True,  True, False, False, False, False,
        True,  True,  False]))
k_hop_subgraph(node_idx: Union[int, List[int], Tensor], num_hops: int, edge_index: Tensor, relabel_nodes: bool = False, num_nodes: Optional[int] = None, flow: str = 'source_to_target', directed: bool = False) Tuple[Tensor, Tensor, Tensor, Tensor][source]

计算在edge_index中所有在node_idx内可达的节点在\(k\)跳内的诱导子图。

flow 参数表示用于查找 \(k\)-hop 邻居的边的方向。如果设置为 "source_to_target",则该方法将找到所有指向初始种子节点集合 node_idx. 的邻居。这模仿了图神经网络中消息传递的自然流向。

该方法返回(1)子图中涉及的节点,(2)过滤后的edge_index连接性,(3)从node_idx中的节点索引到它们新位置的映射,以及(4)指示哪些边被保留的边掩码。

Parameters:
  • node_idx (int, list, tuple 或 torch.Tensor) – 中心种子节点。

  • num_hops (int) – 跳数 \(k\)

  • edge_index (LongTensor) – The edge indices.

  • relabel_nodes (bool, optional) – If set to True, the resulting edge_index will be relabeled to hold consecutive indices starting from zero. (default: False)

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

  • flow (str, 可选) – \(k\)-hop聚合的流向 ("source_to_target""target_to_source"). (默认: "source_to_target")

  • directed (bool, 可选) – 如果设置为 True,将只包括指向种子节点 node_idx 的有向边。 (默认: False)

Return type:

(LongTensor, LongTensor, LongTensor, BoolTensor)

示例

>>> edge_index = torch.tensor([[0, 1, 2, 3, 4, 5],
...                            [2, 2, 4, 4, 6, 6]])
>>> # Center node 6, 2-hops
>>> subset, edge_index, mapping, edge_mask = k_hop_subgraph(
...     6, 2, edge_index, relabel_nodes=True)
>>> subset
tensor([2, 3, 4, 5, 6])
>>> edge_index
tensor([[0, 1, 2, 3],
        [2, 2, 4, 4]])
>>> mapping
tensor([4])
>>> edge_mask
tensor([False, False,  True,  True,  True,  True])
>>> subset[mapping]
tensor([6])
>>> edge_index = torch.tensor([[1, 2, 4, 5],
...                            [0, 1, 5, 6]])
>>> (subset, edge_index,
...  mapping, edge_mask) = k_hop_subgraph([0, 6], 2,
...                                       edge_index,
...                                       relabel_nodes=True)
>>> subset
tensor([0, 1, 2, 4, 5, 6])
>>> edge_index
tensor([[1, 2, 3, 4],
        [0, 1, 4, 5]])
>>> mapping
tensor([0, 5])
>>> edge_mask
tensor([True, True, True, True])
>>> subset[mapping]
tensor([0, 6])
dropout_node(edge_index: Tensor, p: float = 0.5, num_nodes: Optional[int] = None, training: bool = True, relabel_nodes: bool = False) Tuple[Tensor, Tensor, Tensor][source]

从邻接矩阵中随机丢弃节点 edge_index,使用伯努利分布的样本,概率为 p

该方法返回 (1) 保留的 edge_index, (2) 指示哪些边被保留的边掩码。(3) 指示哪些节点被保留的节点掩码。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • p (float, 可选) – Dropout概率。 (默认: 0.5)

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

  • 训练 (bool, 可选) – 如果设置为 False,此操作将无效。(默认值:True

  • relabel_nodes (bool, optional) – 如果设置为 True,生成的 edge_index 将被重新标记为从零开始的连续索引。

Return type:

(LongTensor, BoolTensor, BoolTensor)

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> edge_index, edge_mask, node_mask = dropout_node(edge_index)
>>> edge_index
tensor([[0, 1],
        [1, 0]])
>>> edge_mask
tensor([ True,  True, False, False, False, False])
>>> node_mask
tensor([ True,  True, False, False])
dropout_edge(edge_index: Tensor, p: float = 0.5, force_undirected: bool = False, training: bool = True) Tuple[Tensor, Tensor][source]

从邻接矩阵edge_index中随机删除边,使用伯努利分布的样本,概率为p

该方法返回 (1) 保留的 edge_index, (2) 根据参数 force_undirected 决定是保留边的掩码还是索引。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • p (float, 可选) – Dropout概率。 (默认: 0.5)

  • force_undirected (bool, 可选) – 如果设置为 True,将会 删除或保留无向边的两条边。 (默认: False)

  • 训练 (bool, 可选) – 如果设置为 False,此操作将无效。(默认值:True

Return type:

(LongTensor, BoolTensorLongTensor)

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> edge_index, edge_mask = dropout_edge(edge_index)
>>> edge_index
tensor([[0, 1, 2, 2],
        [1, 2, 1, 3]])
>>> edge_mask # masks indicating which edges are retained
tensor([ True, False,  True,  True,  True, False])
>>> edge_index, edge_id = dropout_edge(edge_index,
...                                    force_undirected=True)
>>> edge_index
tensor([[0, 1, 2, 1, 2, 3],
        [1, 2, 3, 0, 1, 2]])
>>> edge_id # indices indicating which edges are retained
tensor([0, 2, 4, 0, 2, 4])
dropout_path(edge_index: Tensor, p: float = 0.2, walks_per_node: int = 1, walk_length: int = 3, num_nodes: Optional[int] = None, is_sorted: bool = False, training: bool = True) Tuple[Tensor, Tensor][source]

从邻接矩阵edge_index中删除边,基于随机游走。开始随机游走的源节点是从edge_index中以概率p采样得到的,遵循伯努利分布。

该方法返回 (1) 保留的 edge_index, (2) 指示哪些边被保留的边掩码。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • p (float, 可选) – 样本概率。 (默认: 0.2)

  • walks_per_node (int, 可选) – 每个节点的游走次数,与 Node2Vec 相同。(默认值:1

  • walk_length (int, 可选) – 游走长度,与 Node2Vec相同。(默认值:3

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

  • is_sorted (bool, 可选) – 如果设置为 True,将期望 edge_index 已经按行排序。 (默认: False)

  • training (bool, optional) – If set to False, this operation is a no-op. (default: True)

Return type:

(LongTensor, BoolTensor)

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> edge_index, edge_mask = dropout_path(edge_index)
>>> edge_index
tensor([[1, 2],
        [2, 3]])
>>> edge_mask # masks indicating which edges are retained
tensor([False, False,  True, False,  True, False])
dropout_adj(edge_index: Tensor, edge_attr: Optional[Tensor] = None, p: float = 0.5, force_undirected: bool = False, num_nodes: Optional[int] = None, training: bool = True) Tuple[Tensor, Optional[Tensor]][source]

从邻接矩阵中随机删除边 (edge_index, edge_attr),使用伯努利分布的样本以概率 p 进行删除。

警告

dropout_adj 已被弃用,并将在未来的版本中移除。 请改用 torch_geometric.utils.dropout_edge

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – Edge weights or multi-dimensional edge features. (default: None)

  • p (float, optional) – Dropout probability. (default: 0.5)

  • force_undirected (bool, 可选) – 如果设置为 True,将会删除或保留无向边的两条边。 (默认: False)

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

  • training (bool, optional) – If set to False, this operation is a no-op. (default: True)

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> edge_attr = torch.tensor([1, 2, 3, 4, 5, 6])
>>> dropout_adj(edge_index, edge_attr)
(tensor([[0, 1, 2, 3],
        [1, 2, 3, 2]]),
tensor([1, 3, 5, 6]))
>>> # The returned graph is kept undirected
>>> dropout_adj(edge_index, edge_attr, force_undirected=True)
(tensor([[0, 1, 2, 1, 2, 3],
        [1, 2, 3, 0, 1, 2]]),
tensor([1, 3, 5, 1, 3, 5]))
Return type:

Tuple[Tensor, Optional[Tensor]]

homophily(edge_index: Union[Tensor, SparseTensor], y: Tensor, batch: Optional[Tensor] = None, method: str = 'edge') Union[float, Tensor][source]

图的同质性描述了图中具有相同标签的节点彼此接近的可能性。

有许多符合这一定义的同质性度量。 特别是:

  • “超越图神经网络中的同质性:当前局限性和有效设计”论文中,同质性是指图中连接具有相同类别标签节点的边的比例:

    \[\frac{| \{ (v,w) : (v,w) \in \mathcal{E} \wedge y_v = y_w \} | } {|\mathcal{E}|}\]

    该度量被称为边缘同质性比率

  • “Geom-GCN: Geometric Graph Convolutional Networks”论文中,边同质性在邻域中被归一化:

    \[\frac{1}{|\mathcal{V}|} \sum_{v \in \mathcal{V}} \frac{ | \{ (w,v) : w \in \mathcal{N}(v) \wedge y_v = y_w \} | } { |\mathcal{N}(v)| }\]

    该度量被称为节点同质性比率

  • “大规模非同质图学习:新基准和强大的简单方法”论文中, 边同质性被修改为对类的数量和每个类的大小不敏感:

    \[\frac{1}{C-1} \sum_{k=1}^{C} \max \left(0, h_k - \frac{|\mathcal{C}_k|} {|\mathcal{V}|} \right),\]

    其中 \(C\) 表示类别数量,\(|\mathcal{C}_k|\) 表示类别 \(k\) 的节点数量,\(h_k\) 表示类别 \(k\) 节点的边同质性比率。

    因此,该度量被称为类不敏感边同质性比率

Parameters:
  • edge_index (TensorSparseTensor) – 图的连接性。

  • y (Tensor) – 标签。

  • batch (LongTensor, optional) – 批次向量\(\mathbf{b} \in {\{ 0, \ldots,B-1\}}^N\),它将每个节点分配到一个特定的示例中。(默认值:None

  • method (str, optional) – 用于计算同质性的方法, 可以是 "edge"(第一个公式),"node"(第二个 公式)或 "edge_insensitive"(第三个公式)。 (默认值:"edge"

示例

>>> edge_index = torch.tensor([[0, 1, 2, 3],
...                            [1, 2, 0, 4]])
>>> y = torch.tensor([0, 0, 0, 0, 1])
>>> # Edge homophily ratio
>>> homophily(edge_index, y, method='edge')
0.75
>>> # Node homophily ratio
>>> homophily(edge_index, y, method='node')
0.6000000238418579
>>> # Class insensitive edge homophily ratio
>>> homophily(edge_index, y, method='edge_insensitive')
0.19999998807907104
Return type:

Union[float, Tensor]

assortativity(edge_index: Union[Tensor, SparseTensor]) float[source]

来自“网络中的混合模式”论文的度同配系数。 网络中的同配性指的是节点倾向于与其他相似节点连接,而不是与不相似的节点连接。 它是通过节点度的皮尔逊相关系数计算得出的。

Parameters:

edge_index (TensorSparseTensor) – 图的连接性。

Returns:

float – 输入图的度同配性系数的值 \(\in [-1, 1]\)

示例

>>> edge_index = torch.tensor([[0, 1, 2, 3, 2],
...                            [1, 2, 0, 1, 3]])
>>> assortativity(edge_index)
-0.666667640209198
normalize_edge_index(edge_index: Tensor, num_nodes: Optional[int] = None, add_self_loops: bool = True, symmetric: bool = True) Tuple[Tensor, Tensor][source]

对图的边缘应用归一化。

此函数可以向图中添加自环,并根据节点度数应用对称或非对称归一化。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • num_nodes (int, int], optional) – 节点的数量, max_val + 1edge_index。(默认值:None

  • add_self_loops (bool, optional) – If set to False, will not add self-loops to the input graph. (default: True)

  • symmetric (bool, 可选) – 如果设置为 True,则使用对称归一化 (\(D^{-1/2} A D^{-1/2}\)),否则使用非对称归一化 (\(D^{-1} A\))。

Return type:

Tuple[Tensor, Tensor]

get_laplacian(edge_index: Tensor, edge_weight: Optional[Tensor] = None, normalization: Optional[str] = None, dtype: Optional[dtype] = None, num_nodes: Optional[int] = None) Tuple[Tensor, Tensor][source]

计算由edge_index和可选的edge_weight给出的图的拉普拉斯矩阵。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_weight (Tensor, optional) – 一维边权重。 (默认: None)

  • normalization (str, optional) –

    The normalization scheme for the graph Laplacian (default: None):

    1. None: No normalization \(\mathbf{L} = \mathbf{D} - \mathbf{A}\)

    2. "sym": Symmetric normalization \(\mathbf{L} = \mathbf{I} - \mathbf{D}^{-1/2} \mathbf{A} \mathbf{D}^{-1/2}\)

    3. "rw": Random-walk normalization \(\mathbf{L} = \mathbf{I} - \mathbf{D}^{-1} \mathbf{A}\)

  • dtype (torch.dtype, 可选) – 返回张量的期望数据类型,在 edge_weight=None 的情况下。(默认值:None

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2],
...                            [1, 0, 2, 1]])
>>> edge_weight = torch.tensor([1., 2., 2., 4.])
>>> # No normalization
>>> lap = get_laplacian(edge_index, edge_weight)
>>> # Symmetric normalization
>>> lap_sym = get_laplacian(edge_index, edge_weight,
                            normalization='sym')
>>> # Random-walk normalization
>>> lap_rw = get_laplacian(edge_index, edge_weight, normalization='rw')
Return type:

Tuple[Tensor, Tensor]

get_mesh_laplacian(pos: Tensor, face: Tensor, normalization: Optional[str] = None) Tuple[Tensor, Tensor][source]

计算由posface给出的网格的拉普拉斯算子。

计算基于定义的余切矩阵

\[\begin{split}\mathbf{C}_{ij} = \begin{cases} \frac{\cot \angle_{ikj}~+\cot \angle_{ilj}}{2} & \text{if } i, j \text{ is an edge} \\ -\sum_{j \in N(i)}{C_{ij}} & \text{if } i \text{ is in the diagonal} \\ 0 & \text{otherwise} \end{cases}\end{split}\]

归一化取决于定义的质量矩阵

\[\begin{split}\mathbf{M}_{ij} = \begin{cases} a(i) & \text{if } i \text{ is in the diagonal} \\ 0 & \text{otherwise} \end{cases}\end{split}\]

其中 \(a(i)\) 是通过连接顶点 \(i\) 周围的三角形的重心获得的。

Parameters:
  • pos (Tensor) – 节点位置。

  • face (LongTensor) – 面索引。

  • normalization (str, optional) –

    网格拉普拉斯算子的归一化方案(默认:None):

    1. None: 无归一化 \(\mathbf{L} = \mathbf{C}\)

    2. "sym": 对称归一化 \(\mathbf{L} = \mathbf{M}^{-1/2} \mathbf{C}\mathbf{M}^{-1/2}\)

    3. "rw": 行归一化 \(\mathbf{L} = \mathbf{M}^{-1} \mathbf{C}\)

Return type:

Tuple[Tensor, Tensor]

mask_select(src: Tensor, dim: int, mask: Tensor) Tensor[source]

返回一个新的张量,该张量根据布尔掩码 mask 在维度 dim 上对 src 张量进行掩码操作。

Parameters:
  • src (torch.Tensor) – 输入张量。

  • dim (int) – 要进行掩码的维度。

  • mask (torch.BoolTensor) – 包含用于索引的二进制掩码的一维张量。

Return type:

Tensor

index_to_mask(index: Tensor, size: Optional[int] = None) Tensor[source]

将索引转换为掩码表示。

Parameters:
  • index (Tensor) – 索引。

  • size (int, optional) – 掩码的大小。如果设置为 None,则返回最小大小的输出掩码。

示例

>>> index = torch.tensor([1, 3, 5])
>>> index_to_mask(index)
tensor([False,  True, False,  True, False,  True])
>>> index_to_mask(index, size=7)
tensor([False,  True, False,  True, False,  True, False])
Return type:

Tensor

mask_to_index(mask: Tensor) Tensor[source]

将掩码转换为索引表示。

Parameters:

mask (Tensor) – 掩码。

示例

>>> mask = torch.tensor([False, True, False])
>>> mask_to_index(mask)
tensor([1])
Return type:

Tensor

select(src: Union[Tensor, List[Any], TensorFrame], index_or_mask: Tensor, dim: int) Union[Tensor, List[Any]][source]

根据给定的索引或掩码向量选择输入张量或输入列表。

Parameters:
  • src (torch.Tensorlist) – 输入张量或列表。

  • index_or_mask (torch.Tensor) – 索引或掩码向量。

  • dim (int) – 选择所沿的维度。

Return type:

Union[Tensor, List[Any]]

narrow(src: Union[Tensor, List[Any]], dim: int, start: int, length: int) Union[Tensor, List[Any]][source]

将输入张量或输入列表缩小到指定范围。

Parameters:
  • src (torch.Tensorlist) – 输入的张量或列表。

  • dim (int) – The dimension along which to narrow.

  • 开始 (int) – 起始维度。

  • length (int) – 到结束维度的距离。

Return type:

Union[Tensor, List[Any]]

to_dense_batch(x: Tensor, batch: Optional[Tensor] = None, fill_value: float = 0.0, max_num_nodes: Optional[int] = None, batch_size: Optional[int] = None) Tuple[Tensor, Tensor][source]

给定一个稀疏的节点特征批次 \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\)(其中 \(N_i\) 表示图 \(i\) 中的节点数量),创建一个 密集的节点特征张量 \(\mathbf{X} \in \mathbb{R}^{B \times N_{\max} \times F}\)(其中 \(N_{\max} = \max_i^B N_i\))。 此外,返回一个形状为 \(\mathbf{M} \in \{ 0, 1 \}^{B \times N_{\max}}\) 的掩码,用于表示密集表示中假节点的存在信息。

Parameters:
  • x (Tensor) – 节点特征矩阵 \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\).

  • batch (LongTensor, optional) – 批次向量 \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), 它将每个 节点分配到一个特定的示例。必须是有序的。(默认: None)

  • fill_value (float, optional) – 用于结果密集输出张量中无效条目的值。(默认值:0

  • max_num_nodes (int, optional) – 输出节点维度的大小。 (default: None)

  • batch_size (int, optional) – 批量大小。(默认值:None

Return type:

(Tensor, BoolTensor)

示例

>>> x = torch.arange(12).view(6, 2)
>>> x
tensor([[ 0,  1],
        [ 2,  3],
        [ 4,  5],
        [ 6,  7],
        [ 8,  9],
        [10, 11]])
>>> out, mask = to_dense_batch(x)
>>> mask
tensor([[True, True, True, True, True, True]])
>>> batch = torch.tensor([0, 0, 1, 2, 2, 2])
>>> out, mask = to_dense_batch(x, batch)
>>> out
tensor([[[ 0,  1],
        [ 2,  3],
        [ 0,  0]],
        [[ 4,  5],
        [ 0,  0],
        [ 0,  0]],
        [[ 6,  7],
        [ 8,  9],
        [10, 11]]])
>>> mask
tensor([[ True,  True, False],
        [ True, False, False],
        [ True,  True,  True]])
>>> out, mask = to_dense_batch(x, batch, max_num_nodes=4)
>>> out
tensor([[[ 0,  1],
        [ 2,  3],
        [ 0,  0],
        [ 0,  0]],
        [[ 4,  5],
        [ 0,  0],
        [ 0,  0],
        [ 0,  0]],
        [[ 6,  7],
        [ 8,  9],
        [10, 11],
        [ 0,  0]]])
>>> mask
tensor([[ True,  True, False, False],
        [ True, False, False, False],
        [ True,  True,  True, False]])
to_dense_adj(edge_index: Tensor, batch: Optional[Tensor] = None, edge_attr: Optional[Tensor] = None, max_num_nodes: Optional[int] = None, batch_size: Optional[int] = None) Tensor[source]

将由边索引和边属性给出的批量稀疏邻接矩阵转换为单个密集批量邻接矩阵。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • batch (LongTensor, optional) – 批次向量 \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), 它将每个 节点分配给特定的示例。(默认: None)

  • edge_attr (Tensor, optional) – 边的权重或多维边特征。 如果 edge_index 包含重复的边,密集邻接矩阵输出将包含 edge_attr 的累加条目。 (默认: None)

  • max_num_nodes (int, optional) – 输出节点维度的大小。 (default: None)

  • batch_size (int, optional) – 批量大小。(默认值:None

Return type:

Tensor

示例

>>> edge_index = torch.tensor([[0, 0, 1, 2, 3],
...                            [0, 1, 0, 3, 0]])
>>> batch = torch.tensor([0, 0, 1, 1])
>>> to_dense_adj(edge_index, batch)
tensor([[[1., 1.],
        [1., 0.]],
        [[0., 1.],
        [1., 0.]]])
>>> to_dense_adj(edge_index, batch, max_num_nodes=4)
tensor([[[1., 1., 0., 0.],
        [1., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],
        [[0., 1., 0., 0.],
        [1., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]])
>>> edge_attr = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])
>>> to_dense_adj(edge_index, batch, edge_attr)
tensor([[[1., 2.],
        [3., 0.]],
        [[0., 4.],
        [5., 0.]]])
to_nested_tensor(x: Tensor, batch: Optional[Tensor] = None, ptr: Optional[Tensor] = None, batch_size: Optional[int] = None) Tensor[source]

给定一个连续的张量批次 \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times *}\) (其中 \(N_i\) 表示示例 \(i\) 中的元素数量), 创建一个嵌套的 PyTorch 张量。 这是from_nested_tensor()的反向操作。

Parameters:
  • x (torch.Tensor) – 输入张量 \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times *}\).

  • batch (torch.Tensor, optional) – 批次向量 \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), 它将每个 元素分配给特定的示例。必须是有序的。 (默认: None)

  • ptr (torch.Tensor, optional) – batch 的压缩格式的替代表示。(默认值:None

  • batch_size (int, optional) – 批量大小 \(B\)。 (默认值: None)

Return type:

Tensor

from_nested_tensor(x: Tensor, return_batch: bool = False) Union[Tensor, Tuple[Tensor, Tensor]][source]

给定一个嵌套的PyTorch张量,创建一个连续的张量批次 \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times *}\),并且 可以选择性地创建一个批次向量,将每个元素分配给特定的示例。 这是to_nested_tensor()的反向操作。

Parameters:
  • x (torch.Tensor) – 嵌套的输入张量。嵌套张量的大小需要匹配,除了第一个维度。

  • return_batch (bool, 可选) – 如果设置为 True,还将返回 批次向量 \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\)。 (默认: False)

Return type:

Union[Tensor, Tuple[Tensor, Tensor]]

dense_to_sparse(adj: Tensor, mask: Optional[Tensor] = None) Tuple[Tensor, Tensor][source]

将密集的邻接矩阵转换为由边索引和边属性定义的稀疏邻接矩阵。

Parameters:
  • adj (torch.Tensor) – 密集邻接矩阵的形状为 [num_nodes, num_nodes][batch_size, num_nodes, num_nodes]

  • mask (torch.Tensor, optional) – 一个形状为 [batch_size, num_nodes] 的布尔张量,用于保存每个示例中哪些节点是有效的信息。(默认值:None

Return type:

(LongTensor, Tensor)

示例

>>> # For a single adjacency matrix:
>>> adj = torch.tensor([[3, 1],
...                     [2, 0]])
>>> dense_to_sparse(adj)
(tensor([[0, 0, 1],
        [0, 1, 0]]),
tensor([3, 1, 2]))
>>> # For two adjacency matrixes:
>>> adj = torch.tensor([[[3, 1],
...                      [2, 0]],
...                     [[0, 1],
...                      [0, 2]]])
>>> dense_to_sparse(adj)
(tensor([[0, 0, 1, 2, 3],
        [0, 1, 0, 3, 3]]),
tensor([3, 1, 2, 1, 2]))
>>> # First graph with two nodes, second with three:
>>> adj = torch.tensor([[
...         [3, 1, 0],
...         [2, 0, 0],
...         [0, 0, 0]
...     ], [
...         [0, 1, 0],
...         [0, 2, 3],
...         [0, 5, 0]
...     ]])
>>> mask = torch.tensor([
...         [True, True, False],
...         [True, True, True]
...     ])
>>> dense_to_sparse(adj, mask)
(tensor([[0, 0, 1, 2, 3, 3, 4],
        [0, 1, 0, 3, 3, 4, 3]]),
tensor([3, 1, 2, 1, 2, 3, 5]))
is_torch_sparse_tensor(src: Any) bool[source]

如果输入 src 是一个 torch.sparse.Tensor(在任何稀疏布局中),则返回 True

Parameters:

src (Any) – 要检查的输入对象。

Return type:

bool 翻译后的内容: bool 在这个例子中,`bool` 是一个Python函数名称,根据翻译规则1,不需要翻译。因此,翻译后的内容保持不变。

is_sparse(src: Any) bool[source]

如果输入的 src 是类型为 torch.sparse.Tensor(任何稀疏布局)或类型为 torch_sparse.SparseTensor,则返回 True

Parameters:

src (Any) – 要检查的输入对象。

Return type:

bool 翻译后的内容: bool 在这个例子中,`bool` 是一个Python函数名称,根据翻译规则1,不需要翻译。因此,翻译后的内容保持不变。

to_torch_coo_tensor(edge_index: Tensor, edge_attr: Optional[Tensor] = None, size: Optional[Union[int, Tuple[Optional[int], Optional[int]]]] = None, is_coalesced: bool = False) Tensor[source]

将由边索引和边属性定义的稀疏邻接矩阵转换为具有torch.sparse_coo布局的torch.sparse.Tensor。 有关反向操作,请参见to_edge_index()

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – 边的属性。 (default: None)

  • size (int(int, int), 可选) – 稀疏矩阵的大小。 如果给定为一个整数,将创建一个二次稀疏矩阵。 如果设置为 None,将根据 edge_index.max() + 1 推断一个二次稀疏矩阵。(默认值:None

  • is_coalesced (bool) – 如果设置为 True,将假设 edge_index 已经合并,从而避免昂贵的 计算。(默认值:False

Return type:

torch.sparse.Tensor

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> to_torch_coo_tensor(edge_index)
tensor(indices=tensor([[0, 1, 1, 2, 2, 3],
                       [1, 0, 2, 1, 3, 2]]),
       values=tensor([1., 1., 1., 1., 1., 1.]),
       size=(4, 4), nnz=6, layout=torch.sparse_coo)
to_torch_csr_tensor(edge_index: Tensor, edge_attr: Optional[Tensor] = None, size: Optional[Union[int, Tuple[Optional[int], Optional[int]]]] = None, is_coalesced: bool = False) Tensor[source]

将由边索引和边属性定义的稀疏邻接矩阵转换为具有布局torch.sparse_csrtorch.sparse.Tensor。 有关反向操作,请参见to_edge_index()

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – 边的属性。 (default: None)

  • size (int(int, int), 可选) – 稀疏矩阵的大小。 如果给定为一个整数,将创建一个二次稀疏矩阵。 如果设置为 None,将根据 edge_index.max() + 1 推断一个二次稀疏矩阵。(默认值:None

  • is_coalesced (bool) – 如果设置为 True,将假设 edge_index 已经合并,从而避免昂贵的 计算。(默认值:False

Return type:

torch.sparse.Tensor

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> to_torch_csr_tensor(edge_index)
tensor(crow_indices=tensor([0, 1, 3, 5, 6]),
       col_indices=tensor([1, 0, 2, 1, 3, 2]),
       values=tensor([1., 1., 1., 1., 1., 1.]),
       size=(4, 4), nnz=6, layout=torch.sparse_csr)
to_torch_csc_tensor(edge_index: Tensor, edge_attr: Optional[Tensor] = None, size: Optional[Union[int, Tuple[Optional[int], Optional[int]]]] = None, is_coalesced: bool = False) Tensor[source]

将由边索引和边属性定义的稀疏邻接矩阵转换为具有布局torch.sparse_csctorch.sparse.Tensor。 有关反向操作,请参见to_edge_index()

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – The edge attributes. (default: None)

  • size (int(int, int), 可选) – 稀疏矩阵的大小。 如果给定为一个整数,将创建一个二次稀疏矩阵。 如果设置为 None,将根据 edge_index.max() + 1 推断一个二次稀疏矩阵。(默认值:None

  • is_coalesced (bool) – 如果设置为 True,将假设 edge_index 已经合并,从而避免昂贵的 计算。(默认值:False

Return type:

torch.sparse.Tensor

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> to_torch_csc_tensor(edge_index)
tensor(ccol_indices=tensor([0, 1, 3, 5, 6]),
       row_indices=tensor([1, 0, 2, 1, 3, 2]),
       values=tensor([1., 1., 1., 1., 1., 1.]),
       size=(4, 4), nnz=6, layout=torch.sparse_csc)
to_torch_sparse_tensor(edge_index: Tensor, edge_attr: Optional[Tensor] = None, size: Optional[Union[int, Tuple[Optional[int], Optional[int]]]] = None, is_coalesced: bool = False, layout: layout = torch.sparse_coo) Tensor[source]

将由边索引和边属性定义的稀疏邻接矩阵转换为具有自定义layouttorch.sparse.Tensor。 有关反向操作,请参见to_edge_index()

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – The edge attributes. (default: None)

  • size (int(int, int), 可选) – 稀疏矩阵的大小。 如果给定为一个整数,将创建一个二次稀疏矩阵。 如果设置为 None,将根据 edge_index.max() + 1 推断一个二次稀疏矩阵。(默认值:None

  • is_coalesced (bool) – If set to True, will assume that edge_index is already coalesced and thus avoids expensive computation. (default: False)

  • layout (torch.layout, optional) – 输出稀疏张量的布局 (torch.sparse_coo, torch.sparse_csr, torch.sparse_csc). (默认: torch.sparse_coo)

Return type:

torch.sparse.Tensor

to_edge_index(adj: Union[Tensor, SparseTensor]) Tuple[Tensor, Tensor][source]

torch.sparse.Tensortorch_sparse.SparseTensor转换为边索引和边属性。

Parameters:

adj (torch.sparse.TensorSparseTensor) – 邻接矩阵。

Return type:

(torch.Tensor, torch.Tensor)

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> adj = to_torch_coo_tensor(edge_index)
>>> to_edge_index(adj)
(tensor([[0, 1, 1, 2, 2, 3],
        [1, 0, 2, 1, 3, 2]]),
tensor([1., 1., 1., 1., 1., 1.]))
spmm(src: Union[Tensor, SparseTensor], other: Tensor, reduce: str = 'sum') Tensor[source]

稀疏矩阵与密集矩阵的矩阵乘积。

Parameters:
  • src (torch.Tensortorch_sparse.SparseTensorEdgeIndex) – 输入的稀疏矩阵,可以是 torch_sparse.SparseTensor, 一个 torch.sparse.Tensor 或 一个 EdgeIndex

  • 其他 (torch.Tensor) – 输入的密集矩阵。

  • reduce (str, optional) – 使用的reduce操作 ("sum", "mean", "min", "max"). (默认: "sum")

Return type:

Tensor

unbatch(src: Tensor, batch: Tensor, dim: int = 0, batch_size: Optional[int] = None) List[Tensor][source]

根据batch向量沿维度dim分割src

Parameters:
  • src (Tensor) – The source tensor.

  • batch (LongTensor) – 批次向量 \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\),它将 src 中的每个条目分配给特定的示例。必须是有序的。

  • dim (int, optional) – 沿着哪个维度分割 src 张量。(默认值:0

  • batch_size (int, optional) – The batch size. (default: None)

Return type:

List[Tensor]

示例

>>> src = torch.arange(7)
>>> batch = torch.tensor([0, 0, 0, 1, 1, 2, 2])
>>> unbatch(src, batch)
(tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6]))
unbatch_edge_index(edge_index: Tensor, batch: Tensor, batch_size: Optional[int] = None) List[Tensor][source]

Splits the edge_index according to a batch vector.

Parameters:
  • edge_index (Tensor) – 边索引张量。必须是有序的。

  • batch (LongTensor) – 批次向量 \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\),它将每个 节点分配给特定的示例。必须是有序的。

  • batch_size (int, optional) – The batch size. (default: None)

Return type:

List[Tensor]

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3, 4, 5, 5, 6],
...                            [1, 0, 2, 1, 3, 2, 5, 4, 6, 5]])
>>> batch = torch.tensor([0, 0, 0, 0, 1, 1, 1])
>>> unbatch_edge_index(edge_index, batch)
(tensor([[0, 1, 1, 2, 2, 3],
        [1, 0, 2, 1, 3, 2]]),
tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]]))
one_hot(index: Tensor, num_classes: Optional[int] = None, dtype: Optional[dtype] = None) Tensor[source]

接受一个一维的index张量,并返回其形状为[*, num_classes]的独热编码表示,其中除了最后一个维度的索引与输入张量的对应值匹配的位置为1外,其余位置均为零。

注意

这是torch.nn.functional.one_hot()的一个更节省内存的版本,因为你可以自定义输出的dtype

Parameters:
  • index (torch.Tensor) – 一维输入张量。

  • num_classes (int, 可选) – 类别的总数。如果设置为 None,类别的数量将被推断为比输入张量中最大类别值大一的数。 (默认: None)

  • dtype (torch.dtype, optional) – 输出张量的dtype

Return type:

Tensor

normalized_cut(edge_index: Tensor, edge_attr: Tensor, num_nodes: Optional[int] = None) Tensor[source]

计算由边索引和边属性给出的加权图的归一化割 \(\mathbf{e}_{i,j} \cdot \left( \frac{1}{\deg(i)} + \frac{1}{\deg(j)} \right)\)

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor) – 边的权重或多维边特征。

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

Return type:

Tensor

示例

>>> edge_index = torch.tensor([[1, 1, 2, 3],
...                            [3, 3, 1, 2]])
>>> edge_attr = torch.tensor([1., 1., 1., 1.])
>>> normalized_cut(edge_index, edge_attr)
tensor([1.5000, 1.5000, 2.0000, 1.5000])
grid(height: int, width: int, dtype: Optional[dtype] = None, device: Optional[device] = None) Tuple[Tensor, Tensor][source]

返回一个二维网格图的边索引,该网格图的高度为height,宽度为width,并返回其节点位置。

Parameters:
  • height (int) – The height of the grid.

  • width (int) – The width of the grid.

  • dtype (torch.dtype, optional) – 返回的位置张量的期望数据类型。(默认值:None

  • device (torch.device, optional) – 返回张量的期望设备。(默认值:None

Return type:

(LongTensor, Tensor)

示例

>>> (row, col), pos = grid(height=2, width=2)
>>> row
tensor([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])
>>> col
tensor([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])
>>> pos
tensor([[0., 1.],
        [1., 1.],
        [0., 0.],
        [1., 0.]])
geodesic_distance(pos: Tensor, face: Tensor, src: Optional[Tensor] = None, dst: Optional[Tensor] = None, norm: bool = True, max_distance: Optional[float] = None, num_workers: int = 0, **kwargs: Optional[Tensor]) Tensor[source]

计算由posface给出的网格的(归一化)测地距离。如果提供了srcdst,则此方法仅计算相应的源节点和目标节点对的测地距离。

注意

此函数需要gdist包。 要安装,请运行pip install cython && pip install gdist

Parameters:
  • pos (torch.Tensor) – 节点位置。

  • face (torch.Tensor) – 面索引。

  • src (torch.Tensor, optional) – 如果给定,则仅计算指定源索引的测地距离。(默认值:None

  • dst (torch.Tensor, optional) – 如果给定,则仅计算指定目标索引的测地距离。(默认值: None)

  • norm (bool, optional) – 通过\(\sqrt{\textrm{area}(\mathcal{M})}\)归一化测地距离。(默认: True)

  • max_distance (float, optional) – 如果给定,则仅生成大地距离小于 max_distance 的结果。这将显著加快运行时间。(默认值:None

  • num_workers (int, optional) – 用于计算测地距离的子进程数量。 0 表示计算在主进程中进行。 -1 表示使用可用的CPU核心数量。 (默认值: 0)

Return type:

Tensor

示例

>>> pos = torch.tensor([[0.0, 0.0, 0.0],
...                     [2.0, 0.0, 0.0],
...                     [0.0, 2.0, 0.0],
...                     [2.0, 2.0, 0.0]])
>>> face = torch.tensor([[0, 0],
...                      [1, 2],
...                      [3, 3]])
>>> geodesic_distance(pos, face)
[[0, 1, 1, 1.4142135623730951],
[1, 0, 1.4142135623730951, 1],
[1, 1.4142135623730951, 0, 1],
[1.4142135623730951, 1, 1, 0]]
to_scipy_sparse_matrix(edge_index: Tensor, edge_attr: Optional[Tensor] = None, num_nodes: Optional[int] = None) Any[source]

将给定的边索引和边属性图转换为scipy稀疏矩阵。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor, optional) – Edge weights or multi-dimensional edge features. (default: None)

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of index. (default: None)

示例

>>> edge_index = torch.tensor([
...     [0, 1, 1, 2, 2, 3],
...     [1, 0, 2, 1, 3, 2],
... ])
>>> to_scipy_sparse_matrix(edge_index)
<4x4 sparse matrix of type '<class 'numpy.float32'>'
    with 6 stored elements in COOrdinate format>
Return type:

Any

from_scipy_sparse_matrix(A: Any) Tuple[Tensor, Tensor][source]

将scipy稀疏矩阵转换为边索引和边属性。

Parameters:

A (scipy.sparse) – 一个稀疏矩阵。

示例

>>> edge_index = torch.tensor([
...     [0, 1, 1, 2, 2, 3],
...     [1, 0, 2, 1, 3, 2],
... ])
>>> adj = to_scipy_sparse_matrix(edge_index)
>>> # `edge_index` and `edge_weight` are both returned
>>> from_scipy_sparse_matrix(adj)
(tensor([[0, 1, 1, 2, 2, 3],
        [1, 0, 2, 1, 3, 2]]),
tensor([1., 1., 1., 1., 1., 1.]))
Return type:

Tuple[Tensor, Tensor]

to_networkx(data: Union[Data, HeteroData], node_attrs: Optional[Iterable[str]] = None, edge_attrs: Optional[Iterable[str]] = None, graph_attrs: Optional[Iterable[str]] = None, to_undirected: Optional[Union[bool, str]] = False, to_multi: bool = False, remove_self_loops: bool = False) Any[source]

torch_geometric.data.Data实例转换为 networkx.Graph,如果to_undirected设置为True,否则转换为有向的networkx.DiGraph

Parameters:
  • data (torch_geometric.data.Datatorch_geometric.data.HeteroData) – 一个 同质或异质的数据对象。

  • node_attrs (可迭代的字符串, 可选) – 要复制的节点属性。(默认: None)

  • edge_attrs (字符串的可迭代对象, 可选) – 要复制的边属性。(默认: None)

  • graph_attrs (可迭代的字符串, 可选) – 要复制的图属性。(默认: None)

  • to_undirected (boolstr, 可选) – 如果设置为 True,将返回一个 networkx.Graph 而不是 networkx.DiGraph。 默认情况下,将包括所有边并使它们无向。 如果设置为 "upper",无向图将仅对应于输入邻接矩阵的上三角部分。 如果设置为 "lower",无向图将仅对应于输入邻接矩阵的下三角部分。 仅在 data 对象包含同构图时适用。(默认值:False

  • to_multi (bool, 可选) – 如果设置为 True,将返回一个 networkx.MultiGraphnetworkx:MultiDiGraph (取决于 to_undirected 选项),这将不会丢弃 data 中可能存在的重复边。 (默认值:False

  • remove_self_loops (bool, 可选) – 如果设置为 True,将不会在结果图中包含自循环。(默认值:False

示例

>>> edge_index = torch.tensor([
...     [0, 1, 1, 2, 2, 3],
...     [1, 0, 2, 1, 3, 2],
... ])
>>> data = Data(edge_index=edge_index, num_nodes=4)
>>> to_networkx(data)
<networkx.classes.digraph.DiGraph at 0x2713fdb40d0>
Return type:

Any

from_networkx(G: Any, group_node_attrs: Optional[Union[List[str], Literal['all']]] = None, group_edge_attrs: Optional[Union[List[str], Literal['all']]] = None) Data[source]

networkx.Graphnetworkx.DiGraph转换为 torch_geometric.data.Data实例。

Parameters:
  • G (networkx.Graphnetworkx.DiGraph) – 一个 networkx 图。

  • group_node_attrs (List[str] or "all", optional) – 要连接并添加到 data.x 的节点属性。(默认值:None

  • group_edge_attrs (List[str] 或 "all", 可选) – 要连接并添加到 data.edge_attr 的边属性。 (默认: None)

注意

所有 group_node_attrsgroup_edge_attrs 的值必须是数字。

示例

>>> edge_index = torch.tensor([
...     [0, 1, 1, 2, 2, 3],
...     [1, 0, 2, 1, 3, 2],
... ])
>>> data = Data(edge_index=edge_index, num_nodes=4)
>>> g = to_networkx(data)
>>> # A `Data` object is returned
>>> from_networkx(g)
Data(edge_index=[2, 6], num_nodes=4)
Return type:

Data

to_networkit(edge_index: Tensor, edge_weight: Optional[Tensor] = None, num_nodes: Optional[int] = None, directed: bool = True) Any[source]

(edge_index, edge_weight)元组转换为 networkit.Graph

Parameters:
  • edge_index (torch.Tensor) – 图的边索引。

  • edge_weight (torch.Tensor, optional) – 图的边权重。 (default: None)

  • num_nodes (int, optional) – The number of nodes in the graph. (default: None)

  • directed (bool, 可选) – 如果设置为 False,图将是无向的。(默认值:True

Return type:

Any

from_networkit(g: Any) Tuple[Tensor, Optional[Tensor]][source]

networkit.Graph转换为 (edge_index, edge_weight)元组。 如果networkit.Graph没有权重,返回的 edge_weight将是None

Parameters:

g (networkkit.graph.Graph) – 一个 networkit 图对象。

Return type:

Tuple[Tensor, Optional[Tensor]]

to_trimesh(data: Data) Any[source]

torch_geometric.data.Data实例转换为 trimesh.Trimesh

Parameters:

data (torch_geometric.data.Data) – 数据对象。

示例

>>> pos = torch.tensor([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]],
...                    dtype=torch.float)
>>> face = torch.tensor([[0, 1, 2], [1, 2, 3]]).t()
>>> data = Data(pos=pos, face=face)
>>> to_trimesh(data)
<trimesh.Trimesh(vertices.shape=(4, 3), faces.shape=(2, 3))>
Return type:

Any

from_trimesh(mesh: Any) Data[source]

trimesh.Trimesh转换为 torch_geometric.data.Data实例。

Parameters:

网格 (trimesh.Trimesh) – 一个 trimesh 网格。

示例

>>> pos = torch.tensor([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]],
...                    dtype=torch.float)
>>> face = torch.tensor([[0, 1, 2], [1, 2, 3]]).t()
>>> data = Data(pos=pos, face=face)
>>> mesh = to_trimesh(data)
>>> from_trimesh(mesh)
Data(pos=[4, 3], face=[3, 2])
Return type:

Data

to_cugraph(edge_index: Tensor, edge_weight: Optional[Tensor] = None, relabel_nodes: bool = True, directed: bool = True) Any[source]

将由edge_index和可选的edge_weight给出的图转换为cugraph图对象。

Parameters:
  • edge_index (torch.Tensor) – The edge indices of the graph.

  • edge_weight (torch.Tensor, optional) – The edge weights of the graph. (default: None)

  • relabel_nodes (bool, 可选) – 如果设置为 True, cugraph 将移除任何孤立的节点,从而导致节点的重新标记。(默认值: True)

  • directed (bool, 可选) – 如果设置为 False,图将是无向的。(默认值:True

Return type:

Any

from_cugraph(g: Any) Tuple[Tensor, Optional[Tensor]][source]

cugraph图对象转换为edge_index和可选的edge_weight张量。

Parameters:

g (cugraph.Graph) – 一个 cugraph 图对象。

Return type:

Tuple[Tensor, Optional[Tensor]]

to_dgl(data: Union[Data, HeteroData]) Any[source]

torch_geometric.data.Datatorch_geometric.data.HeteroData实例转换为dgl图 对象。

Parameters:

data (torch_geometric.data.Datatorch_geometric.data.HeteroData) – 数据对象。

示例

>>> edge_index = torch.tensor([[0, 1, 1, 2, 3, 0], [1, 0, 2, 1, 4, 4]])
>>> x = torch.randn(5, 3)
>>> edge_attr = torch.randn(6, 2)
>>> data = Data(x=x, edge_index=edge_index, edge_attr=y)
>>> g = to_dgl(data)
>>> g
Graph(num_nodes=5, num_edges=6,
    ndata_schemes={'x': Scheme(shape=(3,))}
    edata_schemes={'edge_attr': Scheme(shape=(2, ))})
>>> data = HeteroData()
>>> data['paper'].x = torch.randn(5, 3)
>>> data['author'].x = torch.ones(5, 3)
>>> edge_index = torch.tensor([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]])
>>> data['author', 'cites', 'paper'].edge_index = edge_index
>>> g = to_dgl(data)
>>> g
Graph(num_nodes={'author': 5, 'paper': 5},
    num_edges={('author', 'cites', 'paper'): 5},
    metagraph=[('author', 'paper', 'cites')])
Return type:

Any

from_dgl(g: Any) Union[Data, HeteroData][source]

dgl图对象转换为 torch_geometric.data.Datatorch_geometric.data.HeteroData实例。

Parameters:

g (dgl.DGLGraph) – dgl 图对象。

示例

>>> g = dgl.graph(([0, 0, 1, 5], [1, 2, 2, 0]))
>>> g.ndata['x'] = torch.randn(g.num_nodes(), 3)
>>> g.edata['edge_attr'] = torch.randn(g.num_edges(), 2)
>>> data = from_dgl(g)
>>> data
Data(x=[6, 3], edge_attr=[4, 2], edge_index=[2, 4])
>>> g = dgl.heterograph({
>>> g = dgl.heterograph({
...     ('author', 'writes', 'paper'): ([0, 1, 1, 2, 3, 3, 4],
...                                     [0, 0, 1, 1, 1, 2, 2])})
>>> g.nodes['author'].data['x'] = torch.randn(5, 3)
>>> g.nodes['paper'].data['x'] = torch.randn(5, 3)
>>> data = from_dgl(g)
>>> data
HeteroData(
author={ x=[5, 3] },
paper={ x=[3, 3] },
(author, writes, paper)={ edge_index=[2, 7] }
)
Return type:

Union[Data, HeteroData]

from_rdmol(mol: Any) Data[source]

rdkit.Chem.Mol实例转换为 torch_geometric.data.Data实例。

Parameters:

mol (rdkit.Chem.Mol) – rdkit 分子。

Return type:

Data

to_rdmol(data: Data, kekulize: bool = False) Any[source]

torch_geometric.data.Data实例转换为 rdkit.Chem.Mol实例。

Parameters:
Return type:

Any

from_smiles(smiles: str, with_hydrogen: bool = False, kekulize: bool = False) Data[source]

将SMILES字符串转换为torch_geometric.data.Data实例。

Parameters:
  • smiles (str) – SMILES 字符串。

  • with_hydrogen (bool, 可选) – 如果设置为 True,将在分子图中存储氢原子。(默认值:False

  • kekulize (bool, 可选) – 如果设置为 True,将芳香键转换为单键/双键。(默认值:False

Return type:

Data

to_smiles(data: Data, kekulize: bool = False) str[source]

torch_geometric.data.Data实例转换为SMILES字符串。

Parameters:
Return type:

str

erdos_renyi_graph(num_nodes: int, edge_prob: float, directed: bool = False) Tensor[source]

Returns the edge_index of a random Erdos-Renyi graph.

Parameters:
  • num_nodes (int) – The number of nodes.

  • edge_prob (float) – Probability of an edge.

  • directed (bool, 可选) – 如果设置为 True,将返回一个有向图。(默认值:False

示例

>>> erdos_renyi_graph(5, 0.2, directed=False)
tensor([[0, 1, 1, 4],
        [1, 0, 4, 1]])
>>> erdos_renyi_graph(5, 0.2, directed=True)
tensor([[0, 1, 3, 3, 4, 4],
        [4, 3, 1, 2, 1, 3]])
Return type:

Tensor

stochastic_blockmodel_graph(block_sizes: Union[List[int], Tensor], edge_probs: Union[List[List[float]], Tensor], directed: bool = False) Tensor[source]

Returns the edge_index of a stochastic blockmodel graph.

Parameters:
  • block_sizes ([int] or LongTensor) – The sizes of blocks.

  • edge_probs ([[float]] 或 FloatTensor) – 表示从一个块到另一个块的边的密度。如果图是无向的,则必须是对称的。

  • directed (bool, 可选) – 如果设置为 True,将返回一个有向图。(默认值:False

示例

>>> block_sizes = [2, 2, 4]
>>> edge_probs = [[0.25, 0.05, 0.02],
...               [0.05, 0.35, 0.07],
...               [0.02, 0.07, 0.40]]
>>> stochastic_blockmodel_graph(block_sizes, edge_probs,
...                             directed=False)
tensor([[2, 4, 4, 5, 5, 6, 7, 7],
        [5, 6, 7, 2, 7, 4, 4, 5]])
>>> stochastic_blockmodel_graph(block_sizes, edge_probs,
...                             directed=True)
tensor([[0, 2, 3, 4, 4, 5, 5],
        [3, 4, 1, 5, 6, 6, 7]])
Return type:

Tensor

barabasi_albert_graph(num_nodes: int, num_edges: int) Tensor[source]

返回一个Barabasi-Albert优先连接模型的edge_index,其中num_nodes个节点的图通过连接具有num_edges条边的新节点来增长,这些新节点优先连接到具有高度数的现有节点。

Parameters:
  • num_nodes (int) – The number of nodes.

  • num_edges (int) – The number of edges from a new node to existing nodes.

示例

>>> barabasi_albert_graph(num_nodes=4, num_edges=3)
tensor([[0, 0, 0, 1, 1, 2, 2, 3],
        [1, 2, 3, 0, 2, 0, 1, 0]])
Return type:

Tensor

negative_sampling(edge_index: Tensor, num_nodes: Optional[Union[int, Tuple[int, int]]] = None, num_neg_samples: Optional[int] = None, method: str = 'sparse', force_undirected: bool = False) Tensor[source]

Samples random negative edges of a graph given by edge_index.

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • num_nodes (int or Tuple[int, int], optional) – The number of nodes, i.e. max_val + 1 of edge_index. If given as a tuple, then edge_index is interpreted as a bipartite graph with shape (num_src_nodes, num_dst_nodes). (default: None)

  • num_neg_samples (int, optional) – 返回的负样本的(近似)数量。 如果设置为 None,将尝试为每个正样本返回一个负样本。(默认值:None

  • method (str, optional) – 用于负采样的方法, "sparse""dense"。 这是内存/运行时间的权衡。 "sparse" 可以处理任何大小的图,而 "dense" 可以更快地执行真负检查。 (默认: "sparse")

  • force_undirected (bool, optional) – 如果设置为 True,采样的负边将是无向的。(默认值:False

Return type:

长整型张量

示例

>>> # Standard usage
>>> edge_index = torch.as_tensor([[0, 0, 1, 2],
...                               [0, 1, 2, 3]])
>>> negative_sampling(edge_index)
tensor([[3, 0, 0, 3],
        [2, 3, 2, 1]])
>>> # For bipartite graph
>>> negative_sampling(edge_index, num_nodes=(3, 4))
tensor([[0, 2, 2, 1],
        [2, 2, 1, 3]])
batched_negative_sampling(edge_index: Tensor, batch: Union[Tensor, Tuple[Tensor, Tensor]], num_neg_samples: Optional[int] = None, method: str = 'sparse', force_undirected: bool = False) Tensor[source]

从由edge_indexbatch给出的多个图中随机抽取负边样本。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • batch (LongTensorTuple[LongTensor, LongTensor]) – 批次向量 \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), 它将每个节点分配到一个特定的示例。 如果以元组形式给出,则 edge_index 被解释为连接两种不同节点类型的二分图。

  • num_neg_samples (int, optional) – 要返回的负样本数量。如果设置为 None,将尝试为每个正样本返回一个负样本。(默认值:None

  • method (str, optional) – 用于负采样的方法, "sparse""dense"。 这是内存/运行时间的权衡。 "sparse" 可以处理任何大小的图,而 "dense" 可以更快地执行真负检查。 (默认: "sparse")

  • force_undirected (bool, optional) – 如果设置为 True,采样的负边将是无向的。(默认值:False

Return type:

长整型张量

示例

>>> # Standard usage
>>> edge_index = torch.as_tensor([[0, 0, 1, 2], [0, 1, 2, 3]])
>>> edge_index = torch.cat([edge_index, edge_index + 4], dim=1)
>>> edge_index
tensor([[0, 0, 1, 2, 4, 4, 5, 6],
        [0, 1, 2, 3, 4, 5, 6, 7]])
>>> batch = torch.tensor([0, 0, 0, 0, 1, 1, 1, 1])
>>> batched_negative_sampling(edge_index, batch)
tensor([[3, 1, 3, 2, 7, 7, 6, 5],
        [2, 0, 1, 1, 5, 6, 4, 4]])
>>> # For bipartite graph
>>> edge_index1 = torch.as_tensor([[0, 0, 1, 1], [0, 1, 2, 3]])
>>> edge_index2 = edge_index1 + torch.tensor([[2], [4]])
>>> edge_index3 = edge_index2 + torch.tensor([[2], [4]])
>>> edge_index = torch.cat([edge_index1, edge_index2,
...                         edge_index3], dim=1)
>>> edge_index
tensor([[ 0,  0,  1,  1,  2,  2,  3,  3,  4,  4,  5,  5],
        [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]])
>>> src_batch = torch.tensor([0, 0, 1, 1, 2, 2])
>>> dst_batch = torch.tensor([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2])
>>> batched_negative_sampling(edge_index,
...                           (src_batch, dst_batch))
tensor([[ 0,  0,  1,  1,  2,  2,  3,  3,  4,  4,  5,  5],
        [ 2,  3,  0,  1,  6,  7,  4,  5, 10, 11,  8,  9]])
structured_negative_sampling(edge_index: Tensor, num_nodes: Optional[int] = None, contains_neg_self_loops: bool = True) Tuple[Tensor, Tensor, Tensor][source]

为图中的每个正边(i,j)采样一个负边(i,k),并以(i,j,k)的形式返回。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

  • contains_neg_self_loops (bool, 可选) – 如果设置为 False,采样的负边将不包含自循环。 (默认: True)

Return type:

(LongTensor, LongTensor, LongTensor)

示例

>>> edge_index = torch.as_tensor([[0, 0, 1, 2],
...                               [0, 1, 2, 3]])
>>> structured_negative_sampling(edge_index)
(tensor([0, 0, 1, 2]), tensor([0, 1, 2, 3]), tensor([2, 3, 0, 2]))
structured_negative_sampling_feasible(edge_index: Tensor, num_nodes: Optional[int] = None, contains_neg_self_loops: bool = True) bool[source]

如果structured_negative_sampling()在由edge_index给出的图上可行,则返回True。 如果至少有一个节点连接到所有其他节点,则structured_negative_sampling()不可行。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • num_nodes (int, optional) – The number of nodes, i.e. max_val + 1 of edge_index. (default: None)

  • contains_neg_self_loops (bool, 可选) – 如果设置为 False,采样的负边将不包含自循环。 (默认: True)

Return type:

bool 翻译后的内容: bool 在这个例子中,`bool` 是一个Python函数名称,根据翻译规则1,不需要翻译。因此,翻译后的内容保持不变。

示例

>>> edge_index = torch.LongTensor([[0, 0, 1, 1, 2, 2, 2],
...                                [1, 2, 0, 2, 0, 1, 1]])
>>> structured_negative_sampling_feasible(edge_index, 3, False)
False
>>> structured_negative_sampling_feasible(edge_index, 3, True)
True
shuffle_node(x: Tensor, batch: Optional[Tensor] = None, training: bool = True) Tuple[Tensor, Tensor][source]

随机打乱特征矩阵 x 的第一个维度。

该方法返回 (1) 打乱后的 x, (2) 表示打乱后原始节点顺序的排列。

Parameters:
  • x (FloatTensor) – 特征矩阵。

  • batch (LongTensor, optional) – Batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each node to a specific example. Must be ordered. (default: None)

  • training (bool, optional) – If set to False, this operation is a no-op. (default: True)

Return type:

(FloatTensor, LongTensor)

示例

>>> # Standard case
>>> x = torch.tensor([[0, 1, 2],
...                   [3, 4, 5],
...                   [6, 7, 8],
...                   [9, 10, 11]], dtype=torch.float)
>>> x, node_perm = shuffle_node(x)
>>> x
tensor([[ 3.,  4.,  5.],
        [ 9., 10., 11.],
        [ 0.,  1.,  2.],
        [ 6.,  7.,  8.]])
>>> node_perm
tensor([1, 3, 0, 2])
>>> # For batched graphs as inputs
>>> batch = torch.tensor([0, 0, 1, 1])
>>> x, node_perm = shuffle_node(x, batch)
>>> x
tensor([[ 3.,  4.,  5.],
        [ 0.,  1.,  2.],
        [ 9., 10., 11.],
        [ 6.,  7.,  8.]])
>>> node_perm
tensor([1, 0, 3, 2])
mask_feature(x: Tensor, p: float = 0.5, mode: str = 'col', fill_value: float = 0.0, training: bool = True) Tuple[Tensor, Tensor][source]

随机从特征矩阵 x 中屏蔽特征,使用来自伯努利分布的样本,概率为 p

该方法返回 (1) 保留的 x, (2) 与 x 可广播的特征掩码 (mode='row'mode='col') 或与 x 形状相同的特征掩码 (mode='all'), 指示哪些特征被保留。

Parameters:
  • x (FloatTensor) – 特征矩阵。

  • p (float, optional) – 掩码比例。(默认值:0.5

  • mode (str, optional) – 用于特征掩码的掩码方案。 ("row", "col""all")。 如果 mode='col',将从特征矩阵中掩码所有节点的整个特征。如果 mode='row',将从特征矩阵中掩码整个节点。如果 mode='all',将掩码所有节点的单个特征。(默认值:'col'

  • fill_value (float, optional) – 输出张量中被掩码特征的值。(默认值:0

  • training (bool, optional) – If set to False, this operation is a no-op. (default: True)

Return type:

(FloatTensor, BoolTensor)

示例

>>> # Masked features are column-wise sampled
>>> x = torch.tensor([[1, 2, 3],
...                   [4, 5, 6],
...                   [7, 8, 9]], dtype=torch.float)
>>> x, feat_mask = mask_feature(x)
>>> x
tensor([[1., 0., 3.],
        [4., 0., 6.],
        [7., 0., 9.]]),
>>> feat_mask
tensor([[True, False, True]])
>>> # Masked features are row-wise sampled
>>> x, feat_mask = mask_feature(x, mode='row')
>>> x
tensor([[1., 2., 3.],
        [0., 0., 0.],
        [7., 8., 9.]]),
>>> feat_mask
tensor([[True], [False], [True]])
>>> # Masked features are uniformly sampled
>>> x, feat_mask = mask_feature(x, mode='all')
>>> x
tensor([[0., 0., 0.],
        [4., 0., 6.],
        [0., 0., 9.]])
>>> feat_mask
tensor([[False, False, False],
        [True, False,  True],
        [False, False,  True]])
add_random_edge(edge_index: Tensor, p: float = 0.5, force_undirected: bool = False, num_nodes: Optional[Union[int, Tuple[int, int]]] = None, training: bool = True) Tuple[Tensor, Tensor][source]

Randomly adds edges to edge_index.

该方法返回(1)保留的edge_index,(2)添加的边索引。

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • p (float) – 添加的边与现有边的比例。 (默认值: 0.5)

  • force_undirected (bool, 可选) – 如果设置为 True, 添加的边将是无向的。 (默认值: False)

  • num_nodes (int, Tuple[int], optional) – 节点的总数, max_val + 1,或源节点和目标节点的数量, (max_src_val + 1, max_dst_val + 1)edge_index。(默认值:None

  • training (bool, optional) – If set to False, this operation is a no-op. (default: True)

Return type:

(LongTensor, LongTensor)

示例

>>> # Standard case
>>> edge_index = torch.tensor([[0, 1, 1, 2, 2, 3],
...                            [1, 0, 2, 1, 3, 2]])
>>> edge_index, added_edges = add_random_edge(edge_index, p=0.5)
>>> edge_index
tensor([[0, 1, 1, 2, 2, 3, 2, 1, 3],
        [1, 0, 2, 1, 3, 2, 0, 2, 1]])
>>> added_edges
tensor([[2, 1, 3],
        [0, 2, 1]])
>>> # The returned graph is kept undirected
>>> edge_index, added_edges = add_random_edge(edge_index, p=0.5,
...                                           force_undirected=True)
>>> edge_index
tensor([[0, 1, 1, 2, 2, 3, 2, 1, 3, 0, 2, 1],
        [1, 0, 2, 1, 3, 2, 0, 2, 1, 2, 1, 3]])
>>> added_edges
tensor([[2, 1, 3, 0, 2, 1],
        [0, 2, 1, 2, 1, 3]])
>>> # For bipartite graphs
>>> edge_index = torch.tensor([[0, 1, 2, 3, 4, 5],
...                            [2, 3, 1, 4, 2, 1]])
>>> edge_index, added_edges = add_random_edge(edge_index, p=0.5,
...                                           num_nodes=(6, 5))
>>> edge_index
tensor([[0, 1, 2, 3, 4, 5, 3, 4, 1],
        [2, 3, 1, 4, 2, 1, 1, 3, 2]])
>>> added_edges
tensor([[3, 4, 1],
        [1, 3, 2]])
tree_decomposition(mol: Any, return_vocab: bool = False) Union[Tuple[Tensor, Tensor, int], Tuple[Tensor, Tensor, int, Tensor]][source]

分子树分解算法来自 “Junction Tree Variational Autoencoder for Molecular Graph Generation” 论文。 返回连接树的图连通性、每个原子到连接树中团的分配映射以及团的数量。

Parameters:
  • mol (rdkit.Chem.Mol) – 一个 rdkit 分子。

  • return_vocab (bool, 可选) – 如果设置为 True,将返回每个团(环、键、桥接化合物、单键)的标识符。 (默认: False)

Return type:

(LongTensor, LongTensor, int) 如果 return_vocabFalse, 否则 (LongTensor, LongTensor, int, LongTensor)

get_embeddings(model: Module, *args: Any, **kwargs: Any) List[Tensor][source]

返回model中所有MessagePassing层的输出嵌入。

在内部,此方法在MessagePassing层的所有MessagePassing上注册前向钩子,并通过调用model(*args, **kwargs)来运行model的前向传递。

Parameters:
  • model (torch.nn.Module) – 消息传递模型。

  • *args – Arguments passed to the model.

  • **kwargs (可选) – 传递给模型的额外关键字参数。

Return type:

List[Tensor]

trim_to_layer(layer: int, num_sampled_nodes_per_hop: Union[List[int], Dict[str, List[int]]], num_sampled_edges_per_hop: Union[List[int], Dict[Tuple[str, str, str], List[int]]], x: Union[Tensor, Dict[str, Tensor]], edge_index: Union[Tensor, Dict[Tuple[str, str, str], Tensor]], edge_attr: Optional[Union[Tensor, Dict[Tuple[str, str, str], Tensor]]] = None) Tuple[Union[Tensor, Dict[str, Tensor]], Union[Tensor, Dict[Tuple[str, str, str], Union[Tensor, SparseTensor]]], Optional[Union[Tensor, Dict[Tuple[str, str, str], Tensor]]]][source]

修剪edge_index表示、节点特征x和边特征edge_attr,使其在当前GNN层layer的有向NeighborLoader场景中达到最小尺寸表示。

这确保了对于不包含在当前GNN层中的节点和边不执行计算,从而在执行邻域采样时避免在GNN中进行不必要的计算。

Parameters:
  • layer (int) – 当前的GNN层。

  • num_sampled_nodes_per_hop (List[int] or Dict[NodeType, List[int]]) – 每跳采样的节点数量。

  • num_sampled_edges_per_hop (List[int] or Dict[EdgeType, List[int]]) – 每跳采样的边数。

  • x (torch.TensorDict[NodeType, torch.Tensor]) – 同构或异构的(隐藏)节点特征。

  • edge_index (torch.TensorDict[EdgeType, torch.Tensor]) – 同质或异质边索引。

  • edge_attr (torch.TensorDict[EdgeType, torch.Tensor], 可选) – 同质或异质(隐藏)边特征。

Return type:

Tuple[Union[Tensor, Dict[str, Tensor]], Union[Tensor, Dict[Tuple[str, str, str], Union[Tensor, SparseTensor]]], Union[Tensor, Dict[Tuple[str, str, str], Tensor], None]]

get_ppr(edge_index: Tensor, alpha: float = 0.2, eps: float = 1e-05, target: Optional[Tensor] = None, num_nodes: Optional[int] = None) Tuple[Tensor, Tensor][source]

使用Andersen算法的变体计算所有或部分节点的个性化PageRank(PPR)向量。

Parameters:
  • edge_index (torch.Tensor) – 图的索引。

  • alpha (float, optional) – PageRank算法的alpha值。 (默认: 0.2)

  • eps (float, optional) – 停止PPR计算的阈值 (edge_weight >= eps * out_degree)。(默认值: 1e-5)

  • target (torch.Tensor, optional) – 要计算PPR的目标节点。 如果未给出,则计算所有节点的PPR向量。 (默认: None)

  • num_nodes (int, optional) – The number of nodes. (default: None)

Return type:

(torch.Tensor, torch.Tensor)

train_test_split_edges(data: Data, val_ratio: float = 0.05, test_ratio: float = 0.1) Data[source]

torch_geometric.data.Data对象的边分割为正向和负向的训练/验证/测试边。 因此,它将用train_pos_edge_indextrain_pos_neg_adj_maskval_pos_edge_indexval_neg_edge_indextest_pos_edge_index属性替换edge_index属性。 如果data具有名为edge_attr的边特征,则 train_pos_edge_attrval_pos_edge_attrtest_pos_edge_attr也将被添加。

警告

train_test_split_edges() 已弃用,并将在未来的版本中移除。 请使用 torch_geometric.transforms.RandomLinkSplit 代替。

Parameters:
  • data (Data) – 数据对象。

  • val_ratio (float, optional) – 正验证边的比例。 (默认: 0.05)

  • test_ratio (float, optional) – 正测试边的比例。 (默认: 0.1)

Return type:

torch_geometric.data.Data