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.

Comments

Popular posts from this blog

Blip Blip Plays Hourly Sounds Similar To Watches

Send Private and Secure Emails with ProtonMail

OPTiM Cafe - A Screen Sharing Service to Replace Office Monitor or Projector