# Tensorflow 2 – One Hot Encoding Examples

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:**

- Tensorflow 2 – Removing all Single Dimensions from a Tensor
- Tensorflow 2 – Get the Indices of Min and Max in a Tensor
- Tensorflow 2 – Aggregation Operators on Tensors
- Tensorflow 2 – Changing the Datatype of a Tensor
- 2 Ways to Expand a Tensor in Tensorflow 2

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

Subscribe

0 Comments