Python TensorFlow matrix initialization and print

Python TensorFlow Basic: Exercise-8 with Solution

Write a Python program that defines a TensorFlow variable to store a matrix of random values. Initialize and print the variable.

Sample Solution:

Python Code:

import tensorflow as tf

# Define the shape of the matrix
matrix_shape = (3, 3)

# Create a TensorFlow variable with random values
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
random_matrix = tf.Variable(tf.random.normal(shape=matrix_shape))

# Print the initialized variable
print("Initialized Variable:")


Initialized Variable:
[[-0.580494    0.07652978 -0.5241451 ]
 [ 1.2946662   0.0206589  -1.4023237 ]
 [ 0.16084932 -1.0415876   1.2840588 ]]


In the exercise above -

  • import tensorflow as tf - This line imports the TensorFlow library.
  • matrix_shape = (3, 3) - Define the shape of the matrix.
  • random_matrix = tf.Variable(tf.random.normal(shape=matrix_shape)) - Create a TensorFlow variable with random values.
    • tf.random.normal(shape=matrix_shape) generates random values following a normal (Gaussian) distribution with the specified shape (in this case, a 3x3 matrix).
    • tf.Variable() is used to create a TensorFlow variable that can be updated during training. We initialize it with the random values.
  • print(random_matrix.numpy()) - Retrieve the values stored in the TensorFlow variable. In TensorFlow 2.x with eager execution, we can access the values directly using .numpy().

Python Code Editor:

Previous: Python TensorFlow graph and session.
Next: Understanding TensorFlow variables and constants.

What is the difficulty level of this exercise?

Follow us on Facebook and Twitter for latest update.