In this tutorial, we want to one-hot encode a NumPy array that contains categorical values. In order to do this, we use the to_categorical() function of Keras.

Import Libraries

First, we import the following python modules:

import numpy as np
from keras.utils import to_categorical

Define Data

Next, we create a NumPy array that contains the categorical values 0, 1 and 2.

x = np.array([1, 2, 0, 0, 2, 1, 2, 1, 1, 0])


One-Hot Encoding

Now, we want to transform categorical numerical values into binary vectors. The principle of One-Hot Endoding is visualized in the following graphic:

You can view this post with the tier: Academy Membership

Join academy now to read the post and get access to the full library of premium posts for academy members only.

Join Academy Already have an account? Sign In