python-kerasHow do I use the to_categorical function in Python Keras?
The to_categorical
function in Python Keras is used to convert a class vector (integers) to binary class matrix. This is useful for using with categorical crossentropy loss function, which expects the labels to follow a binary encoding.
Example
from keras.utils import to_categorical
# define example
data = [1, 3, 2, 0, 3, 2, 2, 1, 0, 1]
# one hot encode
encoded = to_categorical(data)
print(encoded)
Output example
[[0. 1. 0. 0.]
[0. 0. 0. 1.]
[0. 0. 1. 0.]
[1. 0. 0. 0.]
[0. 0. 0. 1.]
[0. 0. 1. 0.]
[0. 0. 1. 0.]
[0. 1. 0. 0.]
[1. 0. 0. 0.]
[0. 1. 0. 0.]]
The to_categorical
function takes the following parameters:
y
: class vector to be converted into a matrix (integers from 0 to num_classes).num_classes
: total number of classes.dtype
: The data type expected by the input, as a string (float32, float64, int32...)
The function returns a binary matrix representation of the input.
Helpful links
More of Python Keras
- How do I use zero padding in Python Keras?
- How can I use Python Keras to develop a reinforcement learning model?
- How to load a model in Python Keras?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
- How can I use Python Keras to create a neural network with zero hidden layers?
- How do I use Python Keras to zip a file?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How can I install the python module tensorflow.keras in R?
- How do I save weights in a Python Keras model?
- How can I improve the validation accuracy of my Keras model using Python?
See more codes...