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 can I use Python Keras on Windows?
- How do I use zero padding in Python Keras?
- What is Python Keras and how is it used?
- How do I use Python Keras to create a Zoom application?
- How do I use validation_data when creating a Keras model in Python?
- How do I check which version of Keras I am using in Python?
- How do I set the input shape when using Keras with Python?
- How do I use Python Keras to zip a file?
- How can I split my data into train and test sets using Python and Keras?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
See more codes...