1
votes

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?

1
why dont you use numpy matrix?kada
@hadik Ew, don't recommend that.cs95
If you are on a recent Python/NumPy version, you can write x @ A @ y.Paul Panzer
Why does it look counter-intuitive? Are you expecting the final output to be sparsey?Divakar
@PaulPanzer Ah, actually I'm still on Python 2.7...p-value

1 Answers

1
votes

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.