19

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?

2
  • 1
    You can use argmax Commented Nov 19, 2017 at 18:50
  • 1
    np.argmax(a, axis = 1) Commented Apr 19, 2018 at 14:27

4 Answers 4

20

Simple.

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

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

Sign up to request clarification or add additional context in comments.

Comments

13

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]

Comments

11

No need to do list comprehension. Simply

numpy.argmax(a, axis=1)

will find argmax in each row for all rows

1 Comment

This should be the answer.
3

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.