缩放 3D 张量行 [英] Scale rows of 3D-tensor
问题描述
我有一个 n
-by-3
-by-3
numpy 数组 A
和一个 n
-by-3
numpy 数组 B
.我现在想将每个 n
3
-by-3
矩阵的每一 row 与B
中对应的标量,即
I have an n
-by-3
-by-3
numpy array A
and an n
-by-3
numpy array B
. I'd now like to multiply every row of every one of the n
3
-by-3
matrices with the corresponding scalar in B
, i.e.,
import numpy as np
A = np.random.rand(10, 3, 3)
B = np.random.rand(10, 3)
for a, b in zip(A, B):
a = (a.T * b).T
print(a)
这也可以不用循环来完成吗?
Can this be done without the loop as well?
推荐答案
您可以使用 NumPy 广播
在添加单例维度后将 B
扩展到 3D
后,让元素乘法以矢量化的方式发生最后是 np.newaxis
或其别名/速记 None
.因此,实现将是 A*B[:,:,None]
或简单地 A*B[...,None]
.
You can use NumPy broadcasting
to let the elementwise multiplication happen in a vectorized manner after extending B
to 3D
after adding a singleton dimension at the end with np.newaxis
or its alias/shorthand None
. Thus, the implementation would be A*B[:,:,None]
or simply A*B[...,None]
.
这篇关于缩放 3D 张量行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!