## Numpy exercise

klayperson
Posts: 1
Joined: Thu Feb 18, 2021 12:37 am

### Numpy exercise

I didn't see a post about this exercise and I wanted to compare with others to see if I made the right approach.
I appended the values from the randomly generated array in order to make my lists.
From my result, using the array dot function is about 34-39 times faster than doing matrix multiplication using lists.
This ratio increases linearly with the increase in input size (i.e. 2x inputs = 2x dt1/dt2)

Let me know what y'all got. And any feedback on my code would be great!

Code: Select all

``````from datetime import datetime
a = np.random.randn(100)
b = np.random.randn(100)
T = 100000

L1=[]
L2=[]

for e, f in zip(a, b):
L1.append(e)
L2.append(f)

def slow_matrix_multiplication(L1, L2):
result = 0
for i in range(len(L1)):
result += L1[i]*L2[i]
return result

t0 = datetime.now()
for t in range(T):
slow_matrix_multiplication(L1, L2)
dt1 = datetime.now() - t0

t0 = datetime.now()
for t in range(T):
a.dot(b)
dt2 = datetime.now() - t0

print("dt1 / dt2: ", dt1.total_seconds() / dt2.total_seconds())``````
BabaKirtos
Posts: 5
Joined: Sat Apr 03, 2021 1:00 pm

### Re: Numpy exercise

Hello, there seems to be some logical problem with your code, the exercise is about comparing matrix multiplication using lists and numpy dot operator. Your code seems to be multiplying randomly generated 1D arrays, using for loop then the dot operator.
I wasn't able to generate random lists, so I used pre initialized lists, you can look at my code below. I observed that the numpy dot operator is around 2-3 times faster than using 3 for loops.

Code: Select all

``````# DLP - Numpy - Exercise

import numpy as np
from datetime import datetime

def matrix_mul_list(L1,L2):
result = 0
R = []
A = []
for l in  range(len(L1)):
for m in range(len(L2[0])):
for n in range(len(L2)):
result += L1[l][n]*L2[n][m]
R.append(result)
result = 0
A.append(R)
R = []
return A

L1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
L2 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

N1 = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
N2 = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

t0 = datetime.now()
print(matrix_mul_list(L1,L2))
dt1 = datetime.now() - t0

print(' ')

t0 = datetime.now()
print(N1.dot(N2))
dt2 = datetime.now() - t0

print(' ')

print('Matrix multiplication is ' + str(dt2/dt1) + ' times faster.')
``````
Last edited by BabaKirtos on Sat Apr 03, 2021 2:38 pm, edited 1 time in total.