其他分享
首页 > 其他分享> > numpy积或张量积问题

numpy积或张量积问题

作者:互联网

如何无循环计算该乘积?我想我需要使用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)

标签:matrix,linear-algebra,python,numpy
来源: https://codeday.me/bug/20191207/2087591.html