add numbers to different dimensions
Numpy / Pytorch
apply different values to different dimensions of an array.
e.g. the data shape is batch x channel x width x height
for every channel, add a different number to all elements of the width x height
this is for simulating different data augmentation per channel.
To achive that, make sure the width and height dimensions are the last dimensions of the shape
Repeat the numbers to be added into a shape matching the channel x width x height
so it can be broadcasted to all batches.
import torch
a = torch.ones((2,3,4,5))
b = torch.tensor([0.1,0.2,0.3])
c = b.repeat_interleave(20).reshape((3,4,5))
a + c
import numpy as np
a = np.ones((2,3,4,5))
b = np.array([0.1,0.2,0.3])
c = b.repeat(20).reshape((3,4,5))
a + c
array([[[[1.1, 1.1, 1.1, 1.1, 1.1],
[1.1, 1.1, 1.1, 1.1, 1.1],
[1.1, 1.1, 1.1, 1.1, 1.1],
[1.1, 1.1, 1.1, 1.1, 1.1]],
[[1.2, 1.2, 1.2, 1.2, 1.2],
[1.2, 1.2, 1.2, 1.2, 1.2],
[1.2, 1.2, 1.2, 1.2, 1.2],
[1.2, 1.2, 1.2, 1.2, 1.2]],
[[1.3, 1.3, 1.3, 1.3, 1.3],
[1.3, 1.3, 1.3, 1.3, 1.3],
[1.3, 1.3, 1.3, 1.3, 1.3],
[1.3, 1.3, 1.3, 1.3, 1.3]]],
[[[1.1, 1.1, 1.1, 1.1, 1.1],
[1.1, 1.1, 1.1, 1.1, 1.1],
[1.1, 1.1, 1.1, 1.1, 1.1],
[1.1, 1.1, 1.1, 1.1, 1.1]],
[[1.2, 1.2, 1.2, 1.2, 1.2],
[1.2, 1.2, 1.2, 1.2, 1.2],
[1.2, 1.2, 1.2, 1.2, 1.2],
[1.2, 1.2, 1.2, 1.2, 1.2]],
[[1.3, 1.3, 1.3, 1.3, 1.3],
[1.3, 1.3, 1.3, 1.3, 1.3],
[1.3, 1.3, 1.3, 1.3, 1.3],
[1.3, 1.3, 1.3, 1.3, 1.3]]]])