Code Explanation:
1. Import TensorFlow
import tensorflow as tf
Imports TensorFlow library.
TensorFlow is used for numerical computing with tensors (multidimensional arrays).
2. Define Tensor x
x = tf.constant([2,4,6], dtype=tf.float32)
Creates a constant tensor with values [2, 4, 6].
Data type is explicitly set to float32.
Value of x:
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([2., 4., 6.], dtype=float32)>
3. Define Tensor y
y = tf.constant([1,2,3], dtype=tf.float32)
Creates another constant tensor with values [1, 2, 3].
Value of y:
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 2., 3.], dtype=float32)>
4. Multiply Element-wise
x * y
TensorFlow performs element-wise multiplication:
[2,4,6]×[1,2,3]=[2,8,18]
5. Reduce Sum
z = tf.reduce_sum(x * y)
tf.reduce_sum adds up all elements in the tensor [2, 8, 18].
2+8+18=28
So, z becomes:
<tf.Tensor: shape=(), dtype=float32, numpy=28.0>
6. Convert Tensor to NumPy
print(z.numpy())
.numpy() extracts the raw number from the Tensor.
Final Output
28.0
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment