我希望标准化从 networkx 有向图获得的稀疏 scipy 矩阵的每一行。
import networkx as nx
import numpy as np
G=nx.random_geometric_graph(10,0.3)
M=nx.to_scipy_sparse_matrix(G, nodelist=G.nodes())
from __future__ import division
print(M[3])
(0, 1) 1
(0, 5) 1
print(M[3].multiply(1/M[3].sum()))
(0, 1) 0.5
(0, 5) 0.5
这没关系,我像往常一样正常化并且它按预期工作。 但如果我写:
>>> M[3]=M[3].multiply(1/M[3].sum())
>>> M[3]
<1x10 sparse matrix of type '<type 'numpy.int64'>'
with 10 stored elements in Compressed Sparse Row format>
(0, 0) 0
(0, 1) 0
(0, 2) 0
(0, 3) 0
(0, 4) 0
(0, 5) 0
(0, 6) 0
(0, 7) 0
(0, 8) 0
(0, 9) 0
我只需要迭代每一行并对这个稀疏 scipy 矩阵进行标准化。 你会怎么做? 谢谢
最佳答案
这是一种方法(来自networkx.pagerank_scipy)。它使用 scipy 线性代数函数而不是迭代每一行。对于大图来说这可能会更快。
In [42]: G=nx.random_geometric_graph(5,0.5)
In [43]: M=nx.to_scipy_sparse_matrix(G, nodelist=G.nodes(), dtype=float)
In [44]: M.todense()
Out[44]:
matrix([[ 0., 1., 0., 1., 1.],
[ 1., 0., 0., 0., 1.],
[ 0., 0., 0., 1., 1.],
[ 1., 0., 1., 0., 1.],
[ 1., 1., 1., 1., 0.]])
In [45]: S = scipy.array(M.sum(axis=1)).flatten()
In [46]: S[S != 0] = 1.0 / S[S != 0]
In [47]: Q = scipy.sparse.spdiags(S.T, 0, *M.shape, format='csr')
In [48]: (Q*M).todense()
Out[48]:
matrix([[ 0. , 0.33333333, 0. , 0.33333333, 0.33333333],
[ 0.5 , 0. , 0. , 0. , 0.5 ],
[ 0. , 0. , 0. , 0.5 , 0.5 ],
[ 0.33333333, 0. , 0.33333333, 0. , 0.33333333],
[ 0.25 , 0.25 , 0.25 , 0.25 , 0. ]])
关于python-2.7 - 归一化矩阵行 scipy 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30260642/