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_categoricalimports theto_categoricalfunction 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 do I use the pad_sequences function in Python Keras?
- How do I use zero padding in Python Keras?
- How do I install the Python Keras .whl file?
- How do I install Keras on Windows using Python?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
- How can I improve the validation accuracy of my Keras model using Python?
- How can I enable verbose mode when using Python Keras?
- How do I use the to_categorical function in Python Keras?
- How do I use Python and Keras to resize an image?
- How can I resolve the issue of Python module Tensorflow.keras not being found?
See more codes...