[英]How to operate elementwise on a matrix of type scipy.sparse.csr_matrix?
In numpy if you want to calculate the sinus of each entry of a matrix (elementise) then 如果你想计算矩阵(elementise)的每个条目的正弦,那么在numpy中
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 如果你想要电源让我们说每个条目2
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. 至少我还没有找到一种方法来做到这一点,除了遍历lil_matrix格式的每个条目并对其进行操作。
I've found this question on SO and tried to adapt this answer but I was not succesful. 我在SO上发现了这个问题,并尝试调整这个答案,但我没有成功。
The Goal is to calculate elementwise the squareroot (or the power to 1/2) of a scipy.sparse matrix of CSR format. 目标是以元素方式计算CSR格式的scipy.sparse矩阵的平方根(或1/2的幂)。
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. 以下技巧适用于将零映射到零的任何操作,并且仅适用于那些操作,因为它仅触及非零元素。 Ie, it will work for sin
and sqrt
but not for cos
. 即,它适用于sin
和sqrt
但不适用于cos
。
Let X
be some CSR matrix... 设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.]])
The non-zero elements' values are X.data
: 非零元素的值是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的最新版本中,您可以执行X.sqrt()
,其中X
是稀疏矩阵,以获取具有X
中元素的平方根的新副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.