python-kerasHow can I use Python and Keras to create a one-hot encoding?
One-hot encoding is a process by which categorical variables are converted into a form that could be provided to ML algorithms to do a better job in prediction. Python and Keras provide a number of ways to perform one-hot encoding.
Below is an example of how to use Python and Keras to create a one-hot encoding.
from keras.utils import to_categorical
# define example
data = [1, 3, 5, 2]
# one hot encode
encoded = to_categorical(data)
print(encoded)
Output example
[[0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]
[0. 0. 1. 0. 0.]]
The code above consists of the following parts:
from keras.utils import to_categorical
imports theto_categorical
function from Keras.data = [1, 3, 5, 2]
defines the data to be encoded.encoded = to_categorical(data)
performs one-hot encoding on the data.print(encoded)
prints 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 validation_data when creating a Keras model in Python?
- 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 use Python Keras to zip a file?
- How do Python Keras and TensorFlow compare in developing machine learning models?
- How do I use Keras with Python?
- How can I use Python and Keras to forecast time series data?
- How do I uninstall Keras from my Python environment?
- How do I use zero padding in Python Keras?
See more codes...