numpy / scipy相当于MATLAB的稀疏函数

时间:2016-11-30 14:31:25

标签: python matlab numpy sparse-matrix

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

这是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]])  

有什么想法吗? 感谢。

2 个答案:

答案 0 :(得分:9)

您正在使用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性能提示。)

(如果您还没有,可能需要阅读NumPy for Matlab users。)

答案 1 :(得分:0)

在这里我做了一次转换。它适用于稀疏的5个参数版本。

adLoader.loadAds(AdRequest.Builder().build(), 1)
相关问题