# Vectorization in Python

This post will take you to the** Vectorization part of Python. **We are aware that a sizable amount of statistics must be handled by the majority of the software. Therefore, a computationally inefficient function might cause a significant bottleneck in the approach and cause your model to operate slowly. We will employ vectorization to help ensure the program is reasonably effective.

Vectorization is part of machine learning and automation. Python contains numerous common mathematical methods that can perform quick computations on whole data arrays without the need for loops. Numpy is one such library that includes such a function. Let’s look at how we may utilize this common function in a vectorization scenario.

## Vectorization:

Without utilizing loops, vectorization speeds up the Python code. Utilizing such a method can effectively minimize the amount of time that code needs to run. We can employ vectorization in Python for a lot of things like scaler multiplication or dot product multiplication.

Now let us see some examples of Vectorization in Python.

## Dot Product:

A dot product is a mathematical process that multiplies two vectors of equal length and yields a single integer. The single integer results in the scaler output which has only magnitude and not any direction. We calculate the dot product as the *element-wise product* of the two vectors added together. We provide 2 matrices of size nx1, a, and b, and we calculate the dot product by getting the transpose of the first matrix and then multiplying the transpose of a and b mathematically.

Python code for the dot product will be:

# importing all the libaries #import time for the timing related computations import time import numpy import array #initializing array1 and array2 with the ranges. array1 = array.array('q') for i in range(100000): array1.append(i); array2 = array.array('q') for i in range(100000, 200000): array2.append(i) # finding dot product initial_time = time.process_time() dot = 0.0; for i in range(len(array1)): dot += array1[i] * array2[i] final_time = time.process_time() print("The dot_product = "+ str(dot)); print("calculated time = " + str(1000*(final_time - initial_time )) + " ms") n_initial_time = time.process_time() n_dot_product = numpy.dot(array1, array2) n_final_time = time.process_time() print("\nThe n_dot_product = "+str(n_dot_product)) print("Calculated time = "+str(1000*(n_final_time - n_initial_time ))+" ms")

Output:

dot_product = 833323333350000.0 Computation time = 31.25 ms n_dot_product = 833323333350000 Computation time = 0.0 ms

With this, we have concluded our tutorial on Vectorizayion in Python. Learn Simplification of images with binarization in OpenCV Python.

## Leave a Reply