Finding the dot product in Python without using Numpy

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 $\vec{X}$ and $\vec{Y}$ are vectors.

$\vec{X}=(x_1,x_2...x_n)$

$\vec{Y}=(y_1,y_2...y_n)$

then the dot product formula will be

$\vec{X}.\vec{Y}=(x_1y_1+x_2y_2+...+x_ny_n)$

Here is an example of dot product of 2 vectors.

$\vec{X}=(6,5,4)\vec {Y}=(3,2,1)$ so $\vec{X}$  dot $\vec{Y}$ will be

$\vec{X}.\vec{Y}=(6*3+5*2+4*1) = 32$

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.

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

We perform 3 steps here i.e.

1. Merge the vectors into pairs
2. Multiply the values in each pair
3. 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.

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.

Or we can make the script more compact like this

By | 2017-04-18T12:16:20+00:00 April 18th, 2017|machine learning, python|0 Comments