Skip to content
ImagineWorld

Vectors and Vector Spaces

node_idnode-book_mathematics-of-machine-learning_chapter-01-vectors-and-vector-spaces
node_typechapter_node
schema_profileworld.chapter_node.v1
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
statusactive
chapter_num1
chapter_titleVectors and Vector Spaces
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

”I want to point out that the class of abstract linear spaces is no larger than the class of spaces whose elements are arrays. So what is gained by abstraction? First of all, the freedom to use a single symbol for an array; this way we can think of vectors as basic building blocks, unencumbered by components. The abstract view leads to simple, transparent proofs of results.”

— Peter D. Lax, in Chapter 1 of his book Linear Algebra and its Applications

The mathematics of machine learning rests upon three pillars: linear algebra, calculus, and probability theory. Linear algebra describes how to represent and manipulate data; calculus helps us fit the models; while probability theory helps interpret them.

These build on top of each other, and we will start at the beginning: representing and manipulating data.

To guide us throughout this section, we will look at the famous Iris dataset ( https://en.wikipedia.org/wiki/Iris_flower_data_set). This contains the measurements from three species of Iris: the lengths and widths of sepals and petals. Each data point includes these four measurements, for which we also have the corresponding species: Iris setosa, Iris virginica, or Iris versicolor. (Sepals are the typically green, leaf-like structures at the base of a flower that protect the developing bud before it opens. Petals are the colorful, soft parts of a flower that attract pollinators like insects or birds.)

The dataset can be loaded right away from scikit-learn (https://scikit-learn.org/), so let’s take a look!

from sklearn.datasets import load_iris
data = load_iris()
X, y = data["data"], data["target"]
X[:10]
array([[5.1, 3.5, 1.4, 0.2],
      [4.9, 3. , 1.4, 0.2],
      [4.7, 3.2, 1.3, 0.2],
      [4.6, 3.1, 1.5, 0.2],
      [5. , 3.6, 1.4, 0.2],
      [5.4, 3.9, 1.7, 0.4],
      [4.6, 3.4, 1.4, 0.3],
      [5. , 3.4, 1.5, 0.2],
      [4.4, 2.9, 1.4, 0.2],
      [4.9, 3.1, 1.5, 0.1]])

Before going into the mathematical definitions, let’s establish a common vocabulary first. The measurements themselves are stored in a tabular format. Rows represent samples, and columns represent measurements. A particular measurement type is often called a feature. As X.shape tells us, the Iris dataset has 150 data points and four features:

X.shape
(150, 4)

(Don’t worry if you are not familiar with NumPy. We’ll learn about the details in due time. For now, it’s enough to understand that an array’s shape describes its dimensions.)

For a given sample, the corresponding species is called the label. In our case, this is either Iris setosa, Iris virginica, or Iris versicolor. Here, the labels are encoded with the numbers 0, 1, and 2:

y
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

In mathematical terms, the Iris dataset forms a matrix, and the data points form vectors. Simply speaking, matrices are tables, while vectors are tuples. (Tuples are just finite and ordered sequences of objects, like (1.297,−2.35,32.3,29.874).) However, this simplistic view doesn’t show us the big picture. Vectors and matrices have a beautiful geometrical and algebraic structure, and exploring their mathematical theory allows us to see the patterns behind the data.

How so? Say, besides representing the data points in a compact form, we want to perform operations on them, like addition and scalar multiplication. Why do we need to add data points together? To give you a simple example, it is often beneficial if the features are on the same scale. If a given feature is distributed on a smaller scale than the others, it will have less influence on the predictions.

Think about this: if somebody is whispering to you something from the next room while speakers blast loud music right next to your ear, you won’t hear anything of what the person is saying to you. Large-scale features are the blasting music, while the smaller ones are the whisper. You may obtain much more information from the whisper, but you need to quiet down the music first.

To see this phenomenon in action, let’s take a look at the distribution of the features of our dataset!

import pandas as pd
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
sns.set_theme(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})
# Create the data
x = X.ravel()
labels = ["sepal length", "sepal width", "petal length", "petal width"]
g = np.tile(labels, len(X))
df = pd.DataFrame(dict(x=x, g=g))
# Initialize the FacetGrid object
pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
g = sns.FacetGrid(df, row="g", hue="g", aspect=10, height=1.5, palette=pal)
# Draw the densities
g.map(sns.kdeplot, "x", bw_adjust=.5, clip_on=False, fill=True, alpha=1, linewidth=1.5)
g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw_adjust=.5)
# Add reference line
g.refline(y=0, linewidth=2, linestyle="-", color=None, clip_on=False)
# Label each plot
g.map(lambda x, color, label: plt.gca().text(0, .2, label, fontweight="bold", color=color,ha="left", va="center", transform=plt.gca().transAxes), "x")
# Adjust subplots and aesthetics
g.figure.subplots_adjust(hspace=-.25)
g.set_titles("")
g.set(yticks=[], ylabel="")
g.despine(bottom=True, left=True)
plt.show()

PIC

Figure 1.1: The raw features of the Iris dataset

You can see in the figure above that some are more stretched out (like sepal length), while others are narrower (like sepal width). In practical scenarios, this can hurt the predictive performance of our algorithms.

To solve it, we can remove the mean and the standard deviation of a dataset. If the dataset consists of the vectors x1,x2,…,x150 , we can calculate their mean by

 150 μ = -1--∑ x ∈ ℝ4 150 i=1 i

and their standard deviation by

 ┌ ---------------- ││ 1 1∑50 σ = ∘ ---- (xi − μ )2 ∈ ℝ4, 150 i=1

where the subtraction and square operation in (xi −μ)2 is taken elementwise.

The components of μ = (μ1,μ2,μ3,μ4) and σ = (σ1,σ2,σ3,σ4) are the means and variances of the individual features. (Recall that the Iris dataset contains 150 samples and 4 features per sample.)

In other words, the mean describes the average of samples, while the standard deviation represents the average distance from the mean. The larger the standard deviation is, the more spread out the samples are.

With these quantities, the scaled dataset can be described as

x1-−-μ- x2-−-μ- x150-−-μ σ , σ ,..., σ ,

where both the subtraction and the division are taken elementwise.

If you are familiar with Python and NumPy, this is how it is done. (Don’t worry if you are not – everything you need to know about them will be explained in the next chapter, with example code.)

X_scaled = (X - X.mean(axis=0))/X.std(axis=0)
X_scaled[:10]
array([[-0.90068117,  1.01900435, -1.34022653, -1.3154443 ],
      [-1.14301691, -0.13197948, -1.34022653, -1.3154443 ],
      [-1.38535265,  0.32841405, -1.39706395, -1.3154443 ],
      [-1.50652052,  0.09821729, -1.2833891 , -1.3154443 ],
      [-1.02184904,  1.24920112, -1.34022653, -1.3154443 ],
      [-0.53717756,  1.93979142, -1.16971425, -1.05217993],
      [-1.50652052,  0.78880759, -1.34022653, -1.18381211],
      [-1.02184904,  0.78880759, -1.2833891 , -1.3154443 ],
      [-1.74885626, -0.36217625, -1.34022653, -1.3154443 ],
      [-1.14301691,  0.09821729, -1.2833891 , -1.44707648]])
