如何对scipy.sparse.csr_matrix类型的矩阵进行元素运算? [英] How to operate elementwise on a matrix of type scipy.sparse.csr_matrix?

查看:752
本文介绍了如何对scipy.sparse.csr_matrix类型的矩阵进行元素运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在numpy中,如果要计算矩阵(元素)的每个条目的窦值,则

a = numpy.arange(0,27,3).reshape(3,3)
numpy.sin(a)

将完成任务!如果您想获得功效,可以说每个条目中的2个

a**2

会做到的.

但是,如果矩阵稀疏,则看起来会更困难.至少除了迭代lil_matrix格式的每个条目并对其进行操作外,我还没有找到一种方法来实现这一点.

我发现此答案,但我没有成功.

目标是逐元素计算CSR格式的scipy.sparse矩阵的平方根(或1/2的幂).

您有什么建议?

解决方案

以下技巧适用于将零映射到零的任何操作,并且仅适用于那些操作,因为它仅涉及非零元素.也就是说,它适用于sinsqrt,但不适用于cos.

X成为一些CSR矩阵...

>>> from scipy.sparse import csr_matrix
>>> X = csr_matrix(np.arange(10).reshape(2, 5), dtype=np.float)
>>> X.A
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.]])

非零元素的值为X.data:

>>> X.data
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

您可以就地更新:

>>> X.data[:] = np.sqrt(X.data)
>>> X.A
array([[ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ],
       [ 2.23606798,  2.44948974,  2.64575131,  2.82842712,  3.        ]])

更新在最新版本的SciPy中,您可以执行X.sqrt()之类的操作,其中X是稀疏矩阵,以获得具有X中元素平方根的新副本. /p>

In numpy if you want to calculate the sinus of each entry of a matrix (elementise) then

a = numpy.arange(0,27,3).reshape(3,3)
numpy.sin(a)

will get the job done! If you want the power let's say to 2 of each entry

a**2

will do it.

But if you have a sparse matrix things seem more difficult. At least I haven't figured a way to do that besides iterating over each entry of a lil_matrix format and operate on it.

I've found this question on SO and tried to adapt this answer but I was not succesful.

The Goal is to calculate elementwise the squareroot (or the power to 1/2) of a scipy.sparse matrix of CSR format.

What would you suggest?

解决方案

The following trick works for any operation which maps zero to zero, and only for those operations, because it only touches the non-zero elements. I.e., it will work for sin and sqrt but not for cos.

Let X be some CSR matrix...

>>> from scipy.sparse import csr_matrix
>>> X = csr_matrix(np.arange(10).reshape(2, 5), dtype=np.float)
>>> X.A
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.]])

The non-zero elements' values are X.data:

>>> X.data
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

which you can update in-place:

>>> X.data[:] = np.sqrt(X.data)
>>> X.A
array([[ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ],
       [ 2.23606798,  2.44948974,  2.64575131,  2.82842712,  3.        ]])

Update In recent versions of SciPy, you can do things like X.sqrt() where X is a sparse matrix to get a new copy with the square roots of elements in X.

这篇关于如何对scipy.sparse.csr_matrix类型的矩阵进行元素运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