Scale rows of 3D-tensor

ぃ、小莉子 提交于 2020-01-19 18:03:15

问题


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?


回答1:


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].



来源:https://stackoverflow.com/questions/38224985/scale-rows-of-3d-tensor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!