Python张量矩阵乘法 [英] Python tensor matrix multiply
本文介绍了Python张量矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有张量
A =
[[[a,b],
[c,d]],
[[e,f],
[g,h]]]
和矩阵
B =
[[1,2],
[3,4]]
我需要获得
C =
[[a*1+e*2,b*1+f*2],
[c*3+g*4,d*3+h*4]]
如何使用矩阵形式的numpy执行此操作?我已经调查过np.tensordot()
,但在这种情况下似乎无济于事.
How can I do this using numpy in matrix form? I've looked into np.tensordot()
but it doesn't seem to help in this case.
推荐答案
您可以尝试以下操作:
>>> import numpy as np
>>> a = np.arange(1,9).reshape(2,2,2)
>>> a
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
>>> b = np.arange(1,5).reshape(2,2)
>>> b
array([[1, 2],
[3, 4]])
>>> (a * b[None,:,:].T).sum(axis = 0)
array([[11, 14],
[37, 44]])
中间步骤如下:
>>> b[None,:,:]
array([[[1, 2],
[3, 4]]])
>>> b[None,:,:].T
array([[[1],
[3]],
[[2],
[4]]])
这篇关于Python张量矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文