点积的总和有效率

时间:2022-11-24 21:25:42

How do I get the sum of a dot product efficiently

如何有效地获得点积的总和

A =  np.random.rand(20,200)
x=  np.random.rand(20)
y=  np.random.rand(20)
num=  np.zeros(20)
for i in range (A.shape[0]):
    num[i] = np.sum(A.T[i,:].dot(x[i]+y[i]))
print num

Is there a way to find num without a for loop

有没有办法在没有for循环的情况下找到num

1 个解决方案

#1


1  

You could use np.einsum -

你可以使用np.einsum -

num = np.einsum('ji,i->i',A[:,:20],x+y)

That slicing of [:,:20] is needed because even though you are iterating along the rows of A.T with A.T[i,:] i.e. columns of A, you are not iterating through all of those columns.

需要切片[:,:20],因为即使您使用A.T [i,:](即A的列)沿A.T的行迭代,您也不会遍历所有这些列。

#1


1  

You could use np.einsum -

你可以使用np.einsum -

num = np.einsum('ji,i->i',A[:,:20],x+y)

That slicing of [:,:20] is needed because even though you are iterating along the rows of A.T with A.T[i,:] i.e. columns of A, you are not iterating through all of those columns.

需要切片[:,:20],因为即使您使用A.T [i,:](即A的列)沿A.T的行迭代,您也不会遍历所有这些列。