w3resource

Updating TensorFlow variables within a session in Python

Python TensorFlow Basic: Exercise-11 with Solution

Write a Python program that demonstrates how to update a TensorFlow variable within a session.

Sample Solution:

Python Code:

import tensorflow as tf

# Create a TensorFlow variable
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
initial_value = 2.0
print("Initial Variable:",initial_value) 
variable_tensor = tf.Variable(initial_value)

# Define a function that updates the variable
@tf.function
def update_variable(new_value):
    variable_tensor.assign(new_value)

# Update the variable within the function
new_value = 7.0
update_variable(new_value)

# Print the updated value
print("Updated Variable:", variable_tensor.numpy())

Output:

Initial Variable: 2.0
Updated Variable: 7.0

Explanation:

In the exercise above -

  • Create a TensorFlow variable named “variable_tensor” with an initial value of 3.0.
  • Define a Python function “update_variable()” and decorate it with @tf.function. This decorator allows you to define a function containing TensorFlow operations.
  • Within the “update_variable()” function, we use the assign method to update the variable's value with a new value.
  • Call the "update_variable()" function with a new value of 5.0 to update the variable.
  • Finally, we print the updated variable value.

Python Code Editor:


Previous: TensorFlow constant and variable operations in Python.
Next: Updating TensorFlow variables in Python.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.