我有两个形状为:
的ndarray:A = (32,512,640)
B = (4,512)
我需要将A和B相乘,以便得到一个新的ndarray:
C = (4,32,512,640)
另一种思考方式是将向量B的每一行沿着A的axis=-2进行乘法运算,这会生成一个新的1,32,512,640的立方体。可以遍历B的每一行,生成1,32,512,640个立方体,然后使用np.concatenate
或np.vstack
来构建C,例如:
# Sample inputs, where the dimensions aren't necessarily known
a = np.arange(32*512*465, dtype='f4').reshape((32,512,465))
b = np.ones((4,512), dtype='f4')
# Using a loop
d = []
for row in b:
d.append(np.expand_dims(row[None,:,None]*a, axis=0))
# Or using list comprehension
d = [np.expand_dims(row[None,:,None]*a,axis=0) for row in b]
# Stacking the final list
result = np.vstack(d)
但我想知道是否有可能使用类似于
np.einsum
或np.tensordot
这样的方法来一次性进行矢量化。 我仍在学习如何使用这两种方法,所以我不确定它是否适用于此处。谢谢!