Skip to main content

MATH 345: Linear Algebra and Optimization

Section 1.1 Vectors

Subsection Vectors as lists of numbers

A real quantity is also called a scalar.

Definition 1.1.1. Vector.

An \(n\)-vector is an ordered list of \(n\) scalars, often written in the form \(\mathbf{v} = (v_1,v_2,\ldots,v_n)\text{.}\) The collection of all \(n\)-vectors is denoted \(\R^n\text{.}\)
We will also encounter vectors written as a row or column of numbers in square brackets, i.e.,
\begin{equation*} \begin{bmatrix} v_1 \amp \cdots \amp v_n \end{bmatrix} \quad\text{and}\quad \begin{bmatrix} v_1 \\ \vdots \\ v_n \end{bmatrix}\text{.} \end{equation*}
It is customary to use bold letters for variables, such as \(\mathbf{v}\) or \(\mathbf{w}\text{,}\) to represent vectors. We let \(\mathbf{0}\) denote the vector \((0,\dots,0)\) consisting only of zeros. Two vectors \(\mathbf{v}\) and \(\mathbf{w}\) are equal if they have the same number of entries and all the corresponding entries are equal. A point in \(n\)-dimensional space can also be identified with an ordered list of \(n\) numbers using Cartesian coordinates. When referring specifically to a point \(P\text{,}\) we write \(P(x_1,x_2,\ldots,x_n)\) to indicate its coordinates.

Subsection Vectors as displacements in space: building intuition

Vectors can be used to represent displacements between points in space. The vector \(\mathbf{v}=(v_1,v_2,v_3)\) represents the displacement from \(P(x_1,y_1,z_1)\) to \(Q(x_2,y_2,z_2)\text{,}\) where \(x_2 = x_1 + v_1\text{,}\) \(y_2 = y_1 + v_2\text{,}\) and \(z_2 = z_1 + v_3\text{.}\) This vector is also written as \(\overrightarrow{PQ}\text{.}\) Because vectors often indicate displacements, they are drawn pictorially as arrows starting at a point, and ending where that point is displaced by the vector.
A vector, represented as an arrow between two points.
Three coordinate axes labeled \(x\text{,}\) \(y\text{,}\) and \(z\) meet at an origin. A thick arrow labeled \(\mathbf{v}\) starts at the red point \(P\) and ends at the red point \(Q\text{,}\) showing the displacement from \(P\) to \(Q\text{.}\)
Figure 1.1.2. A vector \(\mathbf{v}\) represented as an arrow between two points \(P\) and \(Q\text{.}\)

Activity 1.1.3. Vectors as displacements in space (U1-LO2).

What is the vector representing the displacement from the point \(P(1,2)\) to the point \(Q(5,7)\text{.}\)
Solution.
If \(\mathbf{v} = (v_1,v_2)\) was the displacement, then we would have \((1 + v_1, 2 + v_2) = (5,7)\text{,}\) i.e., so that \(1 + v_1 = 5\) and \(2 + v_2 = 7\text{.}\) Solving these equations gives \(v_1 = 4\) and \(v_2 = 5\text{,}\) so that the displacement vector is \(\mathbf{v} = (4,5)\text{.}\)

Definition 1.1.4. Length of a vector.

The length of a vector \(\mathbf{v} = (v_1,\dots,v_n)\text{,}\) also called its Euclidean norm, is the quantity
\begin{equation*} \| \mathbf{v} \| = \sqrt{ v_1^2 + \cdots + v_n^2 }\text{.} \end{equation*}

Activity 1.1.5. Vector length and geometry (U1-LO1).

