In Deep Learning one of the most common operation that is usually done is finding the *dot product *of vectors. In very simple terms dot product is a way of finding the product of the summation of two vectors and the output will be a single vector. This Wikipedia article has more details on dot products.

The following formula should make it clear where * *and * *are vectors.

then the dot product formula will be

Here is an example of dot product of 2 vectors.

so * *dot * *will be

Finding the dot product with *numpy* package is very easy with the numpy.dot package. Here is the implementation of the above example in Python using *numpy*.

1 2 3 4 5 |
import numpy as np X = [6,5,4] Y = [3,2,1] DotProduct = np.dot(X,Y) print('Dot product is : ' , DotProduct) |

If we did not have *numpy* package, then how do we do it in plain Python? Even this approach is not very difficult. Like in the earlier example we will define 2 vectors X and Y

1 2 |
X = [6,5,4] Y = [3,2,1] |

We perform 3 steps here i.e.

- Merge the vectors into pairs
- Multiply the values in each pair
- Add the product of each multiplication in step 2 to arrive at the dot product

For Step 1, we will make use of *zip *function. This function accepts two equal-length vectors and merges them into pairs. To see it in action, we will write a sample code to zip X and Y vectors.

1 2 |
for i, j in zip(X,Y): print(i,j) |

As you can see in the output, the the elements of the vector are now paired together based on their position in the respective vectors.

Once we have these pairs created, multiplication is simple. The last step is to add the products into a final value.

Here is the final script that we can use to get the dot product of two matrices.

1 2 3 4 5 6 |
X = [6,5,4] Y = [3,2,1] dotproduct=0 for i,j in zip(X,Y): dotproduct += i*j print('Dot product is : ' , dotproduct) |

Or we can make the script more compact like this

1 2 3 4 |
X = [6,5,4] Y = [3,2,1] dotproduct = sum(i*j for i,j in zip(X,Y)) print('Dot product is : ' , dotproduct) |

## Leave A Comment