Python Numpy积还是张量积问题
我如何计算没有循环的乘积?我想我需要使用,但我似乎无法正确设置。以下是循环版本:Python Numpy积还是张量积问题,python,matrix,numpy,linear-algebra,Python,Matrix,Numpy,Linear Algebra,我如何计算没有循环的乘积?我想我需要使用,但我似乎无法正确设置。以下是循环版本: 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,:,:]
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
)这对语法有帮助吗
>>> 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]
...
(from)我把情节弄丢了。答案很简单
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)
如果你设定种子,使用随机测试会容易得多,每个人都可以使用相同的方法。