简体   繁体   English

我如何知道在 numpy 中实现 function 时是否需要使用 np.dot() 或 * 运算符?

[英]How do I know if I need to use np.dot() or * operator when implementing a function in numpy?

I would like to implement the following mathematical formulas to calculate a cost function J in numpy:我想实现以下数学公式来计算 numpy 中的成本 function J:

    [1] 𝐴=𝜎(𝑤.𝑇𝑋+𝑏)=(𝑎(1),𝑎(2),...,𝑎(𝑚−1),𝑎(𝑚))

    [2] 𝐽=−1/𝑚 ∑𝑚𝑖=1(𝑦(𝑖)log(𝑎(𝑖))+(1−𝑦(𝑖))log(1−𝑎(𝑖)))

Therefore given:因此给出:

  • w, b, X, Y w, b, X, Y

I already found a solution, but I do not understand why it works that way:我已经找到了解决方案,但我不明白为什么会这样:

 A = sigmoid(np.dot(w.T,X)+b)
 cost = -(1/m) * np.sum((Y*np.log(A))+(1-Y)*np.log(1-A))

My question is: How do I know when to use np.dot for Multiplication and when to use * Operator?我的问题是:我怎么知道什么时候使用 np.dot 进行乘法运算以及什么时候使用 * 运算符? For example, why is w.TX (from formula 1) impelemted by np.dot(wT,X) and not by wT *X?例如,为什么w.TX(来自公式 1)是由 np.dot(wT,X) 而不是 wT *X 推动的?

How do I know to use np.dot() and when to use * Operator when implemening a function in numpy?在 numpy 中实现 function 时,我如何知道使用 np.dot() 以及何时使用 * 运算符?

yes its confusing but you should use the np.dot() function when you want to perform matrix multiplication because it follows the standard rules for matrix multiplication and the * operator when you want to perform element-wise multiplication because it multiplies the corresponding elements of two arrays, regardless of their shape.是的,它令人困惑但是当你想执行矩阵乘法时你应该使用 np.dot() function 因为它遵循矩阵乘法的标准规则和 * 运算符当你想执行逐元素乘法时因为它乘以相应的元素两个 arrays,不管它们的形状如何。

NOTE:using * operator, it's faster than using np.dot() especially when you have large matrices.注意:使用 * 运算符比使用 np.dot() 更快,尤其是当您有大矩阵时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM