I am sorry that the title of my question may sound vague, since I do not know the exact name of such operation.
Given a tensor A
(N×M×M) and a one-dimension array b
(N), I would like to get another tensor B
(N×M×M) such that each item (M×M) in B
is the multiplication between A
and b
.
A possible but ugly solution is to flatten(reshape) A
firstly, ie, converting A
into a 2D array, then apply a dot
operation, and finally reshape back.
Is there any standard/simple operation in numpy
to achieve this?
For example,
A = np.ones(12).reshape(3, 2, 2)
b = np.array([2, 3, 4])
The expected B
is
[[[2, 2],
[2, 2]],
[[3, 3],
[3, 3]],
[[4, 4],
[4, 4]]]
What you are looking for is broadcasting ; in two words, reshape your array b
with the value 1
in some dimensions in order to get more control on what will happen; the total number of elements in b
will remain unchanged but you may choose how the array will behave during the arithmetic operation:
A*b.reshape((3,1,1))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.