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, 選擇性
用於指示密集表示法中空邊緣的值。預設值為 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.]])