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 validation_data when creating a Keras model in Python?
- How do I use Python Keras to zip a file?
- How do I check which version of Keras I am using in Python?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
- How do I choose between Python Keras and Scikit Learn for machine learning?
- How can I use the Python Keras Tokenizer to preprocess text data?
- How do I use Python and Keras to create a stock prediction model?
- How can I use Python Keras to develop a reinforcement learning model?
- How do I set the input shape when using Keras with Python?
- What is Python Keras and how is it used?
See more codes...