w3resource

Convert TensorFlow Tensor data type in Python

Python TensorFlow Basic: Exercise-15 with Solution

Write a Python program that converts a TensorFlow tensor from one data type to another (e.g., from int32 to float64).

Sample Solution:

Python Code:

import tensorflow as tf

# Create a TensorFlow tensor with int32 data type
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
tensor_int32 = tf.constant([100, 200, 300], dtype=tf.int32)

# Convert the tensor to float64 data type
tensor_float64 = tf.cast(tensor_int32, dtype=tf.float64)

# Print the original and converted tensors
print("Original Tensor (int32):", tensor_int32.numpy())
print("Converted Tensor (float64):", tensor_float64.numpy())

Output:

Original Tensor (int32): [100 200 300]
Converted Tensor (float64): [100. 200. 300.]

Explanation:

In the exercise above -

  • Import TensorFlow as tf.
  • Create a TensorFlow tensor tensor_int32 with data type int32 using tf.constant().
  • Use tf.cast() to convert the tensor_int32 tensor to the float64 data type, storing the result in tensor_float64.
  • Finally, we print both the original and the converted tensor.

Python Code Editor:


Previous: Specified TensorFlow Data Type in Python.
Next: Create and print TensorFlow string tensor in Python.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/machine-learning/tensorflow/python-tensorflow-basic-exercise-15.php