I have an array a:
array([[[[14, 59, 18, 92],
[91, 38, 58, 23],
[33, 52, 93, 68],
[19, 21, 50, 77]],
[[90, 37, 22, 55],
[56, 54, 10, 16],
[83, 20, 36, 3],
[84, 87, 85, 81]]],
[[[ 0, 45, 72, 5],
[49, 46, 94, 53],
[34, 51, 75, 8],
[27, 79, 35, 15]],
[[ 7, 86, 64, 31],
[12, 70, 89, 62],
[13, 63, 88, 25],
[39, 11, 26, 6]]]])
I also have a mask b:
array([[[[ 0., 0., 0., 1.],
[ 1., 0., 0., 0.],
[ 0., 1., 1., 0.],
[ 0., 0., 0., 0.]],
[[ 0., 0., 0., 0.],
[ 1., 0., 1., 0.],
[ 0., 0., 0., 0.],
[ 0., 1., 1., 0.]]],
[[[ 0., 0., 0., 0.],
[ 1., 0., 1., 0.],
[ 0., 0., 1., 0.],
[ 0., 1., 0., 0.]],
[[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 1., 1., 0.],
[ 0., 0., 0., 0.]]]])
How can I modify those elements of the array a, which correspond to the ones in the mask b?
In particular, I have an array c:
array([[[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]]],
[[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]]])
How can I add c to a, so that only elements indicated by mask b will be added to?
(This is what I need to do to backpropagate errors through the max-pooling layer in a convolutional neural network)
That's quite easy if you interpret your b
as boolean mask:
b_mask = b.astype(bool)
d = a.copy()
d[b_mask] = a[b_mask] + c.ravel()
d
giving me
array([[[[ 14, 59, 18, 92],
[ 92, 38, 58, 23],
[ 33, 54, 96, 68],
[ 19, 21, 50, 77]],
[[ 90, 37, 22, 55],
[ 60, 54, 15, 16],
[ 83, 20, 36, 3],
[ 84, 93, 92, 81]]],
[[[ 0, 45, 72, 5],
[ 57, 46, 103, 53],
[ 34, 51, 85, 8],
[ 27, 90, 35, 15]],
[[ 7, 98, 64, 31],
[ 12, 70, 102, 62],
[ 13, 77, 103, 25],
[ 39, 11, 26, 6]]]])
or if you want it in-place:
b_mask = b.astype(bool)
a[b_mask] = a[b_mask] + c.ravel()
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.