簡體   English   中英

numpy/scipy 等效於 MATLAB 的稀疏函數

[英]numpy/scipy equivalent of MATLAB's sparse function

我正在用 numpy 和 scipy 在 Python 中移植 MATLAB 代碼,我需要使用 numpy/scipy 等效於 MATLAB 中的稀疏函數。

下面是MATLAB中稀疏函數的用法,

sparse([3; 2], [2; 4], [3; 0])

給出:

Trial>> m = sparse([3; 2], [2; 4], [3; 0])

    m =

       (3,2)        3

    Trial>> full(m)

    ans =

         0     0     0     0
         0     0     0     0
         0     3     0     0

我有這些,但它們沒有給出 MATLAB 版本的功能,

sps.csr_matrix([3, 2], [2, 4], [3, 0])
sps.csr_matrix(np.array([[3], [2]]), np.array([[2], [4]]), np.array([[3], [0]])) 
sps.csr_matrix([[3], [2]], [[2], [4]], [[3], [0]])  

有什么想法嗎? 謝謝。

您使用的是sparse(I, J, SV)形式 [注意:鏈接指向 GNU Octave 的文檔,而不是 Matlab]。 scipy.sparse等價物是csr_matrix((SV, (I, J))) - 是的,是一個包含向量和向量的 2 元組的 2 元組的單個參數。 您還必須更正索引向量,因為 Python 始終使用基於 0 的索引。

>>> m = sps.csr_matrix(([3,0], ([2,1], [1,3]))); m
<3x4 sparse matrix of type '<class 'numpy.int64'>'
    with 2 stored elements in Compressed Sparse Row format>

>>> m.todense()
matrix([[0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 3, 0, 0]], dtype=int64)

請注意,與 Matlab 不同,scipy 不會自動丟棄顯式零,並且將使用整數存儲來存儲僅包含整數的矩陣。 要完美匹配您在 Matlab 中獲得的矩陣,您必須明確要求浮點存儲,並且必須對結果調用eliminate_zeros()

>>> m2 = sps.csr_matrix(([3,0], ([2,1], [1,3])), dtype=np.float)
>>> m2.eliminate_zeros()
>>> m2
<3x4 sparse matrix of type '<class 'numpy.float64'>'
    with 1 stored elements in Compressed Sparse Row format>
>>> m2.todense()
matrix([[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  3.,  0.,  0.]])

您也可以將[3,0]更改為[3., 0.]但我建議使用明確的dtype=參數,因為這將防止您在輸入真實數據時出現意外。

(我不知道 Matlab 的內部稀疏矩陣表示是什么,但 Octave 似乎默認為壓縮稀疏表示。CSC 和 CSR 之間的差異應該只會影響性能。如果您的 NumPy 代碼最終比您的 Matlab 代碼慢,請嘗試使用sps.csc_matrix而不是csr_matrix ,以及所有常用的 NumPy 性能技巧。)

(如果你還沒有,你可能需要為 Matlab 用戶閱讀NumPy 。)

這是我所做的轉換。 它適用於 5 個參數版本的 sparse。

def sparse(i, j, v, m, n):
    """
    Create and compressing a matrix that have many zeros
    Parameters:
        i: 1-D array representing the index 1 values 
            Size n1
        j: 1-D array representing the index 2 values 
            Size n1
        v: 1-D array representing the values 
            Size n1
        m: integer representing x size of the matrix >= n1
        n: integer representing y size of the matrix >= n1
    Returns:
        s: 2-D array
            Matrix full of zeros excepting values v at indexes i, j
    """
    return scipy.sparse.csr_matrix((v, (i, j)), shape=(m, n))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM