问题
If I see the following line in a python code where numpy is imported:
c = a * b
What is the easiest and most practical way to determine if this operation is executed as a Hadamard (elementwise) or dot product (pointwise) operation?
Is it right that for a Hadamard product the column and row size of A and B must be the same. For a dot product only the column size of A must be the same as the row size of B, correct? So I can lookup the shape of both and find out which operation is used?
回答1:
This is discussed in PEP 465. In short, it depends on the types of A and B. If they're numpy.ndarray, star means Hadamard product and matrix multiplication is done with the .dot() method. If they're numpy.matrix, star means matrix multiplication. If they're some other type (e.g. from a library other than NumPy), you'll have to consult that type's documentation. If they're of mixed types, matrix takes priority (according to @ajcr in the comments).
In Python 3.5, this will hopefully be easier, since the @ symbol is being introduced as a dedicated matrix multiplication operator (see the above PEP for details). This won't be backported to 2.7.x, so that's yet another reason to upgrade.
来源:https://stackoverflow.com/questions/30437418/how-can-i-find-out-if-a-b-is-a-hadamard-or-dot-product-in-numpy