0

考虑以下玩具 networkx 图:

import networkx as nx
G = nx.DiGraph()
G.add_edges_from([(0, 1), (1, 2), (2, 3)])
G.nodes[0]["weight"] = 0
G.nodes[1]["weight"] = 10
G.nodes[2]["weight"] = 20
G.nodes[3]["weight"] = 30

我想在dgl中使用它,但我不确定如何读取节点权重。我尝试过:

import dgl
dgl.from_networkx(G, node_attrs="weight")

但这给出了:

File ~/venv/lib/python3.8/site-packages/dgl/convert.py:1279, in from_networkx(nx_graph, node_attrs, edge_attrs, edge_id_attr_name, idtype, device)
   1277 for nid in range(g.number_of_nodes()):
   1278     for attr in node_attrs:
-> 1279         attr_dict[attr].append(nx_graph.nodes[nid][attr])
   1280 for attr in node_attrs:
   1281     g.ndata[attr] = F.copy_to(_batcher(attr_dict[attr]), g.device)

KeyError: 'w'

这样做的正确方法是什么?

4

1 回答 1

1

这里的 dgl doc来看,它看起来node_attrs应该是一个属性名称列表。因此,如果您更改dgl.from_networkx(G, node_attrs="weight")dgl.from_networkx(G, node_attrs=["weight"]),您将获得您想要的结果。

请参见下面的代码:

import networkx as nx
import dgl

G = nx.DiGraph()
G.add_edges_from([(0, 1), (1, 2), (2, 3)])
G.nodes[0]["weight"] = 0
G.nodes[1]["weight"] = 10
G.nodes[2]["weight"] = 20
G.nodes[3]["weight"] = 30

dgl.from_networkx(G, node_attrs=["weight"])

并输出:

Graph(num_nodes=4, num_edges=3,
      ndata_schemes={'weight': Scheme(shape=(), dtype=torch.int64)}
      edata_schemes={})
于 2022-01-21T18:12:01.040 回答