How to Cast Integer to Float and Vice Versa in TensorFlow

In this article, we will learn to convert the data types of tensors to integer and float.

First, let's create two nodes.
node1 = tf.constant(5)    # dtype is int32
node2 = tf.constant(6.0)  # dtype is float32
Let's multiply the two nodes to create a new node
node3 = tf.multiply(node1, node2)
This will throw a
TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type
int32 of argument 'x'.
This is because the node1 data type is an integer while the data type of node2 is a float.

Multiply method doesn't convert the types of its variables automatically. For now, we need to change them before performing any type of arithmetic operations on them. I hope this changes in the future releases.

The correct way is to convert either of the node's type to match the other. Here, we are converting the node1 which is an integer to a float.
tf.to_float(node1, name='ToFloat')
Replacing the node1 with the above line in the multiply method will resolve the issue. To learn, more about other types of casting you can check the official website.

Below is a full code that correctly performs multiplication of two nodes when there are of different types.

In a different scenario, you'll get an error
ValueError: Tensor conversion requested dtype int32 for Tensor with dtype
float64 in Tensorflow.
The solution is same. Convert the first tensor or the second tensor type to match the other.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Create Assets Folder, Add Files and Read Data From It

Add Options Menu to Activity and Fragment

How to Set an Android App as a Default Dialer