Specified TensorFlow Data Type in Python

Python TensorFlow Basic: Exercise-14 with Solution

Write a Python program that creates a TensorFlow tensor with a specified data type (e.g., float32) and prints its data type

Sample Solution:

Python Code:

import tensorflow as tf

# Declare the data type (e.g., float32)
data_type = tf.float32

# Create a TensorFlow tensor with the specified data type
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).

ts = tf.constant([1.0, 2.0, 3.0], dtype=data_type)

# Print the data type of the tensor
print("Data Type of the Tensor:", ts.dtype)


Data Type of the Tensor: <dtype: 'float32'>


In the exercise above -

  • Import TensorFlow as tf.
  • Define the desired data type, such as tf.float32, and store it in the data_type variable.
  • Create a TensorFlow tensor using tf.constant() with the specified data type by providing the dtype argument.
  • Finally, we print the data type of the created tensor using tensor.dtype.

Python Code Editor:

Previous: Common TensorFlow data types in Python.
Next: Convert TensorFlow Tensor data type in Python.

What is the difficulty level of this exercise?

Follow us on Facebook and Twitter for latest update.