If you have a sparse matrix X:
>> print type(X)
<class 'scipy.sparse.csr.csr_matrix'>
…How can you sum the squares of each element in each row, and save them into a list? For example:
>>print X.todense()
[[0 2 0 2]
[0 2 0 1]]
How can you turn that into a list of sum of squares of each row:
[[0²+2²+0²+2²]
[0²+2²+0²+1²]]
or:
[8, 5]
First of all, the csr matrix has a
.summethod (relying on the dot product) which works well, so what you need is the squaring. The simplest solution is to create a copy of the sparse matrix, square its data and then sum it:If you really must save the space, I guess you could just replace
.dataand then replace it back, something along:EDIT: There is actually another nice way, as the csr matrix has a
.multiplymethod for elementwise multiplication:Addition:
Elementwise operations are thus easily done by accessing
csr.datawhich stores the values for all nonzero elements. NOTE: I guess.sum_duplicates()may be necessary, I am not sure what kind of operations would make it necessary.