I have a simple indexing need that I have no idea how to use numpy to achieve it. It's usually the case that we have two dimensional array of E
with shape(N,C)
, and one dimensional array of y
with shape(N)
, which is a label
matrix, when computing the softmax loss
, there is a widely used operation: E[range(N),y]-=1
, this is very efficient code, Now I have a more generalized problem, that I have array E
of shape(C,H,W)
and label y of shape(H,W)
, now C
axis is the first axis and there is 3 dimension
, how can I do the similar operation like E[range(H,W), y]-=1
Asked
Active
Viewed 30 times
0

K.Wanter
- 969
- 3
- 14
- 30
-
@Divakar, as per numpy: Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view)., I want to change the value of original array with advanced indexing, how can I do it? – K.Wanter Jan 05 '18 at 11:33
-
It should work when assigning. So, simply index and assign. – Divakar Jan 05 '18 at 11:38
-
Tried it on my case, can you points where I'm wrong: `grid = np.ogrid[tuple(map(slice, y.shape))]` then `grid.insert(0, idx)` then `E[tuple(grid)]-=1` prompts:`*** IndexError: index 65535 is out of bounds for axis 0 with size 2` – K.Wanter Jan 05 '18 at 11:47
-
Why not try the func itself : `arr[all_idx(idx, axis)] = new_values`? Did you try that? – Divakar Jan 05 '18 at 11:49
-
Yes, in my case I replace `idx` with `y`, and `axis` with `0`, is that right? – K.Wanter Jan 05 '18 at 11:52
-
Yes and `arr` with `E` I suppose. – Divakar Jan 05 '18 at 12:01
-
@Divakar, thank you, turns out it is my problem, that label is out of range:) – K.Wanter Jan 05 '18 at 12:07