Linear Algebra in Practice
local graph
Linear Algebra in Practice
Now that we understand the geometric structure of vector spaces, it’s time to put the theory into practice once again. In this chapter, we’ll take a hands-on look at norms, inner products, and NumPy array operations in general. Most importantly, we’ll also meet matrices for the first time.
The last time we translated theory to code, we left off at finding an ideal representation for vectors: NumPy arrays. NumPy is built for linear algebra and handles computations much faster than the vanilla Python objects.
So, let’s initialize two NumPy arrays to play around with!
import numpy as np
x = np.array([1.8, -4.5, 9.2, 7.3])y = np.array([-5.2, -1.1, 0.7, 5.1])In linear algebra, and in most of machine learning, almost all operations involve looping through the vector components one by one. For instance, addition can be implemented like this.
def add(x: np.ndarray, y: np.ndarray): x_plus_y = np.zeros(shape=len(x))
for i in range(len(x_plus_y)): x_plus_y[i] = x[i] + y[i]
return x_plus_yadd(x, y)array([-3.4, -5.6, 9.9, 12.4])Of course, this is far from optimal. (It may not even work if the vectors have different dimensions.)
For example, addition is massively parallelizable, and our implementation does not take advantage of that. With two threads, we can do two additions simultaneously. So, adding together two-dimensional vectors would require just one step, as one would compute x[0] + y[0], while the other x[1] + y[1]. Raw Python does not have access to such high-performance computing tools, but NumPy does, through functions implemented in C. In turn, C uses the LAPACK (Linear Algebra PACKage) library, which makes calls to BLAS (Basic Linear Algebra Subprograms). BLAS is optimized at the assembly level.
So, whenever it is possible, we should strive to work with vectors in a NumPythonic way. (Yes, I just made that term up.) For vector addition, this is simply the + operator, as we have seen earlier.
np.equal(x + y, add(x, y))array([ True, True, True, True])By the way, you shouldn’t ever compare floats with the == operator, as internal rounding errors can occur due to the float representation. The example below illustrates this.
1.0 == 0.3*3 + 0.1False0.3*3 + 0.10.9999999999999999To compare arrays, NumPy provides the functions np.allclose and np.equal. These compare arrays elementwise, returning a Boolean array. From this, the built-in all function can be used to see if all the elements match.
all(np.equal(x + y, add(x, y)))TrueIn the following section, we’ll briefly review how to work with NumPy arrays in practice.
Bookmark
3.1 Vectors in NumPy
Section titled “3.1 Vectors in NumPy”There are two operations that we definitely want to do with our vectors: apply a function elementwise or take the sum/product of the elements. Since the +, *, and ** operators are implemented for our arrays, certain functions carry over from scalars, as the example below shows.
def just_a_quadratic_polynomial(x): return 3*x**2 + 1
x = np.array([1.8, -4.5, 9.2, 7.3])just_a_quadratic_polynomial(x)array([ 10.72, 61.75, 254.92, 160.87])However, we can’t just plug in ndarrays to every function. For instance, let’s take a look at Python’s built-in exp from its math module.
from math import exp
exp(x)---------------------------------------------------------------------------TypeError Traceback (most recent call last)Cell In[10], line 3 1 from math import exp----> 3 exp(x)
TypeError: only length-1 arrays can be converted to Python scalarsTo overcome this problem, we could manually apply the function elementwise.
def naive_exp(x: np.ndarray): x_exp = np.empty_like(x)
for i in range(len(x)): x_exp[i] = exp(x[i])
return x_exp(Recall that np.empty_like(x) creates an uninitialized array that matches the dimensions of x.)
naive_exp(x)array([6.04964746e+00, 1.11089965e-02, 9.89712906e+03, 1.48029993e+03])A bit less naive implementation would use a list comprehension to achieve the same effect.
def bit_less_naive_exp(x: np.ndarray): return np.array([exp(x_i) for x_i in x])
bit_less_naive_exp(x)array([ 6. , 0. , 9897.1, 1480.3])Even though comprehensions are more concise and readable, they still don’t avoid the core issue: for loops in Python.
This problem is solved by NumPy’s famous ufuncs, that is, functions that operate element by element on whole arrays ( https://numpy.org/doc/stable/reference/generated/numpy.ufunc.html). Since they are implemented in C, they are blazing fast. For instance, the exponential function f(x) = ex is given by np.exp.
np.exp(x)array([6.04964746e+00, 1.11089965e-02, 9.89712906e+03, 1.48029993e+03])Not surprisingly, the results of our implementations match.
all(np.equal(naive_exp(x), np.exp(x)))Trueall(np.equal(bit_less_naive_exp(x), np.exp(x)))TrueAgain, there are more advantages to using NumPy functions and operations than simplicity. In machine learning, we care a lot about speed, and as we are about to see, NumPy delivers once more.
from timeit import timeit
n_runs = 100000size = 1000
t_naive_exp = timeit( "np.array([exp(x_i) for x_i in x])", setup=f"import numpy as np; from math import exp; x = np.ones({size})", number=n_runs)
t_numpy_exp = timeit( "np.exp(x)", setup=f"import numpy as np; from math import exp; x = np.ones({size})", number=n_runs)
print(f"Built-in exponential: \t{t_naive_exp:.5f} s")print(f"NumPy exponential: \t{t_numpy_exp:.5f} s")print(f"Performance improvement: \t{t_naive_exp/t_numpy_exp:.5f} times faster")Built-in exponential: 18.35177 sNumPy exponential: 0.87458 sPerformance improvement: 20.98356 times fasterFor further reference, you can find the list of available ufuncs here: https://numpy.org/doc/stable/reference/ufuncs.html\#available-ufuncs.
What about operations that aggregate the elements and return a single value? Not surprisingly, these can be found within NumPy as well. For instance, let’s take a look at the sum. In terms of mathematical formulas, we are looking to implement the function

A basic approach would be something like this.
def naive_sum(x: np.ndarray): val = 0
for x_i in x: val += x_i
return val
naive_sum(x)np.float64(13.799999999999999)Alternatively, we can use Python’s built-in summing function.
sum(x)np.float64(13.799999999999999)The story is the same: NumPy can do this better. We can either call the function np.sum or use the array method np.ndarray.sum.
np.sum(x)np.float64(13.799999999999999)x.sum()np.float64(13.799999999999999)You know by now that I love timing functions, so let’s compare the performances once more.
t_naive_sum = timeit( "sum(x)", setup=f"import numpy as np; x = np.ones({size})", number=n_runs)
t_numpy_sum = timeit( "np.sum(x)", setup=f"import numpy as np; x = np.ones({size})", number=n_runs)
print(f"Built-in sum: \t{t_naive_sum:.5f} s")print(f"NumPy sum: \t{t_numpy_sum:.5f} s")print(f"Performance improvement: \t{t_naive_sum/t_numpy_sum:.5f} times faster")Built-in sum: 5.52380 sNumPy sum: 0.35774 sPerformance improvement: 15.44076 times fasterSimilarly, the product

is implemented by the np.prod function and the np.ndarray.prod method.
np.prod(x)np.float64(-543.996)On quite a few occasions, we need to find the maximum or minimum of an array. We can do this using the np.max and np.min functions. (Similarly to the others, these are also available as array methods.) The rule of thumb is if you want to perform any array operation, use NumPy functions.
3.1.1 Norms, distances, and dot products
Section titled “3.1.1 Norms, distances, and dot products”Now that we have reviewed how to perform operations on our vectors efficiently, it’s time to dive deep into the really interesting part: norms and distances.
Let’s start with the most important one: the Euclidean norm, also known as the 2-norm, defined by

A straightforward implementation would be the following.
def euclidean_norm(x: np.ndarray): return np.sqrt(np.sum(x**2))Note that our euclidean_norm function is dimension-agnostic; that is, it works for arrays of every dimension.
# a 1D array with 4 elements, which is a vector in 4-dimensional spacex = np.array([-3.0, 1.2, 1.2, 2.1])
# a 1D array with 2 elements, which is a vector in 2-dimensional spacey = np.array([8.1, 6.3])
euclidean_norm(x)np.float64(4.036087214122113)euclidean_norm(y)np.float64(10.261578825892242)But wait, didn’t I just mention that we should use NumPy functions whenever possible? Norms are important enough to have their own functions: np.linalg.norm.
np.linalg.norm(x)np.float64(4.036087214122113)With a quick inspection, we can check that these match for our vector x.
np.equal(euclidean_norm(x), np.linalg.norm(x))np.True_However, the Euclidean norm is just a special case of p-norms. Recall that for any p ∈ [0,∞), we defined the p-norm by the formula

and

for p = ∞. It is a good practice to keep the number of functions in a codebase minimal to reduce maintenance costs. Can we compact all p-norms into a single Python function that takes the value of p as an argument? Sure. We only have a small issue: representing ∞. Python and NumPy both provide their own representations, but we will go with NumPy’s np.inf. Surprisingly, this is a float type.
type(np.inf)floatdef p_norm(x: np.ndarray, p: float): if np.isinf(p): return np.max(np.abs(x)) elif p 1: return (np.sum(np.abs(x)**p))**(1/p) else: raise ValueError("p must be a float larger or equal than 1.0 or inf."Since ∞ can have multiple other representations, such as Python’s built-in math.inf, we can make our function more robust by using the np.isinf function to check if an object represents ∞ or not.
A quick check shows that p_norm works as intended.
x = np.array([-3.0, 1.2, 1.2, 2.1])
for p in [1, 2, 42, np.inf]: print(f"p-norm for p = {p}: \t {p_norm(x, p=p):.5f}"p-norm for p = 1: 7.50000p-norm for p = 2: 4.03609p-norm for p = 42: 3.00000p-norm for p = inf: 3.00000However, once again, NumPy is one step ahead of us. In fact, the familiar np.linalg.norm already does this out of the box. We can achieve the same with less code by passing the value of p as the argument ord, short for order. For ord = 2, we obtain the good old 2-norm.
for p in [1, 2, 42, np.inf]: print(f"p-norm for p = {p}: \t {np.linalg.norm(x, ord=p):.5f}"p-norm for p = 1: 7.50000p-norm for p = 2: 4.03609p-norm for p = 42: 3.00000p-norm for p = inf: 3.00000Somewhat surprisingly, distances don’t have their own NumPy functions. However, as the most common distance metrics are generated from norms (Section 2.1.1), we can often write our own. For instance, here is the Euclidean distance.
def euclidean_distance(x: np.ndarray, y: np.ndarray): return np.linalg.norm(x - y, ord=2)Besides norms and distances, the third component that defines the geometry of our vector spaces is the inner product. During our journey, we’ll almost exclusively use the dot product, defined in the vector space ℝn by

By now, you can easily smash out a Python function that calculates this. In principle, the one-liner below should work.
def dot_product(x: np.ndarray, y: np.ndarray): return np.sum(x*y)Let’s test this out!
x = np.array([-3.0, 1.2, 1.2, 2.1])y = np.array([1.9, 2.5, 3.9, 1.2])
dot_product(x, y)np.float64(4.5)When the dimension of the vectors doesn’t match, the function throws an exception as we expect.
x = np.array([-3.0, 1.2, 1.2, 2.1])y = np.array([1.9, 2.5])
dot_product(x, y)---------------------------------------------------------------------------ValueError Traceback (most recent call last)Cell In[39], line 4 1 x = np.array([-3.0, 1.2, 1.2, 2.1]) 2 y = np.array([1.9, 2.5])----> 4 dot_product(x, y)
Cell In[37], line 2, in dot_product(x, y) 1 def dot_product(x: np.ndarray, y: np.ndarray):----> 2 return np.sum(x*y)
ValueError: operands could not be broadcast together with shapes (4,) (2,)However, upon further attempts to break the code, a strange thing occurs. Our function dot_product should fail when called with an n-dimensional and one-dimensional vector, and this is not what happens.
x = np.array([-3.0, 1.2, 1.2, 2.1])y = np.array([2.0])
dot_product(x, y)np.float64(3.0)I always advocate breaking solutions in advance to avoid later surprises, and the above example excellently illustrates the usefulness of this principle. If the previous phenomenon occurs in production, you would have code that executes properly but gives a totally wrong result. That’s the worst kind of bug.
Behind the scenes, NumPy is doing something called broadcasting. When performing an operation on two arrays with mismatching shapes, it tries to guess the correct sizes and reshape them so that the operation can go through. Check out what takes place when calculating x*y.
x*yarray([-6. , 2.4, 2.4, 4.2])NumPy guessed that we want to multiply all elements of x by the scalar y[0], so it transforms y = np.array([2.0]) into np.array([2.0, 2.0, 2.0, 2.0]), then calculates the elementwise product.
Broadcasting is extremely useful because it allows us to write much simpler code by automagically performing transformations. Still, if you are unaware of how and when broadcasting is done, it can seriously come back to bite you. Just like in our case, as the inner product of a four-dimensional and one-dimensional vector is not defined.
To avoid writing excessive checks for edge cases (or missing them altogether), we calculate the inner product in practice using the np.dot function.
x = np.array([-3.0, 1.2, 1.2, 2.1])y = np.array([1.9, 2.5, 3.9, 1.2])
np.dot(x, y)np.float64(4.5)When attempting to call np.dot with misaligned arrays, it fails as supposed to, even in cases when broadcasting bails out our custom implementation.
x = np.array([-3.0, 1.2, 1.2, 2.1])y = np.array([2.0])
np.dot(x, y)---------------------------------------------------------------------------ValueError Traceback (most recent call last)Cell In[43], line 4 1 x = np.array([-3.0, 1.2, 1.2, 2.1]) 2 y = np.array([2.0])----> 4 np.dot(x, y)
ValueError: shapes (4,) and (1,) not aligned: 4 (dim 0) != 1 (dim 0)Now that we have a basic arsenal of array operations and functions, it is time to do something with them!
3.1.2 The Gram-Schmidt orthogonalization process
Section titled “3.1.2 The Gram-Schmidt orthogonalization process”One of the most fundamental algorithms in linear algebra is the Gram-Schmidt orthogonalization process (Theorem 13), used to turn a set of linearly independent vectors into an orthonormal set.
To be more precise, for our input of a set of linearly independent vectors v1,…,vn ∈ℝn, the Gram-Schmidt process finds the output set of vectors e1,…,en ∈ℝn such that ∥ei∥ = 1 and ⟨ei,ej⟩ = 0 for all i≠j (that is, the vectors are orthonormal), and span(e1,…,ek) = span(v1,…,vk) for all k = 1,…,n.
If you are having trouble recalling how this is done, feel free to revisit Section 2.2.5, where we first described the algorithm. The learning process is a spiral, where we keep revisiting old concepts from new perspectives. For the Gram-Schmidt process, this is our second iteration, where we put the mathematical formulation into code.
Since we are talking about a sequence of vectors, we need a suitable data structure for this purpose. There are several possibilities for this in Python. For now, we are going with the conceptually simplest, albeit computationally rather suboptimal, one: lists.
vectors = [np.random.rand(5) for _ in range(5)] # randomly generated vectors in a listvectors[array([0.85885635, 0.05917163, 0.42449235, 0.39776749, 0.89750107]), array([0.49579437, 0.42797077, 0.21057023, 0.3091438 , 0.52590854]), array([0.73079791, 0.58140107, 0.09823772, 0.14323477, 0.63606972]), array([0.89495164, 0.40614454, 0.60637559, 0.61614928, 0.69006552]), array([0.1996764 , 0.90298211, 0.70604567, 0.45721469, 0.02375226])]The first component of the algorithm is the orthogonal projection operator, defined by

With our NumPy tools, the implementation is straightforward by now.
from typing import List
def projection(x: np.ndarray, to: List[np.ndarray]): """ Computes the orthogonal projection of the vector \`x\` onto the subspace spanned by the set of vectors \`to\`. """ p_x = np.zeros_like(x)
for e in to: e_norm_square = np.dot(e, e) p_x += np.dot(x, e)*e/e_norm_square
return p_xTo check if it works, let’s look at a simple example and visualize the results. Since this book is written in Jupyter Notebooks, we can do it right here.
x = np.array([1.0, 2.0])e = np.array([2.0, 1.0])
x_to_e = projection(x, to=[e])import matplotlib.pyplot as plt
with plt.style.context("seaborn-v0_8"): plt.figure(figsize=(7, 7)) plt.xlim([-0, 3]) plt.ylim([-0, 3]) plt.arrow(0, 0, x[0], x[1], head_width=0.1, color="r", label="x", linewidth=2) plt.arrow(0, 0, e[0], e[1], head_width=0.1, color="g", label="e", linewidth=2) plt.arrow(x_to_e[0], x_to_e[1], x[0] - x_to_e[0], x[1] - x_to_e[1], linestyle="--") plt.arrow(0, 0, x_to_e[0], x_to_e[1], head_width=0.1, color="b", label="projection(x, to=[e])") plt.legend() plt.show()
Figure 3.1: The projection of x to e
Checking the orthogonality of e and x - x to e provides another means of verification.
np.allclose(np.dot(e, x - x_to_e), 0.0)TrueWhen writing code for production, a couple of visualizations and ad hoc checks are not enough. An extensive set of unit tests is customarily written to ensure that a function works as intended. We are skipping this to keep our discussion on track, but feel free to add some of your tests. After all, mathematics and programming are not a spectator’s sport.
With the projection function available to us, we are ready to knock the Gram-Schmidt algorithm out of the park.
def gram_schmidt(vectors: List[np.ndarray]): """ Creates an orthonormal set of vectors from the input that spans the same subspaces. """ output = []
# 1st step: finding an orthogonal set of vectors output.append(vectors[0]) for v in vectors[1:]: v_proj = projection(v, to=output) output.append(v - v_proj)
# 2nd step: normalizing the result output = [v/np.linalg.norm(v, ord=2) for v in output]
return output
gram_schmidt([np.array([2.0, 1.0, 1.0]), np.array([1.0, 2.0, 1.0]), np.array([1.0, 1.0, 2.0])])[array([0.81649658, 0.40824829, 0.40824829]), array([-0.49236596, 0.86164044, 0.12309149]), array([-0.30151134, -0.30151134, 0.90453403])]Let’s quickly test out this implementation with a simple example.
test_vectors = [np.array([1.0, 0.0, 0.0]), np.array([1.0, 1.0, 0.0]), np.array([1.0, 1.0, 1.0])]
gram_schmidt(test_vectors)[array([1., 0., 0.]), array([0., 1., 0.]), array([0., 0., 1.])]So, we have just created our first algorithm from scratch. This is like the base camp for Mount Everest. We have come a long way, but there is much further to go before we can create a neural network from scratch. Until then, the journey is packed with some beautiful sections, and this is one of them. Take a while to appreciate this, then move on when you are ready.
Remark 4. (Linearly dependent inputs of the Gram-Schmidt process)
Recall that if the input vectors of the Gram-Schmidt are linearly dependent, some vectors of the output are zero (Remark 3). In practice, this causes a lot of problems.
For instance, we normalize the vectors in the end, using list comprehension:
output = [v/np.linalg.norm(v, ord=2) for v in output]This can cause numerical issues. If any v is approximately 0, its norm np.linalg.norm(v, ord=2) is going to be really small, and division with such small numbers is problematic.
This issue also affects the projection function. Take a look at the definition below:
def projection(x: np.ndarray, to: List[np.ndarray]): """ Computes the orthogonal projection of the vector ‘x‘ onto the subspace spanned by the set of vectors ‘to‘. """ p_x = np.zeros_like(x)
for e in to: e_norm_square = np.dot(e, e) p_x += np.dot(x, e)*e / e_norm_square
return p_xIf e is (close to) 0, which can happen if the input vectors are linearly dependent, then e_norm_square is small. One way to solve this is to add a small float, say, 1e-16.
def projection(x: np.ndarray, to: List[np.ndarray]): p_x = np.zeros_like(x)
for e in to: e_norm_square = np.dot(e, e)
# note the change below: p_x += np.dot(x, e)*e / (e_norm_square + 1e-16)
return p_xNow, let’s meet the single most important objects in machine learning: matrices.
Bookmark
3.2 Matrices, the workhorses of linear algebra
Section titled “3.2 Matrices, the workhorses of linear algebra”I am quite sure that you were already familiar with the notion of matrices before reading this book. Matrices are one of the most important data structures that can represent systems of equations, graphs, mappings between vector spaces, and many more. Matrices are the fundamental building blocks of machine learning.
At first look, we define a matrix as a table of numbers. If the matrix A has, for instance, n rows and m columns of real numbers, we write

(3.1)
When we don’t want to write out the entire matrix as (3.1), we use the abbreviation A = (ai,j)i=1,j=1n,m.
The set of all n ×m real matrices is denoted by ℝn×m. We will exclusively talk about real matrices, but when referring to other types, this notation is modified accordingly. For instance, ℤ{n×m} denotes the set of integer matrices.
Matrices can be added and multiplied together, or multiplied by a scalar.
Definition 14. (Matrix operations)
(a) Let A ∈ℝn×m be a matrix and c ∈ℝ a real number. The multiple of A by the scalar c is defined by

(b) Let A,B ∈ℝn×m be two matrices of matching dimensions. Their sum A + B is defined by

(c) Let A ∈ℝn×l and B ∈ℝl×m be two matrices. Their product AB ∈ℝn×m is defined by

Scalar multiplication and addition are clear, but matrix multiplication is not as simple to understand. Fortunately, visualization can help. In essence, the (i,j)-th element is the dot product of the i-th row of A and the j-th column of B.

Figure 3.2: Visualizing matrix multiplication
Besides addition and multiplication, there is another operation that is worth mentioning: transposition.
Definition 15. (Matrix transposition)
Let A = (a{i,j}){i,j = 1}{n,m} ∈ ℝ{n×m} be a matrix. The matrix AT , defined by

is called the transpose of A. The operation A→AT is called transposition.
Transposition simply means “flipping” the matrix, replacing rows with columns. For example,

or

As opposed to addition and multiplication, transposition is a unary operation. (Unary means that it takes one argument. Binary operations take two arguments, and so on.)
Let’s take another look at matrix multiplication, one of the most frequently used operations in computing. As it can be performed extremely fast on modern computers, it is common to vectorize certain algorithms just to express it in terms of matrix multiplications.
Thus, the more we know about it, the better. To get a grip on the operation itself, we can take a look at it from a few different angles. Let’s start with a special case!
In machine learning, taking the product of a matrix and a column vector is a fundamental building block of certain models. For instance, this is linear regression in itself, or the famous fully connected layer in neural networks.
To see what happens in this case, let A ∈ℝn×m be a matrix. If we treat x ∈ℝm as a column vector x ∈ℝm×1, then Ax can be written as

Based on this, the matrix A describes a function that takes a piece of data x, then transforms it into the form Ax.
This is the same as taking the linear combination of the columns of A, that is,

With a bit more suggestive notation, by denoting the i-th column as ai, we can write
.png)
(3.2)
If we replace the vector x with a matrix B, the columns in the product matrix AB are linear combinations of the columns of A, where the coefficients are determined by B.
You should really appreciate that certain operations on the data can be written in the form Ax. Elevating this simple property to a higher level of abstraction, we can say that the data has the same representation as the function. If you are familiar with programming languages like Lisp, you know how beautiful this is.
There is one more way to think about the matrix product: taking the columnwise inner products. If ai = (ai,1,…,ai,n) denotes the i-th column of A, then Ax can be written as
.png)
(3.3)
That is, the transformation x→Ax projects the input x to the row vectors of A, then compacts the results in a vector.
3.2.1 Manipulating matrices
Section titled “3.2.1 Manipulating matrices”Because matrix operations are well defined, we can do algebra on matrices just as with numbers. However, there are some major differences. As manipulating matrix expressions is an essential skill, let’s take a look at its fundamental rules!
Theorem 16. (Properties of matrix addition and multiplication)
(a) Let A,B,C ∈ℝn×l be arbitrary matrices. Then,

holds. That is, matrix addition is associative.
(b) Let A ∈ℝn×l, B ∈ℝl×k, C ∈ℝk×m be arbitrary matrices. Then,

holds. That is, matrix multiplication is associative.
(c) Let A ∈ℝn×l and B,C ∈ℝl×m be arbitrary matrices. Then,

holds. That is, matrix multiplication is left-distributive with respect to addition.
(d) Let A,B ∈ℝn×l and C ∈ℝl×m be arbitrary matrices. Then,

holds. That is, matrix multiplication is right-distributive with respect to addition.
As the proof is extremely technical and boring, we are going to skip it. However, there are a few things to note. Most importantly, matrix multiplication is not commutative; that is, AB is not always equal to BA. (It might not even be defined.) For instance, consider

You can verify by hand that

which are not equal.
In line with this, the algebraic identities that we use for scalars are quite different. For instance, if A and B are matrices, then

or

Transposition also behaves nicely with respect to addition and multiplication.
Theorem 17. (Properties of transposition)
(a) Let A,B ∈ℝn×m be arbitrary matrices. Then,

holds.
(b) Let A ∈ℝn×l, B ∈ℝl×m be arbitrary matrices. Then,

holds.
We are not going to prove this either, but feel free to do so as an exercise.
3.2.2 Matrices as arrays
Section titled “3.2.2 Matrices as arrays”To perform computations with matrices inside a computer, we are looking for a data structure that represents a matrix A and supports
- accessing elements by A[i, j],
- assigning elements by A[i, j] = value
- addition and multiplication with the + and * operators,
and works lightning fast. These requirements only specify the interface of our matrix data structure, not the actual implementation. An obvious choice would be a list of lists, but as discussed when talking about representing vectors in computations (Section 1.3), this is highly suboptimal. Can we leverage the C array structure to store a matrix?
Yes, and this is precisely what NumPy does, providing a fast and convenient representation for matrices in the form of multidimensional arrays. Before learning how to use NumPy’s machinery for our purposes, let’s look a bit deeper into the heart of the issue.
At first glance, there seems to be a problem: a computer’s memory is one-dimensional, thus addressed (indexed) by a single key, not two as we want. Thus, we can’t just shove a matrix into the memory. The solution is to flatten the matrix and place each consecutive row next to each other, like Figure 3.3 illustrates in the 3 × 3 case. This is called row-major ordering.
By storing the rows of any n×m matrix in a contiguous array, we get all the benefits of the array data structure at the low cost of a simple index transformation defined by

(Note that for programming languages like Fortran or MATLAB that use column-major ordering — i.e., the columns are concatenated — this index transformation won’t work. I leave figuring out the correct transformation as an exercise to check your understanding.)

Figure 3.3: Flattening a matrix
To demonstrate what’s happening, let’s conjure up a prototypical Matrix class in Python that uses a single list to store all the values, yet supports accessing elements by row and column indices. For the sake of illustration, let’s imagine that a Python list is actually a static array. (At least until this presentation is over.) This is for educational purposes only, as at the moment, we only want to understand the process, not to maximize performance.
Take a moment to review the code below. I’ll explain everything line by line.
from typing import Tuple
class Matrix: def __init__(self, shape: Tuple[int, int]): if len(shape) != 2: raise ValueError("The shape of a Matrix object must be a two-dimensional tuple."
self.shape = shape self.data = [0.0 for _ in range(shape[0]*shape[1])]
def _linear_idx(self, i: int, j: int): return i*self.shape[1] + j
def __getitem__(self, key: Tuple[int, int]): linear_idx = self._linear_idx(*key) return self.data[linear_idx]
def __setitem__(self, key: Tuple[int, int], value): linear_idx = self._linear_idx(*key) self.data[linear_idx] = value
def __repr__(self): array_form = [ [self[i, j] for j in range(self.shape[1])] for i in range(self.shape[0]) ] return "\n".join(["\t".join([f"{x}" for x in row]) for row in array_form])The Matrix object is initialized with the __init__ method. This is called when an object is created, like we are about to do now.
M = Matrix(shape=(3, 4))Upon initialization, we supply the dimensions of the matrix in the form of a two-dimensional tuple, passed for the shape argument. In our concrete example, M is a 3 × 4 matrix, represented by an array of length 12. For simplicity, our simple Matrix is filled up with zeros by default.
Overall, the __init__ method performs three main tasks:
- Validates the shape parameter to ensure correctness
- Stores the shape in an instance attribute for future reference
- Initializes a list of size shape[0] * shape[1], which serves as the primary data storage
The second method, suggestively named _linear_idx, is responsible for translating between the row-column indices of the matrix and the linear index for our internal one-dimensional representation. (In Python, it is customary to prefix methods with an underscore if they are not intended to be called externally. Many other languages, such as Java, support private methods. Python is not one of them, so we have to make do with such polite suggestions instead of strictly enforced rules.)
We can implement item retrieval via indexing by providing the __getitem__ method, which expects a two-dimensional integer tuple as the key. For any key = (i, j), the method:
- Calculates the linear index using our _linear_idx method.
- Retrieves the element located at the given linear index from the list.
Item assignment happens similarly, as given by the __setitem__ magic method. Let’s try these out to see if they work.
M[1, 2] = 3.14M[1, 2]3.14By providing a __repr__ method, we specify how a Matrix object is represented as a string. So, we can print it out to the standard output in a pretty form.
M0.0 0.0 0.0 0.00.0 0.0 3.14 0.00.0 0.0 0.0 0.0Pretty awesome. Now that we understand some of the internals, it is time to see how much we can achieve with NumPy.
3.2.3 Matrices in NumPy
Section titled “3.2.3 Matrices in NumPy”As foreshadowed earlier, NumPy provides an excellent out-of-the-box representation for matrices in the form of multidimensional arrays. (These are often called tensors, but I’ll just stick to the naming array.)
I have some fantastic news: these are the same np.ndarray objects we have been using! We can create one by simply providing a list of lists during initialization.
import numpy as np
A = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
B = np.array([[5, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5]])Aarray([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])Everything works the same as we have seen so far. Operations are performed elementwise, and you can plug them into functions like np.exp.
A + B # pointwise additionarray([[ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]])A*B # pointwise multiplicationarray([[ 0, 5, 10, 15], [20, 25, 30, 35], [40, 45, 50, 55]])np.exp(A) # pointwise application of the exponential functionarray([[1.00000000e+00, 2.71828183e+00, 7.38905610e+00, 2.00855369e+01], [5.45981500e+01, 1.48413159e+02, 4.03428793e+02, 1.09663316e+03], [2.98095799e+03, 8.10308393e+03, 2.20264658e+04, 5.98741417e+04]])Since we are working with multidimensional arrays, the transposition operator can be defined. Here, this is conveniently implemented as the np.transpose function, but can also be accessed at the np.ndarray.T attribute.
np.transpose(A)array([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]])A.T # is the same as np.transpose(A)array([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]])As expected, we can get and set elements with the indexing operator []. The indexing starts from zero. (Don’t even get me started.)
A[1, 2] # 1st row, 2nd column (if we index rows and columns from zero)np.int64(6)Entire rows and columns can be accessed using slicing. Instead of giving the exact definitions, I’ll just provide a few examples and let you figure it out with your internal pattern matching engine. (That is, your brain.)
A[:, 2] # 2nd columnarray([ 2, 6, 10])A[1, :] # 1st rowarray([4, 5, 6, 7])A[2, 1:4] # 2nd row, 1st-4th elementsarray([ 9, 10, 11])A[1] # 1st rowarray([4, 5, 6, 7])When used as an iterable, a two-dimensional array yields its rows at every step.
for row in A: print(row)[0 1 2 3][4 5 6 7][ 8 9 10 11]Initializing arrays can be done with the familiar np.zeros, np.ones, and other functions.
np.zeros(shape=(4, 5))array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]])As you have guessed, that shape argument specifies the dimensions of the array. We are going to explore this property next. Let’s initialize an example multidimensional array with three rows and four columns.
A = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])Aarray([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])The shape of an array, stored inside the attribute np.ndarray.shape, is a tuple object describing its dimensions. In our example, since we have a 3 × 4 matrix, the shape equals (3, 4).
A.shape(3, 4)This innocent-looking attribute determines what kind of operations you can perform with your arrays. Let me tell you, as a machine learning engineer, shape mismatches will be the bane of your existence. You want to calculate the product of two matrices A and B? The second dimension of A must match the first dimension of B. Pointwise products? Matching or broadcastable shapes are required. Understanding shapes is vital.
However, we have just learned that multidimensional arrays are linear arrays in disguise. (See Section 3.2.2.) Because of this, we can reshape an array by slicing the linear view differently. For example, A can be reshaped into arrays with shapes (12, 1), (6, 2), (4, 3), (3, 4), (2, 6), and (1, 12).
A.reshape(6, 2) # reshapes A into a 6 x 2 matrixarray([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11]])The np.ndarray.reshape method returns a newly constructed array object but doesn’t change A. In other words, reshaping is not destructive in NumPy.
Aarray([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])Reshaping is hard to wrap your head around for the first time. To help you visualize the process, Figure 3.4 shows precisely what happens in our case.
If you are unaware of the exact dimension along a specific axis, you can get away by inputting -1 there during the reshaping. Since the product of dimensions is constant, NumPy is smart enough to figure out the missing one for you. This trick will get you out of trouble all the time, so it is worth taking note.
A.reshape(-1, 2)array([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11]])A.reshape(-1, 4)array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
Figure 3.4: Reshaping a one-dimensional array into multiple possible shapes
We won’t go into the details now, but as you probably guessed, multidimensional arrays can have more than two dimensions. The range of permitted shapes for the operations will be even more complicated, then. So, building a solid understanding now will provide a massive head start in the future.
3.2.4 Matrix multiplication, revisited
Section titled “3.2.4 Matrix multiplication, revisited”Without a doubt, one of the most important operations regarding matrices is multiplication. Computing determinants and eigenvalues? Matrix multiplication. Passing data through a fully connected layer? Matrix multiplication. Convolution? Matrix multiplication. We will see how these seemingly different things can be traced back to matrix multiplication; but first, let’s discuss the operation itself from a computational perspective.
First, recap the mathematical definition. For any A ∈ℝn×m and B ∈ℝm×l, their product is defined by the formula

Notice that the element in the i-th row and j-th column of AB is the dot product of A’s i-th row and B’s j-th column.
We can put this into code using the tools we have learned so far.
from itertools import product
def matrix_multiplication(A: np.ndarray, B: np.ndarray): # checking if multiplication is possible if A.shape[1] != B.shape[0]: raise ValueError("The number of columns in A must match the number of rows in B."
# initializing an array for the product AB = np.zeros(shape=(A.shape[0], B.shape[1]))
# calculating the elements of AB for i, j in product(range(A.shape[0]), range(B.shape[1])): AB[i, j] = np.sum(A[i, :]*B[:, j])
return ABLet’s test our function with an example that is easy to verify by hand.
A = np.ones(shape=(4, 6))B = np.ones(shape=(6, 3))matrix_multiplication(A, B)array([[6., 6., 6.], [6., 6., 6.], [6., 6., 6.], [6., 6., 6.]])The result is correct, as we expected.
Of course, matrix multiplication has its own NumPy function in the form of numpy.matmul.
np.matmul(A, B)array([[6., 6., 6.], [6., 6., 6.], [6., 6., 6.], [6., 6., 6.]])This yields the same result as our custom function. We can test it out by generating a bunch of random matrices and checking if the results match.
for _ in range(100): n, m, l = np.random.randint(1, 100), np.random.randint(1, 100), np.random.randint(1, 100) A = np.random.rand(n, m) B = np.random.rand(m, l)
if not np.allclose(np.matmul(A, B), matrix_multiplication(A, B)): print(f"Result mismatch for\n{A}\n and\n{B}" breakelse: print("All good! Yay!"All good! Yay!According to this small test, our matrix_multiplication function yields the same result as NumPy’s built-in one. We are happy, but don’t forget: always use your chosen framework’s implementations in practice, whether it be NumPy, TensorFlow, or PyTorch.
Since writing np.matmul is cumbersome when lots of multiplications are present, NumPy offers a way to abbreviate using the @ operator.
A = np.ones(shape=(4, 6))B = np.ones(shape=(6, 3))
np.allclose(A @ B, np.matmul(A, B))True3.2.5 Matrices and data
Section titled “3.2.5 Matrices and data”Now that we are familiar with matrix multiplication, it’s time to make sense of them outside of linear algebra. Let’s take a matrix A ∈ℝn×m and a vector x ∈ℝm. By treating x as a column vector x ∈ℝm×1, the product of A and x can be calculated by

Mathematically speaking, looking at x as a column vector is perfectly natural. Think of it as extending ℝm with a dummy dimension, thus obtaining ℝm×1. This form also comes naturally by considering that the columns of a matrix are images of the basis vectors by their very definition.
In practice, things are not as simple as they look. Implicitly, we have made a choice here: to represent datasets as a horizontal stack of column vectors. To elaborate further, let’s consider two data points with four features and a matrix that maps these into a three-dimensional feature space. That is, let x1,x2 ∈ℝ4 and A ∈ℝ3×4.
x1 = np.array([2, 0, 0, 0]) # first data pointx2 = np.array([-1, 1, 0, 0]) # second data point
A = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) # a feature transformation(I specifically selected these numbers so that the calculations would be easily verifiable by hand.) To be sure, we double-check the shapes.
A.shape(3, 4)x1.shape(4,)What happens when we call the np.matmul function?
np.matmul(A, x1)array([ 0, 8, 16])The result is correct. However, when we have a bunch of input data points, we prefer to calculate the images using a single operation. This way, we can take advantage of vectorized code, locality of reference, and all the juicy computational magic we have seen so far.
We can achieve this by horizontally stacking the column vectors, each one representing a data point. Mathematically speaking, we want to perform the calculation in code.

Upon looking up the NumPy documentation, we quickly find that the np.hstack function might be the tool for the job, at least according to its official documentation ( https://numpy.org/doc/stable/reference/generated/numpy.hstack.html). Yay!
np.hstack([x1, x2]) # np.hstack takes a list of np.ndarrays as its argumentarray([ 2, 0, 0, 0, -1, 1, 0, 0])Not yay. What happened? np.hstack treats one-dimensional arrays differently, and even though the math works out perfectly by creatively abusing the notation, we don’t get away that easily in the trenches of real-life computations. Thus, we have to reshape our inputs manually. Meet the true skill gap between junior and senior machine learning engineers: correctly shaping multidimensional arrays.
# x.reshape(-1,1) turns x into a column vectordata = np.hstack([x1.reshape(-1, 1), x2.reshape(-1, 1)])dataarray([[ 2, -1], [ 0, 1], [ 0, 0], [ 0, 0]])Let’s try this one more time.
np.matmul(A, data)array([[ 0, 1], [ 8, 1], [16, 1]])Yay! (For real this time.)
Note that we made an extremely impactful choice in this chapter: representing individual data points as column vectors. I have written this in bold to emphasize its importance.
Why? Because we could have gone the other way and treated samples as row vectors. With our current choice, we ended up with a multidimensional array of shape

as opposed to

The former is called batch-last, while the latter is called batch-first format. Popular frameworks like TensorFlow and PyTorch use batch-first, but we are going with batch-last. The reasons go back to the very definition of matrices, where columns are the images of basis vectors under the given linear transformation. This way, we can write multiplication from left to right, like Ax and AB.
Should we define matrices as rows of basis vector images, everything turns upside down. This way, if f and g are linear transformations with “matrices” A and B, the “matrix” of the composed transformation f ∘g would be BA. This makes the math complicated and ugly.
On the other hand, batch-first makes the data easier to store and read. Think about a situation when you have thousands of data points in a single CSV file. Due to how input-output is implemented, files are read line by line, so it is natural and convenient to have a single line correspond to a single sample.
There are no good choices here; there are sacrifices either way. Since the math works out much easier for batch-last, we will use that format. However, in practice, you’ll find that batch-first is more common. With this textbook, I don’t intend to give you just a manual. My goal is to help you understand the internals of machine learning. If I succeed, you’ll be able to apply your knowledge to translate between batch-first and batch-last seamlessly.
Bookmark
3.3 Summary
Section titled “3.3 Summary”In this chapter, we finally dug into the trenches of practice instead of merely looking out from the towers of theory. Previously, we saw that NumPy arrays are the ideal tools for numeric computations, especially linear algebra. Now, we use them to provide fast and elegant implementations of what we learned in the previous chapter: norms, distances, dot products, and the Gram-Schmidt process.
Besides vectors, we also finally introduced matrices, one of the most important tools of machine learning. This time, we introduced, in a practical manner, viewing matrices as a table of numbers. Matrices can be transposed and added together, and unlike vectors, they can be multiplied with each other as well.
Speaking of our “from scratch” approach, before looking into how to actually work with matrices in practice, we created our very own Matrix implementation in vanilla Python. Closing the chapter, we dealt with the fundamentals and best practices of two-dimensional NumPy arrays, the prime matrix representation that Python can offer.
In the next chapter, we’ll once more take a theoretical approach. This is how we do it in this book: looking at both aspects at once, supercharging our understanding of mathematics (and machine learning, along the way). We’ll see that matrices are not just plain tables of numbers; they are data transformations as well. This property is beautiful beyond words: data and their transformations are represented by the same object.
Let’s get to it!
Bookmark
3.4 Problems
Section titled “3.4 Problems”Problem 1. Implement the mean squared error

both with and without using NumPy functions and methods. (The vectors x and y should be represented by NumPy arrays in both cases.)
Problem 2. Compare the performances of the built-in maximum function max and NumPy’s np.max using timeit.timeit, like we did above. Try running a different number of experiments and changing the array sizes to figure out the breakeven point between the two performances.
Problem 3. Instead of implementing the general p-norm as we did earlier in this chapter in Section 3.1.1 , we can change things around to obtain the version below.
def p_norm(x: np.ndarray, p: float): if p 1: return (np.sum(np.abs(x)**p))**(1/p) elif np.isinf(p): return np.max(np.abs(x)) else: raise ValueError("p must be a float larger or equal than 1.0 or inf."However, this doesn’t work for p = ∞. What is the problem with it?
Problem 4. Let w ∈ℝn be a vector with nonnegative elements. Use NumPy to implement the weighted p-norm by

Can you come up with a scenario where this can be useful in machine learning?
Problem 5. Implement the cosine similarity function, defined by the formula

(Whenever possible, use built-in NumPy functions.)
Problem 6. Calculate the product of the following matrices.
(a)

(b)

Problem 7. The famous Fibonacci numbers are defined by the recursive sequence
F0= 0,
F1=1,
Fn= Fn−1 + Fn−2
(a) Write a recursive function that computes the n-th Fibonacci number. (Expect it to be really slow.)
(b) Show that

and use this identity to write a non-recursive function that computes the n-th Fibonacci number.
Use Python’s built-in timeit function to measure the execution of both functions. Which one is faster?
Problem 8. Let A,B ∈ℝn×m be two matrices. Their Hadamard product is defined by

Implement a function that takes two identically shaped NumPy arrays, then performs the Hadamard product on them. (There are two ways to do this: with for loops and with NumPy operations. It is instructive to implement both.)
Problem 9. Let A ∈ℝn×n be a square matrix. Functions of the form