我怎样才能知道A * B是在Numpy中是Hadamard还是Dot产品?

时间:2022-03-29 01:30:58

If I see the following line in a python code where numpy is imported:

如果我在python代码中看到输入numpy的代码:

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?

什么是最简单和最实用的方法来确定这个操作是作为一个Hadamard (elementwise)或点产品(pointwise)操作执行的?

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?

对于Hadamard产品来说,a和B的列和行大小必须相同。对于一个点积,只有a的列大小必须等于B的行大小,对吗?所以我可以查找两者的形状并找出使用哪个操作?

1 个解决方案

#1


9  

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).

这是在PEP 465中讨论的。简而言之,这取决于A和b的类型,如果它们是numpy。ndarray, star意味着Hadamard产品和矩阵乘法是用.dot()方法完成的。如果他们numpy。矩阵,恒星表示矩阵乘法。如果它们是其他类型的(例如来自于NumPy之外的库),您将不得不参考该类型的文档。如果它们是混合类型,矩阵会优先考虑(根据@ajcr在评论中)。

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.

在Python 3.5中,这将更容易实现,因为@符号是作为专用矩阵乘法运算符引入的(参见上面的PEP)。这不会被反向移植到2.7。这是另一个升级的理由。

#1


9  

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).

这是在PEP 465中讨论的。简而言之,这取决于A和b的类型,如果它们是numpy。ndarray, star意味着Hadamard产品和矩阵乘法是用.dot()方法完成的。如果他们numpy。矩阵,恒星表示矩阵乘法。如果它们是其他类型的(例如来自于NumPy之外的库),您将不得不参考该类型的文档。如果它们是混合类型,矩阵会优先考虑(根据@ajcr在评论中)。

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.

在Python 3.5中,这将更容易实现,因为@符号是作为专用矩阵乘法运算符引入的(参见上面的PEP)。这不会被反向移植到2.7。这是另一个升级的理由。