# Create the data
x = X_scaled.ravel()
labels = ["sepal length", "sepal width", "petal length", "petal width"]
g = np.tile(labels, X_scaled.shape[0])
df = pd.DataFrame(dict(x=x, g=g))
# Initialize the FacetGrid object
pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
grid = sns.FacetGrid(df, row="g", hue="g", aspect=10, height=1.5, palette=pal)
# Draw the densities
grid.map(sns.kdeplot, "x", bw_adjust=.5, clip_on=False, fill=True, alpha=1, linewidth=1.5)
grid.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw_adjust=.5)
# Add reference line
grid.refline(y=0, linewidth=2, linestyle="-", color=None, clip_on=False)
# Add labels to each plot
grid.map(lambda x, color, label: plt.gca().text(0, .2, label, fontweight="bold", color=color,ha="left", va="center", transform=plt.gca().transAxes), "x")
# Adjust subplots and aesthetics
grid.figure.subplots_adjust(hspace=-.25)
grid.set_titles("")
grid.set(yticks=[], ylabel="")
grid.despine(bottom=True, left=True)
plt.show()

PIC

Figure 1.2: The scaled features of the Iris dataset

If you compare the modified version to the original, you can see that its features are on the same scale. In other words, we transformed the dataset to a more expressive one. From a (very) abstract point of view, machine learning is nothing else but a series of learned data transformations, turning raw data into a form where prediction is simple.

In a mathematical setting, manipulating data and modeling its relations to the labels arise from the concept of vector spaces and transformations between them. Let’s take the first steps by making the definition of vector spaces precise!

day-mode Bookmark

Representing multiple measurements as a tuple (x1,x2,…,xn) is a natural idea that has a ton of merits. The tuple form suggests that the components belong together in a precise order, giving a clear and concise way to store information.

However, this comes at a cost: now we have to work with more complex objects. Despite dealing with tuples like (x1,…,xn) instead of numbers, there are similarities. For instance, any two tuple x = (x1,…,xn) and y = (y1,…,yn)

  • can be added together by x+ y = (x1 + y1,…,xn + yn),
  • and can be multiplied with scalars: if c ∈ℝ, then cx = (cx1,…,cxn).

It’s almost like using a number.

These operations have clear geometric interpretations as well. Addition is the same as translation, while multiplication with a scalar is a simple stretching. (Or squeezing, if |c|<1.)

PIC

Figure 1.3: Geometric interpretation of addition and scalar multiplication

On the other hand, if we want to follow our geometric intuition (which we definitely do), it is unclear how to define vector multiplication. Even though the definition

xy = (x1y1,...,xnyn)

makes sense algebraically, we don’t see what it means in a geometric sense.

When we think about vectors and vector spaces, we are thinking about a mathematical structure that fits our intuitive views and expectations. So, let’s turn these into the definition!

Definition 2. (Vector spaces)

A vector space is a mathematical structure (V,F,+,⋅), where

(a) V is the set of vectors,

(b) F is a field of scalars (most commonly the real numbers ℝ or the complex numbers ℂ),

(c) + : V ×V → V is the addition operation, satisfying the following properties:

  • x+ y = y + x (commutativity),
  • x+ (y + z) = (x+ y) + z (associativity),
  • there is an element 0 ∈V such that x + 0 = x (existence of the null vector),
  • and there is an inverse −x ∈V for each x ∈V such that x+(−x) = 0 (existence of additive inverses)

for all vectors x,y,z ∈V ,

(d) and ⋅ : F ×V →V is the scalar multiplication operation, satisfying

  • a(bx) = (ab)x (associativity),
  • a(x+ y) = ax + ay (distributivity),
  • and 1x = x

for all scalars a,b ∈F and vectors x,y ∈V .

This definition is overloaded with new concepts, so let’s unpack it.

First, looking at operations like addition and scalar multiplication as functions might be unusual for you, but this is a perfectly natural representation. (We’ll learn about functions later in detail, but for now, feel free to think about them intuitively.) In writing, we use the notation x + y , but when thinking about + as a function of two variables, we might as well write +(x,y). The form x + y is called infix notation, while +(x,y) is called prefix notation.

In vector spaces, the inputs of addition are two vectors and the result is a single vector, thus + is a function that maps the Cartesian product V ×V to V .

Similarly, scalar multiplication takes a scalar and a vector, resulting in a vector; meaning a function that maps F ×V to V .

(The Cartesian product V ×V is just a set of ordered pairs:

V × V = {(u,v) : u,v ∈ V }.

Feel free to check out the set theory appendix (Appendix C) for more details, but for now, the intuitive understanding is enough.)

This is also good place to note that mathematical definitions are always formalized in hindsight, after the objects themselves are somewhat crystallized and familiar to the users. Mathematics is often presented as definitions first, theorems second. This is not how it is done in practice. Examples motivate definitions, not the other way around.

In general, the field of scalars can be something other than real or complex numbers. The term field refers to a well-defined mathematical structure, which makes a natural notion mathematically precise. Without going into the technical details, we will think about fields as “a set of numbers where addition and multiplication work just as for real numbers”.

Since we are not concerned with the most general case, we will use ℝ or ℂ to avoid unnecessary difficulty. If you are not familiar with the exact mathematical definition of a field, don’t worry – just think of ℝ each time you read the word “field”.

When everything is clear from the context, (V,ℝ,+,⋅) will often be referred to as V for notational simplicity. So, if the field F is not specified, it is implicitly assumed to be ℝ. When we want to emphasize this, we’ll call these real vector spaces.

At first sight, Definition 2 is certainly too complex to comprehend. It seems like just a bunch of sets, operations, and properties thrown together. However, to help us build a mental model, we can imagine a vector as an arrow, starting from the null vector. (Recall that the null vector 0 is that special one for which x + 0 = x holds for all x. Thus, it can be considered as an arrow with zero length; the origin.)

To further familiarize ourselves with the concept, let’s see some examples of vector spaces!

Examples are one of the best ways of building insight into seemingly difficult concepts like vector spaces. We humans, usually think in terms of models instead of abstractions. (Yes, this includes pure mathematicians. Even though they might deny it.)

Example 1. The most ubiquitous instance of the vector space is (ℝn,ℝ,+,⋅), the same one we used to motivate the definition itself. (ℝn refers to the n-fold Cartesian product of the set of real numbers. If you are unfamiliar with this notion, check the set theory tutorial in Appendix C.)

(ℝn,ℝ,+,⋅) is the canonical model, the one we use to guide us throughout our studies. If n = 2, we are simply talking about the familiar Euclidean plane.

PIC

Figure 1.4: The Euclidean plane as a vector space

Using ℝ2 or ℝ3 for visualization can help a lot. What works here will usually work in the general case, although sometimes this can be dangerous. Math relies on both intuition and logic. We develop ideas using our intuition, but we confirm them with our logic.

Example 2. Vector spaces are not just a collection of finite tuples. An example is the space of polynomial functions with real coefficients, defined by

 ∑n ℝ [x ] = { pixi : pi ∈ ℝ, n = 0,1,...}. i=0

Two polynomials p(x) and q(x) can be added together by

 ∑n i p(x)+ q(x) := (pi + qi)x , k=1

and can be multiplied with a real scalar by

 ∑n cp(x) = cpixi. k=1

With these operations, (ℝ[x],ℝ,+,⋅) is a vector space. Although most of the time we percieve polynomials as functions, they can be represented as tuples of coefficients as well:

∑n pixi ← → (p0,...,pn). i=0

Note that n – the degree of the polynomial – is unbounded. As a consequence, this vector space has a significantly richer structure than ℝn.

Example 3. The previous example can be further generalized. Let C([0,1]) denote the set of all continuous real functions f : [0,1] →ℝ. Then (C(ℝ),ℝ,+,⋅) is a vector space, where the addition and scalar multiplication are defined elementwise:

(f + g )(x) := f(x)+ g(x), (cf)(x) = cf (x )

for all f,g ∈C(ℝ) and c ∈ℝ. (Although continuity is a concept that we haven’t defined yet, feel free to think of a continuous function as one whose graph can be drawn without lifting your pen.)

