Tensorflow 2 – One Hot Encoding Examples

Last updated on September 2, 2021 A Goodman Loading... Post a comment

In simple words, one hot encoding means converting categorical variables into a form that could be taken by a machine learning algorithm for more effective prediction.

In Tensorflow 2, you can do one-hot encoding by using the tf.one_hot function. Below are a few examples of using it in practice.

Example 1

import tensorflow as tf

input = [1, 2, 3, 4]

output = tf.one_hot(input, depth=4)
tf.print(output)

Output:

[[0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]
 [0 0 0 0]]

Example 2

Using custom values for one-hot encoding:

import tensorflow as tf

x = [0, 1, 2, 3, 4, 5]

y = tf.one_hot(x, depth=6, on_value="On", off_value="Off")
tf.print(y)

Output:


0s
import tensorflow as tf

x = [0, 1, 2, 3, 4, 5]

y = tf.one_hot(x, depth=6, on_value="On", off_value="Off")
tf.print(y)
[["On" "Off" "Off" "Off" "Off" "Off"]
 ["Off" "On" "Off" "Off" "Off" "Off"]
 ["Off" "Off" "On" "Off" "Off" "Off"]
 ["Off" "Off" "Off" "On" "Off" "Off"]
 ["Off" "Off" "Off" "Off" "On" "Off"]
 ["Off" "Off" "Off" "Off" "Off" "On"]]

You can find more details about the mentioned function in the official docs.

Further reading:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like