如何将 scipy.sparse.csr 矩阵的元素四舍五入到小数点后两位?
How do round off the elements of scipy.sparse.csr matrix to 2 decimal places ?
由于内存错误,无法转换为numpy数组。
我们可以将np.round
应用于矩阵的data
属性:
In [34]: from scipy import sparse
In [35]: M = sparse.random(5,5,.2,'csr')
In [36]: M
Out[36]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements in Compressed Sparse Row format>
In [37]: M.A
Out[37]:
array([[0. , 0. , 0.28058287, 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0.81478819, 0. , 0. , 0. ],
[0. , 0. , 0. , 0.06805299, 0.51048128],
[0. , 0. , 0. , 0.64388578, 0. ]])
In [38]: M.data
Out[38]: array([0.28058287, 0.81478819, 0.06805299, 0.51048128, 0.64388578])
In [39]: M.data=np.round(M.data,2)
In [40]: M.data
Out[40]: array([0.28, 0.81, 0.07, 0.51, 0.64])
In [41]: M.A
Out[41]:
array([[0. , 0. , 0.28, 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0.81, 0. , 0. , 0. ],
[0. , 0. , 0. , 0.07, 0.51],
[0. , 0. , 0. , 0.64, 0. ]])
由于内存错误,无法转换为numpy数组。
我们可以将np.round
应用于矩阵的data
属性:
In [34]: from scipy import sparse
In [35]: M = sparse.random(5,5,.2,'csr')
In [36]: M
Out[36]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements in Compressed Sparse Row format>
In [37]: M.A
Out[37]:
array([[0. , 0. , 0.28058287, 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0.81478819, 0. , 0. , 0. ],
[0. , 0. , 0. , 0.06805299, 0.51048128],
[0. , 0. , 0. , 0.64388578, 0. ]])
In [38]: M.data
Out[38]: array([0.28058287, 0.81478819, 0.06805299, 0.51048128, 0.64388578])
In [39]: M.data=np.round(M.data,2)
In [40]: M.data
Out[40]: array([0.28, 0.81, 0.07, 0.51, 0.64])
In [41]: M.A
Out[41]:
array([[0. , 0. , 0.28, 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0.81, 0. , 0. , 0. ],
[0. , 0. , 0. , 0.07, 0.51],
[0. , 0. , 0. , 0.64, 0. ]])