简体   繁体   English

了解 numpy.dot() 的规则

[英]Understanding the rule of numpy.dot()

I am trying to understand the following rule of numpy.dot():我试图理解 numpy.dot() 的以下规则:

"When a is ND array, b is MD array(where M>=2). The dot product is defindes as the sum product over the last axis of a and the second-to-last axis of b" “当 a 是 ND 数组时,b 是 MD 数组(其中 M>=2)。点积定义为 a 的最后一个轴和 b 的倒数第二个轴的和积”

What I want to understand is, how the calculation looks in detail for a specific example:我想了解的是,具体示例的计算细节如何:

a = np.array([[[2,3,4],[5,6,7],[1,2,3]],[[1,3,4],[7,1,2],[6,2,1]]])

print(a)

    [[[2 3 4]
    [5 6 7]
    [1 2 3]]

    [[1 3 4]
    [7 1 2]
    [6 2 1]]]

b = np.array([[1 , 2, 3],[4, 5 ,6],[7, 8, 9]])

print (b)

b = [[1 2 3]
    [4 5 6]
    [7 8 9]] 

np.dot(a,b) = [[[ 42  51  60]
              [ 78  96 114]
              [ 30  36  42]]

              [[ 41  49  57]
              [ 25  35  45]
              [ 21  30  39]]]
  • How to I get the first value "42" of the dot product?如何获得点积的第一个值“42”?
  • What is the last axis of a and what is the second-to last axis of b? a 的最后一个轴是什么,b 的倒数第二个轴是什么?

I couldn't seem to figure out how to get the first value.我似乎无法弄清楚如何获得第一个值。 I understood the other rules of the numpy.dot() definition, but not this last one.我了解 numpy.dot() 定义的其他规则,但不了解最后一条。

From the documentation ofnumpy.dot :来自numpy.dot的文档:

If a is an ND array and b is an MD array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:如果 a 是 ND 数组,b 是 MD 数组(其中 M>=2),则它是 a 的最后一个轴与 b 的倒数第二个轴的和积:

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

In your example, a has shape (2,3,3) and the axis are (0,1,2).在您的示例中, a形状为 (2,3,3),轴为 (0,1,2)。 So the last axis of a is 2. b has shape (3,3) and axis are (0,1).所以a的最后一个轴是 2。b 的形状是b 3,3),轴是 (0,1)。 The meaning of second to last axis is penultimate axis.倒数第二个轴的意思是倒数第二个轴。 Since b has just 2 axis, the penultimate axis is 0.由于 b 只有 2 个轴,倒数第二个轴为 0。

Data along last axis of a: [2,3, 4] Data along penultimate axis of b: [1, 4,7]沿 a 的最后一个轴的数据:[2,3, 4] 沿 b 的倒数第二个轴的数据:[1, 4,7]

sum product = sum([2*1,3*4,4*7]) = 42.总和乘积 = sum([2*1,3*4,4*7]) = 42。

Same logic can be applied for all values of the output.可以对 output 的所有值应用相同的逻辑。

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

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