【问题标题】:How to set the DGL node features from networkx graph如何从 networkx 图中设置 DGL 节点特征
【发布时间】:2023-01-29 01:56:49
【问题描述】:

我想将 networkx 图转换为 dgl 数据。
但是当我尝试像教程一样使用dgl.from_networkx时,出现了意想不到的结果。

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

#Construct the networkx graph G containing three nodes, 2 undirected edges, 
#and three node attributes (i.e., 3-dimension of node features)
G = nx.Graph()

G.add_nodes_from([
    (1, {"x_0": 0.1, "x_1": 0.3, "x_2": 0.7}),
    (2, {"x_0": 0.1, "x_1": 0.3, "x_2": 0.7}),
    (3, {"x_0": 0.1, "x_1": 0.3, "x_2": 0.7}),
])

G.add_edges_from([(1, 2), (2, 1), (1, 3), (3,1)])

#Additionally, I add this code because the original dataset is called from .csv file.
#So, the below code means the list of features
#.csv file: node(row) x features(colum)
cols = list(["x_0", "x_1", "x_2"])

#Convert networkx from dgl
dgl_graph = dgl.from_networkx(G, node_attrs=cols)

#DGL Result
#Graph(num_nodes=3, num_edges=4,
#      ndata_schemes={'x_0': Scheme(shape=(), dtype=torch.float32), 'x_1': Scheme(shape=(), dtype=torch.float32), 'x_2': Scheme(shape=(), dtype=torch.float32)}
#      edata_schemes={})

当我在 pytorch geometric 中运行它时,它会返回我的想法。

from torch_geometric.utils.convert import from_networkx

pyg_graph = from_networkx(G, group_node_attrs=all)
pyg_graph

#PyG Result
#Data(edge_index=[2, 4], x=[3, 3])

DGL 结果与 PyG 结果是否具有相同的含义? 如果没有,如何将节点属性移动到 DGL 节点功能?

【问题讨论】:

    标签: python networkx pytorch-geometric dgl


    【解决方案1】:

    DGL 结果与 PyG 结果是否具有相同的含义?如果没有,如何将节点属性移动到 DGL 节点功能?

    DGL 图总是有向的,而pyg_graph 将从G(无向)继承属性。这就是为什么 dgl_graph 中的边数是 4,而 pyg_graph 中的边数是 2。

    关于节点属性,已经在dgl_graph里面了,可以使用dgl_graph.ndata查看。

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2021-05-14
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      • 2021-03-13
      相关资源
      最近更新 更多