mal*_*sit 2 python matlab numpy sparse-matrix
我正在使用numpy和scipy在Python中移植MATLAB代码,我需要在MATLAB中使用numpy/scipy等效的稀疏函数.
这是MATLAB中稀疏函数的用法,
sparse([3; 2], [2; 4], [3; 0])
Run Code Online (Sandbox Code Playgroud)
得到:
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
Run Code Online (Sandbox Code Playgroud)
我有这些,但他们没有给出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]])
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢.
你正在使用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)
Run Code Online (Sandbox Code Playgroud)
请注意,与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.]])
Run Code Online (Sandbox Code Playgroud)
您也可以更改[3,0]为[3., 0.]但我建议使用明确的dtype=参数,因为这可以防止在您输入实际数据时出现意外情况.
(我不知道Matlab的内部稀疏矩阵表示是什么,但是Octave似乎默认为压缩稀疏列表示.CSC和CSR之间的区别只会影响性能.如果你的NumPy代码最终比你的Matlab代码慢,试试使用sps.csc_matrix代替csr_matrix,以及所有常见的NumPy性能提示.)
(如果你还没有,你可能需要为Matlab用户阅读NumPy.)