'Efficiently consolidate matches by class ID in numpy
I'm working on a machine learning task where I'm correlating a set of (Ni) instances with a set of (Nr) annotated regions, that correspond to particular (Nc) classes.
As an analogy, let's imagine we have a satellite picture with lots of animals in. We already know where all the animals are, but somebody's drawn boxes/circles/polygons/whatever around groups of them - to tag them as particular species (horse, cow, chicken, etc).
I already have:
- A
matches (Ni, Nr)matrix which describes whether each instance falls within each annotated region - A
class_ids (Nr,)array describing the class ID of each region (0 to Nc-1)
I'm looking for an efficient way to get to an (Ni, Nc) result matrix which is 1 where any annotated region for class c captured instance i - and 0 otherwise.
It feels like there should be some magic indexing/assignment operator(s) that would help with this but I'm just not seeing it.
For example the following doesn't quite work:
# Example inputs
Nc = 6 # (Nr = 3, Ni = 5 below)
class_ids = np.array([2, 5, 5])
matches = np.array([
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 1, 1],
[1, 1, 0],
])
# Non-working method:
result = np.zeros((Ni, Nc))
result[:, class_ids] = matches
# Result:
# Sets `i, c` to 1 only where the *last* annotation of type `c` in the list
# matched that instance.
array([
[0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.], # Final should be 1
[0., 0., 0., 0., 0., 1.],
[0., 0., 1., 0., 0., 0.], # Final should be 1
])
I understand of course there are for loop-y ways of doing this by starting with result = np.zeros((Ni, Nc)) and then iteratively patching it from the matches, but felt like there should be some better, direct/vectorized way. Maybe there is some option to do a partitioned max on matches and then the assignment? Hope some numpy wizard can see something I'm missing
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
