NumPy:在两个4D矩阵中乘以每对3D矩阵的有效方法?

2024-06-01 09:14:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个NumPy的4d矩阵,它们的高度、宽度和深度是相同的

x = np.random.random((125,3,4,4)).astype(np.float32)
y = np.random.random((14,3,4,4)).astype(np.float32)

我想将x中的每个3d矩阵与y中的每个3d矩阵相乘,这样结果就是一个5d矩阵,其形状res[x.shape[0],y.shape[0],…]。目前,我正在遵循此代码

xb,xd,xh,xw = x.shape
yb,yd,yh,yw = y.shape

res = np.zeros((xb,yb,xd,xh,xw))
for i in range(xb):
    for j in range(yb):
        res[i,j,...] = np.multiply(x[i,...],y[j,...])

有没有其他方法可以在没有循环的情况下实现这一点?更快的方式


Tags: infornprangeres矩阵randomshape
1条回答
网友
1楼 · 发布于 2024-06-01 09:14:26

我认为可以将x和y的尺寸和扩展为5,并在新尺寸上重复可用的4个尺寸上的值,以便x和y具有相同的(125,14,3,4,4)形状。然后,您可以像在嵌套for循环中一样使用elementwise乘法:

x = np.random.random((125,3,4,4)).astype(np.float32)
y = np.random.random((14,3,4,4)).astype(np.float32)
x = np.repeat(x[:,np.newaxis,:,:,:], 14, axis=1)
y = np.repeat(y[np.newaxis,:,:,:,:], 125, axis=0)
xy = np.multiply(x,y)

相关问题 更多 >