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 can I use Python Keras to create a neural network with zero hidden layers?
- How do I use Python Keras to create a Zoom application?
- How do I use Python Keras to zip a file?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
- How can I use Python and Keras to create a Variational Autoencoder (VAE)?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I improve the validation accuracy of my Keras model using Python?
- How do I use Python and Keras to create a VGG16 model?
- How can I enable verbose mode when using Python Keras?
See more codes...