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 create a Zoom application?
- How can I enable verbose mode when using 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 YOLO with Python and Keras?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How do I use a webcam with Python and Keras?
- How can I install the python module tensorflow.keras in R?
- How do I save weights in a Python Keras model?
See more codes...