How can I find out if A * B is a Hadamard or Dot Product in Numpy?

天涯浪子 提交于 2021-02-07 10:08:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!