Numpy reverse keras to_categorical

Viewed 17127

In keras I have used to_categorical to convert by binary nx1 vector y to a nx2 matrix where the first columns is 1 if y=1 and the second column is y=0. How do I reverse this action using numpy?

4 Answers

Simple.

numpy.argmax(a, axis=None, out=None)

This returns the indices of the maximum values along an axis.

Adding to MazeRunner09's answer. If you used to_categorical from keras, you will have a list and can use a list comprehension over the entire one-hot encoded list:

y_classes = [np.argmax(y, axis=None, out=None) for y in y_test]

No need to do list comprehension. Simply

numpy.argmax(a, axis=1)

will find argmax in each row for all rows

This is a complete example of how to reverse labels in tensorflow keras:

label = [0,1,1,0]
label = tf.keras.utils.to_categorical(label)
print(label) #output: label = [[1,0],[0,1],[0,1],[1,0]]
label = tf.math.argmax(label, axis=1)
print(label) #output back to [0,1,1,0]
Related