Verify, using planar geometry, that the length of a \(2\)-vector is the length of the line-segment of the arrow representing the vector.
Solution.
Let \(\mathbf{v} = (x,y)\) be an arbitrary \(2\)-vector. Consider a triangle with vertices \(P(0,0)\text{,}\) \(Q(x,0)\text{,}\) and \(R(x,y)\) (see FigureΒ 1.1.6).
A triangle drawn to determine the length of the line-segment upon which a 2-vector is based.
The figure shows \(x\)- and \(y\)-axes with a vector \(\mathbf{v}\) drawn from \(P(0,0)\) to \(R(x,y)\text{.}\) A horizontal segment from \(P\) to \(Q(x,0)\) and a vertical segment from \(Q\) to \(R\) form a right triangle whose hypotenuse is the vector.
Figure 1.1.6. A triangle with vertices \(P(0,0)\text{,}\) \(Q(x,0)\text{,}\) and \(R(x,y)\text{,}\) drawn to determine the length of the line-segment upon which a \(2\)-vector is based.
This triangle is right-angled (the two legs are horizontal and vertical), and the hypotenuse is the line-segment upon which the vector \(\mathbf{v}\) is built. The length of the leg from \(P(0,0)\) to \(Q(x,0)\) is \(|x|\text{,}\) and the length of the leg from \(Q(x,0)\) to \(R(x,y)\) is \(|y|\text{.}\) By Pythagoras’ theorem, we conclude that the length of the hypotenuse is
\begin{equation*} \sqrt{ |x|^2 + |y|^2 } = \sqrt{x^2 + y^2} = \| \mathbf{v} \|\text{.} \end{equation*}
In a calculus course, you may have mostly seen a vector as a displacement, but in this course it can also be a row of data or a list of model parameters, among other important applications. The same operations below will later compare documents, tokens, and feature vectors.

Subsection Adding and scaling vectors

Two displacements can be combined: just apply one displacement after the other is applied. This naturally leads to the notion of adding two vectors.

Definition 1.1.7. Adding vectors.

The sum of two \(n\)-vectors \(\mathbf{v} = (v_1,\dots,v_n)\) and \(\mathbf{w} = (w_1,\dots,w_n)\text{,}\) denoted \(\mathbf{v} + \mathbf{w}\text{,}\) is the vector given by the tuple \((v_1 + w_1, \dots, v_n + w_n)\text{.}\)

Remark 1.1.8.

The sum of two vectors can be illustrated pictorially as in FigureΒ 1.1.9 by drawing the parallelogram with the vectors placed along two sides of the parallelogram.
The sum of two vectors.
A blue vector \(\mathbf{v}\) and a red vector \(\mathbf{w}\) start at the origin. Dashed copies of each vector are translated to the tip of the other vector, and both translated arrows meet at a shared endpoint. A green arrow from the origin to that endpoint is labeled \(\mathbf{v}+\mathbf{w}\text{.}\)
Figure 1.1.9. The sum of two vectors \(\mathbf{v}\) and \(\mathbf{w}\text{.}\)
One can also scale a vector by a given scalar quantity.

Definition 1.1.10. Scaling vectors.

If \(\mathbf{v} = (v_1,\cdots,v_n)\) is an \(n\)-vector and \(t \in \R\) is a scalar, we let \(t \mathbf{v}\) denote the vector \((tv_1, \cdots, tv_n)\text{,}\) i.e., multiplying each entry of the vector \(\mathbf{v}\) by \(t\text{.}\)

Definition 1.1.11. Linear combinations and convex combinations of vectors.

If \(\mathbf{v}_1,\ldots,\mathbf{v}_k\) are vectors in \(\mathbb R^n\) and \(c_1,\ldots,c_k\) are scalars, then
\begin{equation*} c_1\mathbf{v}_1+\cdots+c_k\mathbf{v}_k \end{equation*}
is a linear combination of \(\mathbf{v}_1,\ldots,\mathbf{v}_k\text{.}\) The scalars \(c_1,\ldots,c_k\) are the coefficients of the linear combination. If \(c_i\ge 0\) for all \(i\) and \(c_1+\cdots+c_k=1\text{,}\) then the linear combination is a convex combination.
A convex combination can be interpreted as a weighted average.

Activity 1.1.12. A weighted average (U1-LO8).

Let \(\mathbf{v}_1=(10,0)\text{,}\) \(\mathbf{v}_2=(0,10)\text{,}\) and \(\mathbf{v}_3=(10,10)\text{.}\) Let \(\alpha_1=1/4\text{,}\) \(\alpha_2=1/4\text{,}\) and \(\alpha_3=1/2\text{.}\) Compute \(\alpha_1\mathbf{v}_1+\alpha_2\mathbf{v}_2+\alpha_3\mathbf{v}_3\text{.}\)
Solution.
We have
\begin{align*} \frac14(10,0) \amp = \left(\frac52,0\right)\\ \frac14(0,10) \amp = \left(0,\frac52\right)\\ \frac12(10,10) \amp = (5,5)\\ \alpha_1\mathbf{v}_1+\alpha_2\mathbf{v}_2+\alpha_3\mathbf{v}_3 \amp = \left(\frac{15}{2},\frac{15}{2}\right)\\ \amp = (7.5,7.5)\text{.} \end{align*}
The coefficients are nonnegative and add to \(1\text{,}\) so this is a convex combination.

