I'm trying to calculate the dot product between a scipy parse matrix and a numpy array.
First I was using a numpy matrix, which you can see in the following code:
def power_iteration(matrix, n):
b_k = np.random.rand(matrix.shape[1])
for _ in range(n):
b_k = np.dot(matrix, b_k)
return b_k
Here the matrix is a numpy matrix and no error occurs.
If you pass a scipy sparse matrix as a parameter, the following error occurs: ValueError: shapes (6762,6762) and (1,6762) not aligned: 6762 (dim 1) != 1 (dim 0)
I have changed
b_k = np.random.rand(matrix.shape[1])
into
b_k = np.random.rand(matrix.shape[1], 1)
which makes the dot product work, but doesn't return the right b_k shape. The shape I need is: (6762,)
Edit: so far I've tried to reshape like this:
b_k = np.reshape(b_k, (matrix.shape[1],))
but this transforms the shape (6762, 1) into (1, 6762), instead of (6762,)
Any tips? Thanks!
b_k
is - is it a 1dndarray
, or a 2d sparse matrix? A sparse matrix is always 2d. What does a dot with such a matrix produce? – hpauljtype
anddtype
ofb_k
after one dot product? Ismatrix
is sparse, thenmatrix.dot(b_k)
, andnp.dot(matrix.b_k)
will produce different objects. Mixing sparse and dense array has to be done with care. And if the intermediateb_k
isnp.matrix
orsparse
matrix, it can't be reshaped to 1d. – hpaulj