Convert class labels to categories using keras

Class labels can be converted to OneHot encoded array using keras.utils.to_categorical.
The resultant array has number of rows equal to the number of samples, and number of columns equal to the number of classes.

Let’s take an example of an arrray containing labels.
First we need to import numpy to create the labels array and then define the labels array.

import numpy as np
labels = np.array([0,0,1,2,1,3,2,1])

The labels contain four categories.

np.unique(labels)
array([0, 1, 2, 3])

To convert the labels to OneHot encoded array, excute the following:

import tensorflow as tf
labels_encoded = tf.keras.utils.to_categorical(labels)
print(labels_encoded)
[[1. 0. 0. 0.]
 [1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 1. 0. 0.]
 [0. 0. 0. 1.]
 [0. 0. 1. 0.]
 [0. 1. 0. 0.]]

This encoded array can be used for training multiclass classification model.

Privacy Overview
Analytics Notes

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.