Example 1.1.13. Subtracting vectors as a linear combination.

Subtracting a vector means adding its negative:
\begin{equation*} \mathbf{u}-\mathbf{v}=\mathbf{u}+(-\mathbf{v})=1\mathbf{u}+(-1)\mathbf{v}. \end{equation*}
Thus, \(\mathbf{u}-\mathbf{v}\) is a linear combination of \(\mathbf{u}\) and \(\mathbf{v}\) with coefficients \(1\) and \(-1\text{.}\) For example, if \(\mathbf{u}=(4,1)\) and \(\mathbf{v}=(1,3)\text{,}\) then
\begin{equation*} \mathbf{u}-\mathbf{v}=(4,1)+(-1,-3)=(3,-2). \end{equation*}
Geometrically, \(-\mathbf{v}\) has the same length as \(\mathbf{v}\) but points in the opposite direction. We can therefore use the parallelogram construction from FigureΒ 1.1.9 with \(\mathbf{u}\) and \(-\mathbf{v}\text{,}\) as shown on the left in FigureΒ 1.1.14. Equivalently, when \(\mathbf{u}\) and \(\mathbf{v}\) start at the same point, the arrow from the tip of \(\mathbf{v}\) to the tip of \(\mathbf{u}\) represents \(\mathbf{u}-\mathbf{v}\text{.}\) Here, it is the displacement from \(P(1,3)\) to \(Q(4,1)\text{,}\) shown on the right.
Two views of vector subtraction: adding the negative vector and joining the tips of the original vectors.
On the left, a blue arrow \(\mathbf{u}=(4,1)\) and a red arrow \(-\mathbf{v}=(-1,-3)\) start at the same point. Dashed translated copies complete a parallelogram, whose green diagonal is \(\mathbf{u}-\mathbf{v}=(3,-2)\text{.}\) On the right, blue \(\mathbf{u}\) and red \(\mathbf{v}\) start at the origin and end at \(Q(4,1)\) and \(P(1,3)\text{,}\) respectively. A green arrow from \(P\) to \(Q\) represents the same difference \(\mathbf{u}-\mathbf{v}\text{.}\)
Figure 1.1.14. The difference \(\mathbf{u}-\mathbf{v}\) as the sum \(\mathbf{u}+(-\mathbf{v})\) (left) and as the displacement from the tip of \(\mathbf{v}\) to the tip of \(\mathbf{u}\) (right).

Subsection Dot products of vectors

Definition 1.1.15. Dot product.

The dot product of two \(n\)-vectors \(\mathbf{v} = (v_1,\dots,v_n)\) and \(\mathbf{w} = (w_1,\dots,w_n)\) is the scalar quantity
\begin{equation*} \mathbf{v} \cdot \mathbf{w} = v_1 w_1 + \cdots + v_n w_n\text{.} \end{equation*}
Geometrically, the dot product of two vectors is a quantity which is related to the angle between the two vectors \(\mathbf{v}\) and \(\mathbf{w}\text{.}\) If we draw the two vectors as arrows with the same starting point, then they form an angle on the plane containing both vectors, and the angle \(\theta\) is given below.
The dot product can be thought of as a measure of the similarity between two vectors. Suppose \(\theta\) is the angle between two vectors \(\mathbf{v}\) and \(\mathbf{w}\text{:}\)
  • If \(\theta\) is close to zero, then the two vectors are close to pointing in the same direction. Since \(\cos(0^\circ) = 1\text{,}\) this occurs precisely when
    \begin{equation*} \frac{\mathbf{v} \cdot \mathbf{w}}{\| \mathbf{v} \| \| \mathbf{w} \|} \approx 1\text{.} \end{equation*}
  • If \(\theta\) is close to \(180^\circ\text{,}\) then the two vectors are close to pointing in opposite directions. Since \(\cos(180^\circ) = -1\text{,}\) this occurs precisely when
    \begin{equation*} \frac{\mathbf{v} \cdot \mathbf{w}}{\| \mathbf{v} \| \| \mathbf{w} \|} \approx -1\text{.} \end{equation*}
  • If \(\theta\) is close to \(90^\circ\text{,}\) the two vectors are close to pointing at right angles. Since \(\cos(90^\circ) = 0\text{,}\) this occurs precisely when
    \begin{equation*} \frac{\mathbf{v} \cdot \mathbf{w}}{\| \mathbf{v} \| \| \mathbf{w} \|} \approx 0\text{.} \end{equation*}
    When \(\mathbf{v} \cdot \mathbf{w} = 0\text{,}\) so that \(\theta = 90^\circ\text{,}\) we say the two vectors are perpendicular, or orthogonal.
