使用节点 id 在 numpy 中索引矩阵
Indexing matrix in numpy using Node id
有没有办法索引一个 numpy 矩阵,通过 networkx 作为邻接矩阵构建,使用节点名称
(我从 .txt 文件构建了 networkx 图解析行。
每条线代表一条边,形式为SourceNode:DestNode:EdgeWeight
)
我需要矩阵因为我要计算一些节点的命中概率
无论您如何构建图形,都可以计算它的邻接矩阵。 docs 表示如果您不指定,此图中行和列的顺序将是 "as produced by G.nodes()
"。
例如,
# create your graph
G = nx.DiGraph()
with open("spec.txt") as f:
for line in f:
for src, dest, weight in line.split(':'):
G.add_edge(src, dest, weight=weight)
# create adjacency matrix
# - store index now, in case graph is changed.
nodelist = G.nodes()
# extract matrix, and convert to dense representation
A = nx.adjacency_matrix(G, nodelist=nodelist).todense()
# normalise each row by incoming edges, or whatever
B = A / A.sum(axis=1).astype(float)
让我们假设您的节点按字母顺序标记为 C-G。节点排序只是根据字典哈希,这个序列对我来说是:['C', 'E', 'D', 'G', 'F']
。
如果你想从矩阵中查找信息,你可以使用这样的查找:
ix = nodelist.index('D') # ix is 2 here
print A[ix,:]
有没有办法索引一个 numpy 矩阵,通过 networkx 作为邻接矩阵构建,使用节点名称
(我从 .txt 文件构建了 networkx 图解析行。
每条线代表一条边,形式为SourceNode:DestNode:EdgeWeight
)
我需要矩阵因为我要计算一些节点的命中概率
无论您如何构建图形,都可以计算它的邻接矩阵。 docs 表示如果您不指定,此图中行和列的顺序将是 "as produced by G.nodes()
"。
例如,
# create your graph
G = nx.DiGraph()
with open("spec.txt") as f:
for line in f:
for src, dest, weight in line.split(':'):
G.add_edge(src, dest, weight=weight)
# create adjacency matrix
# - store index now, in case graph is changed.
nodelist = G.nodes()
# extract matrix, and convert to dense representation
A = nx.adjacency_matrix(G, nodelist=nodelist).todense()
# normalise each row by incoming edges, or whatever
B = A / A.sum(axis=1).astype(float)
让我们假设您的节点按字母顺序标记为 C-G。节点排序只是根据字典哈希,这个序列对我来说是:['C', 'E', 'D', 'G', 'F']
。
如果你想从矩阵中查找信息,你可以使用这样的查找:
ix = nodelist.index('D') # ix is 2 here
print A[ix,:]