如何在没有循环的情况下计算这个乘积?我想我需要使用numpy.tensordot
,但我似乎不能正确设置它。下面是循环版本:
import numpy as np
a = np.random.rand(5,5,3,3)
b = np.random.rand(5,5,3,3)
c = np.zeros(a.shape[:2])
for i in range(c.shape[0]):
for j in range(c.shape[1]):
c[i,j] = np.sum(a[i,j,:,:] * b[i,j,:,:])
(结果是形状为(5,5)
的numpy数组c
)
我看不懂剧情了。答案很简单
c = a * b
c = np.sum(c,axis=3)
c = np.sum(c,axis=2)
或一行
c = np.sum(np.sum(a*b,axis=2),axis=2)
这对语法有帮助吗?
>>> from numpy import *
>>> a = arange(60.).reshape(3,4,5)
>>> b = arange(24.).reshape(4,3,2)
>>> c = tensordot(a,b, axes=([1,0],[0,1])) # sum over the 1st and 2nd dimensions
>>> c.shape
(5,2)
>>> # A slower but equivalent way of computing the same:
>>> c = zeros((5,2))
>>> for i in range(5):
... for j in range(2):
... for k in range(3):
... for n in range(4):
... c[i,j] += a[k,n,i] * b[n,k,j]
...
(来自http://www.scipy.org/Numpy_Example_List head-a46c9c520bd7a7b43e0ff166c01b57ec76eb96c7)