The cosine similarity between the nonzero vectors \(\mathbf{v}\) and \(\mathbf{w}\) is denoted by
\begin{equation*} \operatorname{cosim}(\mathbf{v},\mathbf{w}) = \frac{\mathbf{v} \cdot \mathbf{w}}{\| \mathbf{v} \| \| \mathbf{w} \|}. \end{equation*}
It ranges between \(-1\) and \(1\text{,}\) and measures the degree to which the two vectors point in the same, or opposite, directions. This terminology is especially common in certain areas of data science.

Warning 1.1.17.

Cosine similarity is undefined if either vector is the zero vector.

Activity 1.1.18. Computing cosine similarity (U1-LO1).

Calculate the cosine similarity between the two vectors \(\mathbf{v} = (1,2)\) and \(\mathbf{w} = (\sqrt{3} + 2, 2\sqrt{3} - 1)\text{.}\)
Solution.
We begin by calculating the lengths of the two vectors, i.e
\begin{equation*} \| \mathbf{v} \| = \sqrt{ (1)^2 + (2)^2 } = \sqrt{5} \end{equation*}
and
\begin{align*} \| \mathbf{w} \| \amp = \sqrt{ (\sqrt{3} + 2)^2 + (2\sqrt{3} - 1)^2 }\\ \amp = \sqrt{ (3 + 4 \sqrt{3} + 4) + (12 - 4 \sqrt{3} + 1) }\\ \amp = \sqrt{20}\text{.} \end{align*}
Next, we calculate the dot product
\begin{align*} \mathbf{v} \cdot \mathbf{w} \amp = (1)(\sqrt{3} + 2) + (2)(2\sqrt{3} - 1)\\ \amp = \sqrt{3} + 2 + 4\sqrt{3} - 2\\ \amp = 5 \sqrt{3}\text{.} \end{align*}
Therefore, the cosine similarity between the two vectors is
\begin{align*} \frac{\mathbf{v} \cdot \mathbf{w}}{\| \mathbf{v} \| \| \mathbf{w} \|} \amp = \frac{5 \sqrt{3}}{\sqrt{5} \sqrt{20}}\\ \amp = \sqrt{3}/2\text{.} \end{align*}
The two vectors from ActivityΒ 1.1.18.
A dashed coordinate grid is shown with \(x\)- and \(y\)-axes. A blue arrow from the origin ends at \((1,2)\text{,}\) while a longer red arrow from the origin ends at \((\sqrt{3}+2, 2\sqrt{3}-1)\text{.}\) The two arrows represent the vectors used in the cosine-similarity activity.
Figure 1.1.19. The vectors \(\mathbf{v}\) and \(\mathbf{w}\) from ActivityΒ 1.1.18, drawn as arrows from the origin.

Activity 1.1.20. Finding the angle between vectors (U1-LO1).

Calculate the angle between the two vectors
\begin{equation*} \mathbf{v} = \begin{bmatrix} 2 \\ 3 \\ 0 \\ 2 \end{bmatrix} \quad\text{and}\quad \mathbf{w} = \begin{bmatrix} 1 \\ 0 \\ 1 \\ -1 \end{bmatrix}\text{.} \end{equation*}
Solution.
We calculate that
\begin{align*} \mathbf{v} \cdot \mathbf{w} \amp= (2)(1) + (3)(0) + (0)(1) + (2)(-1)\\ \amp= 2 + 0 + 0 - 2 = 0\text{.} \end{align*}
Thus if \(\theta\) is the angle between the two vectors, then
\begin{equation*} \cos(\theta) = \frac{\mathbf{v} \cdot \mathbf{w}}{\| \mathbf{v} \| \| \mathbf{w} \|} = \frac{0}{\| \mathbf{v} \| \| \mathbf{w} \|} = 0\text{.} \end{equation*}
Thus
\begin{equation*} \theta = \cos^{-1}(0) = 90^\circ\text{.} \end{equation*}

Note 1.1.21.

