TensorFlow – How to create one hot tensor

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

One hot tensor is a Tensor in which all the values at indices where i =j and i!=j is same. 

Method Used:

  • one_hot: This method accepts a Tensor of indices, a scalar defining depth of the one hot dimension and returns a one hot Tensor with default on value 1 and off value 0. These on and off values can be modified.

Example 1:

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the library
import tensorflow as tf
  
# Initializing the Input
indices = tf.constant([1, 2, 3])
  
# Printing the Input
print("Indices: ", indices)
  
# Generating one hot Tensor
res = tf.one_hot(indices, depth = 3)
  
# Printing the resulting Tensors
print("Res: ", res )

chevron_right


Output:

Indices:  tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
Res:  tf.Tensor(
[[0. 1. 0.]
 [0. 0. 1.]
 [0. 0. 0.]], shape=(3, 3), dtype=float32)

Example 2: This example explicitly defines the on and off values for the one hot tensor.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the library
import tensorflow as tf
  
# Initializing the Input
indices = tf.constant([1, 2, 3])
  
# Printing the Input
print("Indices: ", indices)
  
# Generating one hot Tensor
res = tf.one_hot(indices, depth = 3, on_value = 3, off_value =-1)
  
# Printing the resulting Tensors
print("Res: ", res )

chevron_right


Output:

Indices:  tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
Res:  tf.Tensor(
[[-1  3 -1]
 [-1 -1  3]
 [-1 -1 -1]], shape=(3, 3), dtype=int32)


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.