In this Python tutorial, we will learn how to use the TensorFlow one_hot function in Python. Additionally, we will cover the following topics.
- TensorFlow one_hot example
- TensorFlow one_hot to index
- TensorFlow one_hot encoding example
- TensorFlow one_hot axis
- TensorFlow one hot categorical
- TensorFlow one hot encoding string
- TensorFlow one hot to dense
- TensorFlow text one hot encoding
- reverse one hot encoding tensorflow
- TensorFlow sparse one hot
- TensorFlow multilabel one hot
Python TensorFlow one_hot
- In this section, we will discuss how to use the one_hot() function in TensorFlow Python.
- In python, one-hot encoding is a technique used a convert categorical data into numbers so that you can use it for machine learning algorithms.
- Suppose we have random variables that indicate the indices numbers and now we want to convert these numbers into numerical integer numbers (0,1).
- To perform this particular task, we are going to use the tf.one_hot() function. This function will help the user to returns a one-hot tensor.
Syntax:
Let’s have a look at the syntax and understand the working of the tf.one_hot() function in TensorFlow Python.
tf.one_hot
(
indices,
depth,
on_value=None,
off_value=None,
axis=None,
dtype=None,
name=None
)
- It consists of a few parameters
- indices: This parameter indicates the index number which we want to operate and it is a tensor of indices.
- depth: This defines the dimension of a hot tensor no of rows and columns.
- on_value: By default it takes 1 value if it is not provided.
- off_value: By default it takes 0 value if it is not provided.
- axis: This parameter defines the axis to fill and by default its value is -1.
- dtype: The datatype of the output tensor.
Note: If the data type is not provided then by default the datatype of on_value and off_value will be tf.float32 and it must be the same data type in both parameters. If it does not match then the type error will raise.
Example:
Let’s take an example and check how to use the one_hot() function in Python TensorFlow.
Source Code:
import tensorflow as tf
new_indi = [2, 3, 5]
new_val = 4
result=tf.one_hot(new_indi, new_val)
print(result)
In the above code we have imported the TensorFlow library and then initialize a list in which we have assigned the indices numbers. After that, we have used the tf.one_hot() function and within this function, we have passed the indices and depth as an argument.
Here is the implementation of the following given code.
Also, read: TensorFlow Tensor to NumPy
TensorFlow one_hot example
- In this section, we will discuss the example of one_hot function in Python TensorFlow.
- To do this task, we are going to use the tf.one_hot() function and it will convert the random number with binary integer numbers.
- In this example we have create the session by importing the tf.compat.v1.disable_eager_execution() function.
- Next, we will declare the indices numbers in the list and then we are going to use the tf.one_hot() function and assign the indices, depth axis as an argument.
Example:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_ind = [0,2,3,4,1]
tens = tf.constant(4)
result = tf.one_hot(new_ind, tens,on_value=1.0,off_value=0.0, axis =-1)
with tf.compat.v1.Session() as val:
new_output=val.run(result)
print(new_output)
Here is the execution of the following given code.
As you can see in the Screenshot the output displays the tensor one_hot.
Read: TensorFlow get shape
TensorFlow one_hot to index
- In this Program, we will discuss how to convert the one_hot to index in Python TensorFlow.
- To do this task, first, we will display the tensor of one-hot and then convert it into an index number. By using the tf.argmax() function we can easily convert the one-hot tensor into the index.
- In Python, the tf.argmax() function is used to return the indices of the given input tensor.
Syntax:
Let’s have a look at the syntax and understand the working of the tf.argmax() function.
tf.argmax
(
x,
axis
)
Example:
Let’s take an example and check how to convert the one-hot tensor to index in Python TensorFlow.
Source Code:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_ind = [0,2,3,4,1]
tens = tf.constant(4)
result = tf.one_hot(new_ind, tens,on_value=1.0,off_value=0.0, axis =-1)
new_result = tf.argmax(result, axis=1)
with tf.compat.v1.Session() as val:
new_output=val.run(new_result)
print(new_output)
Here is the implementation of the following given code.
As you can see in the Screenshot the output displays the indices numbers.
Read: Import error no module named TensorFlow
TensorFlow one_hot encoding example
- In this section, we will discuss the example one_hot encoding in TensorFlow Python.
- By using the tf.one_hot() function, we can easily perform this particular task and use all the parameters in function.
Example:
Let’s have a look at the example and understand the working of the tf.one_hot() function.
Source code:
import tensorflow as tf
tens=[1,3,4,5]
result= tf.one_hot(tens, depth=4, on_value="True", off_value="False")
tf.print(result)
In the following given code we have imported the TensorFlow library and then initialize a list that indicates the indices number. After that, we have used the tf.one_hot() function and within this function, we have assigned the depth, on_value, and off_value as an argument.
In this example we have set the on_value=”True” and off_value=”False”. Once you will execute this code the output displays the one-hot tensor in the order of boolean values.
Here is the Screenshot of the following given code.
Read: Python Copy NumPy Array
TensorFlow one_hot axis
- In this section, we will discuss we are going to use the axis parameter in one_hot() function in TensorFlow Python.
- To do this task, we will use the tf.one_hot() function and inside this function, we have set the axis=-1 that indicates the innermost axis.
Syntax:
Let’s have a look at the Syntax and understand the working of the TensorFlow one_hot() function in Python.
tf.one_hot
(
indices,
depth,
on_value=None,
off_value=None,
axis=None,
dtype=None,
name=None
)
Example:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
result = tf.one_hot([1,3,5,2], 6,axis =-1)
with tf.compat.v1.Session() as val:
new_output=val.run(result)
print(new_output)
In the following given code we have created a session by importing the tf.compat.v1.disable_eager_execution() function and then specified the axis=-1 in tf.onehot() function.
Here is the Screenshot of the following given code.
Read: Python TensorFlow expand_dims
TensorFlow one hot categorical
- Here we are going to discuss how to use the one_hot categorical() function in Python TensorFlow.
- In this example, we are going to use the tfp.distribution.OneHotCategorical() function is parameterized by the log probabilities and then we will create a class distribution.
Syntax:
Here is the Syntax of tfp.distributions.OneHotCategorical() function.
tfp.distributions.Categorical
(
logits=None,
probs=None,
dtype=tf.int32,
validate_args=False,
allow_nan_stats=True,
name='Categorical'
)
Example:
Let’s take an example and understand the working of tfp.distributions.OneHotCategorical() function.
import tensorflow as tf
import tensorflow_probability as tfp
tens=tfp.distributions.OneHotCategorical(probs=[0.7,0.4,0.5])
print(tens)
result=tens.sample()
print(result)
Here is the implementation of the following given code.
As you can see in the Screenshot the output displays the event shape as 3 which means the random variable is now a vector.
Read: Python NumPy Savetxt + Examples
TensorFlow one hot encoding string
- In this section, we will discuss how to get the string value in output by creating a tensor in Python.
- In this example we have set the parameter on_value=’x’ and off_value=’y’ in tf.one_hot() function. once you will execute this code the output displays the string value in a one-hot tensor.
Example:
import tensorflow as tf
tens=[1,3,6,5,4,7]
result= tf.one_hot(tens, depth=6, on_value='x', off_value='y')
tf.print(result)
Here is the Screenshot of the following given code.
Read: Python TensorFlow truncated normal
TensorFlow one hot to dense
- In this section, we will discuss how to convert one hot tensor to dense in Python TensorFlow.
- By using the slicing and tf.where() function we can easily convert the one_hot tensor to dense.
- To do this task first we will import the tf.compat.v1.disable_eager_execution() module for creating a session and then we are going to use the tf.constant() function for creating tensor indices.
Syntax:
Here is the Syntax of tf.where() function
tf.where
(
condition,
x=None,
y=None,
name=None
)
Example:
Let’s take an example and check how to convert the one_hot tensor to dense in Python.
Source Code:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
tens = tf.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
dense = tf.where(tf.equal(tens, 1))
indices = dense[:,1]
with tf.compat.v1.Session() as val:
new_output=val.run(indices)
print(new_output)
Here is the Screenshot of the following given code
Read: Convert list to tensor TensorFlow
TensorFlow text one hot encoding
- In this section, we will discuss how to encode a text into a list of words in Python.
- To perform this particular task we are going to use the tf.keras.preprocessing.text.one_hot() function and this function is used to convert the text into a list of words. In this example we will take a string as a input and it will return a list of encoded integers.
Syntax:
Let’s have a look at the Syntax and understand the working of tf.Keras.preprocessing.text.one_hot() function.
tf.keras.preprocessing.text.one_hot
(
input_text,
n,
filters='!"#$%&,
lower=True,
split=' ',
)
- It consists of a few parameters
- input_text: This parameter indicates the input text that will be string.
- n: This defines the size of input text
- split: This parameter is used for word splitting.
Example:
Let’s take an example and check how to encode a text into a list of words in Python.
Source Code:
import tensorflow as tf
tens_text = "Python Programming"
new_output = tf.keras.preprocessing.text.one_hot(tens_text,n=3)
print(new_output)
Here is the implementation of the following given code
Read: Tensorflow custom loss function
reverse one hot encoding tensorflow
- In this section, we will discuss how to reverse the one-hot encoding Tensor in Python TensorFlow.
- To perform this particular task we are going to create one_hot tensor by using the tf.one_hot() function and then we are going to reverse the one-hot tensor elements by applying the tf.reverse() function in Python.
- This function is used to reverse a tensor based on axis and it is available in TensorFlow package.
Syntax:
Let’s have a look at the Syntax and understand the working of tf.reverse() function.
tf.reverse
(
tensor,
axis,
name=None
)
- It consists of a few parameters
- tensor: This parameter indicates the tensor and it must be a integer datatype.
- axis: The indices of the dimension to reverse.
- name: By default it takes none value and it indicates the name of the operation.
Example:
Let’s take an example and check how to reverse the one-hot encoding Tensor in Python.
Source Code:
import tensorflow as tf
new_indi = [3, 1, 2]
new_val = 4
result=tf.one_hot(new_indi, new_val)
print(result)
b_reversed = tf.reverse(result, axis=[0, 1])
print(b_reversed)
You can refer to the below Screenshot.
Read: TensorFlow next_batch
TensorFlow sparse one hot
- In this Program, we will discuss how to use the tf.sparse.to_dense() function in Python TensorFlow.
- By using the tf.sparse.to_dense() function is used to convert the sparse tensor to dense tensor.
Syntax:
Here is the Syntax of tf.sparse.to_dense() function.
tf.sparse.to_dense
(
sp_input,
default_value=None,
validate_indices=True,
name=None
)
- It consists of a few parameters
- sp_input: This parameter indicates the input spare tensor which we want to operate.
- default_value:By default it takes none value and it is used to set for indices.
- validate_indices: This parameter specifies there is no reptition and it will check the condition if the value is true then they are sorted in lexicographic order.
Example:
Let’s have a look at the example and understand the working of tf.sparse.to_dense() function.
Source Code:
import tensorflow as tf
tens_input = tf.SparseTensor(
dense_shape=[3, 6],
values=[3, 4,5],
indices =[[0, 1],
[0, 3],
[2, 0]])
result=tf.sparse.to_dense(tens_input).numpy()
print(result)
In the following given code we have imported the TensorFlow library and then use the tf.SparseTensor() function and within this function we have assigned the dense shape, values, and indices as an argument.
Here is the implementation of the following given code.
As you can see in the Screenshot the output displays the dense tensor.
Read: TensorFlow Sparse Tensor
TensorFlow multilabel one hot
- Here we are going to discuss how to use multi labels in one_hot() function in Python TensorFlow.
- To do this task we are going to use the tf.raggged.constant() function and this function is used when we have a nested list in Tensor.
- Next, we will declare a variable and assign the tf.one_hot() function and within this function, we will assign the depth as an argument.
Syntax:
Here is the Syntax of tf.raggged.constant() function.
tf.ragged.constant
(
pylist,
dtype=None,
ragged_rank=None,
inner_shape=None,
name=None,
row_splits_dtype=tf.dypes.int64
)
Example:
import tensorflow as tf
new_indices = tf.ragged.constant([[2, 3], [2], [1, 2]])
one_hot_tensor = tf.one_hot(new_indices, 5)
multi_labels = tf.reduce_max(one_hot_tensor, axis=1)
print(multi_labels)
Here is the Screenshot of the following given code.
You may also like to read the following Python TensorFlow tutorials.
- TensorFlow cross-entropy loss
- Binary Cross Entropy TensorFlow
- Tensorflow embedding_lookup
- TensorFlow Graph – Detailed Guide
In this Python tutorial, we have learned how to use the TensorFlow one_hot function in Python. Also, we have covered the following topics.
- TensorFlow one_hot example
- TensorFlow one_hot to index
- TensorFlow one_hot encoding example
- TensorFlow one_hot axis
- TensorFlow one hot categorical
- TensorFlow one hot encoding string
- TensorFlow one hot to dense
- Tensorflow dataset onehot encode
- TensorFlow text one hot encoding
- reverse one hot encoding tensorflow
- TensorFlow sparse one hot
- TensorFlow multilabel one hot
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.