Note that \(\| \mathbf{v} \|^2 = \mathbf{v} \cdot \mathbf{v}\) for any \(\mathbf{v} \in \R^n\text{.}\)
We will study the dot product in far more detail in UnitΒ 4 and UnitΒ 7.

Definition 1.1.22. Distance between vectors.

The Euclidean distance between two vectors \(\mathbf{u},\mathbf{v} \in \R^n\) is
\begin{equation*} \operatorname{dist}(\mathbf{u},\mathbf{v}) = \| \mathbf{u} - \mathbf{v} \|. \end{equation*}
As illustrated in FigureΒ 1.1.14, \(\mathbf{u}-\mathbf{v}\) points from the tip of \(\mathbf{v}\) to the tip of \(\mathbf{u}\) when the two vectors start at the same point. Its Euclidean norm therefore measures how far apart those endpoints are. For the vectors in ExampleΒ 1.1.13,
\begin{equation*} \operatorname{dist}(\mathbf{u},\mathbf{v})=\|(3,-2)\|=\sqrt{3^2+(-2)^2}=\sqrt{13}. \end{equation*}
In contrast, cosine similarity compares direction after normalization.

Subsection Applications of vectors

Vectors can represent quantities other than displacements. The entries of a vector can record measurements, counts, samples, or features. The meaning of a vector depends on what its coordinates represent.
Table 1.1.23. Some vector representations
Object Meaning of the entries
Color red, green, and blue intensities
Time series measurements at successive times
Portfolio amounts held in each asset
Image pixel intensities, listed in a fixed order
Document counts of selected words
Customer purchases of selected products
Object with features measured attributes such as size, price, weight, or rating
The same vector operations can have different interpretations. A sum can add purchases, add word counts, or add two time series. A scalar multiple can rescale an image, double a portfolio, or change units. A dot product can produce a score. A distance can compare two feature vectors. Cosine similarity compares direction after normalization.

Activity 1.1.24. Word-count vectors (U1-LO1, U1-LO2).

Use the dictionary linear, matrix, data. A document vector records the number of times these words appear, in this order. The query
\begin{equation*} \mathbf{q}=\begin{bmatrix}1\\0\\1\end{bmatrix} \end{equation*}
represents the phrase β€œlinear data”. Consider three document vectors
\begin{equation*} \mathbf{D}_1=\begin{bmatrix}3\\0\\3\end{bmatrix},\qquad \mathbf{D}_2=\begin{bmatrix}1\\1\\0\end{bmatrix},\qquad \mathbf{D}_3=\begin{bmatrix}0\\2\\0\end{bmatrix}. \end{equation*}
Compute the cosine similarities and Euclidean distances between \(\mathbf{q}\) and each \(\mathbf{D}_i\text{.}\) Rank the documents from most to least similar by cosine similarity and from closest to farthest by Euclidean distance.
Solution.
First,
\begin{align*} \operatorname{cosim}(\mathbf{q},\mathbf{D}_1) \amp= \frac{\mathbf{q}\cdot\mathbf{D}_1}{\|\mathbf{q}\|\|\mathbf{D}_1\|}\\ \amp= \frac{6}{\sqrt{2}\sqrt{18}}\\ \amp= 1. \end{align*}
Next,
\begin{align*} \operatorname{cosim}(\mathbf{q},\mathbf{D}_2) \amp= \frac{\mathbf{q}\cdot\mathbf{D}_2}{\|\mathbf{q}\|\|\mathbf{D}_2\|}\\ \amp= \frac{1}{\sqrt{2}\sqrt{2}}\\ \amp= \frac12. \end{align*}
Finally, \(\operatorname{cosim}(\mathbf{q},\mathbf{D}_3)=0\text{.}\)
The vector \(\mathbf{D}_1\) points in exactly the same direction as \(\mathbf{q}\) because \(\mathbf{D}_1=3\mathbf{q}\text{.}\) The vector \(\mathbf{D}_2\) shares the word β€œlinear” with the query but also contains β€œmatrix”. The vector \(\mathbf{D}_3\) contains only β€œmatrix”, so it is orthogonal to the query.
So the ranking by cosine similarity is
\begin{equation*} \mathbf{D}_1,\ \mathbf{D}_2,\ \mathbf{D}_3. \end{equation*}
For the Euclidean distances,
\begin{align*} \operatorname{dist}(\mathbf{q},\mathbf{D}_1) \amp= \|\mathbf{q}-\mathbf{D}_1\|\\ \amp= \left\|\begin{bmatrix}1\\0\\1\end{bmatrix}-\begin{bmatrix}3\\0\\3\end{bmatrix}\right\|\\ \amp= \left\|\begin{bmatrix}-2\\0\\-2\end{bmatrix}\right\|=\sqrt{8}=2\sqrt{2},\\ \operatorname{dist}(\mathbf{q},\mathbf{D}_2) \amp= \|\mathbf{q}-\mathbf{D}_2\|\\ \amp= \left\|\begin{bmatrix}1\\0\\1\end{bmatrix}-\begin{bmatrix}1\\1\\0\end{bmatrix}\right\|\\ \amp= \left\|\begin{bmatrix}0\\-1\\1\end{bmatrix}\right\|=\sqrt{2},\\ \operatorname{dist}(\mathbf{q},\mathbf{D}_3) \amp= \|\mathbf{q}-\mathbf{D}_3\|\\ \amp= \left\|\begin{bmatrix}1\\0\\1\end{bmatrix}-\begin{bmatrix}0\\2\\0\end{bmatrix}\right\|\\ \amp= \left\|\begin{bmatrix}1\\-2\\1\end{bmatrix}\right\|=\sqrt{6}. \end{align*}
Since \(\sqrt{2}\lt\sqrt{6}\lt2\sqrt{2}\text{,}\) the ranking from smallest to largest Euclidean distance is
\begin{equation*} \mathbf{D}_2,\ \mathbf{D}_3,\ \mathbf{D}_1. \end{equation*}
In the previous activity, \(\mathbf{D}_1\) is most similar to the query by cosine similarity but farthest from it by Euclidean distance; \(\mathbf{D}_2\) is closest by Euclidean distance. The two measures select different documents because cosine similarity compares direction after normalization, while Euclidean distance also depends on vector length.

