To process to output of a multi-class classification I'd like to process a numpy array in such a way, that every True
from the first column results in a class1
and a True
in class2
correspondingly. A row with no True
's should be translated into class3
.
My initial array looks like that:
[[True False],
[False False],
[False True],
...
[True False],
[False True]]
(A row containing [True True] can not arise.)
What I'd like to get out is:
[class1 class3 class2 ... class1 class2]
Ideas for an elegant and fast approach are highly appreciated. Thanks in advance!
CodePudding user response:
You can use numpy.select
.
import numpy as np
cls = np.array([[True, False],[False, False],[False, True],[True, False],[False, True]])
mask = cls.any(-1)
condlist = [(mask & cls[..., 0]),
(mask & cls[..., 1]),
(mask==False)]
choicelist = ['class1', 'class2', 'class3']
res = np.select(condlist, choicelist, 'Not valid')
print(res)
Output:
['class1' 'class3' 'class2' 'class1' 'class2']
CodePudding user response:
Using Python 3.10 syntax:
def replace_array(a):
out = []
for element in a:
match element:
case True, False:
out.append("class1") # Or an actual class, depending
case False, True:
out.append("class2") # Or an actual class, depending
case False, False:
out.append("class3") # Or an actual class, depending
case _:
raise Exception()
return out