Numpy乘积或张量乘积问题

3 投票
2 回答
2056 浏览
提问于 2025-04-17 02:27

我该如何在不使用循环的情况下计算这个乘积呢?我觉得我需要用到 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

2 个回答

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)

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)

撰写回答