Performing matrix multiplication with TensorFlow in Python
Python TensorFlow Building and Training a Simple Model: Exercise-3 with Solution
Write a Python program that creates a TensorFlow operation to perform matrix multiplication between two tensors.
Sample Solution:
Python Code:
import tensorflow as tf
# Create two example tensors
ts1 = tf.constant([[1, 3], [5, 7]], dtype=tf.float32)
ts2 = tf.constant([[2, 4], [6, 8]], dtype=tf.float32)
print("Original matrices")
print(ts1.numpy())
print(ts2.numpy())
# Perform matrix multiplication
result_tensor = tf.matmul(ts1, ts2)
# Print the result
print("\nMatrix Multiplication Result:")
print(result_tensor.numpy())
Output:
Original matrices [[1. 3.] [5. 7.]] [[2. 4.] [6. 8.]] Matrix Multiplication Result: [[20. 28.] [52. 76.]]
Explanation(Output):
In the exercise above -
- Import TensorFlow as tf.
- Create two example tensors, ts1 and ts2, using tf.constant(). These tensors represent 2x2 matrices.
- Perform matrix multiplication between tensor1 and tensor2 using tf.matmul(). This operation computes the dot product of the two matrices.
- Finally, we print the matrix multiplication result.
Python Code Editor:
Previous: Defining a TensorFlow constant Tensor for Neural Network Weights.
Next: Building a Feedforward neural network in TensorFlow.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics