w3resource

Python TensorFlow create and update tensor shape

Python TensorFlow Basic: Exercise-3 with Solution

Write a Python program to create a TensorFlow tensor of shape (3, 3) filled with zeros and then change its value to nine.

Sample Solution:

Python Code:

import tensorflow as tf
# Create a TensorFlow tensor of shape (3, 3) filled with zeros
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
zeros_tensor = tf.zeros(shape=(3, 3), dtype=tf.float32)
print("Original Tensor:")
print(zeros_tensor.numpy())
# Change the values to nine
updated_tensor = tf.constant(9.0, shape=(3, 3), dtype=tf.float32)

# Print the updated tensor
print("\nUpdated Tensor:")
print(updated_tensor.numpy())

Output:

Original Tensor:
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Updated Tensor:
[[9. 9. 9.]
 [9. 9. 9.]
 [9. 9. 9.]]
 

Explanation:

In the exercise above, we first create a tensor "zeros_tensor" filled with zeros of shape (3, 3). Then, we create another tensor "updated_tensor" with the same shape and set all its values to nine. Finally, we print the updated tensor, which should contain all nine values.

Python Code Editor:


Previous: Python TensorFlow element-wise addition.
Next: Python TensorFlow scalar multiplication.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.