Activity 1.1.25. The same rankings in code (U1-LO2, U1-LO8).

The following code repeats the cosine-similarity and Euclidean-distance rankings from ActivityΒ 1.1.24. We compute the cosine similarities between the query and each document, then the Euclidean distances by taking the norm of each difference.
import numpy as np

D1 = np.array([3., 0., 3.])
D2 = np.array([1., 1., 0.])
D3 = np.array([0., 2., 0.])
q = np.array([1., 0., 1.])

score1 = (D1 @ q) / (np.linalg.norm(D1) * np.linalg.norm(q))
score2 = (D2 @ q) / (np.linalg.norm(D2) * np.linalg.norm(q))
score3 = (D3 @ q) / (np.linalg.norm(D3) * np.linalg.norm(q))

distance1 = np.linalg.norm(D1 - q)
distance2 = np.linalg.norm(D2 - q)
distance3 = np.linalg.norm(D3 - q)

(score1, score2, score3), (distance1, distance2, distance3)
Output (approximately):
((1.0, 0.5, 0.0),
 (2.8284271247461903, 1.4142135623730951, 2.449489742783178))
The first tuple gives the cosine similarities and the second gives the Euclidean distances, each in the order \(\mathbf{D}_1\text{,}\) \(\mathbf{D}_2\text{,}\) \(\mathbf{D}_3\) relative to \(\mathbf{q}\text{.}\) Smaller distances mean closer documents.
  1. Which score corresponds to \(\mathbf{D}_2\text{?}\)
  2. Where does the code compute \(\mathbf{D}_1\cdot\mathbf{q}\text{?}\)
  3. Which document is most similar to the query by cosine similarity?
  4. Which line computes \(\|\mathbf{D}_2-\mathbf{q}\|\text{?}\)
  5. Rank the documents from closest to farthest from the query by Euclidean distance. How does this ranking compare with the cosine-similarity ranking?
Solution.
The score for \(\mathbf{D}_2\) is score2. The expression D1 @ q computes \(\mathbf{D}_1\cdot\mathbf{q}\text{.}\) Since score1 is largest, \(\mathbf{D}_1\) is most similar to the query.
The line distance2 = np.linalg.norm(D2 - q) computes \(\|\mathbf{D}_2-\mathbf{q}\|\text{.}\) The distances are \(2\sqrt{2}\text{,}\) \(\sqrt{2}\text{,}\) and \(\sqrt{6}\text{,}\) respectively, so the ranking from closest to farthest is \(\mathbf{D}_2\text{,}\) then \(\mathbf{D}_3\text{,}\) then \(\mathbf{D}_1\text{.}\) By cosine similarity, the ranking is \(\mathbf{D}_1\text{,}\) then \(\mathbf{D}_2\text{,}\) then \(\mathbf{D}_3\text{.}\) Thus, \(\mathbf{D}_1\) is first by cosine similarity, while \(\mathbf{D}_2\) is first by Euclidean distance.

