![]() |
VOOZH | about |
Keras provides numpy utility library, which provides functions to perform actions on numpy arrays. Using the method to_categorical(), a numpy array (or) a vector which has integers that represent different categories, can be converted into a numpy array (or) a matrix which has binary values and has columns equal to the number of categories in the data.
Syntax: tf.keras.utils.to_categorical(y, num_classes=None, dtype="float32")
Parameters:
y (input vector): A vector which has integers representing various classes in the data. num_classes: Total number of classes. If nothing is mentioned, it considers the largest number of the input vector and adds 1, to get the number of classes. Its default value is "None". dtype: It is the desired data type of the output values. By default, it's value is 'float32'.
Output:
This function returns a matrix of binary values (either '1' or '0'). It has number of rows equal to the length of the input vector and number of columns equal to the number of classes.
Code: Converting Cifar10 dataset labels vector to categorical data matrix:
Output:
#Labels before applying the function #Training set labels array([[6], [9], [9], ..., [9], [1], [1]], dtype=uint8) #Training set labels shape (50000, 1) #Testing set labels array([[3], [8], [8], ..., [5], [1], [7]], dtype=uint8) #Testing set labels shape (10000, 1) #Labels after applying the function #Training set labels [[0 0 0 ... 0 0 0] [0 0 0 ... 0 0 1] [0 0 0 ... 0 0 1] ... [0 0 0 ... 0 0 1] [0 1 0 ... 0 0 0] [0 1 0 ... 0 0 0]] #Training set labels shape (50000, 10) #Testing set labels [[0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 1. 0.] [0. 0. 0. ... 0. 1. 0.] ... [0. 0. 0. ... 0. 0. 0.] [0. 1. 0. ... 0. 0. 0.] [0. 0. 0. ... 1. 0. 0.]] #Testing set labels shape (10000, 10)
Code: Considering an input vector with 7 classes. (It can have values ranging from 0 to 6(n-1)).
Output:
[[0 0 1 0 0 0 0] [0 0 0 0 0 1 0] [0 0 0 0 0 0 1] [0 1 0 0 0 0 0] [0 0 0 0 1 0 0] [0 0 1 0 0 0 0] [0 0 0 1 0 0 0] [0 0 1 0 0 0 0]]