﻿ Python TensorFlow dot product of two vectors

Python TensorFlow dot product of two vectors

Python TensorFlow Basic: Exercise-5 with Solution

Write a Python program that uses TensorFlow to compute the dot product of two vectors (1-D tensors).

Sample Solution:

Python Code:

``````import tensorflow as tf

# Create two 1-D TensorFlow tensors (vectors)
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
vector1 = tf.constant([1, 3, 5], dtype=tf.float32)
vector2 = tf.constant([2, 4, 6], dtype=tf.float32)

# Compute the dot product
dot_product = tf.reduce_sum(tf.multiply(vector1, vector2))

# Print the result
print("Vector 1:", vector1.numpy())
print("Vector 2:", vector2.numpy())
print("Dot Product of the said to vectors:", dot_product.numpy())
```
```

Output:

```Vector 1: [1. 3. 5.]
Vector 2: [2. 4. 6.]
Dot Product of the said to vectors: 44.0
```

Explanation:

In the exercise above, we first create two 1-D TensorFlow tensors vector1 and vector2 with the values [1.0, 3.0, 5.0] and [2.0, 4.0, 6.0], respectively. Next we use "tf.multiply" to perform element-wise multiplication of the two vectors and "tf.reduce_sum" to compute the sum of the resulting elements, which is the dot product. Finally, we print the original vectors and the dot product result.

Python Code Editor:

What is the difficulty level of this exercise?

﻿