scipy.sparse.csgraph.
csgraph_to_dense#
- scipy.sparse.csgraph.csgraph_to_dense(csgraph, null_value=0)#
将稀疏图表示转换为密集表示
0.11.0 版本中新增。
- 参数:
- csgraphcsr_array, csc_array, 或 lil_array
图的稀疏表示。
- null_valuefloat, optional (可选)
用于指示密集表示中的空边的值。默认值为 0。
- 返回:
- graphndarray
稀疏图的密集表示。
注释
对于正常的稀疏图表示,调用 null_value=0 的 csgraph_to_dense 会产生与在主稀疏包中使用密集格式转换等效的结果。但是,当稀疏表示具有重复值时,结果会有所不同。 scipy.sparse 中的工具将添加重复值以获得最终值。此函数将选择重复值中的最小值以获得最终值。例如,这里我们将创建一个具有从节点 0 到节点 1 的多个边的两节点有向稀疏图,权重为 2 和 3。这说明了行为上的差异
>>> from scipy.sparse import csr_array, csgraph >>> import numpy as np >>> data = np.array([2, 3]) >>> indices = np.array([1, 1]) >>> indptr = np.array([0, 2, 2]) >>> M = csr_array((data, indices, indptr), shape=(2, 2)) >>> M.toarray() array([[0, 5], [0, 0]]) >>> csgraph.csgraph_to_dense(M) array([[0., 2.], [0., 0.]])
这种差异的原因是允许压缩稀疏图表示任意两个节点之间的多条边。由于大多数稀疏图算法都关注任意两个节点之间的单个最低成本边,因此在这种情况下,scipy.sparse 默认的加权多个权重的行为没有意义。
使用此例程的另一个原因是允许具有零权重边的图。让我们看一下一个由权重为零的边连接的两个节点有向图的例子
>>> from scipy.sparse import csr_array, csgraph >>> data = np.array([0.0]) >>> indices = np.array([1]) >>> indptr = np.array([0, 1, 1]) >>> M = csr_array((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_array >>> from scipy.sparse.csgraph import csgraph_to_dense
>>> graph = csr_array( [ ... [0, 1, 2, 0], ... [0, 0, 0, 1], ... [0, 0, 0, 3], ... [0, 0, 0, 0] ... ]) >>> graph <Compressed Sparse Row sparse array of dtype 'int64' with 4 stored elements and shape (4, 4)>
>>> csgraph_to_dense(graph) array([[0., 1., 2., 0.], [0., 0., 0., 1.], [0., 0., 0., 3.], [0., 0., 0., 0.]])