How To Convert An Integer Into One Hot Encoded List

Suppose you are training a model where the target class is given as integer. For example, when you are training a spam checker, you might find each of your sample data marked as 0 for being not spam and 1 for being spam. In machine learning,

import numpy as np

num_classes = 2

a = np.array(y_train)
b = np.zeros((len(y_train), num_classes))

b[np.arange(len(y_train)), a] = 1

Now, b will contain the one hot encoded numpy array.

When using keras, it has built-in method for this:

y_train = keras.utils.to_categorical(y_train, num_classes)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top