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 Python Keras to zip a file?
- How can I split my data into train and test sets using Python and Keras?
- How can I enable verbose mode when using Python Keras?
- How can I use Python Keras to develop a reinforcement learning model?
- How can I use Python Keras online?
- How do I use Python and Keras to access datasets?
- How do I use zero padding in Python Keras?
- How can I use YOLO with Python and Keras?
- How do I install the Python Keras .whl file?
- How can I install the python module tensorflow.keras in R?
See more codes...