w3resource

Understanding TensorFlow variables and constants

Python TensorFlow Basic: Exercise-9 with Solution

Write a Python program that explains the difference between TensorFlow variables and constants.

Sample Solution:

Python Code:

import tensorflow as tf

# Define a TensorFlow constant
constant_ts = tf.constant([1.0, 2.0, 3.0])

# Define a TensorFlow variable
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
nums = [4.0, 5.0, 6.0]
variable_ts = tf.Variable(nums)
print("Initial variable Tensor:", variable_ts.numpy())

# Modify the variable
new_value = [7.0, 8.0, 9.0]
variable_ts.assign(new_value)

# Print the constant and variable tensors
print("Constant Tensor:", constant_ts.numpy())
print("Modified variable Tensor:", variable_ts.numpy())

Output:

Initial variable Tensor: [4. 5. 6.]
Constant Tensor: [1. 2. 3.]
Modified variable Tensor: [7. 8. 9.]

Explanation:

The above program demonstrates the difference between TensorFlow variables and constants:

Constants:

  • Constants are created using tf.constant().
  • Constants have fixed values that cannot be changed after initialization.

Variables:

  • Variables are created using tf.Variable() and require an initial value.
  • Variables can be modified during the execution of a TensorFlow program using methods like assign.

Python Code Editor:


Previous: Python TensorFlow matrix initialization and print.
Next: TensorFlow constant and variable operations in Python.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.