缩放3D张量的行 [英] Scale rows of 3D-tensor
本文介绍了缩放3D张量的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个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?
推荐答案
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屋!
查看全文