python-kerasHow can I use the to_categorical attribute in the tensorflow.python.keras.utils module?
The to_categorical()
attribute in the tensorflow.python.keras.utils
module can be used to convert a class vector (integers) to binary class matrix. This is useful for working with categorical data in machine learning models.
Here is an example of using to_categorical()
:
from tensorflow.python.keras.utils import to_categorical
# example of class vector
y = [0, 1, 2, 2, 1]
# convert to binary class matrix
y_cat = to_categorical(y)
print(y_cat)
The output of this code is:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]
[0. 0. 1.]
[0. 1. 0.]]
The to_categorical()
attribute takes two parameters:
y
: class vector to be converted into a matrixnum_classes
: total number of classes
The y
parameter is the class vector that needs to be converted to a binary class matrix. The num_classes
parameter is the total number of classes in the data.
Helpful links
More of Python Keras
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How do I use zero padding in Python Keras?
- How do I use Python Keras to zip a file?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I install the python module tensorflow.keras in R?
- How can I use YOLO with Python and Keras?
- How do I install Keras on Windows using Python?
- How do I create a layer in Python using Keras?
- How do I install the Python Keras .whl file?
- How do I check which version of Keras I am using in Python?
See more codes...