Example 1.1.26. Neural networks and transformers.

A neural network is a function built from layers. A layer takes numbers as input, combines them using weights, applies a rule, and sends output numbers to the next layer. In many neural networks, the input and output of a layer are vectors. The weights are adjusted from data during training.
A transformer is a neural-network architecture for sequences. In a language model, text is first broken into tokens. A token can be a word, part of a word, punctuation mark, or other text fragment. Each token position carries a vector.
A transformer layer produces a new vector at each token position. The token itself does not change; its vector becomes context-dependent. In the phrase β€œsmall red bird”, the new vector at the bird position can gather information from β€œsmall” and β€œred”. In a next-token model, the vector at this final position can then help predict what comes next.
For one output position, its query is used to decide which positions are relevant. Each token has a key used in that comparison and a value containing the information it can contribute. Queries and keys determine the weights; values are what get averaged. Every position has all three roles, but the next activity computes only the attention output at the bird position.
A neural network diagram with input, hidden, and output layers.
Three red input nodes are arranged vertically on the left, four blue hidden-layer nodes appear in the center, and two green output nodes appear on the right. Black arrows connect each input node to the hidden layer, and gray arrows connect the hidden layer to the outputs, showing information moving left to right through the network.
Figure 1.1.27. A neural network diagram with input, hidden, and output layers. Source: Wikipedia, Neural network (machine learning), using Colored neural network.svg by Glosser.ca, derivative of Artificial neural network.svg, licensed under CC BY-SA 3.0.
A transformer processes a sequence of token vectors.
The diagram has two vertical stacks: an encoder stack for a source sequence on the left and a decoder stack for a target sequence on the right. Each stack shows embeddings and positional encoding feeding into attention and feed-forward blocks, with arrows indicating repeated layers. The decoder also points upward to a final linear and softmax prediction step.
Figure 1.1.28. A transformer processes a sequence of token vectors. The activities below focus on the vector operations visible in the diagram: token embeddings, dot-product scores, weighted averages, and affine layers. Source: Wikipedia, Transformer (deep learning architecture), using Transformer, full architecture.png by dvgodoy, licensed under CC BY 4.0.

Activity 1.1.29. Gathering context for the bird position (U1-LO1, U1-LO8).

Consider the token sequence
\begin{equation*} \text{small}, \qquad \text{red}, \qquad \text{bird}. \end{equation*}
We compute the attention output at the position occupied by β€œbird”. The bird position is the destination; β€œsmall”, β€œred”, and β€œbird” itself are possible sources of information.
The query \(\mathbf{q}_{\text{bird}}\) is compared with each key \(\mathbf{k}_i\) to produce a relevance score. The scores are converted into weights, and those weights are used to average the value vectors:
\begin{align*} \text{query--key scores} &\longrightarrow \text{weights}\\ &\longrightarrow \text{weighted average of values}. \end{align*}
For this activity, the score for token \(i\) is
\begin{equation*} \operatorname{score}_i=\mathbf{q}_{\text{bird}}\cdot \mathbf{k}_i. \end{equation*}
Use
\begin{equation*} \mathbf{q}_{\text{bird}}=\begin{bmatrix}1\\1\end{bmatrix},\qquad \mathbf{k}_{\text{small}}=\begin{bmatrix}1\\0\end{bmatrix},\qquad \mathbf{k}_{\text{red}}=\begin{bmatrix}0\\1\end{bmatrix},\qquad \mathbf{k}_{\text{bird}}=\begin{bmatrix}1\\1\end{bmatrix}. \end{equation*}
  1. Compute the three scores
    \begin{equation*} \mathbf{q}_{\text{bird}}\cdot \mathbf{k}_{\text{small}},\qquad \mathbf{q}_{\text{bird}}\cdot \mathbf{k}_{\text{red}},\qquad \mathbf{q}_{\text{bird}}\cdot \mathbf{k}_{\text{bird}}. \end{equation*}
  2. Normalize the positive scores by dividing each score by the sum of all three scores. Call the resulting weights
    \begin{equation*} \boldsymbol{\alpha}= \begin{bmatrix} \alpha_{\text{small}}\\ \alpha_{\text{red}}\\ \alpha_{\text{bird}} \end{bmatrix}. \end{equation*}
  3. The coordinates of the value vectors are abstract toy features. Use
    \begin{equation*} \mathbf{v}_{\text{small}}=\begin{bmatrix}4\\0\end{bmatrix},\qquad \mathbf{v}_{\text{red}}=\begin{bmatrix}0\\4\end{bmatrix},\qquad \mathbf{v}_{\text{bird}}=\begin{bmatrix}4\\4\end{bmatrix} \end{equation*}
    to compute
    \begin{equation*} \mathbf{h}_{\text{bird}} = \alpha_{\text{small}}\mathbf{v}_{\text{small}} + \alpha_{\text{red}}\mathbf{v}_{\text{red}} + \alpha_{\text{bird}}\mathbf{v}_{\text{bird}}. \end{equation*}
  4. Which token receives the largest weight? What total weight is assigned to β€œsmall” and β€œred” together? What does this say about the information gathered at the bird position?
