Module 2, topic 13, week 7, Tuesday
Linear Algebra: vectors and vector operations
Why linear algebra matters in this course, then vectors from the beginning: adding and scaling, length and distance, the dot product, angles and projection. Worked by hand.
Introduction: the first lesson of Module 2
The first lesson of Module 2. This module is a mathematics course: the work is done with a pencil, on paper, and the goal is to understand the ideas and to calculate with confidence. This guide first explains why linear algebra matters in this course and where you will meet it again. Then it teaches vectors from the very beginning: what a vector is, how to add vectors and multiply them by a number, how to measure their length and the distance between them, and the most used operation of all, the dot product, with its meaning as an angle. Every idea comes as a definition, a picture and worked examples calculated by hand. Then it walks through 20 solved problems from the easiest to the hardest, each with the reasoning written out. At the end there are 34 practice problems with a hint and a full solution for each.
You need no mathematics beyond school arithmetic, simple equations, the theorem of Pythagoras and square roots. A calculator is enough for the square roots and the angles. Python appears only once, in a short part near the end that shows how to check your results.
What you will learn
- 1.Why linear algebra is the language of data science and machine learning, and where it appears in this course
- 2.What a vector is: a list of numbers, an arrow, a point, a row of data
- 3.Adding and subtracting vectors, and what the result means
- 4.Multiplying a vector by a number, parallel vectors, midpoints and linear combinations
- 5.The length of a vector, unit vectors, the distance between two points and the triangle inequality
- 6.The dot product: how to calculate it, its rules and what it measures
- 7.The angle between two vectors, perpendicular vectors, the Cauchy-Schwarz inequality, cosine similarity and projection
- 8.Where these calculations are used: a prediction, a similarity search and a nearest neighbour
| Written | Meaning |
|---|---|
| a vector with the components 3 and 4; vectors are printed in bold | |
| , | the first and the second component of |
| the zero vector | |
| the length of | |
| the dot product of and | |
| an angle (the Greek letter theta) | |
| the vector from the point to the point | |
| ordinary multiplication of two numbers; the dot is kept for the dot product |
1Why linear algebra?
1.1Data is made of vectors
Look at one row of a table:
| name | age | years | salary | score |
|---|---|---|---|---|
| Konul | 29 | 4 | 1710 | 3.8 |
Take away the name, and the employee is a list of four numbers: . Such an ordered list of numbers is called a vector. The whole table is a stack of vectors, one for every row.
This is not special to tables. Almost everything a computer learns from is turned into vectors first:
| The thing | As a vector |
|---|---|
| A customer | (age, orders, money spent, ...) |
| A photo of 28 by 28 pixels | 784 numbers, the brightness of every pixel |
| A sentence | the count of every word, or a list of a few hundred numbers called an embedding |
| A song | (tempo, loudness, energy, ...) |
| A point on a map | (latitude, longitude) |
Linear algebra is the mathematics of vectors: how to add them, scale them, measure them and compare them. A model that learns from data does these operations millions of times. So linear algebra is not one more topic next to machine learning. It is the language machine learning is written in.
1.2Where you will meet it again in this course
| Later in the course | The vector idea behind it |
|---|---|
| Linear and logistic regression | a prediction is a dot product: weights times features, plus a number |
| k-Nearest Neighbors, k-means clustering | "similar" means a small distance between two vectors |
| Feature scaling | changing the size of the features so that no feature dominates the distance |
| Support Vector Machines | the side of a line a point lies on is the sign of a dot product |
| Principal Component Analysis (PCA) | projecting data onto the most useful directions |
| Images and convolutional networks | an image is a vector of pixels; a filter is a dot product moved over the image |
| Word embeddings | words as vectors; similar words point in similar directions (cosine similarity) |
| Neural networks | every neuron calculates a dot product of its inputs and its weights |
| RAG and vector databases | finding the texts whose vectors are closest to the vector of the question |
Three operations carry almost all of this: addition, multiplication by a number and the dot product. They are the subject of this lesson. The next two lessons build on them: matrices (many vectors at once), then eigenvectors and norms.
1.3Why by hand?
A library can calculate a dot product in one line, and you already know the line. But a library cannot tell you what the number means, whether it is plausible, or which operation a problem needs. That understanding comes from doing the calculations yourself with small numbers. In this module every example is worked out by hand. Read with a pencil: cover the solution, calculate, then compare.
2What is a vector?
2.1Scalars and vectors
A scalar is one single number: , , . A temperature, a price, an age.
A vector is an ordered list of numbers:
- The numbers are the components of the vector. The first component of is , the second is .
- The number of components is the dimension of the vector. is a 2-dimensional vector, is 3-dimensional, is 4-dimensional.
- The order matters: and are different vectors.
- Two vectors are equal only when they have the same dimension and every component is equal.
In this lesson a vector is printed in bold, , as in most books. On paper nobody can write bold, so by hand a vector gets an arrow above the letter, . A vector can be written in a row, , or in a column. For this lesson the two mean the same; the difference matters in the next lesson, with matrices.
Example. For which and is ?
One vector equation is as many ordinary equations as the vector has components.
2.2A vector as an arrow
A 2-dimensional vector can be drawn. The vector is the arrow that goes 3 steps to the right and 4 steps up.
An arrow has two properties: a direction and a length. That is the physical idea of a vector: a quantity with a size and a direction, such as a velocity (60 km/h to the north) or a force. A scalar has only a size.
A negative component goes the other way: goes 2 steps to the left and 1 up.
2.3Where the arrow starts does not matter
A vector says how far to go and in which direction, not where to start. All three arrows below are the same vector : each goes 2 to the right and 1 up.
Usually we draw a vector from the origin . Then its tip is at the point with the same coordinates, so a vector can also be seen as a point. Both pictures are used: arrows when we add and scale, points when the vectors are data (a cloud of customers, each a point).
2.4The vector from one point to another
The vector that leads from the point to the point is written . Its components are the coordinates of the end minus the coordinates of the start:
For and :
"End minus start" is worth learning by heart. The opposite vector leads back.
2.5Vectors in more dimensions
A vector with 3 components is an arrow in space. A vector with 4, 100 or 784 components cannot be drawn, but nothing else changes: every rule of this lesson works in the same way for any number of components. The pictures in 2 dimensions build the intuition; the formulas do the work in 784 dimensions.
2.6Special vectors
- The zero vector has only zeros: , . It is written . It has no length and no direction.
- The standard unit vectors have one 1 and zeros elsewhere. In 2 dimensions: (one step to the right) and (one step up). In 3 dimensions there are three: , , .
Try it yourself
Show a hint
Show the solution
Answer: and .
The two vectors are opposite: the same arrow, walked in the other direction.
3Adding and subtracting vectors
3.1Addition
Two vectors of the same dimension are added component by component:
Example 1.
Example 2. With three components and negative numbers:
Example 3. Three vectors are added in the same way, all first components together, all second components together:
3.2What addition means
Walk along , then walk along . The sum is the arrow from where you started to where you ended. This is the tip-to-tail rule: put the tail of at the tip of .
The order does not matter. Walking first and then ends at the same point: the two paths are the sides of a parallelogram, and the sum is its diagonal. This is the parallelogram rule.
In data terms: if is what a shop sold of three products on Monday and what it sold on Tuesday, then is what it sold on both days.
3.3Subtraction
Example.
is the vector you must add to to arrive at . Drawn from the origin, and are two points, and is the arrow from the tip of to the tip of . It is the rule "end minus start" again.
This picture is worth remembering: the difference of two vectors is the arrow between them. Its length is the distance between the two points (Part 5), and that is how a computer decides that two customers are similar.
is the same arrow in the opposite direction.
Move the sliders: the blue arrow is the result.
a + b = (2 + 1, 1 + 3) = (3, 4)
b starts where a ends. The blue arrow goes from the start of a to the end of b.
3.4The rules of addition
For all vectors of the same dimension:
| Rule | In symbols | Name |
|---|---|---|
| The order does not matter | commutative | |
| Grouping does not matter | associative | |
| Adding the zero vector changes nothing | zero vector | |
| Every vector has an opposite | opposite vector |
Why are they true? Because the work is done with ordinary numbers, component by component, and ordinary numbers obey these rules. For example and , and .
Because of these rules, vector equations are solved like ordinary ones.
Example. Find with .
3.5Only the same dimension
has no meaning: the second vector has a component without a partner. Before any operation with two vectors, check that they have the same number of components.
Try it yourself
Show a hint
Show the solution
Answer: and .
4Multiplying a vector by a number
4.1Scalar multiplication
A vector is multiplied by a number (a scalar) by multiplying every component:
Examples.
We write for "2 times ", and for .
4.2What it means
The number scales the arrow, which is where the word scalar comes from:
- a number greater than 1 stretches the arrow,
- a number between 0 and 1 shrinks it,
- a negative number turns it around,
- the line the arrow lies on never changes.
Choose the number c and watch the vector c a.
1.5 a = (1.5 × 2, 1.5 × 1) = (3, 1.5)
The direction stays the same, and the arrow is 1.5 times as long.
4.3Parallel vectors
Two vectors are parallel when one is a multiple of the other: for some number . They lie on the same line through the origin.
To test two vectors, divide their components in pairs. The same number every time means parallel.
| The vectors | The ratios | Result |
|---|---|---|
| and | and | parallel: |
| and | and | not parallel |
| and | every ratio is | parallel, opposite directions |
Three points on one line. The points , and lie on one straight line exactly when the vectors and are parallel.
4.4The rules of scalar multiplication
| Rule | In symbols |
|---|---|
| A number goes into a sum of vectors | |
| A sum of numbers can be split | |
| Two numbers can be multiplied first | |
| Multiplying by 1 changes nothing |
Example. Simplify .
Vectors are handled like letters in ordinary algebra, as long as you only add them and multiply them by numbers.
4.5The midpoint and other points of a segment
The point halfway between two points and is their average:
For and :
More generally, start at and go a part of the way to :
Example. One third of the way from to :
With you are at , with at , with at the midpoint.
4.6Linear combinations
Scaling and adding together give the most important construction of linear algebra. A linear combination of the vectors and is
for any two numbers and : scale each vector, then add.
Example. With and :
A linear combination is a recipe: "two steps of and one step of ". The word linear in linear algebra comes from here: only these two operations are allowed, scaling and adding.
Every vector is a linear combination of the standard unit vectors, with its own components as the numbers:
The opposite question. Given a vector, find the recipe. Write as a linear combination of and .
Each component gives one equation:
Adding the two equations removes : , so , and then .
One vector equation in 2 dimensions became two ordinary equations with two unknowns. Solving such systems for many unknowns at once is what matrices are for, in the next lesson.
Try it yourself
Show a hint
Show the solution
Answer: .
5Length and distance
5.1The length of a vector
The vector is the long side of a right-angled triangle with the sides 3 and 4. By the theorem of Pythagoras its length is
The same works in any dimension. The length (also called the magnitude or the norm) of a vector is written ; many books write .
Square every component, add, take the square root.
Examples.
A negative component causes no trouble, because it is squared. When the number under the root is not a perfect square, leave the root () or give a decimal ().
5.2Facts about the length
- A length is never negative, and only the zero vector has the length 0.
- Scaling a vector scales its length by the size of the number: . Here is the absolute value of the number. Example: has the length , and has the length 10 as well.
- The triangle inequality: . The straight road is never longer than a detour.
Example for the triangle inequality. and :
The two sides are equal only when and point in the same direction. So remember: the length of a sum is not the sum of the lengths.
This length is the usual, straight-line one. There are other ways to measure the size of a vector (other norms); they come in Topic 15.
5.3Unit vectors
A unit vector has the length 1. It carries a direction and nothing else. Every vector except the zero vector can be turned into the unit vector of the same direction by dividing it by its length. This is called normalizing:
For , with :
Why does it always work? By fact 2 above, dividing by divides the length by , and a number divided by itself is 1.
A vector of a given length. To get a vector of the length 10 in the direction of , first normalize, then multiply by 10:
5.4The distance between two points
See two vectors as two points. The distance between them is the length of the arrow from one to the other, and that arrow is their difference:
Examples.
It is called the Euclidean distance. Three facts:
- The distance from to equals the distance from to , because the squares remove the signs.
- The distance is 0 only when the two points are the same.
- Going through a third point is never shorter: . This is the triangle inequality again.
This one formula is behind every method that works with "similar" data points: two customers are similar when the distance between their vectors is small.
Try it yourself
Show a hint
Show the solution
Answer: and the unit vector is .
Check: . The unit vector keeps the signs of , so it points in the same direction.
6The dot product
6.1The definition
There is a way to multiply two vectors that gives one number. Multiply the components in pairs and add the products:
It is called the dot product (also the scalar product or the inner product). Two things to notice: both vectors must have the same dimension, and the result is a scalar, not a vector.
Examples.
A good habit: write every product first, then add. Most mistakes are lost minus signs.
6.2The dot product is a weighted sum
Most uses of the dot product read like this: one vector holds amounts, the other holds what each amount is worth.
A shopping bill. You buy 4 notebooks, 10 pens and 2 books. They cost 2.5, 1.2 and 4.0.
A final grade. Homework counts 20%, the midterm 30% and the final exam 50%. A student got 80, 70 and 90.
Work in physics. A force moves an object along . The work done is : only the part of the force along the movement counts.
Every time you "multiply pairs and add them up", you are calculating a dot product.
6.3The rules of the dot product
| Rule | In symbols |
|---|---|
| The order does not matter | |
| It goes into a sum | |
| A number can be taken out | |
| A vector with itself gives its length squared | |
| With the zero vector it is 0 |
Each rule follows from the definition. The fourth one: , and that is exactly what stands under the root in the length. So
Example: .
Checking a rule with numbers. , , :
What does not exist. There is no dot product of three vectors: is a number, and a number cannot be "dotted" with . And you cannot divide by a vector.
6.4The square of a sum
With these rules the dot product behaves like ordinary multiplication:
It is the formula for vectors, and it will be used in the next part.
Try it yourself
Show a hint
Show the solution
Answer: 3 and 0.
The second dot product is 0. The next part shows what that means: the two vectors are perpendicular.
7What the dot product measures: angles
7.1The geometric formula
The dot product has a second formula, and it is the reason the dot product is so useful:
where is the angle between the two vectors (between and ). So the dot product knows three things at once: the two lengths and the angle.
Where it comes from. The vectors , and form a triangle. The law of cosines from school says
The square-of-a-sum formula of Part 6, with a minus, says
Compare the two lines: .
7.2Calculating an angle
Turn the formula around:
Example 1. and .
Example 2. and .
The last step uses the inverse cosine of a calculator (the key or arccos). Some angles are worth knowing:
7.3The sign of the dot product
Lengths are never negative, so the sign of the dot product is the sign of the cosine, and that says in which way the two vectors point:
| Dot product | The angle | The vectors |
|---|---|---|
| positive | less than (acute) | point in a similar direction |
| zero | exactly (right) | are perpendicular |
| negative | more than (obtuse) | point in opposite directions |
a · b = 5
less than 90°
a · b = 0
exactly 90°
a · b = -5
more than 90°
In all three pictures . With the dot product is 5, with it is , and with it is . Often the sign is all you need, and it costs no square root.
Move the sliders and watch the dot product, the angle and the shadow of a on b.
a · b = 2 × 4 + 3 × 2 = 14
|a| = 3.61, |b| = 4.47, cos θ = 14 / (3.61 × 4.47) = 0.87, θ = 29.7°
The projection of a onto b (blue): (2.8, 1.4)
The dot product is positive: the angle is less than 90°, and the vectors point in a similar direction.
7.4Perpendicular vectors
Two vectors are perpendicular (the word in linear algebra is orthogonal) when the angle between them is . Because :
This is the fastest test there is. , so the two are orthogonal. The standard unit vectors are orthogonal to each other: .
A useful trick in 2 dimensions. A vector perpendicular to is : swap the components and change one sign. Check: .
Pythagoras for vectors. When and are orthogonal, the middle term of the square of a sum disappears: . The theorem of Pythagoras is a special case of the dot product.
In data, orthogonal vectors have "nothing in common": two texts that share no word have count vectors with the dot product 0.
7.5The Cauchy-Schwarz inequality
A cosine is always between and . Put this into :
The dot product of two vectors is never larger in size than the product of their lengths. This is the Cauchy-Schwarz inequality, one of the most used facts of mathematics. The two sides are equal exactly when the vectors are parallel.
Example. , : , and . Indeed .
It is also a check for your own work: if you ever calculate a cosine larger than 1, there is a mistake in the dot product or in a length.
7.6Cosine similarity
The cosine of the angle is used so often to compare two vectors that it has its own name, the cosine similarity:
By Cauchy-Schwarz it is always between and :
- : the same direction,
- : perpendicular, nothing in common,
- : exactly opposite directions.
It looks only at the direction and ignores the lengths. Multiplying a vector by a positive number does not change its cosine similarity with any other vector. A short text and a long text about the same subject have count vectors of very different length but nearly the same direction, so their cosine similarity is close to 1. That is why search engines, recommendation systems, word embeddings and RAG all use it.
Example. Three users rated four films from 0 to 5: Aylin , Murad , Leyla . Call their vectors , and .
That was Aylin and Murad. Now Aylin and Leyla:
Aylin and Murad like the same films. Aylin and Leyla have a very different taste.
7.7Projection: how much of one vector lies along another
The last idea of this part answers the question: how far does go in the direction of ? Imagine a light shining straight down onto the line of . The shadow of on that line is the projection of onto .
Two formulas. The scalar projection is the length of the shadow:
The vector projection is the shadow as a vector:
Where they come from. In the right-angled triangle of the picture, the shadow has the length . Since , this is . To make a vector of this length along , multiply by the unit vector ; the two lengths in the denominator give .
Example. and :
Check the rest against : . The check shows the picture in numbers: what is left of after taking away the shadow is perpendicular to . So every vector can be split into a part along and a part perpendicular to :
When is a unit vector, the scalar projection is simply : the dot product with a unit vector measures how far a vector goes in that direction. PCA, later in the course, is built on this sentence.
A negative scalar projection means that the shadow falls on the other side: goes against the direction of .
Try it yourself
Show a hint
Show the solution
Answer: .
The picture agrees: points straight up, and is the diagonal, halfway between up and right.
8Where these calculations are used
Three small examples of methods you will learn later. Each is one operation of this lesson, calculated by hand.
8.1A prediction is a dot product
A model that predicts the price of a flat from three features has learned one weight for every feature and one extra number, the bias:
| Feature | Value () | Weight () |
|---|---|---|
| area in m² | 80 | 1200 |
| rooms | 3 | 15000 |
| age of the building in years | 10 |
With the bias 20000:
Every square metre adds 1200, every room 15000, and every year of age takes away 800. This is linear regression (Topic 22): learning means finding the weights. A neuron of a neural network does the same calculation and then passes the result through one more function.
8.2Search by similarity
Three short texts are turned into vectors by counting three words: "python", "data" and "football". The question is , the texts are , and . The length of the question is .
Text A points in exactly the same direction as the question, although it is twice as long. Text B shares one word, text C none. Sorting by this number is the heart of a search engine, and of the retrieval step in RAG at the end of the course. There the vectors have hundreds of components, but the formula is the same.
8.3The nearest neighbour
A shop knows two numbers about each customer: visits per month and average bill. Anar and Sona are regular customers, Emil is a rare one. A new customer is .
The new customer is closest to Anar, so the best guess is "regular". This is k-Nearest Neighbors (Topics 32 and 33) with : the distance of Part 5 and nothing else.
One warning that later lessons take seriously: the bill has much larger numbers than the visits, so it dominates the distance. That is why features are scaled before distances are used (Topic 24).
Try it yourself
Show a hint
Show the solution
Answer: 28.
9Common mistakes
Adding vectors of different dimensions. is not defined. Check the dimensions first.
Writing a dot product as a vector. , one number. Writing and stopping there is the most common mistake of the topic.
Losing a minus sign. In the second product is , so the result is . Write every product before adding.
Forgetting the square root in the length. is 5, not 25. is the length squared.
Taking the root of each part. is , not . The root of a sum is not the sum of the roots.
Adding the lengths. is not . For and : , but .
Subtracting in the wrong order. : end minus start. For a distance the order does not matter; for a direction it does.
Taking the angle from the dot product alone. The dot product must be divided by both lengths before the inverse cosine is taken.
Reading a zero dot product as a zero vector. means that the vectors are perpendicular. Neither of them has to be zero.
Cancelling a vector. From it does not follow that . Example: , , : both dot products are 0.
Normalizing the zero vector. Its length is 0, and dividing by 0 is not possible.
Degrees and radians. Set the calculator to degrees before using the inverse cosine, or convert: radians.
| Mistake | What is right |
|---|---|
| only vectors of the same dimension can be added | |
| "dot product 0 means a zero vector" | it means perpendicular vectors |
| a cosine larger than 1 | impossible: recalculate (Cauchy-Schwarz) |
10Solved problems (from the easiest to the hardest)
Each problem has the question, the idea behind it with the part of the lesson it uses, and the calculation step by step. Cover the solution and try first.
Level 1: The operations
Problem 1: Add and subtract
For and find and .
Idea. Addition and subtraction work component by component (Part 3). Keep the signs carefully: subtracting a negative number adds.
Why: the third component of is . A quick check for any subtraction: must give again, and .
Problem 2: A linear combination
For and find .
Idea. Scale first, then add (Part 4). Do it in two clear steps.
Why: writing the scaled vectors on their own lines avoids the most common slip, a lost minus sign in the second component.
Problem 3: Two lengths
Find the length of and of .
Idea. Square, add, take the root (Part 5).
Why: is , so its length is : scaling a vector scales its length. Recognising a multiple of a known vector saves the calculation.
Problem 4: Two dot products
Find and .
Idea. Multiply in pairs and add (Part 6).
Why: the second result is 0, so and are perpendicular. A dot product is never only a number to calculate; always read its sign.
Problem 5: A unit vector
Find the unit vector in the direction of .
Idea. Divide the vector by its length (Part 5).
Why: the sign of a component does not change the length, because it is squared. The unit vector keeps the signs: it points in the same direction as .
Problem 6: The bill
A cafe sold 12 teas, 5 coffees and 8 cakes. A tea costs 1.5, a coffee 3.0 and a cake 4.5. Write the two vectors and find the money earned.
Idea. Amounts and what each is worth: a dot product (Part 6).
Why: the order of the components must be the same in both vectors: tea, coffee, cake. A vector is an ordered list.
Problem 7: From one point to another
For the points and find the vector , the distance between the points and the midpoint of the segment.
Idea. The vector between two points is end minus start (Part 2), the distance is its length (Part 5), and the midpoint is the average of the two points (Part 4).
Why: the midpoint can be checked with the vector: go half of from , . Two ways to the same point is the best check there is.
Level 2: Length, distance and angle
Problem 8: The angle between two vectors
Find the angle between and .
Idea. (Part 7).
Why: the picture agrees. lies along the x axis, and is the diagonal of a square, exactly halfway to the y axis.
Problem 9: Make them perpendicular
For which number are and perpendicular?
Idea. Perpendicular means the dot product is 0 (Part 7). Write the dot product with the unknown and solve.
Why: the condition "perpendicular" turned into one small equation. Many problems of linear algebra work like this: translate the geometric word into a dot product.
Problem 10: A distance in three dimensions
Find the distance between the points and .
Idea. The distance is the length of the difference (Part 5).
Why: the third components are equal, so the two points are at the same height and the problem is really the 3-4-5 triangle in a plane. Looking at the difference vector before calculating often shows such a shortcut.
Problem 11: Two walks
A hiker walks 3 km to the east and 4 km to the north. After a break she walks 1 km to the west and 2 km to the north. How far is she from the start in a straight line, and how far did she walk?
Idea. Each walk is a vector (east, north). The total displacement is the sum; the straight-line distance is its length (Parts 3 and 5).
Why: she walked 7.24 km but is only 6.32 km from the start. : this is the triangle inequality of Part 5 in real life.
Problem 12: Find the recipe
Write as a linear combination of and .
Idea. We look for two numbers and with (Part 4). Each component gives one equation.
Adding the two equations gives , so and .
Why: one vector equation in 2 dimensions is two ordinary equations. Always put the numbers back in at the end: the check takes ten seconds.
Problem 13: Three points on one line?
Do the points , and lie on one straight line?
Idea. They do exactly when and are parallel, that is, when one is a multiple of the other (Part 4).
The two vectors are parallel, so the three points are on one line.
Why: both vectors start at the same point . Two parallel arrows from the same point lie on the same line, so their tips and are on that line too.
Problem 14: A weighted average
A course has three grades with the weights 2, 3 and 5. A student got 90, 60 and 80. Find the weighted average.
Idea. Weights times grades is a dot product; divide by the sum of the weights (Part 6).
Why: the plain average of 90, 60 and 80 is 76.67. The weighted one is lower because the weakest grade has a larger weight than the strongest.
Problem 15: How similar are two texts?
Two texts are described by how often the words "data", "model" and "price" appear: and . Find their cosine similarity.
Idea. (Part 7).
Why: all counts are zero or positive, so the similarity of two count vectors is always between 0 and 1. A value of 0.775 says: mostly the same subject.
Level 3: Putting ideas together
Problem 16: A projection
Project onto . Give the vector projection and the part of that is perpendicular to .
Idea. The projection is (Part 7). What is left, minus the projection, must be perpendicular to .
Check: .
Why: : one part along the diagonal and one part across it. The check with the dot product catches almost every calculation mistake in a projection.
Problem 17: A right-angled triangle
A triangle has the corners , and . Show that it has a right angle, and find the lengths of its three sides.
Idea. The sides are vectors between points (Part 2). A right angle at a corner means that the two sides leaving it have the dot product 0 (Part 7).
The dot product is 0, so the angle at is . The lengths of the sides:
Why: a point is not a side. The corners are given as points; the sides are the arrows between them, and every question about angles and lengths is asked about those arrows. For the angle at a corner, both arrows must start at that corner.
Problem 18: Classify by the nearest neighbour
Known flowers, described by (petal length, petal width) in cm: is of type A, is of type B, is of type C. A new flower measures . Which type is the best guess?
Idea. Calculate the distance to every known flower and take the smallest (Parts 5 and 8).
The nearest flower is , so the best guess is type B.
Why: to find only the nearest one, the square roots are not even needed: the smallest squared distance (0.13) belongs to the smallest distance. Programs use this to save time.
Problem 19: Lengths and an angle, no components
Two vectors have the lengths and , and the angle between them is . Find , and .
Idea. The geometric formula gives the dot product from lengths and angle (Part 7). The square of a sum gives the length of from the dot product (Part 6); for the middle term changes its sign.
Why: the components of the vectors were never needed. The angle is more than , so the vectors point against each other: their sum is shorter than alone, and their difference is longer.
Problem 20: Which feature decides?
A model scores loan applications with the weights for the features (income in thousands, number of late payments, age) and the bias . An application is accepted when the score is positive. Applicant 1 is , applicant 2 is . Who is accepted, and which feature costs applicant 2 the most?
Idea. The score is (Part 8). The single products show what every feature contributes.
Why: the single products of applicant 2 are , and . The three late payments take away 6 points, more than the income adds. The sign of decides on which side of a border an applicant falls: this is the idea of logistic regression and of Support Vector Machines.
11Practice problems
Thirty-four problems in three levels. Solve each one on paper, type your result into the answer boxes and press Check. Under every problem there is a hint and a full solution: look at the hint only when you are stuck, and at the solution only after you have an answer of your own.
Level 1: The operations
- 1.For and find and .
Show a hint
Work component by component.Show one possible solution
Answer: and .
- 2.For find and .
Show a hint
Multiply every component by the number.Show one possible solution
Answer: and .
The negative number turns the direction around.
- 3.For and find .
Show a hint
Scale each vector first, then add.Show one possible solution
Answer: .
- 4.Find the length of .
Show a hint
Square, add, take the root.Show one possible solution
Answer: 13.
- 5.Find the length of .
Show a hint
A negative component becomes positive when it is squared.Show one possible solution
Answer: 3.
- 6.Find .
Show a hint
Multiply the first components, multiply the second components, add.Show one possible solution
Answer: 2.
- 7.Find .
Show a hint
Four pairs, four products.Show one possible solution
Answer: 3.
- 8.Find the unit vector in the direction of .
Show a hint
Divide the vector by its length.Show one possible solution
Answer: .
Check: .
- 9.Find the distance between the points and .
Show a hint
The distance is the length of the difference.Show one possible solution
Answer: 5.
The difference is , and its length is .
- 10.Find the midpoint of the segment from to .
Show a hint
The midpoint is the average of the two points.Show one possible solution
Answer: .
- 11.Which of these vectors are parallel to : , , ?
Show a hint
A parallel vector is a multiple of : divide the components and look for the same number every time.Show one possible solution
Answer: and are parallel to ; is not.
, because . For the ratios are , and : not the same, so it is not parallel. : parallel, pointing the opposite way.
Level 2: Length, distance and angle
- 12.Find and so that .
Show a hint
Two vectors are equal when every component is equal: each component gives one equation.Show one possible solution
Answer: and .
- 13.For and find the vector with .
Show a hint
Solve the equation as with numbers: .Show one possible solution
Answer: .
Check: .
- 14.Find the angle between and , in degrees with 2 decimals.
Show a hint
. Both lengths are 5.Show one possible solution
Answer: .
- 15.For which are and perpendicular?
Show a hint
Set the dot product equal to 0.Show one possible solution
Answer: .
Check: .
- 16.Without calculating the angle: is the angle between and less than, equal to or more than ?
Show a hint
The sign of the dot product is enough.Show one possible solution
Answer: More than .
. A negative dot product means an angle of more than .
- 17.A shop sold 12, 5 and 8 pieces of three products. Their prices are 3.5, 10 and 2.25. Find the money earned with a dot product.
Show a hint
Amounts times prices, added up.Show one possible solution
Answer: 110.
- 18.Three courses have 3, 4 and 2 credits. A student got 85, 70 and 95. Find the average weighted by the credits, with 2 decimals.
Show a hint
Dot product of credits and grades, divided by the sum of the credits.Show one possible solution
Answer: 80.56.
- 19.Normalize and check that the result has the length 1.
Show a hint
The length of the vector is a whole number.Show one possible solution
Answer: , about .
You can type the fractions in the answer box:
(1/3, 2/3, 2/3). - 20.Find the vector of the length 15 that points in the direction of .
Show a hint
First the unit vector, then multiply by 15.Show one possible solution
Answer: .
- 21.Find the cosine similarity of and , with 3 decimals.
Show a hint
Both vectors have three ones, so both lengths are .Show one possible solution
Answer: 0.667.
- 22.A delivery robot drives 5 km to the east, then 3 km to the north, then 2 km to the west. How far is it from the start in a straight line (2 decimals)?
Show a hint
Write each part as a vector (east, north) and add them.Show one possible solution
Answer: 4.24 km.
- 23.Do the points , and lie on one straight line?
Show a hint
Compare the vectors and : are they parallel?Show one possible solution
Answer: Yes.
and . The ratios are and , so . The vectors are parallel and start at the same point, so the three points are on one line.
- 24.A model predicts an exam score as with , and the features (homework score, midterm score). Find the prediction.
Show a hint
First the dot product, then add the bias.Show one possible solution
Answer: 73.
Level 3: Putting ideas together
- 25.Project onto . Give the vector projection.
Show a hint
.Show one possible solution
Answer: .
Check: the rest has the dot product with .
- 26.Find the numbers and with .
Show a hint
Each component gives one equation. Multiply the second equation by 2 and subtract the first to remove .Show one possible solution
Answer: and .
Twice the second equation is . Subtracting the first leaves , so , and then .
Check: .
- 27.A triangle has the corners , and . Find the angle at the corner , in degrees with 2 decimals.
Show a hint
The angle at is the angle between the vectors and .Show one possible solution
Answer: .
- 28.Find a unit vector that is perpendicular to .
Show a hint
Swap the two components and change one sign to get a perpendicular vector. Then normalize.Show one possible solution
Answer: , or the opposite vector .
is perpendicular to , because . Its length is 5, so the unit vector is . The opposite vector is a second right answer.
- 29.Find the point that lies one quarter of the way from to .
Show a hint
Start at and add a quarter of the vector .Show one possible solution
Answer: .
- 30.Find the angle between and , in degrees with 2 decimals. Then check the Cauchy-Schwarz inequality for them: give and .
Show a hint
Both lengths are whole numbers.Show one possible solution
Answer: , and .
- 31.Known points: is red, is blue, is blue. Which colour does the nearest neighbour give to the new point ?
Show a hint
Calculate the three distances and take the smallest.Show one possible solution
Answer: Red.
is the nearest, and is red.
- 32.Three users rated three films: Aylin , Murad , Leyla . Whose taste is closer to Aylin's by cosine similarity? Give both similarities with 3 decimals.
Show a hint
Calculate the similarity of Aylin with each of the two.Show one possible solution
Answer: Murad: 0.966. Leyla: 0.507. Murad is closer.
Aylin's vector has the length .
- 33.Two vectors have the lengths and , and the angle between them is . Find and (2 decimals).
Show a hint
Use with , then .Show one possible solution
Answer: and .
The components were never needed: the lengths and the angle were enough.
- 34.For and check that : give the value of both sides. When is equal to 0?
Show a hint
Calculate both sides. For the second question look at the right side.Show one possible solution
Answer: Both sides are 5. The product is 0 exactly when the two vectors have the same length.
The right side is 0 when . In a picture: and are the two diagonals of the parallelogram of and , and they are perpendicular when all four sides are equally long.
12Check yourself
Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.
0 of 12 answered.
13Checking your work with NumPy
This is the only code of the lesson. After you have solved a problem by hand, NumPy can confirm the result. A vector is a 1D array (Topics 8 and 9).
import numpy as np
a = np.array([2, 1])
b = np.array([1, 3])
print(a + b, a - b, 2 * a - 3 * b)
print(np.linalg.norm(a))
print(np.linalg.norm(a - b))
print(a @ b)
cos = (a @ b) / (np.linalg.norm(a) * np.linalg.norm(b))
print(round(cos, 4), round(np.degrees(np.arccos(cos)), 2))
print((a @ b) / (b @ b) * b)Output
[3 4] [ 1 -2] [ 1 -7] 2.23606797749979 2.23606797749979 5 0.7071 45.0 [0.5 1.5]
Change it and run: put the vectors of a problem you solved by hand into a and b, and compare the numbers.
| By hand | In NumPy |
|---|---|
| , , | a + b, a - b, c * a |
np.linalg.norm(a) | |
| the distance | np.linalg.norm(a - b) |
a @ b or np.dot(a, b) | |
| the angle | np.degrees(np.arccos(cos)) |
One trap: a * b in NumPy multiplies element by element and gives a vector. It is not the dot product. The dot product is a @ b.
14Quick summary
| Idea | Definition or formula |
|---|---|
| Vector | an ordered list of numbers; its dimension is the number of components |
| Vector between two points | (end minus start) |
| Addition, subtraction | component by component; is the arrow from to |
| Scalar multiplication | ; stretches or turns the arrow |
| Parallel vectors | for some number |
| Midpoint | |
| Linear combination | |
| Length | |
| Unit vector | |
| Distance | |
| Triangle inequality | |
| Dot product | , one number |
| Length from the dot product | |
| Square of a sum | |
| Geometric formula | |
| Angle | |
| Perpendicular (orthogonal) | |
| Cauchy-Schwarz inequality | |
| Cosine similarity | , from to |
| Scalar projection of onto | |
| Vector projection of onto | |
| Prediction of a linear model |