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 do I use Python Keras to zip a file?
- How can I use Python and Keras to forecast time series data?
- How can I resolve the issue of Python module Tensorflow.keras not being found?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How do I save weights in a Python Keras model?
- How can I use Python Keras on Windows?
- How do I install Keras on Windows using Python?
- How do I use a webcam with Python and Keras?
See more codes...