0
0
TensorFlowml~15 mins

Tensor math operations in TensorFlow - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Tensor math operations
Problem:You want to perform basic math operations on tensors using TensorFlow to understand how tensors work and how math operations affect them.
Current Metrics:No model or accuracy metrics yet, just tensor values before and after operations.
Issue:You are new to tensor math and want to see how addition, multiplication, and other operations change tensor values.
Your Task
Create two tensors and perform addition, subtraction, multiplication, and division. Verify the results by printing the output tensors.
Use TensorFlow 2.x API.
Use only basic math operations on tensors.
Do not convert tensors to numpy arrays for operations.
Hint 1
Hint 2
Hint 3
Solution
TensorFlow
import tensorflow as tf

# Create two tensors
tensor_a = tf.constant([[2, 4], [6, 8]], dtype=tf.float32)
tensor_b = tf.constant([[1, 3], [5, 7]], dtype=tf.float32)

# Perform math operations
add_result = tf.add(tensor_a, tensor_b)
sub_result = tf.subtract(tensor_a, tensor_b)
mul_result = tf.multiply(tensor_a, tensor_b)
div_result = tf.divide(tensor_a, tensor_b)

# Print results
print('Addition result:\n', add_result)
print('Subtraction result:\n', sub_result)
print('Multiplication result:\n', mul_result)
print('Division result:\n', div_result)
Created two 2x2 tensors with float values.
Applied addition, subtraction, multiplication, and division using TensorFlow math functions.
Printed the results directly without converting tensors to numpy arrays.
Results Interpretation

Before operations, tensors are:
tensor_a = [[2, 4], [6, 8]]
tensor_b = [[1, 3], [5, 7]]

After operations:
Addition = [[3, 7], [11, 15]]
Subtraction = [[1, 1], [1, 1]]
Multiplication = [[2, 12], [30, 56]]
Division = [[2.0, 1.3333], [1.2, 1.1429]]

TensorFlow allows easy element-wise math operations on tensors, which is fundamental for building and training machine learning models.
Bonus Experiment
Try performing matrix multiplication (dot product) on the two tensors and compare it with element-wise multiplication.
💡 Hint
Use tf.matmul for matrix multiplication and compare the results with tf.multiply.