Yes, that is right: functions can be thought of as vectors as well. Spaces of functions play a significant role in mathematics, and they come in several different forms. We often restrict the space to continuous functions, differentiable functions, or basically any subset that is closed under the given operations.

(In fact, ℝn can be also thought of as a function space. From an abstract viewpoint, each vector x = (x1,…,xn) is a mapping from {1,2,…,n} to ℝ.)

Function spaces are encountered in more advanced topics, such as inverting ResNet architectures, which we won’t deal with in this book. However, it is worth seeing examples that are different (and not as straightforward) as ℝn.

day-mode Bookmark

Although our vector spaces contain infinitely many vectors, we can reduce the complexity by finding special subsets that can express any other vector.

To make this idea precise, let’s consider our recurring example ℝn. There, we have a special vector set

e1= (1,0,…,0)
e2= (0,1,…,0)
.. .
en= (0,0,…,1)

which can be used to express each vector x = (x1,…,xn) as

 n x = ∑ xe , x ∈ ℝ, e ∈ ℝn i i i i i=1

For instance, e1 = (1,0) and e2 = (0,1) in ℝ2.

What we have just seen feels extremely trivial and it seems to only complicate things. Why would we need to write vectors in the form of x = ∑ i=1nxiei, instead of simply using the coordinates (x1,…,xn) ? Because, in fact, the coordinate notation depends on the underlying vector set ({e1,…,en} in our case) used to express other vectors.

A vector is not the same as its coordinates! A single vector can have multiple different coordinates in different systems, and switching between these is a useful tool.

Thus, the set E = {e1,…,en}⊆ℝn is rather special, as it significantly reduces the complexity of representing vectors. With the vector addition and scalar multiplication operations, it spans our vector space entirely. E is an instance of a vector space basis, a set that serves as a skeleton of ℝn.

In this section, we are going to introduce and study the concept of vector space basis in detail.

1.2.1 Linear combinations and independence

Section titled “1.2.1 Linear combinations and independence”

Let’s zoom out from the special case ℝn and start talking about general vector spaces. From our motivating example regarding bases, we have seen that sums of the form

∑n xivi, i=1

where the vi-s are vectors and the xi coefficients are scalars, play a crucial role. These are called linear combinations. A linear combination is called trivial if all of the coefficients are zero.

Given a set of vectors, the same vector can potentially be expressed as a linear combination in multiple ways. For example, if v1 = (1,0),v2 = (0,1), and v3 = (1,1), then

(2,1)= 2v1 + v2
= v1 + v3.

This suggests that the set S = {v1,v2,v3} is redundant, as it contains duplicate information. The concept of linear dependence and independence makes this precise.

Definition 3. (Linear dependence and independence)

Let V be a vector space and S = {v1,…,vn} be a subset of its vectors. S is said to be linearly dependent if it only contains the zero vector, or there is a nonzero vk that can be expressed as a linear combination of the other vectors v1,…,vk−1,vk+1,…,vn.

S is said to be linearly independent if it is not linearly dependent.

Linear dependence and independence can be looked at from a different angle. If

 k∑−1 ∑n vk = xivi + xivi, i=1 i=k+1

for some nonzero vk, then by subtracting vk, we obtain that the null vector can be obtained as a nontrivial linear combination

 ∑n 0 = xivi i=1

for some scalars xi, where xk = −1. This is an equivalent definition of linear dependence. With this, we have proved the following theorem.

Theorem 2.

Let V be a vector space and S = {v1,…,vn}be a subset of its vectors.

(a) S is linearly dependent if and only if the null vector 0 can be obtained as a nontrivial linear combination.

(b) S is linearly independent if and only if whenever 0 = ∑ i=1nxivi, all coefficients xi are zero.

Linear combinations provide a way to take a small set of vectors and generate a whole lot of others from them. For a set of vectors S, taking all of its possible linear combinations is called spanning, and the generated set is called the span. Formally, it is defined by

 ∑n span(S ) = { xivi : n ∈ ℕ, vi ∈ S,xi is a scalar}. i=1

Note that the vector set S is not necessarily finite. To help illustrate the concept of span, we can visualize the process in three dimensions. The span of two linearly independent vectors is a plane.

PIC

Figure 1.5: The span of two linearly independent vectors u,v ∈ℝ3

When we talk about the span of a finite set {v1,…,vn}, we denote the span as

span (v ,...,v ). 1 n

This helps us avoid overcomplicating notations by naming every set.

Proposition 1. Let V be a vector space and S,S1,S2 ⊆V be subsets of its vectors.

(a) If S1 ⊆S2, then span(S1) ⊆ span(S2).

(b) span(span(S)) = span(S).

This is our very first proof! Give it a read, and if it’s too difficult, move on and revisit it later. Just make sure that you understand what the proposition says.

Proof. The property (a) follows directly from the definition. To prove (b), we have to show that span(S) ⊆ span(span(S)) and span(span(S)) ⊆ span(S).

(This is one of those steep learning curve moments, but think about it for a second: two sets A and B are equal if and only if A ⊆ B and B ⊆A.)

The former follows from the definition. For the latter, let x ∈ span(span(S)). Then

 ∑n x = xivi i=1

for some vi ∈ span(S). Because of vi being in the span of S, we have

 ∑m vi = vi,juj j=1

for some uj ∈S. Thus,

 ∑n ∑n ∑m ∑m ∑n x = xivi = xi vi,juj = ( xivi,j)uj, i=1 i=1 j=1 j=1 i=1

implying that x ∈ span(S) as well.

Because of span(span(S)) = span(S), if S is linearly dependent, we can remove the redundant vectors and still keep the span the same.

Think about it: if S = {v1,…,vn} and, say, vn = ∑ i=1n−1xivi , then vn ∈ span(S ∖{vn}). So,

span(S ∖{vn }) = span (span(S ∖ {vn})) = span (S ).

(The operation A ∖B is the set difference, containing all that are elements of A, but not elements of B. Feel free to check out Appendix C for more details.)

Among sets of vectors, those that generate the entire vector space are special. After all this setup, we are ready to make a formal definition. Any set of vectors S that have the property span(S) = V is called a generating set for V .

S can be thought of as a “lossless compression” of V , as it contains all the information needed to reconstruct any element in V , yet it is smaller than the entire space. Thus, we want to reduce the size of the generating set as much as possible. This leads us to one of the most important concepts in linear algebra: minimal generating sets, or bases, as we prefer to call them.

With all the intuition we have built so far, let’s jump into the definition right away!

Definition 4. (Basis)

Let V be a vector space and S be a subset of its vectors. S is a basis of V if:

(a) S is linearly independent,

(b) and span(S) = V .

The elements of a basis set are called basis vectors.

It can be shown that these defining properties mean that every vector x can be uniquely written as a linear combination of S. (This is left as an exercise for the reader.)

Let’s see some examples! In ℝ3, the set {(1,0,0),(0,1,0),(0,0,1)} is a basis, but so is {(1,1,1),(1,1,0),(0,1,1)}. So, there can be more than one basis for the same vector space.

For ℝn, the most commonly used basis is {e1,…,en}, where ei is a vector whose all coordinates are 0, except the i-th one, which is 1. This is called the standard basis.

In terms of the “information” contained in a set of vectors, bases hit the sweet spot. Adding any new vector to a basis set would introduce redundancy; removing any of its elements would cause the set to be incomplete.

These notions are formalized in the two theorems below.

Theorem 3.

Let V be a vector space and S = {v1,…,vn} be a subset of vectors. The following are equivalent:

(a) S is a basis.

(b) S is linearly independent and for any x ∈V ∖S, the vector set S ∪{x} is linearly dependent. In other words, S is a maximal linearly independent set.

