TensorFlow – How to create one hot tensor
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
import tensorflow as tf
indices = tf.constant([ 1 , 2 , 3 ])
print ( "Indices: " , indices)
res = tf.one_hot(indices, depth = 3 )
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
import tensorflow as tf
indices = tf.constant([ 1 , 2 , 3 ])
print ( "Indices: " , indices)
res = tf.one_hot(indices, depth = 3 , on_value = 3 , off_value = - 1 )
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...