Numpy, Scipy, and Pandas provide a significant increase in computational efficiency with complex mathematical operations as compared to Python's built-in arithmetic functions. In this lab, you will calculate and compare the processing speed required for calculating a dot product using both basic arithmetic operations in Python and Numpy's .dot()
method.
You will be able to:
- Compare the performance of high-dimensional matrix operations in Numpy vs. pure Python
Write a routine to calculate the dot product between two
a) Pure Python (no libraries)
b) Numpy's .dot()
method
Create two $200 \times 200$ matrices in Python and fill them with random values using np.random.rand()
# Compare 200x200 matrix-matrix multiplication speed
import numpy as np
# Set up the variables
A = None
B = None
- Initialize a zeros-filled
numpy
matrix - In Python, calculate the dot product using the formula
- Use Python's
timeit
library to calculate the processing time - Visit this link for an in-depth explanation on how to time a function or routine in Python
Hint: Use a nested for
loop for accessing, calculating, and storing each scalar value in the resulting matrix.
import timeit
# Start the timer
start = None
# Matrix multiplication in pure Python
time_spent = None
print('Pure Python time:', time_spent, 'sec.')
Set the timer and calculate the time taken by the .dot()
method for multiplying
# Start the timer
start = None
# Matrix multiplication in numpy
time_spent = None
print('Numpy time:', time_spent, 'sec.')
In this lab, you performed a quick comparison between calculating a dot product in Numpy vs pure Python. You saw that Numpy is computationally much more efficient than pure Python code because of the sophisticated implementation of Numpy source code. You're encouraged to always perform time tests to fully appreciate the use of an additional library in Python.