Skip to content
Related Articles

Related Articles

TensorFlow – How to create one hot tensor

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Aug, 2020

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




# 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 )

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




# 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 )

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)



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!