w3resource

TensorFlow constant and variable operations in Python

Python TensorFlow Basic: Exercise-10 with Solution

Write a Python program that creates a TensorFlow constant and a TensorFlow variable. Add, subtract, multiply and divide them and print the result.

Sample Solution:

Python Code:

import tensorflow as tf

# Create a TensorFlow constant and a TensorFlow variable
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
constant_ts = tf.constant(4.0)
initial_value = 5.0
variable_ts = tf.Variable(initial_value)

# Perform mathematical operations
add_result = constant_ts + variable_ts
subtract_result = constant_ts - variable_ts
multiply_result = constant_ts * variable_ts
divide_result = constant_ts / variable_ts

# Print the results
print("Constant:", constant_ts.numpy())
print("Variable (initial value):", initial_value)  # Variables are not initialized explicitly in TensorFlow 2.x
print("Addition Result:", add_result.numpy())
print("Subtraction Result:", subtract_result.numpy())
print("Multiplication Result:", multiply_result.numpy())
print("Division Result:", divide_result.numpy())

Output:

Constant: 4.0
Variable (initial value): 5.0
Addition Result: 9.0
Subtraction Result: -1.0
Multiplication Result: 20.0
Division Result: 0.8

Explanation:

In the exercise above -

  • Create a TensorFlow constant named constant_tensor with the value 5.0.
  • Create a TensorFlow variable named variable_tensor with an initial value of 3.0.
  • Perform addition, subtraction, multiplication, and division operations between the constant and the variable.
  • Initialize the variable using tf.compat.v1.global_variables_initializer().run() (for TensorFlow 2.x, use tf.compat.v1.global_variables_initializer().run()).
  • Finally, we print the values of the constant, the initialized variable, and the results of mathematical operations.

Python Code Editor:


Previous: Understanding TensorFlow variables and constants.
Next: Updating TensorFlow variables within a session in Python.

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