Updating TensorFlow variables in Python
Python TensorFlow Basic: Exercise-12 with Solution
Write a Python program that initializes a TensorFlow variable with an initial value and then updates its value within a loop. Print the variable's value after each update.
Sample Solution:
Python Code:
import tensorflow as tf
# Create a TensorFlow variable with an initial value
x = tf.Variable(100.0, dtype=tf.float32)
# Define the number of updates
num_updates = 10
# Perform updates within a loop
for i in range(num_updates):
# Update the variable (e.g., double its value)
updated_value = x * 2.0
x.assign(updated_value)
# Print the updated value
print(f"Update {i + 1}: x = {x.numpy()}")
# Print the final value of the variable
print("Final Variable Value:", x.numpy())
Output:
Update 1: x = 200.0 Update 2: x = 400.0 Update 3: x = 800.0 Update 4: x = 1600.0 Update 5: x = 3200.0 Update 6: x = 6400.0 Update 7: x = 12800.0 Update 8: x = 25600.0 Update 9: x = 51200.0 Update 10: x = 102400.0 Final Variable Value: 102400.0
Explanation:
In the exercise above -
- Initialization: We start by creating a TensorFlow variable named 'x' with an initial value of 10.0. This variable can hold and update floating-point values.
- Number of Updates: Define 'num_updates' as 5, which represents the number of times e want to update the variable.
- Updating in a Loop: Use a for loop to update the variable within each iteration. In this case, we double the current value of the variable (x * 2.0) and assign the updated value back to the variable using variable_tensor.assign(updated_value).
- Printing Updated Values: After each update within the loop, we print the updated value of the variable to observe how it changes.
- Final Value: Finally, after all updates are completed, we print the final value of the variable to see the result of multiple updates.
Python Code Editor:
Previous: Updating TensorFlow variables within a session in Python.
Next: Common TensorFlow data types in Python.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics