Module 2 · NumPy and SciPy · Lesson 14 of 66

SciPy: math built on NumPy

Solve equations, take matrices apart and handle huge, mostly empty matrices with SciPy.

In this lesson · about 15 minutes

  • Find a determinant, eigenvalues and an LU decomposition with scipy.linalg
  • Solve a system of linear equations
  • Build and solve a sparse matrix

SciPy is a library of ready-made math built on NumPy arrays: linear algebra, statistics, optimization, signal processing, interpolation and more. Much of scikit-learn runs on it. Each area is a submodule you import on its own, such as scipy.linalg for matrices.

Linear algebra

For a square matrix A, linalg.det(A) gives its determinant (zero means the matrix can't be inverted), and linalg.eig(A) gives its eigenvalues and eigenvectors: the directions the matrix only stretches, and by how much. PCA, later in the course, is built on exactly this.

linalg.lu splits A into a permutation matrix P (it reorders rows), a lower triangular L and an upper triangular U. Multiplied back together they give A again. Computers use this to solve equations quickly.

A system of linear equations such as x + 2y + 3z = 2, 4x + 5y + 6z = 3, 7x + 8y + 8z = 5 is the matrix equation A @ s = v. linalg.solve(A, v) finds s.

Exercise

Solve three equations

Solve the three equations above: A is ready, and v is np.array([2, 3, 5]). Put the answer in s and end with it. Then, to check, A @ s should give back v.

Code that runs before yours
import numpy as np
from scipy import linalg
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 8]])

Exercise

Eigenvalues

Get the eigenvalues and eigenvectors of A with linalg.eig as EW and EV. The eigenvalues come back as complex numbers; end with just their real parts, EW.real.

Code that runs before yours
import numpy as np
from scipy import linalg
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 8]])

Sparse matrices

Many real matrices are huge and almost all zeros: which customer bought which of a million products, or which word appears in which document. Storing every zero wastes memory. scipy.sparse stores only the non-zero values. A lil_matrix (list of lists) is easy to fill in; convert it with .tocsr() (compressed sparse rows) before doing math, which is much faster in that form.

Exercise

Build a sparse matrix

Make a 500 × 500 lil_matrix called M, set its diagonal to 2 with M.setdiag(2), and set the top-right corner, M[0, 499], to 7. Convert it to CSR form, still called M, and end with M.nnz, the number of values stored.

Code that runs before yours
import numpy as np
from scipy import sparse

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.