Proof. To show the equivalence of two propositions, we have to prove two things: that (a) implies (b); and that (b) implies (a). Let’s start with the first one!

(a) =⇒ (b) If S is a basis, then any x ∈V can be written as

 n ∑ x = xivi i=1

for some xi ∈ℝ. Thus, by definition, S ∪{x} is linearly dependent.

(b) =⇒ (a) Our goal is to show that any x can be written as a linear combination of the vectors in S. By our assumption, S ∪{x} is linearly dependent, so 0 can be written as a nontrivial linear combination:

 ∑n 0 = αx + xivi, i=1

where not all coefficients are zero. Because S is linearly independent, α cannot be zero (as it would imply the linear dependence of S, which would go against our assumptions). Thus,

 ∑n x = − xivi, i=1 α

showing that S is a basis.

Next, we are going to show that every vector of a basis is essential.

Theorem 4.

Let V be a vector space and S = {v1,…,vn}a basis. Then, for any vi ∈S,

span(S ∖ {vi}) ⊂ V,

that is, the span of S ∖{vi}is a proper subset of V .

Proof. We are going to prove this by contradiction. Without loss of generality, we can assume that i = 1. If

span(S ∖{v1 }) = V,

then

 n ∑ v1 = xivi. i=2

This means that S = {v1,…,vn} is not linearly independent, contradicting our assumptions.

In other words, the above results mean that a basis is a maximal linearly independent and a minimal generating set at the same time.

Given a basis S = {v1,…,vn}, we implictly write the vector x = ∑ i=1nxivi as x = (x1,…,xn). Since this decomposition is unique, we can do this without issues. The coefficients xi are also called coordinates. (Note that the coordinates strongly depend on the basis. Given two different bases, the coordinates of the same vector can be different.)

As we have seen previously, a single vector space can have many different bases, so bases are not unique. A very natural question that arises in this context is the following. If S1 and S2 are two bases for V , then does jS1j = jS2j hold? (Where jSj denotes the cardinality of the set S, that is, its “size”.)

In other words, can we do better if we select our basis more cleverly? It turns out that we cannot, and the sizes of any two basis sets is equal. We are not going to prove this, but here is the theorem in its entirety.

Theorem 5.

Let V be a vector space, and let S1 and S2 be two bases of V . Then, |S1| = |S2| .

This gives us a way to define the dimension of a vector space, which is simply the cardinality of its basis. We’ll denote the dimension of V as dim(V ). For example, ℝn is n-dimensional, as shown by the standard basis {(1,0,…,0),…,(0,0,…,1)}.

If you recall the previous theorems, we assumed that a basis is finite. You might ask the question: is this always true? The answer is no. Examples 2 and 3 show that this is not the case. For instance, the countably infinite set {1,x,x2,x3,…} is a basis for ℝ[x]. So, according to the theorem above, no finite basis can exist there.

This marks an important distinction between vector spaces: those with finite bases are called finite-dimensional. I have some good news: all finite-dimensional real vector spaces are essentially ℝn. (Recall that we call a vector space real if its scalars are the real numbers.)

To see why, suppose that V is an n-dimensional real vector space with basis {v1,…,vn}, and define the mapping φ : V →ℝn by

 ∑n φ : xivi → (x1,...,xn). i=1

φ is invertible and preserves the structure of V , that is, the addition and scalar multiplication operations. Indeed, if u,v ∈V and α,β ∈ℝ, then φ(αu + βv) = αφ(x) + βφ(y). Such mappings are called isomorphisms. The word itself is derived from ancient Greek, with isos meaning same and morphe meaning shape. Even though this sounds abstract, the existence of an isomorphism between two vector spaces mean that they have the same structure. So, ℝn is not just an example of finite dimensional real vector spaces, it is a universal model of them. Note that if the scalars are not the real numbers, the isomorphism to ℝn is not true. (We’ll talk more about transformations like this in later chapters.)

Considering that we’ll almost exclusively deal with finite dimensional real vector spaces, this is good news. Using ℝn is not just a heuristic, it is a good mental model.

If every finite-dimensional real vector space is essentially the same as ℝn, what do we gain from abstraction? Sure, we can just work with ℝn without talking about bases, but to develop a deep understanding of the core mathematical concepts in machine learning, we need the abstraction.

Let’s look ahead briefly and see an example. If you have some experience with neural networks, you know that matrices play an essential role there. Without any context, matrices are just a table of numbers with seemingly arbitrary rules of computation. Have you ever wondered why matrix multiplication is defined the way it is?

Although we haven’t precisely defined matrices yet, you have probably encountered them previously. We’ll learn all about them in Chapter 3 and Chapter 4, but for the two matrices

 ⌊ ⌋ ⌊ ⌋ |a1,1 a1,2 ... a1,n| | b1,1 b1,2 ... b1,n| ||a2,1 a2,2 ... a2,n|| || b2,1 b2,2 ... b2,n|| | . . . . | | . . . . | A = || .. .. .. .. || , B = || .. .. .. .. || , ||a a ... a || ||b b ... b || ⌈ n,1 n,2 n,n⌉ ⌈ n,1 n,2 n,n⌉

their product AB is defined by

 ⌊∑ ∑ ∑ ⌋ nk=1 a1,kbk,1 nk=1 a1,kbk,2 ... nk=1a1,kbk,n ||∑n ∑n ∑n || || k=1 a2,kbk,1 k=1 a2,kbk,2 ... k=1a2,kbk,n|| AB = || ... ... ... ... || , |∑n ∑n ∑n | |⌈ k=1 an,kbk,1 k=1 an,kbk,2 ... k=1an,kbk,n|⌉

that is, the (i,j)-th element of AB is defined by

 n ∑ a b . i,kk,j k=1

This definition feels random. Why not just take the componentwise product (ai,jbi,j)i,j=1n? The definition becomes crystal clear once we look at a matrix as a tool to describe linear transformations between vector spaces, as the elements of the matrix describe the images of basis vectors. In this context, multiplication of matrices is just the composition of linear transformations.

Instead of just putting out the definition and telling you how to use it, I want you to understand why it is defined that way. In the next chapters, we are going to learn every nook and cranny of matrix multiplication.

At this point, you might ask the question: for a given vector space, are we guaranteed to find a basis? Without such a guarantee, the previous setup might be wasted. (As there might not be a basis to work with.)

Fortunately, this is not the case. As the proof is extremely difficult, we will not show this, but this is so important that we should at least state the theorem. If you are interested in how this can be done, I included a proof sketch. Feel free to skip this, as it is not going to be essential for our purposes.

Theorem 6.

Every vector space has a basis.

Proof. (Sketch.) The proof of this uses an advanced technique called transfinite induction, which is way beyond our scope. (Check out Naive Set Theory by Paul Halmos for details.) Instead of being precise, let’s just focus on building intuition about how to construct a basis for any vector space.

For our vector space V , we will build a basis one by one. Given any non-null vector v1, if span(S1)≠V , the set S1 = {v1} is not yet a basis. Thus, we can find a vector v2 ∈ V ∖ span(S1) so that S2 := S1 ∪{v2} is still linearly independent.

Is S2 a basis? If not, we can continue the process. In case the process stops in finitely many steps, we are done. However, this is not guaranteed. Think about ℝ[x], the vector space of polynomials, which is not finite-dimensional, as we saw in Section 1.2.4.

This is where we need to employ some set-theoretical heavy machinery (which we don’t have).

If the process doesn’t stop, we need to find a set Sℵ0 that contains all Si as a subset. (Finding this Sℵ0 set is the tricky part.) Is Sℵ0 a basis? If not, we continue the process.

This is difficult to show, but the process eventually stops, and we can’t add any more vectors to our linearly independent vector set without destroying the independence property. When this happens, we have found a maximal linearly independent set — that is, a basis.

For finite dimensional vector spaces, the above process is easy to describe. In fact, one of the pillars of linear algebra is the so-called Gram-Schmidt process, used to explicitly construct special bases for vector spaces. As several quintessential results rely on this, we are going to study it in detail during the next chapters.

Before we get our hands dirty with vectors in Python, there is one more subject we need to talk about, one that will come in handy when talking about linear transformations. (But again, linear transformations are at the heart of machine learning. Everything we learn is to get to know them better.) For a given vector space V , we are often interested in one of its subsets that is a vector space in its entirety. This is described by the concept of subspaces.

Definition 5. (Subspaces)

Let V be a vector space. The set U ⊆V is a subspace of V if it is closed under addition and scalar multiplication.

U is a proper subspace if it is a subspace and U ⊂V .

By definition, subspaces are vector spaces themselves, so we can define their dimension as well. There are at least two subspaces of each vector space: itself and {0}. These are called trivial subspaces. Besides those, the span of a set of vectors is always a subspace. One such example is illustrated in Figure 1.5.

One of the most important aspects of subspaces is that we can use them to create more subspaces. This notion is made precise below.

Definition 6. (Direct sum of subspaces)

Let V be a vector space and U1,U2 be two of its subspaces. The direct sum of U1 and U2 is defined by

U1 + U2 = {u1 + u2 : u1 ∈ U1, u2 ∈ U2}.

You can easily verify that U1 + U2 is a subspace indeed, moreover U1 + U2 = span(U1 ∪U2). Subspaces and their direct sum play an essential role in several topics, such as matrix decompositions. For example, we’ll see later that many of them are equivalent to decomposing a linear space into a sum of vector spaces.

The ability to select a basis whose subsets span certain given subspaces often comes in handy. This is formalized by the next result.

Theorem 7.

Let V be a vector space and U1,U2 be two of its subspaces such that U1 + U2 = V . Moreover, let {p1,…,pk} ⊆ U1 be a basis of U1 and {q1,…,ql}⊆U2 be a basis of U2. Then the union

{p1,...,pk} ∪ {q1,...,ql}

is a basis in V .

Proof. This follows directly from the direct sum’s definition. If V = U1 + U2, then any x ∈V can be written in the form x = a + b, where a ∈U1 and b ∈U2.

In turn, since p1,…,pk form a basis in U1 and q1,…,ql form a basis in U2, the vectors a and b can be written as

 k l a = ∑ a p , b = ∑ bq . i=1 i i i=1 i i

Thus, any x takes the form

 ∑k ∑ l x = aipi + biqi, i=1 i=1

which is the definition of the basis.

We are barely scratching the surface. Bases are essential, but they only provide the skeleton for the vector spaces encountered in practice. To properly represent and manipulate data, we need to build a geometric structure around this skeleton. How can we measure the “distance” between two measurements? What about their similarity?

Besides all that, there is an even more crucial question: how on earth will we represent vectors inside a computer? In the next section, we will take a look at the data structures of Python, laying the foundation for the data manipulations and transformations we’ll do later.

day-mode Bookmark

So far, we have mostly talked about the theory of vectors and vector spaces. However, our ultimate goal is to build computational models for discovering and analyzing patterns in data. To put theory into practice, we will take a look at how vectors are represented in computations.

In computer science, there is a stark contrast between how we think about mathematical structures and how we represent them inside a computer. Until this point, our goal was to develop a mathematical framework that enables us to reason about the structure of data and its transformations. We want a language that is

  • expressive,
  • easy to speak,
  • as compact as possible.

However, our goals change when we aim to do computations instead of pure logical reasoning. We want implementations that are

  • easy to work with,
  • memory-efficient,
  • fast to access, manipulate and transform.

These are often contradicting requirements, and particular situations might prefer one over the other. For instance, if we have plenty of memory but want to perform lots of computations, we can sacrifice size for speed. Because of all the potential use-cases, there are multiple formats to represent the same mathematical concepts. These are called data structures.

Different programming languages implement vectors differently. Because Python is ubiquitous in data science and machine learning, it’ll be our language of choice. In this chapter, we are going to study all the possible data structures in Python to see which one is suitable to represent vectors for high performance computations.

In standard Python, there are (at least) two built-in data structures that can be used to represent vectors: tuples and lists. Let’s start with tuples! They can be simply defined by enumerating their elements between two parentheses, separating them with commas.

v_tuple = (1, 3.5, -2.71, "a string", 42)
v_tuple
(1, 3.5, -2.71, ’a string’, 42)
type(v_tuple)
tuple

A single tuple can hold elements of various types. Even though we’ll exclusively deal with floats in computational linear algebra, this property is extremely useful for general-purpose programming.

We can access the elements of a tuple by indexing. Just like in several other programming languages, indexing starts from zero. This is in stark contrast with mathematics, where we often start indexing from one. Accordingly, in most languages designed for scientific computing, such as Fortran, Matlab, or Julia, indexing starts from one.

(Don’t tell this to anybody else, but indexing from zero used to drive me crazy. I am a mathematician by training.)

v_tuple[0]
1

The size of a tuple can be accessed by calling the built-in len function.

len(v_tuple)
5

Besides indexing, we can also access multiple elements by slicing.

v_tuple[1:4]
(3.5, -2.71, ’a string’)

Slicing works by specifying the first and last elements with an optional step size, using the syntax object[first:last:step].

Tuples are rather inflexible, as you cannot change their components. Attempting to do so results in a TypeError, Python’s standard way of telling you that the object does not support the method you are trying to call. (In our case, item assignment.)

v_tuple[0] = 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[22], line 1
----> 1 v_tuple[0] = 2
TypeError: 'tuple' object does not support item assignment

Besides that, extending the tuple with additional elements is also not supported. As we cannot change the state of a tuple object in any way after it has been instantiated, they are immutable. Depending on the use-case, immutability can be an advantage and a disadvantage as well. Immutable objects eliminate accidental changes, but each operation requires the creation of a new object, resulting in a computational overhead. Thus, tuples are not going to be optimal to represent large amounts of data in complex computations.

This issue is solved by lists. Let’s take a look at them, and the new problems they introduce!

Lists are the workhorses of Python. In contrast with tuples, lists are extremely flexible and easy to use, albeit this comes at the cost of runtime. Similarly to tuples, a list object can be created by enumerating its objects between square brackets, separated by commas.

v_list = [1, 3.5, -2.71, "qwerty"]
type(v_list)
list

Just like tuples, accessing the elements of a list is done by indexing or slicing. We can do all kinds of operations on a list: overwrite its elements, append items, or even remove others.

v_list[0] = "this is a string"
v_list
[’this is a string’, 3.5, -2.71, ’qwerty’]

This example illustrates that lists can hold elements of various types as well. Adding and removing elements can be done with methods like append, push, pop, and remove.

Before trying that, let’s quickly take note of the memory address of our example list, accessed by calling the id function.

v_list_addr = id(v_list)
v_list_addr
126433407319488

This number simply refers to an address in my computer’s memory, where the v_list object is located. Quite literally, as this book is compiled on my personal computer.

Now, we are going to perform a few simple operations on our list and show that the memory address doesn’t change. Thus, no new object is created.

v_list.append([42]) # adding the list [42] to the end of our list
v_list
[’this is a string’, 3.5, -2.71, ’qwerty’, [42]]
id(v_list) == v_list_addr # adding elements doesn’t create any new objects
True
v_list.pop(1) # removing the element at the index "1"
v_list
[’this is a string’, -2.71, ’qwerty’, [42]]
id(v_list) == v_list_addr # removing elements still doesn’t create any new objects
True

Unfortunately, adding lists together achieves a result that is completely different from our expectations.

