p-value
p-value

Reputation: 648

Matrix multiplication of a sparse SciPy matrix with two NumPy vectors

Suppose I want to compute the quadratic form x^T A y, where x and y are NumPy vectors, and I have stored A as a SciPy csc_matrix for efficiency.

It seems that one way to perform the computation is

(x * A).dot(y)

since SciPy uses * for matrix products, and NumPy uses .dot instead.

While this approach gives me the correct answer, it seems rather counter-intuitive to me, and I wonder if there's a more readable/efficient approach?

Upvotes: 2

Views: 2652

Answers (1)

user6655984
user6655984

Reputation:

As Paul Panzer said, x @ A @ y is most readable and works as expected (requires Python 3.5+ and NumPy 1.10+).

SciPy uses dot for matrix multiplication too, in their own examples on sparse matrices page. So you can use dot consistently like

x.dot(A.dot(y))

or A.dot(y).dot(x) although the latter is harder to read because x is out of place.

The only reason you can't use x.dot(A).dot(y) is that NumPy does not understand sparse matrices, so the dot method of x is unsuitable for multiplication by a sparse matrix.

Although SciPy sparse matrices interpret x * A and A * y as matrix multiplication, I prefer to never use that option, because of the risk of wrong operation if A changes to a dense matrix for some reason. It doesn't look like this usage of * is promoted in SciPy documentation; all examples use dot.

Upvotes: 1

Related Questions