Issue
I have a multidimensional array and a set of scale factors that I want to apply along the first axis:
>>> data.shape, scale_factors.shape
((22, 20, 2048, 2048), (22,))
>>> data * scale_factors
ValueError: operands could not be broadcast together with shapes (22,20,2048,2048) (22,)
I can do this with apply_along_axis, but is there a vectorized way to do this? I found a similar question, but the solution is specific to a 1-D * 2-D operation. The "data" ndarray will not always be the same shape, and won't even always have the same number of dimensions. But the length of the 1-D scale_factors will always be the same as axis 0 of data.
Solution
You can try reshape the data
into 2D, then broadcast scale_factor
to 2D, and reshape back:
(data.reshape(data.shape[0], -1) * scale_factors[:,None]).reshape(data.shape)
Or, you can swap the 0
-th axis to the last so you can broadcast:
(data.swapaxes(0,-1) * scale_factors).swapaxes(0,-1)
Answered By - Quang Hoang
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.