torch_geometric.utils
从 |
|
返回按值沿给定维度升序排序张量 |
|
在给定的维度 |
|
减少 |
|
将 |
|
返回 |
|
计算给定一维索引张量的(未加权)度数。 |
|
计算稀疏评估的softmax。 |
|
使用一系列键执行间接稳定排序。 |
|
按行排序 |
|
按行排序 |
|
如果由 |
|
将 |
|
如果由 |
|
移除由 |
|
将自循环从图中分离出来。 |
|
向由 |
|
将剩余的自环 \((i,i) \in \mathcal{E}\) 添加到由 |
|
返回由 |
|
如果由 |
|
从由 |
|
返回模型聚合信息的跳数。 |
|
返回包含 |
|
返回包含 |
|
计算在 |
|
从邻接矩阵 |
|
从邻接矩阵 |
|
从邻接矩阵 |
|
从邻接矩阵 |
|
图的同质性描述了图中具有相同标签的节点彼此接近的可能性。 |
|
来自"网络中的混合模式"论文的度同配系数。 |
|
对图的边缘应用归一化。 |
|
计算由 |
|
计算由 |
|
返回一个新的张量,该张量根据布尔掩码 |
|
将索引转换为掩码表示。 |
|
将掩码转换为索引表示。 |
|
根据给定的索引或掩码向量选择输入张量或输入列表。 |
|
将输入张量或输入列表缩小到指定范围。 |
|
给定一个稀疏的节点特征批次 \(\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{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times *}\)(其中 \(N_i\) 表示示例 \(i\) 中的元素数量),创建一个 嵌套的 PyTorch 张量。 |
|
给定一个嵌套的PyTorch张量,创建一个连续的张量批次\(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times *}\),并可选地创建一个批次向量,将每个元素分配给特定的示例。 |
|
将密集的邻接矩阵转换为由边索引和边属性定义的稀疏邻接矩阵。 |
|
如果输入 |
|
如果输入的 |
|
将由边索引和边属性定义的稀疏邻接矩阵转换为具有布局torch.sparse_coo的 |
|
将由边索引和边属性定义的稀疏邻接矩阵转换为具有布局torch.sparse_csr的 |
|
将由边索引和边属性定义的稀疏邻接矩阵转换为具有布局torch.sparse_csc的 |
|
将由边索引和边属性定义的稀疏邻接矩阵转换为具有自定义 |
|
将 |
|
稀疏矩阵与密集矩阵的矩阵乘积。 |
|
根据 |
|
根据 |
|
接受一个一维的 |
|
计算由边索引和边属性给出的加权图的归一化割 \(\mathbf{e}_{i,j} \cdot \left( \frac{1}{\deg(i)} + \frac{1}{\deg(j)} \right)\)。 |
|
返回一个具有高度 |
|
计算由 |
|
将给定的边索引和边属性转换为scipy稀疏矩阵。 |
|
将scipy稀疏矩阵转换为边索引和边属性。 |
|
将 |
|
将 |
|
将 |
|
将 |
|
将 |
|
将 |
|
将由 |
|
将 |
|
将 |
|
将 |
|
将 |
|
将 |
|
将SMILES字符串转换为 |
|
将 |
|
返回一个随机Erdos-Renyi图的 |
|
返回一个随机块模型图的 |
|
返回一个Barabasi-Albert优先连接模型的 |
|
从由 |
|
对由 |
|
对于图中由 |
|
随机打乱特征矩阵 |
|
使用伯努利分布的样本,以概率 |
|
随机向 |
|
分子树分解算法来自"Junction Tree Variational Autoencoder for Molecular Graph Generation"论文。 |
|
返回 |
|
修剪 |
|
使用Andersen算法的变体计算所有或部分节点的个性化PageRank(PPR)向量。 |
|
将 |
实用工具包。
- 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:
- 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)return_consecutive (bool, 可选) – 如果设置为
True,将不会 将输出偏移为从0开始每个组。 (默认: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:
- 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:
示例
>>> 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]])
- 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:
- 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:
- 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:
- degree(index: Tensor, num_nodes: Optional[int] = None, dtype: Optional[dtype] = None) Tensor[source]
计算给定一维索引张量的(未加权)度数。
- Parameters:
index (LongTensor) – 索引张量。
num_nodes (int, optional) – 节点的数量,即
max_val + 1的index。(默认值: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:
- 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:
- 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.Tensor 或 List[torch.Tensor], 可选) – 边的权重 或多维边特征。 如果以列表形式给出,将重新洗牌并删除所有 条目中的重复项。(默认值:
None)num_nodes (int, optional) – The number of nodes, i.e.
max_val + 1ofedge_index. (default:None)sort_by_row (bool, 可选) – 如果设置为
False,将会按列/目标节点排序edge_index。 (默认:True)
- Return type:
LongTensor如果未传递edge_attr,否则 (LongTensor,Optional[Tensor]或List[Tensor]])
警告
从 PyG >= 2.3.0 开始,每当
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.Tensor 或 List[torch.Tensor], 可选) – 边的权重 或多维边特征。 如果以列表形式给出,将重新洗牌并删除所有 条目中的重复项。(默认值:
None)num_nodes (int, optional) – The number of nodes, i.e.
max_val + 1ofedge_index. (default:None)reduce (str, optional) – 用于合并边特征的reduce操作 (
"sum","mean","min","max","mul","any"). (默认:"sum")
- Return type:
LongTensor如果未传递edge_attr,否则 (LongTensor,Optional[Tensor]或List[Tensor]])
警告
从 PyG >= 2.3.0 开始,只要
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:
- 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 (Tensor 或 List[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:
LongTensorifedge_attris not passed, else (LongTensor,Optional[Tensor]orList[Tensor]])
警告
From PyG >= 2.3.0 onwards, this function will always return a tuple whenever
edge_attris passed as an argument (even in case it is set toNone).示例
>>> 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 (float 或 Tensor 或 str, 可选) – 生成自环边特征的方式(在
edge_attr != None的情况下)。 如果给定为float或torch.Tensor,自环的边特征将直接由fill_value给出。 如果给定为str,自环的边特征将通过聚合指向特定节点的所有边的特征来计算,根据一个归约操作("add","mean","min","max","mul")。(默认值:1.)num_nodes (int 或 Tuple[int, int], 可选) – 节点的数量, 即
max_val + 1的edge_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 (float 或 Tensor 或 str, 可选) – 生成自环边特征的方式(在
edge_attr != None的情况下)。 如果给定为float或torch.Tensor,自环的边特征将直接由fill_value给出。 如果给定为str,自环的边特征将通过聚合指向特定节点的所有边的特征来计算, 根据一个归约操作。("add","mean","min","max","mul")。(默认值:1.)num_nodes (int, optional) – The number of nodes, i.e.
max_val + 1ofedge_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:
- 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:
- 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:
- 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:
- 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)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 resultingedge_indexwill be relabeled to hold consecutive indices starting from zero. (default:False)num_nodes (int, optional) – The number of nodes, i.e.
max_val + 1ofedge_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:
- 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:
- Return type:
(
LongTensor,BoolTensor或LongTensor)
示例
>>> 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)num_nodes (int, optional) – The number of nodes, i.e.
max_val + 1ofedge_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 + 1ofedge_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]))
- 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 = 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
- assortativity(edge_index: Union[Tensor, SparseTensor]) float[source]
来自“网络中的混合模式”论文的度同配系数。 网络中的同配性指的是节点倾向于与其他相似节点连接,而不是与不相似的节点连接。 它是通过节点度的皮尔逊相关系数计算得出的。
- Parameters:
edge_index (Tensor 或 SparseTensor) – 图的连接性。
- 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 + 1的edge_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:
- 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 + 1ofedge_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')
- get_mesh_laplacian(pos: Tensor, face: Tensor, normalization: Optional[str] = None) Tuple[Tensor, Tensor][source]
计算由
pos和face给出的网格的拉普拉斯算子。计算基于定义的余切矩阵
\[\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:
- Return type:
- mask_select(src: Tensor, dim: int, mask: Tensor) Tensor[source]
返回一个新的张量,该张量根据布尔掩码
mask在维度dim上对src张量进行掩码操作。- Parameters:
src (torch.Tensor) – 输入张量。
dim (int) – 要进行掩码的维度。
mask (torch.BoolTensor) – 包含用于索引的二进制掩码的一维张量。
- Return type:
- index_to_mask(index: Tensor, size: Optional[int] = None) Tensor[source]
将索引转换为掩码表示。
示例
>>> 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:
- mask_to_index(mask: Tensor) Tensor[source]
将掩码转换为索引表示。
- Parameters:
mask (Tensor) – 掩码。
示例
>>> mask = torch.tensor([False, True, False]) >>> mask_to_index(mask) tensor([1])
- Return type:
- select(src: Union[Tensor, List[Any], TensorFrame], index_or_mask: Tensor, dim: int) Union[Tensor, List[Any]][source]
根据给定的索引或掩码向量选择输入张量或输入列表。
- Parameters:
src (torch.Tensor 或 list) – 输入张量或列表。
index_or_mask (torch.Tensor) – 索引或掩码向量。
dim (int) – 选择所沿的维度。
- Return type:
- narrow(src: Union[Tensor, List[Any]], dim: int, start: int, length: int) Union[Tensor, List[Any]][source]
将输入张量或输入列表缩小到指定范围。
- 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:
- 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:
- 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)
- Return type:
- 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()的反向操作。
- 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:
- 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_csr的
torch.sparse.Tensor。 有关反向操作,请参见to_edge_index()。- Parameters:
- 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_csc的
torch.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]
将由边索引和边属性定义的稀疏邻接矩阵转换为具有自定义
layout的torch.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 thatedge_indexis 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.Tensor或torch_sparse.SparseTensor转换为边索引和边属性。- Parameters:
adj (torch.sparse.Tensor 或 SparseTensor) – 邻接矩阵。
- Return type:
示例
>>> 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.Tensor 或 torch_sparse.SparseTensor 或 EdgeIndex) – 输入的稀疏矩阵,可以是 PyG
torch_sparse.SparseTensor, 一个 PyTorchtorch.sparse.Tensor或 一个 PyGEdgeIndex。其他 (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:
- 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_indexaccording to abatchvector.- Parameters:
- 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:
- 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:
- 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]
计算由
pos和face给出的网格的(归一化)测地距离。如果提供了src和dst,则此方法仅计算相应的源节点和目标节点对的测地距离。注意
此函数需要
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 = 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:
- 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.]))
- 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.Data 或 torch_geometric.data.HeteroData) – 一个 同质或异质的数据对象。
node_attrs (可迭代的字符串, 可选) – 要复制的节点属性。(默认:
None)edge_attrs (字符串的可迭代对象, 可选) – 要复制的边属性。(默认:
None)graph_attrs (可迭代的字符串, 可选) – 要复制的图属性。(默认:
None)to_undirected (bool 或 str, 可选) – 如果设置为
True,将返回一个networkx.Graph而不是networkx.DiGraph。 默认情况下,将包括所有边并使它们无向。 如果设置为"upper",无向图将仅对应于输入邻接矩阵的上三角部分。 如果设置为"lower",无向图将仅对应于输入邻接矩阵的下三角部分。 仅在data对象包含同构图时适用。(默认值:False)to_multi (bool, 可选) – 如果设置为
True,将返回一个networkx.MultiGraph或networkx: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:
- 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.Graph或networkx.DiGraph转换为torch_geometric.data.Data实例。- Parameters:
注意
所有
group_node_attrs和group_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:
- 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)
- Return type:
- from_networkit(g: Any) Tuple[Tensor, Optional[Tensor]][source]
将
networkit.Graph转换为(edge_index, edge_weight)元组。 如果networkit.Graph没有权重,返回的edge_weight将是None。
- 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:
- 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:
- 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)
- Return type:
- from_cugraph(g: Any) Tuple[Tensor, Optional[Tensor]][source]
将
cugraph图对象转换为edge_index和可选的edge_weight张量。
- to_dgl(data: Union[Data, HeteroData]) Any[source]
将
torch_geometric.data.Data或torch_geometric.data.HeteroData实例转换为dgl图 对象。- Parameters:
data (torch_geometric.data.Data 或 torch_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:
- from_dgl(g: Any) Union[Data, HeteroData][source]
将
dgl图对象转换为torch_geometric.data.Data或torch_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:
- from_rdmol(mol: Any) Data[source]
将
rdkit.Chem.Mol实例转换为torch_geometric.data.Data实例。- Parameters:
mol (rdkit.Chem.Mol) –
rdkit分子。- Return type:
- to_rdmol(data: Data, kekulize: bool = False) Any[source]
将
torch_geometric.data.Data实例转换为rdkit.Chem.Mol实例。- Parameters:
data (torch_geometric.data.Data) – 分子图数据。
- Return type:
- from_smiles(smiles: str, with_hydrogen: bool = False, kekulize: bool = False) Data[source]
将SMILES字符串转换为
torch_geometric.data.Data实例。
- to_smiles(data: Data, kekulize: bool = False) str[source]
将
torch_geometric.data.Data实例转换为SMILES字符串。- Parameters:
data (torch_geometric.data.Data) – 分子图。
- Return type:
- erdos_renyi_graph(num_nodes: int, edge_prob: float, directed: bool = False) Tensor[source]
Returns the
edge_indexof a random Erdos-Renyi graph.- Parameters:
示例
>>> 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:
- stochastic_blockmodel_graph(block_sizes: Union[List[int], Tensor], edge_probs: Union[List[List[float]], Tensor], directed: bool = False) Tensor[source]
Returns the
edge_indexof a stochastic blockmodel graph.- Parameters:
示例
>>> 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:
- barabasi_albert_graph(num_nodes: int, num_edges: int) Tensor[source]
返回一个Barabasi-Albert优先连接模型的
edge_index,其中num_nodes个节点的图通过连接具有num_edges条边的新节点来增长,这些新节点优先连接到具有高度数的现有节点。- Parameters:
示例
>>> 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:
- 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 + 1ofedge_index. If given as a tuple, thenedge_indexis 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_index和batch给出的多个图中随机抽取负边样本。- Parameters:
edge_index (LongTensor) – The edge indices.
batch (LongTensor 或 Tuple[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:
- 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:
- 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:
- 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” 论文。 返回连接树的图连通性、每个原子到连接树中团的分配映射以及团的数量。
- 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:
- 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.Tensor 或 Dict[NodeType, torch.Tensor]) – 同构或异构的(隐藏)节点特征。
edge_index (torch.Tensor 或 Dict[EdgeType, torch.Tensor]) – 同质或异质边索引。
edge_attr (torch.Tensor 或 Dict[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:
- 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_index、train_pos_neg_adj_mask、val_pos_edge_index、val_neg_edge_index和test_pos_edge_index属性替换edge_index属性。 如果data具有名为edge_attr的边特征,则train_pos_edge_attr、val_pos_edge_attr和test_pos_edge_attr也将被添加。警告
train_test_split_edges()已弃用,并将在未来的版本中移除。 请使用torch_geometric.transforms.RandomLinkSplit代替。- Parameters:
- Return type: