This notebook is meant to be a quick refresher of linear algebra and a brief introduction of NumPy
(Python package for scientific computing), and it is by no means a through review. I assume that you have a prior experience of learning linear algebra such as taking an introductory course a while ago. The goal is to go over some of the important properties of matrices and showcase some of the NumPy
methods through practical examples. We consider linear regression and three different solutions: algebraic, analytic, and geometric. I heavily cite and highly recommend Kolter's review notes on linear algebra [2].
Appendix
A. Linear algebra visualized
B. Transpose and 1-dimensional arrays in NumPy
C. Outer products in NumPy
Reference
Why is linear algebra important in machine learning? Machine learning methods often involves a large amount of data, and linear algebra provides a clever way to analyze and manipulate them. To make the argument concrete, let's take a look at a sample dataset.
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from IPython.display import Image, IFrame
np.set_printoptions(suppress=True, linewidth=120, precision=2)
We can load boston dataset from sklearn
package, which is a very popular and easy to use machine learning package of Python. It implements many kinds of machine learning algorithms and utility functions. The loaded dataset has the following attributes.
boston = load_boston()
print(boston.__dir__())
print(boston.DESCR)
The data and target values are stored in arrays of type numpy.ndarray
. In the data array, each row corresponds to a sample, a Boston suburb or town in this example, and each column corresponds to a feature that is described above. Note that numpy.ndarray
is not just multi-dimensional array (or list
in Python). It implements many useful numeric methods and indexing feature. Refer to the ndarray document and indexing document for the details. Here, I show the first 10 samples, each of which consists of 13 feature values, and some of their statistics by slicing the data array.
print(boston.feature_names)
print(boston.data[:10])
print('\nmean')
print(boston.data[:10].mean(axis=0))
print('\nvariance')
print(boston.data[:10].var(axis=0))
The target values are the following. Our task here is to predict the target value, or the "median value of owner-occupied homes in $1000's" in a Boston town, given its feature values such as "per capita crime rate by town" and "average number of rooms per dwelling."
print('MEDV')
print(boston.target[:10])
Linear regression is one of the simplest statistical models. It assumes that the target variable is explained by a weighted sum of feature values . In an equation,
where is a bias term. Intuitively, terms define the relative up/down from the standard target value. This standard value is what the bias term accounts for. You may wonder if the relationship is really that simple.
"Essentially, all models are wrong, but some are useful."
George Box, 1987
Assuming that the linear regression model is valid and we know all the weights and bias, we can estimate a median house price of a Boston town from its feature values. The bad news is that we don't know the weights... The good news is that we have training samples (a set of features and target pair)! We want to find a set of weights such that the equation holds for the training samples. To this end, we can solve systems of equations.
Great, we can solve it, ...or can we (more on this later)? Let's rewrite the equations with a better notation.
More simply,
or even...
Yes, this is beautiful. This notation is used in linear algebra, and it is a very powerful tool given to us to tackle machine learing problems. The objective here is to find a set of weights that solves this equation. We call this process to learn from data.
A matrix is a rectangular array of numbers. The dimension of matrix is number of rows by number of columns. is the entry of , which is in the th row and the th column.
A = np.array(np.arange(0, 6)).reshape((2, 3))
print(A)
print(A.shape)
for i in range(A.shape[0]):
for j in range(A.shape[1]):
print("{},{} entry: {}".format(i, j, A[i, j]))
A vector is a matrix. Here is said to be a 4-dimensional vector because it has 4 elements in it. denotes the th element of .
y = np.array(2*np.arange(0, 4))
print(y)
print(y.shape)
for i in range(y.shape[0]):
print("{} element: {}".format(i, y[i]))
A = np.array([[1, 0],
[2, 5],
[3, 1]])
B = np.array([[4, 0.5],
[2, 5],
[0, 1]])
assert A.shape == B.shape
print(A + B)
A = np.array([[1, 0],
[2, 5],
[3, 1]])
print(3*A)
matrix (m rows, n columns)
matrix (n-dimensional vector)
matrix (m-dimensional vector)
To get , multiply 's ith row with vector element-wise, then add them up.
Hint:
A = np.array([[1, 2, 1, 5],
[0, 3, 0, 4],
[-1, -2, 0, 0]])
x = np.array([[1],
[3],
[2],
[1]])
assert x.shape[0] == A.shape[1]
y = np.dot(A, x)
y = A.dot(x) # another way to calculate the dot product
print(y)
matrix (l rows, m columns matrix)
matrix (m rows, n columns matrix)
matrix (l rows, n columns matrix)
Hint:
Note and are not the same, i.e. matrix multiplication is NOT commutative. Actually, the latter is not necessarily defined. Check dimension.
A = np.array([[1, 4],
[5, 3],
[2, 6]])
B = np.array([[1, 8, 7, 4],
[5, 6, 2, 3]])
print(A)
print(B)
print(A.dot(B))
try:
print(B.dot(A))
except ValueError as e:
print(e)
Is linear algebra all about saving papers? Definitely NO! Do you remember terminologies such as linear independence, rank, span, etc that you learned in the linear algebra course? Did you get the ideas? Being able to calculate them is important, but understanding the concept is more (at least as) important for the purpose of this course (we can use computers for calculation after all). Let's review the properties of matrices while solving the linear regression of Boston house price. The goal is to solve the following equation.
where and . is greater than because there are more samples than the number of features (remember rows are samples). In other words, is a vertically long matrix.
Here, let's assume that all the features (columns of ) are linearly independent.
A set of vectors is said to be (linearly) independent if no vector can be represented as a linear combination of the remaining vectors. [2]
Otherwise, it is linearly dependent. For example, if we have temperature in Fahrenheit and in Celsius as two different features, the latter is represented in terms of the first as
Such features are linearly dependent. For another example, if we have categorical features like gender, we could have two columns one for male and the other for female. For male samples we have ones in the male column and zeros in the female column, and the opposite for female samples. Did you notice that we have a linear dependence here because these features can be represented in the form
For a matrix where , if its columns are linearly independent, it is said to be full rank. Formally,
The column rank of a matrix is the size of the largest subset of columns of that constitute a linearly independent set. With some abuse of terminology, this is often referred to simply as the number of linearly independent columns of . In the same way, the row rank is the largest number of rows of that constitute a linearly independent set.
For any matrix , it turns out that the column rank of is equal to the row rank of (though we will not prove this), and so both quantities are referred to collectively as the rank of , denoted as .
For , . If , then is said to be full rank. [2]
Therefore, the first statement holds.
The inverse of a square matrix is denoted , and is the unique matrix such that
Note that not all matrices have inverses. Non-square matrices, for example, do not have inverses by definition. However, for some square matrices , it may still be the case that may not exist. In particular, we say that is invertible or non-singular if exists and non-invertible or singular otherwise. In order for a square matrix to have an inverse , then must be full rank. [2]
So, again, let's assume that the columns of are linearly independent, i.e. is full rank. Here's our first attempt to solve the equation for .
Can we do this?
Remember that our is a vertically long matrix i.e. non-square, and cannot be inverted by definition.
Therefore, we can't do .
By convention, an n-dimensional vector is often thought of as a matrix with n rows and 1 column, known as a column vector. If we want to explicitly represent a row vector — a matrix with 1 row and n columns — we typically write . (2)
The transpose can be generalized to matrices.
The transpose of a matrix results from "flipping" the rows and columns. Given a matrix , its transpose, written , is the matrix whose entries are given by
(2)
What is the dimension of ?
A = np.array([[1, 2],
[3, 4],
[5, 6]])
print(A)
print(np.dot(A.T, A))
is always a square matrix (). If is full rank, is also invertible.
Note that the second line multiplies both sides by the transpose of from the left. Then, we can solve for because is invertible.
This is a valid algebraic approach.
Why don't we get the intuition behind the solution. Consider the linear system
where
This equation is saying that is a linear combination of column vectors of .
However, there are no such weights.
With linear algebra's terminology, doesn't lie in the column space of , or the space that column vectors of spans. Formally,
The span of a set of vectors is the set of all vectors that can be expressed as a linear combination of . That is,
(2)
Especially, when 's are the columns of a matrix , their span is said to be the range or the column space of and denoted .
Back to the equation, although the target vector is 3-dimensional, there are only two column vectors that span the space, i.e. the range of is just a 2-dimensional plane. Therefore, there certainly exists 3-dimensional vectors that don't lie on this plane, like the above. Visually, it looks something like below.
Image('../images/linear-algebra/4.5.png', height=300, width=400)
But we want to represent in terms of 's. The best we can do is to find a vector that lies in the range of , but is also as close to as possible.
This objective can be formulated by using norm by saying to find that minimizes .
A norm of a vector is informally a measure of the “length” of the vector. For example, we have the commonly-used Euclidean or norm,
Note that . (2)
If you take the norm of difference of vectors, it is a measure of distance between them. There are several types of norms, but another popular one is norm. Given a vector ,
Let's use norm as a measure of distance for now. For convinience, we can minimize the square of norm without loss of generality. To find weights that minimizes , we can take its derivative with respect to and set to zero. Easy, right?
To this end, the notion of gradient, which is a natural extension of partial derivatives to a vector setting, comes in handy.
Suppose that is a function that takes as input a matrix of size and returns a real value. Then the gradient of (with respect to ) is the matrix of partial derivatives, defined as:
i.e., an matrix with
Note that the size of is always the same as the size of . So if, in particular, is just a vector ,
(2)
The third approach (analytical)
Let denote , meaning Resisual Sum of Squares.
Take the gradient of with respect to .
Note that denotes k-th column vector of . Also, is a row vector and is a column vector, so the last line calculates the dot product. This result lead us to the following gradient expression.
Setting the gradient to a zero vector.
We reached to the same solution as the algebraic approach.
Don't worry, you don't have to calculate this all the time. The gradient is a special case of matrix calculus, where we take the derivative of a scalar function with respect to a vector. Similarly, there are cases we take the derivative of vector with respect to vector and derivative of scalar function with respect to matrix, etc. Fortunatelly, matrix/vector calculus can be done by natural analogies of multivariable calculus, and here are some formulas that we can use.
Therefore,
The rest is the same.
I will introduce yet another approach to the linear regression, which is geometric.
It's kind of silly to introduce dot product (also known as inner product) now since we have been using it extensively, but I wanted to make sure that we have the same picture in our mind. The dot product of two vectors can be obtained by taking their correxponding elements, multiply them, and add them together. For example, given
which is in general case where ,
So, dot product seems to be an operator that maps vectors to a scalar value, but how can we interpret it?
To tackle this question I'm going to present an alternative (but equivalent!) way to define the dot product: given vectors and , let be the angle between them, and define their dot product to be:
(2)
Note that the dot product is represented in terms of the magnitude of the vectors and the angle between them. This is the basis of our geometric intuition. If you want to learn why these definitions are equivalent (the duality of dot products), check out this episode in Essense of linear algebra series [3].
Consider the following vector pairs.
Image('../images/linear-algebra/4.9.png')
Recall that
Therefore, the dot products of the given vector pairs are, respectively,
Notice that the dot product is maximized when the two vectors are perfectly aligned () and gets smaller as their discrepancy grows. In this sense, dot product works as a measure of the similarity between vectors.
Now, let me introduce projection. I assume you have learned them in geometry or physics. Basically, we want to give a name to the following component.
Image('../images/linear-algebra/4.10.png', height=300, width=400)
The formal definition is the following.
The projection of a vector onto the span of (here we assume ) is the vector , such that is as close as possible to , as measured by the Euclidean norm . We denote the projection as and can define it formally as,
(2)
When we project onto the span of single vector, like the above image, the projection is calculated by
Notice that projection is a vector, i.e. it has a direction. The part defines the length of projection and the part defines its direction. Using the definition of dot products,
If is a unit vector, , therefore,
It turns out that this is a very useful construction. For example, projections give us a way to make orthogonal things. By the nature of “projecting” vectors, if we connect the endpoints of with its projection , we get a vector orthogonal to our reference direction . In other words, the vector is orthogonal to . [1]
When we say things are orthogonal, it basically means they are perpendicular. But the notion is more general and can be extended to higher dimensional spaces. The formal definition is the following.
Two vectors are orthogonal if . A vector is normalized if . A square matrix is orthogonal (note the different meanings when talking about vectors versus matrices) if all its columns are orthogonal to each other and are normalized (the columns are then referred to as being orthonormal). [2]
Note that if a vector is in the span of orthogonal vectors , then can be represented as the sum of projections onto s, that is
Essentially, what this means is that you can reconstruct a vector from its projections as visualized below.
Image('../images/linear-algebra/4.11.1.png')
If you can have as many linearly independent projections as the dimension of the target vector, you can perfectly reconstruct the original vector. What if we can't? Notice the similarity of this question and linear regression. The problem of linear regression is that is not in the range of .
The geometric approach to the linear regression model is to get the projection of onto the range of like the image below.
Image('../images/linear-algebra/4.11.2.png', height=300, width=400)
The component of which is orthogonal to the range of is the difference between and .
We know this vector is orthogonal to any vector on the plane including all the column vectors of . It means that their dot product is zero. Let's formulate the problem.
This solution by geometric approach is exactly the same as the algebraic and analytical approach.
We reviewed the basic operations and properties of linear algebra through the example of linear regression model. On the way, we have shown that the solution for the linear regression is by three different approaches: algebraic, analytical, and geometric.
Finally, by using Python
we get the following solution.
X = boston.data
y = boston.target
w = np.linalg.inv(np.dot(X.T, X)).dot(np.dot(X.T, y))
print(w)
You can test the accuracy of the linear regression estiamtor with these weights by using a new dataset called testing dataset, which is out of scope of this review. Unfortunately, however, this solution is not practical. First, np.linalg.inv
should not be used to solve systems of linear equations with matrices. It's more efficient and stable to use np.linalg.solve
. Please refer to the Appendix D for more details. Second, even with np.linalg.solve
, solving linear systems in closed form is prohibitively expensive () for non-trivial problems. For problems of the scale that we handle in machine learning, iterative methods, like gradient descent and its variants, should be used. To learn more about linear algebra in general, please refer to the Appendix A.
Are you curious why matrices have to be full rank to be invertible? What it means to multiply a vector by a matrix and to multiply matrices by their inverse? Watch these videos. These are some selections from a short course, Essence of linear algebra [3]. Grant Sanderson (the author) visualized major concepts of linear algebra very very very well.
You might be wondering why vectors are printed horizontally in NumPy
. When 1d arrays are used, NumPy
does not distinguish column vectors and row vectors unlike mathematical expressions. To see this:
a = np.array(np.arange(0, 3))
at = a.transpose()
print(a, at)
print(a.shape, at.shape)
As you can see, they are just 1d arrays. To create a column vector, you need to explicitly create an matrix, i.e. 2d array.
a = np.array([[i] for i in range(3)])
at = a.T
print('column vector')
print(a)
print(a.shape)
print('\ntranspose')
print(at)
print(at.shape)
Note that in order to access the th element of a column vector , we need to use y[i][0]
, not y[i]
. Also, it's relatively tricky to index arrays with (n, 1)
array as opposed to (n,)
array. These subtle differences often cause bugs. Therefore, although we use column vectors in mathematical expression, I recommend to use (n,)
array in code unless you really need (n, 1)
array. In case you want to collapse dimensions, you can use ravel()
method. When you want to turn (n,)
array to (n, 1)
array, there are several ways as shown below.
a = np.array([[i] for i in range(3)])
print('2d')
print(a)
a = a.ravel()
print('\n1d')
print(a)
b = np.atleast_2d(a).T
c = a[:, np.newaxis]
print('\n2d')
print(b)
print(c)
Read the indexing document to learn more. It's powerful!
The outer product is defined as the vector multiplication , where and are column vectors. Note that is a row vector. For example, if and , then
Or generally, is a matrix whose entries are given by,
To calculate this, you might want to do something like the following.
u = np.array([1, 2, 3])
v = np.array([2, 2])
try:
print(np.dot(u, v.T))
except ValueError as e:
print(e)
I told you, it doesn't work. Why? because the u
and v
in the above code are not column vectors. They are just arrays so that you cannot transpose them. There are basically two ways to handle this.
outer
method provided by NumPy
.# Option 1
u = np.array([1, 2, 3])[:, np.newaxis]
v = np.array([2, 2])[:, np.newaxis]
print(u.shape, v.T.shape)
print(np.dot(u, v.T))
# Option 2
u = np.array([1, 2, 3])
v = np.array([2, 2])
print(u.shape, v.shape)
print(np.outer(u, v))
You know which I recommend:)
np.linalg.inv
, np.linalg.solve
, and np.linalg.lstsq
¶This (https://stackoverflow.com/questions/31256252/why-does-numpy-linalg-solve-offer-more-precise-matrix-inversions-than-numpy-li) StackOverflow answer describes the problem well. In short, np.linalg.inv
involves steps for solving for that is not necessary to solve the systems of linear equations. These extra steps make the solution not only inefficient but also numerically unstable if is ill-conditioned matrix.
At this point, you could also use np.linalg.lstsq
. This solver uses SVD under the hood where np.linalg.solve
uses LU decompoition. The implication of such difference is that np.linalg.solve
is cheaper, but it can only handle square and full rank matrix, while np.linalg.lstsq
can deal with over/under determined cases.
X = boston.data
y = boston.target
# np.linalg.inv
start = time.time()
inv_w = np.linalg.inv(np.dot(X.T, X)).dot(np.dot(X.T, y))
inv_time = time.time() - start
# np.linalg.solve
start = time.time()
solve_w = np.linalg.solve(np.dot(X.T, X), np.dot(X.T, y))
solve_time = time.time() - start
# np.linalg.lstsq
start = time.time()
lstsq_w, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
lstsq_time = time.time() - start
print(">>inv")
print("time", inv_time)
print("solution", inv_w)
print("\n>>solve")
print("time", solve_time)
print("solution", solve_w)
print("\n>>lstsq")
print("time", lstsq_time)
print("solution", lstsq_w)
[1] Breen, J., 2015. Understanding the Dot Product and the Cross Product.
Available online: http://www.math.ucla.edu/~josephbreen/Understanding_the_Dot_Product_and_the_Cross_Product.pdf
[2] Kolter, Z., 2008. Linear Algebra Review and Reference.
Available online: http://cs229.stanford.edu/section/cs229-linalg.pdf
[3] Sanderson, G. (3Blue1Brown), 2016. Essence of linear algebra.
Available online: https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab