scipy.sparse.csgraph.csgraph_to_dense¶
- scipy.sparse.csgraph.csgraph_to_dense(csgraph, null_value=0)¶
将稀疏图形表示转换为密集表示
0.11.0 新版功能.
- 参数
- csgraphcsr矩阵、csc矩阵或lil矩阵
图形的稀疏表示。
- null_value浮动,可选
用于指示密集表示中的空边的值。默认值为0。
- 退货
- graphndarray
稀疏图的稠密表示。
注意事项
对于普通稀疏图形表示,使用NULL_VALUE=0调用csgraph_to_dense会产生与在主稀疏包中使用密集格式转换等效的结果。但是,当稀疏表示具有重复值时,结果将不同。scipy.parse中的工具将添加重复值以获得最终值。此函数将在重复值中选择最小值,以获得最终值。例如,这里我们将创建一个具有从节点0到节点1的多条边(权重为2和3)的两节点有向稀疏图。这说明了行为上的差异:
>>> from scipy.sparse import csr_matrix, csgraph >>> data = np.array([2, 3]) >>> indices = np.array([1, 1]) >>> indptr = np.array([0, 2, 2]) >>> M = csr_matrix((data, indices, indptr), shape=(2, 2)) >>> M.toarray() array([[0, 5], [0, 0]]) >>> csgraph.csgraph_to_dense(M) array([[0., 2.], [0., 0.]])
这种差异的原因是允许压缩的稀疏图表示任意两个节点之间的多条边。由于大多数稀疏图算法关注的是任意两个节点之间的单个最低成本边,因此在这种情况下,对多个权重求和的默认scipy.稀疏行为没有意义。
使用此例程的另一个原因是考虑到具有零权重边的图。让我们看一个由权重为零的边连接的两节点有向图的示例:
>>> from scipy.sparse import csr_matrix, csgraph >>> data = np.array([0.0]) >>> indices = np.array([1]) >>> indptr = np.array([0, 1, 1]) >>> M = csr_matrix((data, indices, indptr), shape=(2, 2)) >>> M.toarray() array([[0, 0], [0, 0]]) >>> csgraph.csgraph_to_dense(M, np.inf) array([[inf, 0.], [inf, inf]])
在第一种情况下,零权重边在密集表示中丢失。在第二种情况下,我们可以选择不同的空值并查看图形的真实形式。
示例
>>> from scipy.sparse import csr_matrix >>> from scipy.sparse.csgraph import csgraph_to_dense
>>> graph = csr_matrix( [ ... [0, 1, 2, 0], ... [0, 0, 0, 1], ... [0, 0, 0, 3], ... [0, 0, 0, 0] ... ]) >>> graph <4x4 sparse matrix of type '<class 'numpy.int64'>' with 4 stored elements in Compressed Sparse Row format>
>>> csgraph_to_dense(graph) array([[0., 1., 2., 0.], [0., 0., 0., 1.], [0., 0., 0., 3.], [0., 0., 0., 0.]])