我在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矩阵相乘,以便结果是形状为res [x.shape [0],y.shape [0],...]的5d矩阵。目前,我正在遵循此代码。
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,...])
还有其他方法可以实现无循环吗?一些更快的NumPy方法?
我认为您可以将x和y的尺寸和值扩展为5,并在新尺寸的4个可用尺寸上重复值,以便x和y具有相同的形状(125,14,3,4,4)。然后,您可以像在嵌套的for循环中一样使用逐元素乘法:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句