This tutorial will illustrate how to convert dictionary to tensor TensorFlow by using Python. and also we will look at some examples of how we can use the tf.convert_to_tensor() function in TensorFlow. And we will cover these topics.
- How to convert dictionary to tensor tensorflow
- How to convert array to tensor Pytorch
- How to convert tensor to float tensorflow
- How to convert image to tensor tensorflow
- TensorFlow empty tensor
How to convert dictionary to tensor tensorflow
- This section will discuss how to convert dictionary to tensor TensorFlow.
- To do this task, we are going to use the for-loop method and in this example first, we initialized a dictionary and assign an element in the form of a key-value pair element.
- Next, we want to convert the given dictionary into a tensor and for this, we will use the for loop and set the condition if n > m then it will store in the result.
Example:
Let’s take an example and check how to convert the dictionary to tensor in Python TensorFlow.
Source Code:
City_name_USA = {'New York': {'3': 17, '2': 17, '2': 18},
'Los Angeles': {'3': 45, '1': 78, '2': 78}}
num = 0
for m, new_val in City_name_USA.items():
for n in new_val.keys():
if int(n) > int(num):
num = int(n)
result = []
for new_val in City_name_USA.values():
lst = [0] * (num+1)
for n, val2 in sorted(new_val.items()):
lst[int(n)] = val2
result.append(lst)
print(result)
You can refer to the below Screenshot.
This is how to convert the dictionary to tensor in Python TensorFlow.
Read: Tensorflow convert sparse tensor to tensor
How to convert array to tensor Pytorch
- Here we will discuss how to convert the array to Pytorch tensor in Python.
- Similar to numpy.ndarray is a PyTorch tensor. The distinction between these two is that a tensor makes use of the GPUs to speed up computations involving numbers.
- The torch.from is used to transform a numpy.ndarray into a PyTorch tensor(). And the numpy() method converts a tensor to a numpy.ndarray.
- First, we have to require the torch and Numpy library and then convert an array to Pytorch tensor by using the torch.from_numpy().
Syntax:
Let’s look at the Syntax and understand the working of a torch.from_numpy() function.
torch.from_numpy(ndarray)
Note: This function takes only one parameter ndarray and that specifies the input array which we want to convert with tensor.
Example:
import torch
import numpy as np
Population_in_USA = np.array([13,45,7,78,90])
# Convert Numpy array to torch.Tensor
result = torch.from_numpy(Population_in_USA)
print(result)
In the following given code, we created an array by using the np.array() function and within this function, we assign the integer values as an argument. Next, we will use the torch.from_numpy() function and within this function, we assigned the dictionary as an argument.
Here is the implementation of the following given code.
As you can see in the Screenshot we converted the NumPy array to Pytorch Tensor.
Read: Module ‘tensorflow’ has no attribute ‘sparse_placeholder’
How to convert tensor to float tensorflow
- This section will discuss how to convert the tensorflow tensor to float in Python.
- To perform this task we are going to use the tf.cast() function this function is used to cast the given input tensor to a new datatype. This function takes two main parameters which are the input tensor that is being cast.
Syntax:
Here is the Syntax of tf.cast() function in Python TensorFlow
tf.cast(
x, dtype, name=None
)
- It consists of a few parameters
- x: This parameter defines the input tensor and a numeric type Tensor, SparseTensor, or IndexedSlices. It might be an int8, int16, int32, int64, float16, float32, float64, complex64, complex128, or bfloat16. It might also be an uint8, int8, int16, int32, or int64.
- dtype: This parameter specifies the data type of the input tensor.
- name: By default, it takes none value and specifies the name of the operation.
Example:
import tensorflow as tf
input_tens = tf.constant([23,45,67,8])
result=tf.cast(input_tens, tf.float32)
print(result)
In the above code, we have used the tf.constant() function for the creation of the input tensor. And then we used the tf.cast() for converting the integer datatype to float datatype.
Here is the implementation of the following given code.
This is how to convert the input tensor to float value by using TensorFlow.
Read: Module ‘tensorflow’ has no attribute ‘div’
How to convert image to tensor tensorflow
- In this section, we will discuss how to convert an image to a tensor and for typical axis order for an image tensor.
- The image must be a PIL image or a numpy image. ndarray (HxWxC) in the [0, 255] range. Here, H, W, and C stand for the image’s height, breadth, and number of channels.
- In the given example h is the height and w is the width image, c is the channel image.
Example:
import tensorflow as tf
image = tf.io.read_file("tiger.png")
input_tensor = tf.io.decode_image(image, channels=3, dtype=tf.dtypes.float32)
tensor = tf.image.resize(input_tensor, [224, 224])
result = tf.expand_dims(tensor, axis=0)
print(result)
Here is the execution of the following given code.
In this example, we have converted the image to a tensor.
Read: Module ‘tensorflow’ has no attribute ‘truncated_normal’
TensorFlow empty tensor
- Let us discuss how to create an empty tensor in Python TensorFlow.
- To perform this task we are going to use the tf.experimental.numpy.empty() function and this function variants the empty’s value.
Syntax:
Here is the Syntax of tf.experimental.numpy.empty() function in Python TensorFlow
tf.experimental.numpy.empty(
shape, dtype=float
)
- It consists of a few parameters
- shape: This parameter defines the shape of the empty tensor.
- dtype: By default, it takes the float value and specifies the data type of the input tensor.
Example:
import tensorflow as tf
result= tf.experimental.numpy.empty(shape=(2,2),dtype=float)
print(result)
Here is the Screenshot of the following given code
Also, take a look at some more Python TensorFlow tutorials.
- TensorFlow Fully Connected Layer
- Batch Normalization TensorFlow
- Tensorflow custom loss function
- TensorFlow Sparse Tensor
In this tutorial, we have understood how to convert a dictionary to a tensor by using Python TensorFlow. and also we will look at some examples of how we can use the tf.convert_to_tensor() function in TensorFlow. And we will cover these topics.
- Convert dictionary to tensor tensorflow
- Convert array to tensor Pytorch
- Convert tensor to float tensorflow
- Convert image to tensor tensorflow
- TensorFlow empty tensor
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.