Numpy产品或张量产品问题

时间:2011-09-16 15:41:09

标签: python matrix numpy linear-algebra

如何在没有循环的情况下计算此产品?我想我需要使用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,:,:])

(结果是形状为c

的numpy数组(5,5)

2 个答案:

答案 0 :(得分:3)

我失去了情节。答案就是

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)

答案 1 :(得分:0)

这可以帮助您解决语法吗?

>>> 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