[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]

Instead of adding the corresponding elements together, like we want vectors to behave, the lists are concatenated. This feature is handy when writing general-purpose applications. However, this is not well-suited for scientific computations. “Scalar multiplication” also has strange results.

3*[1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Multiplying a list with an integer repeats the list by the specified number of times. Given the behavior of the + operator on lists, this seems logical as multiplication with an integer is repeated addition:

a⋅b = b◟+--⋅◝⋅⋅◜+--b◞. a times

Overall, lists can do much more than we need to represent vectors. Although we potentially want to change elements of our vectors, we don’t need to add or remove elements from them, and we also don’t need to store objects other than floats. Can we sacrifice these extra features and obtain an implementation that’s suitable for our purposes yet has lightning-fast computational performance? Yes. Enter NumPy arrays.

Even though Python’s built-in data structures are amazing, they are optimized for ease of use, not for scientific computation. This problem was realized early on in the language’s development and was addressed by the NumPy library.

One of the main selling points of Python is how fast and straightforward it is to write code, even for complex tasks. This comes at the price of speed. However, in machine learning, speed is crucial for us. When training a neural network, a small set of operations are repeated millions of times. Even a small percentage of improvement in performance can save hours, days, or even weeks in the case of extremely large models.

The C language is at the other end of the spectrum. While C code is hard to write, it executes blazingly fast when done correctly. As Python is written in C, a tried and true method for achieving fast performance is to call functions written in C from Python. In a nutshell, this is what NumPy provides: C arrays and operations, all in Python.

To get a glimpse into the deep underlying issues with Python’s built-in data structures, we should put numbers and arrays under our magnifying glass. Inside a computer’s memory, objects are represented as fixed-length 0-1 sequences. Each component is called a bit. Bits are usually grouped into 8-, 16-, 32-, 64-, or even 128 sized chunks. Depending on what we want to represent, identical sequences can mean different things. For instance, the 8-bit sequence 00100110 can represent the integer 38 or the ASCII character “&.

PIC

Figure 1.6: An 8-bit object in memory

By specifying the data type, we can decode binary objects. 32-bit integers are called int32 types, 64-bit floats are float64, and so on.

Since a single bit contains very little information, memory is addressed by dividing it into 32- or 64-bit sized chunks and numbering them consecutively. This address is a hexadecimal number, starting from 0. (For simplicity, let’s assume that the memory is addressed by 64 bits. This is customary in modern computers.)

A natural way to store a sequence of related objects (with matching data type) is to place them next to each other in the memory. This data structure is called an array.

PIC

Figure 1.7: An array of int64 objects

By storing the memory address of the first object, say 0x23A0, we can instantly retrieve the k-th element by accessing the memory at 0x23A0 + k.

We call this the static array or often the C array because this is how it is done in the magnificent C language. Although this implementation of arrays is lightning fast, it is relatively inflexible. First, you can only store objects of a single type. Second, you have to know the size of your array in advance, as you cannot use memory addresses that overextend the pre-allocated part. Thus, before you start working with your array, you have to allocate memory for it. (That is, reserve space so that other programs won’t overwrite it.)

However, in Python, you can store arbitrarily large and different objects in the same list, with the option of removing and adding elements to it.

l = [2**142 + 1, "a string"]
l.append(lambda x: x)
l
[5575186299632655785383929568162090376495105,
'a string',
<function __main__.<lambda>(x)>]

In the example above, l[0] is an integer so large that it doesn’t fit into 128 bits. Also, there are all kinds of objects in our list, including a function. How is this possible?

Python’s list provides a flexible data structure by

  1. Overallocating the memory, and
  2. Keeping memory addresses to the objects in the list instead of the objects themselves.

(At least in the most widespread CPython implementation ( https://docs.python.org/3/faq/design.html\#how-are-lists-implemented-in-cpython).)

PIC

Figure 1.8: CPython implementation of lists

By checking the memory addresses of each object in our list l, we can see that they are all over the memory.

[id(x) for x in l]
[126433412959232, 126433407528240, 126433410174944]

Due to the overallocation, deletion or insertion can always be done simply by shifting the remaining elements. Since the list stores the memory address of its elements, all types of objects can be stored within a single structure.

However, this comes at a cost. Because the objects are not contiguous in memory, we lose locality of reference (https://en.wikipedia.org/wiki/Locality_of_reference), meaning that since we frequently access distant locations of the memory, our reads are much slower. Thus, looping over a Python list is not efficient.

So, NumPy arrays are essentially the good old C arrays in Python, with the user-friendly interface of Python lists. (If you have ever worked with C, you know how big of a blessing this is.) Let’s see how to work with them!

First, we import the numpy library. (To save on the characters, it is customary to import it as np.)

import numpy as np

The main data structure is np.ndarray, short for n-dimensional array. We can use the np.array function to create NumPy arrays from standard Python containers or initialize from scratch. (Yes, I know. This is confusing, but you’ll get used to it. Just take a mental note that np.ndarray is the class, and np.array is the function you use to create NumPy arrays from Python objects.)

X = np.array([87.7, 4.5, -4.1, 42.1414, -3.14, 2.001]) # creating a NumPy array from a Python list
X
array([87.7   ,  4.5   , -4.1   , 42.1414, -3.14  ,  2.001 ])
np.ones(shape=7) # initializing a NumPy array from scratch using ones
array([1., 1., 1., 1., 1., 1., 1.])
np.zeros(shape=5) # initializing a NumPy array from scratch using zeros
array([0., 0., 0., 0., 0.])

We can even initialize NumPy arrays using random numbers.

np.random.rand(10)
array([0.92428404, 0.37719596, 0.92071695, 0.56905245, 0.12024811,
      0.02868856, 0.53215047, 0.51749348, 0.21022765, 0.96749756])

Most importantly, when we have a given array, we can initialize another one with the same dimensions using the np.zeros_like, np.ones_like, and np.empty_like functions.

np.zeros_like(X)
array([0., 0., 0., 0., 0., 0.])

Just like Python lists, NumPy arrays support item assignments and slicing.

X[0] = 1545.215
X
array([1545.215 ,    4.5   ,   -4.1   ,   42.1414,   -3.14  ,    2.001 ])
X[1:4]
array([ 4.5   , -4.1   , 42.1414])

However, as expected, you can only store a single data type within each ndarray. When trying to assign a string as the first element, we get an error message.

X[0] = "str"
---------------------------------------------------------------------------
ValueError                              Traceback (most recent call last)
Cell In[48], line 1
----> 1 X[0] = "str"
ValueError: could not convert string to float: ’str’

As you might have guessed, every ndarray has a data type attribute that can be accessed at ndarray.dtype. If a conversion can be made between the value to be assigned and the data type, it is automatically performed, making the item assignment successful.

X.dtype
dtype(’float64’)
val = 23
type(val)
int
X[0] = val
X
array([23.    ,  4.5   , -4.1   , 42.1414, -3.14  ,  2.001 ])

NumPy arrays are iterable, just like other container types in Python.

for x in X:
print(x)
23.0
4.5
-4.1
42.1414
-3.14
2.001

Are these suitable to represent vectors? Yes. We’ll see why!

Let’s talk about vectors once more. From now on, we are going to use NumPy ndarray-s to model vectors.

v_1 = np.array([-4.0, 1.0, 2.3])
v_2 = np.array([-8.3, -9.6, -7.7])

The addition and scalar multiplication operations are supported by default and perform as expected.

v_1 + v_2 # adding v_1 and v_2 together as vectors
array([-12.3,  -8.6,  -5.4])
10.0*v_1 # multiplying v_1 with a scalar
array([-40.,  10.,  23.])
v_1 * v_2 # the elementwise product of v_1 and v_2
array([ 33.2 ,  -9.6 , -17.71])
np.zeros(shape=3) + 1
array([1., 1., 1.])

Because of the dynamic typing of Python, we can (often) plug NumPy arrays into functions intended for scalars.

def f(x):
return 3*x**2 - x**4
f(v_1)
array([-208.    ,    2.    ,  -12.1141])

So far, NumPy arrays satisfy almost everything we require to represent vectors. There is only one box to be checked: performance. To investigate this, we measure the execution time with Python’s built-in timeit tool.

In its first argument, timeit (https://docs.python.org/3/library/timeit.html) takes a function to be executed and timed. Instead of passing a function object, it also accepts executable statements as a string. Since function calls have a significant computational overhead in Python, we are passing code rather than a function object in order to be more precise with the time measurements.

Below, we compare adding together two NumPy arrays vs. Python lists containing a thousand zeros.

from timeit import timeit
n_runs = 100000
size = 1000
t_add_builtin = timeit(
"[x + y for x, y in zip(v_1, v_2)]",
setup=f"size={size}; v_1 = [0 for _ in range(size)]; v_2 = [0 for _ in range(size)]",
number=n_runs
)
t_add_numpy = timeit(
"v_1 + v_2",
setup=f"import numpy as np; size={size}; v_1 = np.zeros(shape=size);
v_2 = np.zeros(shape=size)",
number=n_runs
)
print(f"Built-in addition: \t{t_add_builtin} s")
print(f"NumPy addition: \t{t_add_numpy} s")
print(f"Performance improvement: \t{t_add_builtin/t_add_numpy:.3f} times faster")
Built-in addition:             3.3522969299992837 s
NumPy addition:               0.09616518099937821 s
Performance improvement:       34.860 times faster

NumPy arrays are much-much faster. This is because they are

  • contiguous in memory,
  • homogeneous in type,
  • with operations implemented in C.

This is just the tip of the iceberg. We have only seen a small part of it, but NumPy provides much more than a fast data structure. As we progress in the book, we’ll slowly dig deeper and deeper, eventually discovering the vast array of functionalities it provides.

NumPy is designed to be faster than vanilla Python. Is this really the case? Not all the time. If you use it wrong, it might even hurt performance! To know when it is beneficial to use NumPy, we will look at why exactly it is faster in practice.

To simplify the investigation, our toy problem will be random number generation. Suppose that we need just a single random number. Should we use NumPy? Let’s test it! We are going to compare it with the built-in random number generator by running both ten million times, measuring the execution time.

from numpy.random import random as random_np
from random import random as random_py
n_runs = 10000000
t_builtin = timeit(random_py, number=n_runs)
t_numpy = timeit(random_np, number=n_runs)
print(f"Built-in random:\t{t_builtin} s")
print(f"NumPy random: \t{t_numpy} s")
Built-in random:      0.47474874800172984 s
NumPy random:         5.1664929229991685 s

For generating a single random number, NumPy is significantly slower. Why is this the case? What if we need an array instead of a single number? Will this also be slower?

This time, let’s generate a list/array of a thousand elements.

size = 1000
n_runs = 10000
t_builtin_list = timeit(
"[random_py() for _ in range(size)]",
setup=f"from random import random as random_py; size={size}",
number=n_runs
)
t_numpy_array = timeit(
"random_np(size)",
setup=f"from numpy.random import random as random_np; size={size}",
number=n_runs
)
print(f"Built-in random with lists:\t{t_builtin_list}s")
print(f"NumPy random with arrays: \t{t_numpy_array}s")
Built-in random with lists:    0.5773125300001993s
NumPy random with arrays:       0.08449692800058983s

(Again, I don’t want to wrap the timed expressions in lambdas since function calls have an overhead in Python. I want to be as precise as possible, so I pass them as strings to the timeit function.)

Things are looking much different now. When generating an array of random numbers, NumPy wins hands down.

There are some curious things about this result as well. First, we generated a single random number 10000000 times. Second, we generated an array of 1000 random numbers 10000 times. In both cases, we have 10000000 random numbers in the end. Using the built-in method, it took ˜2x time when we put them in a list. However, with NumPy, we see a ˜30x speedup compared to itself when working with arrays! (The actual numbers might be different on your computer.)

To see what happens behind the scenes, we are going to profile the code using cProfiler (https://docs.python.org/3/library/profile.html). With this, we’ll see exactly how many times a given function was called and how much time we spent inside it.

Let’s take a look at the built-in function first. In the following function, we create 10000000 random numbers, just as before.

def builtin_random_single(n_runs):
for _ in range(n_runs):
random_py()

From Jupyter Notebooks, where this book is written, cProfiler can be called with the magic command %prun.

n_runs = 10000000
%prun builtin_random_single(n_runs)
10000558 function calls (10000539 primitive calls) in 2.082 seconds
   Ordered by: internal time
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       1    0.937    0.937    1.671    1.671 2471337341.py:1(builtin_random_single)
 10000000    0.911    0.000    0.911    0.000 {method ’random’ of ’_random.Random’ objects}
     4/0    0.213    0.053    0.000         {method ’poll’ of ’select.epoll’ objects}
      10    0.009    0.001    0.016    0.002 socket.py:626(send)
       2    0.009    0.004    0.015    0.008 {method ’__exit__’ of ’sqlite3.Connection’ objects}

There are two important columns here for our purposes. ncalls shows how many times a function was called, while tottime is the total time spent in a function, excluding time spent in subfunctions.

The built-in function random.random() was called 10000000 times as expected. Take note of the total time spent in the function. (I can’t give you an exact figure here, as it depends on the machine this book is built on.)

What about the NumPy version? The results are surprising.

def numpy_random_single(n_runs):
for _ in range(n_runs):
random_np()
%prun numpy_random_single(n_runs)
448 function calls (444 primitive calls) in 7.203 seconds
   Ordered by: internal time
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       1    7.029    7.029    7.029    7.029 2015715881.py:1(numpy_random_single)
       2    0.136    0.068    0.136    0.068 {method ’poll’ of ’select.epoll’ objects}
       2    0.015    0.007    0.015    0.007 {method ’__exit__’ of ’sqlite3.Connection’ objects}
       1    0.011    0.011    0.011    0.011 {method ’execute’ of ’sqlite3.Connection’ objects}
       3    0.010    0.003    7.339    2.446 base_events.py:1910(_run_once)
       7    0.000    0.000    0.000    0.000 socket.py:626(send)
       1    0.000    0.000    0.000    0.000 {method ’disable’ of ’_lsprof.Profiler’ objects}
       1    0.000    0.000    0.026    0.026 history.py:833(_writeout_input_cache)
       1    0.000    0.000    0.000    0.000 inspect.py:3102(_bind)
   88/84    0.000    0.000    0.000    0.000 {built-in method builtins.isinstance}

Similarly, as before, the numpy.random.random() function was indeed called 10000000 times, as expected. Yet, the script spent significantly more time in this function than in the Python built-in random before. Thus, it is more costly per call.

When we start working with large arrays and lists, things change dramatically. Next, we generate a list/array of 1000 random numbers, while measuring the execution time.

def numpy_random_single(n_runs):
for _ in range(n_runs):
random_np()
%prun numpy_random_single(n_runs)
448 function calls (444 primitive calls) in 7.203 seconds
   Ordered by: internal time
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       1    7.029    7.029    7.029    7.029 2015715881.py:1(numpy_random_single)
       2    0.136    0.068    0.136    0.068 {method ’poll’ of ’select.epoll’ objects}
       2    0.015    0.007    0.015    0.007 {method ’__exit__’ of ’sqlite3.Connection’ objects}
       1    0.011    0.011    0.011    0.011 {method ’execute’ of ’sqlite3.Connection’ objects}
       3    0.010    0.003    7.339    2.446 base_events.py:1910(_run_once)
       7    0.000    0.000    0.000    0.000 socket.py:626(send)
       1    0.000    0.000    0.000    0.000 {method ’disable’ of ’_lsprof.Profiler’ objects}
       1    0.000    0.000    0.026    0.026 history.py:833(_writeout_input_cache)
       1    0.000    0.000    0.000    0.000 inspect.py:3102(_bind)
   88/84    0.000    0.000    0.000    0.000 {built-in method builtins.isinstance}

As we see, about 60% of the time was spent on the list comprehensions. (Note that tottime doesn’t count subfunction calls like calls to random.random() here.)

Now we are ready to see why NumPy is faster when used right.

def numpy_random_array(size, n_runs):
for _ in range(n_runs):
random_np(size)
%prun numpy_random_array(size, n_runs)
149 function calls (148 primitive calls) in 0.132 seconds
   Ordered by: internal time
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       1    0.122    0.122    0.122    0.122 1681905588.py:1(numpy_random_array)
       2    0.009    0.004    0.009    0.004 {method ’__exit__’ of ’sqlite3.Connection’ objects}
     2/1    0.000    0.000    0.122    0.122 {built-in method builtins.exec}

With each of the 10000 function calls, we get a numpy.ndarray of 1000 random numbers. The reason why NumPy is fast when used right is that its arrays are extremely efficient to work with. They are like C arrays instead of Python lists.

As we have seen, there are two significant differences between them.

  • Python lists are dynamic, so for instance, you can append and remove elements. NumPy arrays have fixed lengths, so you cannot add or delete without creating a new one.
  • Python lists can hold several data types simultaneously, while a NumPy array can only contain one.

So, NumPy arrays are less flexible but significantly more performant. When this additional flexibility is not needed, NumPy outperforms Python.

To see precisely at which size does NumPy overtakes Python in random number generation, we can compare the two by measuring the execution times for several sizes.

sizes = list(range(1, 100))
runtime_builtin = [
timeit(
"[random_py() for _ in range(size)]",
setup=f"from random import random as random_py; size={size}",
number=100000
)
for size in sizes
]
runtime_numpy = [
timeit(
"random_np(size)",
setup=f"from numpy.random import random as random_np; size={size}",
number=100000
)
for size in sizes
sizes = import matplotlib.pyplot as plt
with plt.style.context("seaborn-v0_8"):
plt.figure(figsize=(10, 5))
plt.plot(sizes, runtime_builtin, label="built-in")
plt.plot(sizes, runtime_numpy, label="NumPy")
plt.xlabel("array size")
plt.ylabel("time (seconds)")
plt.title("Runtime of random array generation")
plt.legend()
plt.show()

PIC

Figure 1.9: Runtime of random array generation

Around 20, NumPy starts to beat Python in performance. Of course, this number might be different for other operations like calculating the sine or adding numbers together, but the tendency will be the same. Python will slightly outperform NumPy for small input sizes, but NumPy wins by a large margin as the size grows.

day-mode Bookmark

In this chapter, we have learned what vectors are and why we must use them in data science and machine learning. Vectors are not just a bunch of numbers bundled together but a mathematical structure that allows us to reason about data more effectively, both in theory and in practice. Contrary to popular belief, vectors are vectors not because they have direction and magnitude but because you can add them together.

This is formalized by the concept of vector spaces, providing the mathematical framework for our studies. Vector spaces are best described by bases, that is, minimal and linearly independent generating sets. Understanding vector spaces and their bases will pay enormous dividends when we study linear transformations, the most important building block of predictive models.

Besides the leap of abstraction provided by vectors, we reap significant benefits in practice by vectorizing our code, compressing complex logic into one-liners such as data scaling:

X_scaled = (X - X.mean(axis=0)) / X.std(axis=0)

Besides the conceptual jump from scalars to vectors and matrices, efficient data processing is made possible by NumPy (short for Numerical Python), the number one library in the machine learning toolkit. If a tensor library doesn’t use NumPy, it is inspired by it. We already understand its basics and know why and when to use it.

In the next chapter, we continue exploring vector spaces. Bases are cool and all, but besides them, vector spaces have a beautiful and rich geometric structure. Let’s see it!

day-mode Bookmark

Problem 1. Not all vector spaces are infinite. There are some that only contain a finite number of vectors, as we shall see next in this problem. Define the set

ℤ2 := {0,1},

where the operations +,⋅ are defined by the rules

0 + 0= 0
0 + 1= 1
1 + 0= 1
1 + 1= 0

and

0 ⋅ 0= 0
0 ⋅ 1= 0
1 ⋅ 0= 0
1 ⋅ 1= 1.

This is called binary (or modulo-2) arithmetic.

(a) Show that (ℤ2,ℤ2,+,⋅) is a vector space.

(b) Show that(ℤ2n,ℤ2,+,⋅) is also a vector space, where ℤ2n is the n-fold Cartesian product

 n ℤ 2 = ℤ◟2-×-⋅⋅◝◜⋅×-ℤ2◞, n times

and the addition and scalar multiplication are defined elementwise:

x+ y= (x1 + y1,…,xn + yn), x,y ∈ℤ2n,
cx= (cx1,…,cxn), c ∈ℤ2.

Problem 2. Are the following vector sets linearly independent?

(a) S1 = {(1,0,0),(1,1,0),(1,1,1)}⊆ℝ3

(b) S2 = {(1,1,1),(1,2,4),(1,3,9)}⊆ℝ3

(c) S3 = {(1,1,1),(1,1,−1),(1,−1,−1)}⊆ℝ3

(d) S4 = {(π,e),(−42,13∕6),(π3,−2)}⊆ℝ2

Problem 3. Let V be a finite n-dimensional vector space and let S = {v1,…,vm} be a linearly independent set of vectors, m>n. Show that there is a basis set B such that S ⊂B.

Problem 4. Let V be a vector space and S = {v1,…,vn} be its basis. Show that every vector x ∈V can be uniquely written as a linear combination of vectors in S. (That is, if x = ∑ i=1nαivi = ∑ i=1nβivi, then αi = βi for all i = 1,…,n.)

Problem 5. Let V be an arbitrary vector space and U1,U2 ⊆V be two of its subspaces. Show that U1 + U2 = span(U1 ∪U2).

Hint: to prove the equality of these two sets, you need to show two things: 1) if x ∈U1 + U2, then x ∈ span(U1 ∪U2) as well, 2) if x ∈ span(U1 ∪U2), then x ∈U1 + U2 as well.

Problem 6. Consider the vector space of polynomials with real coefficients, defined by

 n ℝ [x] = {p(x) = ∑ pxi : p ∈ ℝ, n = 0,1,...}. i i i=0

(a) Show that

 ∑n i xℝ[x] := {p(x) = pix : pi ∈ ℝ, n = 1,2,...} i=1

is a proper subspace of ℝ[x].

(b) Show that

f : ℝ[x] → xℝ [x ], p(x) ↦→ xp(x)

is a bijective and linear. (A function f : X →Y is bijective if every y ∈Y has exactly one x ∈X for which f(x) = y. If you are not comfortable with this notion, feel free to revisit this problem after Chapter 9.)

In general, a linear and bijective function f : U →V between vector spaces is called an isomorphism. Given the existence of such a function, we call the vector spaces U and V isomorphic, meaning that they have an identical algebraic structure.

Combining (a) and (b), we obtain that ℝ[X] is isomorphic with its proper subspace xℝ[X]. This is quite an interesting phenomenon: a vector space that is algebraically identical to its proper subspace. (Note that this cannot happen in finite dimensions, such as ℝn.)