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.