dgl.from_networkx

dgl.from_networkx(nx_graph, node_attrs=None, edge_attrs=None, edge_id_attr_name=None, idtype=None, device=None)[source]

从NetworkX图创建一个图并返回。

注意

从NetworkX图创建DGLGraph的速度并不快,尤其是在大规模情况下。 建议首先将NetworkX图转换为节点张量的元组, 然后使用dgl.graph()构建DGLGraph。

Parameters:
  • nx_graph (networkx.Graph) – 包含图结构及节点/边属性的NetworkX图。 如果节点标签不是从零开始的连续整数,DGL将重新标记节点。如果输入图是无向的,DGL会通过networkx.Graph.to_directed()将其转换为有向图。

  • node_attrs (list[str], optional) – 要从NetworkX图中检索的节点属性的名称。如果提供,DGL会将检索到的节点属性存储在返回图的ndata中,并使用它们的原始名称。属性数据必须可转换为Tensor类型(例如,标量、numpy.ndarray、列表等)。

  • edge_attrs (list[str], optional) – 要从NetworkX图中检索的边属性的名称。如果提供,DGL会将检索到的边属性存储在返回图的edata中,并使用它们的原始名称。属性数据必须可转换为Tensor类型(例如,标量、numpy.ndarray、列表等)。如果nx_graph是无向图,则必须为None。

  • edge_id_attr_name (str, optional) – 存储边ID的边属性的名称。如果指定,DGL在创建图时将根据此属性分配边ID,因此该属性必须是有效的ID,即从零开始的连续整数。默认情况下,返回图的边ID可以是任意的。如果nx_graph是无向的,则必须为None。

  • idtype (int32 or int64, optional) – The data type for storing the structure-related graph information such as node and edge IDs. It should be a framework-specific data type object (e.g., torch.int32). By default, DGL uses int64.

  • device (device context, optional) – The device of the resulting graph. It should be a framework-specific device object (e.g., torch.device). By default, DGL stores the graph on CPU.

Returns:

创建的图表。

Return type:

DGLGraph

注释

DGL internally maintains multiple copies of the graph structure in different sparse formats and chooses the most efficient one depending on the computation invoked. If memory usage becomes an issue in the case of large graphs, use dgl.DGLGraph.formats() to restrict the allowed formats.

示例

以下示例使用PyTorch后端。

>>> import dgl
>>> import networkx as nx
>>> import numpy as np
>>> import torch

创建一个2边的NetworkX图。

>>> nx_g = nx.DiGraph()
>>> # Add 3 nodes and two features for them
>>> nx_g.add_nodes_from([0, 1, 2], feat1=np.zeros((3, 1)), feat2=np.ones((3, 1)))
>>> # Add 2 edges (1, 2) and (2, 1) with two features, one being edge IDs
>>> nx_g.add_edge(1, 2, weight=np.ones((1, 1)), eid=np.array([1]))
>>> nx_g.add_edge(2, 1, weight=np.ones((1, 1)), eid=np.array([0]))

将其转换为仅包含结构的DGLGraph。

>>> g = dgl.from_networkx(nx_g)

检索图的节点/边特征。

>>> g = dgl.from_networkx(nx_g, node_attrs=['feat1', 'feat2'], edge_attrs=['weight'])

使用预定的边顺序。

>>> g.edges()
(tensor([1, 2]), tensor([2, 1]))
>>> g = dgl.from_networkx(nx_g, edge_id_attr_name='eid')
(tensor([2, 1]), tensor([1, 2]))

在第一个GPU上创建一个数据类型为int32的图形。

>>> g = dgl.from_networkx(nx_g, idtype=torch.int32, device='cuda:0')

另请参阅

graph, from_scipy