简体   繁体   English

在没有for循环的情况下在python中获取两个数组的点积

[英]Taking the dot product of two arrays in python without for loops

I have two arrays W and x . 我有两个数组Wx W has the shape (16, 10) and x has the shape (10000, 16) . W的形状为(16, 10)x的形状为(10000, 16) I need to take the dot product between the transpose of W and x . 我需要在Wx的转置之间取点积。 The problem is that the shapes of x and W are very different so I keep getting an error when trying to do this. 问题在于xW的形状非常不同,因此在尝试执行此操作时会出现错误。 Of course I can do this with for loops but I want to do it without using any for loops. 当然,我可以使用for循环来做到这一点,但是我想不使用任何for循环来做到这一点。

for i in range(x.shape[0])
    s = (np.dot(W.transpose(), x[i])) + b

The above code produces an array, s , which consists of 10 entries. 上面的代码生成一个数组s ,该数组包含10个条目。 I'm trying to get s to be 10,000 lines with 10 entries in each line (without using a for loop). 我试图使s为10,000行,每行10个条目(不使用for循环)。

You're probably looking for 您可能正在寻找

s = x.dot(W)

Or 要么

s = x @ W

dot behaves as a for product for simple 1D vectors, but is full blown matrix multiplication otherwise. dot行为与简单一维向量的乘积相同,但在其他情况下则为完整矩阵乘法。 Since you want a (10000, 10) result shape, you need to set up your matrices to have that shape in the outer dimensions, and match the inner ones: 由于您想要一个(10000, 10)结果形状,因此需要设置矩阵以在外部尺寸中具有该形状,并与内部尺寸匹配:

(10000, 16) x (16, 10) -> (10000, 10)

To perform the sum in whatever order you want, you can use np.einsum : 要以任意顺序执行总和,可以使用np.einsum

s= np.einsum('ik,ji->jk', W, x)

Or simply 或者简单地

s = np.einsum('ik,ji', W, x)

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

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