将numpy数组中的每个元素相乘并求和

时间:2020-12-23 19:34:06

I have two numpy arrays, X and y. X is of size m, and y is of size n. I need to multiply each element of y by every element of X, and then sum up.

我有两个numpy数组,X和y, X的大小是m, y的大小是n,我需要把y的每个元素乘以X的每个元素,然后求和。

Something like [sum(X[0]*y) sum(X[1]*y) sum(X[n]*y)]

类似[总和(X[0]* y)和(X[1]* y)和(X[n]* y)]

This is what I mean

这就是我的意思

np.sum(X[:, np.newaxis] * y, axis=1)

However typically X and y are really large and so doing

但是通常X和y都很大

X[:, np.newaxis] * y

creates a huge temporary array, which blows up stuff. Is there a better way of implementing this?

创建一个巨大的临时数组,它会爆炸东西。有更好的方法来实现这一点吗?

1 个解决方案

#1


4  

If you're multiplying each element of y by every element of X, just multiply all the elements of X together first, then use multiply the array y by this number and sum:

如果你把y的每个元素乘以X的每个元素,先把X的所有元素相乘,然后用数组y乘以这个数,然后求和:

num = X.prod()

(num * y).sum()

Edit: the array you specify can be obtained by multiplying the array X by the sum of the elements of y:

编辑:您指定的数组可以通过将数组X乘以y元素的和得到:

X * y.sum()

#1


4  

If you're multiplying each element of y by every element of X, just multiply all the elements of X together first, then use multiply the array y by this number and sum:

如果你把y的每个元素乘以X的每个元素,先把X的所有元素相乘,然后用数组y乘以这个数,然后求和:

num = X.prod()

(num * y).sum()

Edit: the array you specify can be obtained by multiplying the array X by the sum of the elements of y:

编辑:您指定的数组可以通过将数组X乘以y元素的和得到:

X * y.sum()