Solution.
The scores are
\begin{align*} \mathbf{q}_{\text{bird}}\cdot \mathbf{k}_{\text{small}} \amp= 1,\\ \mathbf{q}_{\text{bird}}\cdot \mathbf{k}_{\text{red}} \amp= 1,\\ \mathbf{q}_{\text{bird}}\cdot \mathbf{k}_{\text{bird}} \amp= 2. \end{align*}
The sum of the scores is
\begin{equation*} 1+1+2=4. \end{equation*}
Thus
\begin{equation*} \boldsymbol{\alpha} = \begin{bmatrix} 1/4\\ 1/4\\ 1/2 \end{bmatrix}. \end{equation*}
The attention output at the bird position is the weighted average
\begin{equation*} \mathbf{h}_{\text{bird}} = \frac14 \begin{bmatrix}4\\0\end{bmatrix} + \frac14 \begin{bmatrix}0\\4\end{bmatrix} + \frac12 \begin{bmatrix}4\\4\end{bmatrix} = \begin{bmatrix}3\\3\end{bmatrix}. \end{equation*}
The token β€œbird” receives the largest weight because its key vector has the largest dot product with \(\mathbf{q}_{\text{bird}}\text{.}\) The bird position assigns weight \(1/2\) to β€œbird” itself and total weight \(1/2\) to β€œsmall” and β€œred”. Thus the attention output combines information from the token itself with information from its context. Including the destination among the possible sources helps retain information about the token at that position. The coordinates of \(\mathbf{h}_{\text{bird}}\) remain abstract toy features; the important interpretation is how the weights distribute across the three source positions. A full transformer layer combines this attention output with the current vector at the bird position and processes it further.
Attention at the bird position combines value vectors from small, red, and bird.
The bird position is shown as the destination, with query \(\mathbf{q}_{\text{bird}}\text{.}\) Arrows compare that query with the keys for the three possible source positions β€œsmall”, β€œred”, and β€œbird”, producing scores \(1\text{,}\) \(1\text{,}\) and \(2\text{.}\) The corresponding value vectors flow into a weighted average with weights \(1/4\text{,}\) \(1/4\text{,}\) and \(1/2\text{,}\) producing the attention output \(\mathbf{h}_{\text{bird}}=[3,3]^T\text{.}\) A final row shows the current bird-position vector and the attention output being combined and processed further to form the next bird-position vector. Only one destination is shown; a full transformer layer performs the analogous calculation at every token position.
Figure 1.1.30. Attention at one destination position. The bird query produces scores \(1,1,2\) and weights \(1/4,1/4,1/2\) for the value vectors at β€œsmall”, β€œred”, and β€œbird”. Their weighted average is the attention output at the bird position. A full transformer layer performs an analogous calculation at every token position and processes each attention output further.

Warning 1.1.31.

This activity isolates one part of a transformer layer. It uses normalization by the sum of positive scores to keep the arithmetic simple. Real transformer attention usually uses a different rule to convert scores into weights, but it follows the same pattern:
\begin{equation*} \text{scores} \quad \longrightarrow \quad \text{weights} \quad \longrightarrow \quad \text{weighted average of values}. \end{equation*}
A full layer then combines the attention output with the current token representation and processes the result further.