w3resource

Python TensorFlow constant: Shape and data type

Python TensorFlow Basic: Exercise-1 with Solution

Write a Python program that creates a TensorFlow constant with the values [100, 200, 300]. Print its shape and data type.

Sample Solution:

Python Code:

import tensorflow as tf
# Create a TensorFlow constant tensor
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
t = tf.constant([100, 200, 300])
# Print the shape and data type
print("Tensor Shape:", t.shape)
print("Data Type:", t.dtype)


Output:

Tensor Shape: (3,)
Data Type: <dtype: 'int32'>
 

Explanation:

In the exercise above -

  • import tensorflow as tf - This line imports the TensorFlow library, allowing you to use TensorFlow functions and classes in your program.
  • t = tf.constant([100, 200, 300]) - 'tf.constant()' function in TensorFlow creates a constant tensor with the specified values. In this case, you're creating a 1-D tensor with the values [100, 200, 300].
  • print("Tensor Shape:", t.shape) – 't.shape' is an attribute of the TensorFlow tensor 't' that returns the shape (dimensionality) of the tensor. In this case, it's a 1-D tensor, so the shape is (3,), indicating that it has 3 elements along the first dimension.
  • print("Data Type:", t.dtype) – 't.dtype' is an attribute of the TensorFlow tensor 't' that returns the data type of the tensor's elements. In this case, the data type is inferred to be int32 by default because the elements are integers.

Python Code Editor:


Previous: Python TensorFlow Basic Exercises Home.
Next: Python TensorFlow element-wise addition.

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://w3resource.com/machine-learning/tensorflow/python-tensorflow-basic-exercise-1.php