如何从 networkx 获取节点权重到 dgl
How to get node weights from networkx to dgl
考虑以下 toy 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'
正确的做法是什么?
从the dgl doc here看来,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={})
考虑以下 toy 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'
正确的做法是什么?
从the dgl doc here看来,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={})