我有一个scipy Compressed Sparse Row(CSR)矩阵,我试图从中提取偏心率以查看信息传播的平均距离。不幸的是,在使用networkx将其转换为networkx图后使用networkx.convert_matrix.from_scipy_sparse_matrix(https://networkx.github.io/documentation/latest/reference/generated/networkx.convert_matrix.from_scipy_sparse_matrix.html)时,我一直无限。
有没有办法可以将连接组件生成的标签集转换回原始值,然后对它们执行单独的偏心公式?
由于图形偏心率是最大最短路径距离,因此使用scipy稀疏矩阵运算可能更容易,更快捷:
import numpy as np
from scipy.sparse.csgraph import connected_components, shortest_path
from scipy.sparse import csr_matrix
def sparse_component_eccentricity(graph, directed=False):
n_components, labels = connected_components(csgraph=graph, directed=directed, return_labels=True)
component_eccentricity = np.zeros(graph.shape[0])
for icomp in range(n_components):
subgraph_indices = np.where(labels == icomp)[0]
subgraph = graph[subgraph_indices][:,subgraph_indices]
dist_matrix = shortest_path(subgraph, directed=directed)
component_eccentricity[subgraph_indices] = np.nanmax(dist_matrix, axis=1)
return component_eccentricity