12 Ways to Boost Data Science Matrix Ops: Numpy to Cython
Python Matrix Ops: Faster, Further, Better
Lately, I’ve been using Python for scientific computing, but I’m bothered by its slow speed.
Matrix calculations are also sluggish. Let me share some tips to speed things up.
You can accelerate in two ways: through high-level API and low-level API.
Low-Level API
The simplest and crudest way is to directly traverse with a triple loop:
def matrix_multiplication_loop(A, B):
m = A.shape[0]
n = A.shape[1]
l = B.shape[1]
C = np.zeros([m, l])
for i in range(m):
for j in range(l):
for k in range(n):
C[i][j] += A[i][k] * B[k][j] # Accumulate the result of each multiplication
return C
A = np.random.random([300, 12])
B = np.random.random([12, 256])
%timeit C = matrix_multiplication_loop(A, B)
1 loop, best of 3: 2.22 s per loop
Keep reading with a 7-day free trial
Subscribe to Top Python Libraries to keep reading this post and get 7 days of free access to the full post archives.