python-kerasHow do I use keras.utils.to_categorical in Python?
Keras.utils.to_categorical is a utility function used to convert a numerical label vector (integers) to a binary class matrix. This is useful for working with a categorical data set in a neural network.
An example of using this function is shown below:
import numpy as np
from keras.utils import to_categorical
# define input data
data = np.array([1, 3, 2, 0, 3, 2, 2, 1, 0, 1])
# one hot encode the data
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.]]
Code explanation
import numpy as np
: import numpy library for array operations.from keras.utils import to_categorical
: import to_categorical function from keras.utils.data = np.array([1, 3, 2, 0, 3, 2, 2, 1, 0, 1])
: define input data.encoded = to_categorical(data)
: one hot encode the data.print(encoded)
: print the encoded data.
Helpful links
More of Python Keras
- How do I use Python Keras to zip a file?
- How can I use Python with Keras to build a deep learning model?
- How can I use YOLO with Python and Keras?
- How do I use a webcam with Python and Keras?
- How can I improve the validation accuracy of my Keras model using Python?
- How can I use Python Keras on Windows?
- How can I visualize a Keras model using Python?
- How can I use Python Keras to create a neural network with zero hidden layers?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How do I install Keras on Windows using Python?
See more codes...