Module 2 · Beginner · Before you start: the Python and maths you need

Linear algebra for machine learning

Linear algebra for machine learning: vectors, matrices, dot products, distance, cosine similarity and matrix multiplication, with NumPy code.

By theprogrammers team · · 10 min read

An estate agent prices a flat in her head: "₹5,000 per square foot, plus a bit for each bedroom, minus a bit for every year of age." She's doing linear algebra without knowing it. Most of the linear algebra for machine learning is like that: lists of numbers and tables of numbers, and simple ways to combine them. A house becomes a list of numbers (area, bedrooms, age). A dataset of houses becomes a table. A photo becomes a grid of pixel values.

You don't need proofs. You need five ideas, what they mean in machine learning, and how to compute them in NumPy. Each one links to a full lesson in the linear algebra course if you want more.

What you need first: the NumPy array tutorial and data, features and labels.

Key terms

  • Vector: a list of numbers, such as one house's features [1200, 3, 10].
  • Matrix: a table of numbers; in ML, one row per example and one column per feature.
  • Dot product: multiply matching numbers in two vectors and add the results: a weighted sum.
  • Norm: the length of a vector; the distance between two points is the norm of their difference.
  • Shape: the size of an array along each direction, such as (100, 3) for 100 rows and 3 columns.

Linear algebra for machine learning: scalars, vectors, matrices and tensors

The full lessons are scalars, vectors, matrices and tensors and what is a vector? Here's the short version.

NameWhat it isNumPy shapeML example
ScalarA single number()A house price: 75
VectorA list of numbers(3,)One house: [1200, 3, 10]
MatrixA table: rows × columns(100, 3)100 houses, 3 features each
Tensor3 or more dimensions(32, 28, 28)32 greyscale images, 28 × 28 pixels
import numpy as np

house = np.array([1200, 3, 10])            # area, bedrooms, age: a vector
houses = np.array([[1200, 3, 10],
                   [800,  2, 25],
                   [1500, 4,  5]])          # 3 houses × 3 features: a matrix
print(house.shape, houses.shape)
(3,) (3, 3)

The convention throughout ML: each row is one example, each column is one feature. When you see X.shape print (4601, 57), read it as "4,601 examples, 57 features". New to arrays? Start with the NumPy array tutorial.

Vectors as points and arrows

A vector with two numbers, like [3, 4], is a point on a graph: 3 along, 4 up. With 57 features, each example is a point in 57-dimensional space. You can't picture 57 dimensions, but the maths works exactly as it does in two, and that's the key insight: similar examples are points close together.

Adding vectors and multiplying them by a number work element by element:

a = np.array([1, 2])
b = np.array([4, 6])
print(a + b)
print(3 * a)
[5 8]
[3 6]

Idea 1: the dot product, the heart of predictions

The dot product multiplies matching elements and adds them up:

x = np.array([1200, 3, 10])         # a house: area, bedrooms, age
w = np.array([0.05, 4, -0.5])       # how much each feature matters
print(x @ w)
67.0

That's 1200 × 0.05 + 3 × 4 + 10 × (−0.5) = 60 + 12 − 5 = 67. Read the formula aloud as "area times its weight, plus bedrooms times theirs, plus age times its". @ is NumPy's operator for the dot product.

Look at what just happened: we predicted a price of 67 lakh from a weighted sum of features. That is linear regression. The numbers in w are the model's weights: positive weights push the prediction up, negative ones (older houses) pull it down. Training a linear model means finding the best weights.

Predict, then run: the same house is 30 years old instead of 10. Which single number changes, and what's the new price?

older = np.array([1200, 3, 30])
print(older @ w)
57.0

Only the age term changes: 30 × (−0.5) = −15 instead of −5, so the price falls by 10, from 67 to 57 lakh. Each weight says exactly how much its feature moves the prediction. Experiment: change the bedroom weight from 4 to 10 and predict the new price of the original house before running x @ np.array([0.05, 10, -0.5]).

Every neuron in a neural network does the same thing: a dot product of inputs and weights, plus a bias, passed through a function. Billions of dot products are why AI needs GPUs, which are very good at exactly this.

Idea 2: length and distance

The full lessons are L1 and L2 norms explained and distance between vectors.

The length (or norm) of a vector is how far it is from the origin, using Pythagoras' theorem: for [3, 4], √(3² + 4²) = √25 = 5, read "the square root of 3 squared plus 4 squared":

print(np.linalg.norm(np.array([3, 4])))
5.0

The distance between two points is the length of their difference:

p = np.array([1, 2])
q = np.array([4, 6])
print(np.linalg.norm(p - q))
5.0

Distance means similarity. The k-nearest neighbours algorithm classifies a new example by finding the closest training examples. K-means clustering groups points that are close together. This is also why feature scaling matters: if area is in thousands and bedrooms in single digits, area dominates every distance.

Idea 3: cosine similarity, comparing direction

The full lesson is cosine similarity and the angle between vectors.

Sometimes direction matters more than size. Cosine similarity measures the angle between two vectors: 1 means the same direction, 0 means unrelated (at right angles), −1 means opposite. The formula, a · b ÷ (|a| × |b|), reads "the dot product divided by both lengths multiplied together"; dividing by the lengths removes size, leaving only direction.

def cosine_similarity(a, b):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))

print(cosine_similarity(np.array([1, 2, 3]), np.array([2, 4, 6])))
print(cosine_similarity(np.array([1, 0]), np.array([0, 1])))
1.0
0.0

[2, 4, 6] is just [1, 2, 3] doubled, so the two point the same way: 1.0. [1, 0] points along and [0, 1] points up, at right angles: 0.0.

This powers modern AI search. Language models turn sentences into embedding vectors, and sentences with similar meanings point in similar directions. "How do I reset my password?" and "I forgot my login" get a high cosine similarity even though they share no words. Recommendation systems compare users and products the same way.

Idea 4: matrix multiplication, predictions for everyone at once

The full lessons are matrix-vector multiplication explained and matrix multiplication explained.

Multiply a matrix of examples by a weight vector and you get a dot product for every row: a prediction for every house in one line:

houses = np.array([[1200, 3, 10],
                   [800,  2, 25],
                   [1500, 4,  5]])
w = np.array([0.05, 4, -0.5])
print(houses @ w)
[67.  35.5 88.5]
A 3 by 3 matrix of houses, with columns area, bedrooms and age, multiplied by the weight vector 0.05, 4 and −0.5, gives the predictions 67, 35.5 and 88.5. The first row is worked out: 1200 × 0.05 + 3 × 4 + 10 × (−0.5) = 60 + 12 − 5 = 67.

In the picture, follow the highlighted first row across: multiply each number by the matching weight, then add. Each row gives one prediction.

The shape rule: (rows, n) @ (n, cols) gives (rows, cols). The inner numbers must match. Here, (3, 3) @ (3,) gives (3,): three predictions. With 1,000 houses, it's still one line, and NumPy runs it in fast compiled code rather than a Python loop.

A neural network layer is a matrix multiplication too: inputs @ weights + bias, where the weight matrix connects every input to every neuron. "Matrix shapes don't match" is one of the most common errors in deep learning, so learn to read shapes now.

Idea 5: the transpose

The full lesson is the transpose of a matrix.

The transpose flips a matrix so rows become columns. In NumPy it's .T:

m = np.array([[1, 2, 3],
              [4, 5, 6]])
print(m.shape, m.T.shape)
(2, 3) (3, 2)

You'll often transpose to make shapes line up for multiplication, as in the formula for linear regression, which uses X.T @ X.

What you can skip for now

Linear algebra courses cover a lot more: determinants, matrix inverses, eigenvalues, eigenvectors, singular value decomposition. They matter for understanding PCA and some advanced methods, and you can learn them when you get there. For now, NumPy and scikit-learn handle them for you.

Practice

  1. Compute the dot product of [2, 3, 1] and [4, -1, 5] by hand, then check it with NumPy.
Show the answer

2 × 4 + 3 × (−1) + 1 × 5 = 8 − 3 + 5 = 10.

print(np.array([2, 3, 1]) @ np.array([4, -1, 5]))
10
  1. Without running it, predict the shape of houses.T @ houses for the 3 × 3 houses matrix, and for a data matrix X of shape (500, 8).
Show the answer

houses.T is (3, 3), so the result is (3, 3). For X, X.T is (8, 500), and (8, 500) @ (500, 8) gives (8, 8): one row and column per feature, whatever the number of examples. That's the X.T @ X in the linear regression formula.

  1. Two product reviews are turned into word-count vectors. One is a short review, [1, 2, 0], and one is a long review about the same things, [5, 10, 0]. Why would cosine similarity call them identical while Euclidean distance calls them far apart?
Show the answer

The long review is exactly the short one times 5, so the two vectors point the same way: cosine similarity 1.0. But their tips are far apart (distance about 8.9), purely because one review is longer. When you care about what's said rather than how much, compare directions.

  1. Which customer is closer to customer A = [25, 40000] (age, income): B = [27, 41000] or C = [60, 40000]? What's misleading about the answer?
Show the answer
A, B, C = np.array([25, 40000]), np.array([27, 41000]), np.array([60, 40000])
print(np.linalg.norm(A - B), np.linalg.norm(A - C))
1000.001999998 35.0

C looks far closer, purely because income is measured in much bigger numbers than age, so a 35-year age gap counts for less than a ₹1,000 income difference. Scale the features before measuring distance.

  1. A matrix X has shape (500, 8). What shape must the weight vector w have for X @ w to work, and what is the shape of the result?
Show the answer

w must have shape (8,), one weight per feature, and the result has shape (500,): one prediction per example.

Interview questions

Why is linear algebra important in machine learning?

Data is represented as vectors and matrices, models are defined by weight matrices, and predictions and training are mostly matrix operations. Vectorised linear algebra lets libraries and GPUs process whole datasets efficiently instead of looping example by example.

What is the dot product, and what does it mean geometrically?

The sum of the products of corresponding elements. Geometrically, a · b = |a| |b| cos θ, so it measures how aligned two vectors are, scaled by their lengths. It's positive when they point in similar directions, zero when perpendicular, and negative when opposite.

When would you use cosine similarity instead of Euclidean distance?

When direction matters more than magnitude, as in text embeddings or document word counts, where a long document and a short one about the same topic should count as similar. Euclidean distance would treat them as far apart because their lengths differ.

What are the conditions for multiplying two matrices?

The number of columns in the first must equal the number of rows in the second: an (m × n) matrix times an (n × p) matrix gives an (m × p) result. Matrix multiplication isn't commutative: A @ B usually differs from B @ A.

Key takeaways

  • Data is vectors (one example) and matrices (many examples: rows are examples, columns are features).
  • The dot product, a weighted sum, is how linear models and neurons make predictions.
  • Distance measures similarity, which is why feature scaling matters.
  • Cosine similarity compares directions and powers embedding search.
  • Matrix multiplication makes predictions for all examples at once; inner shapes must match.

Frequently asked questions

How much linear algebra do I need for machine learning?

To start: vectors, matrices, the dot product, norms and matrix multiplication, and reading shapes. Eigenvalues and decompositions come later, for PCA and some advanced methods.

Do I need to do matrix calculations by hand?

No. NumPy does them. Working one small example by hand, like the 67 lakh house, is still the best way to understand what the code computes.

Is linear algebra or calculus more important for machine learning?

You need both, for different jobs. Linear algebra describes data and models (how predictions are computed); calculus describes training (how the weights are improved).

What to learn next

  1. Learn to describe data with statistics for machine learning.
  2. Build each idea in depth in the linear algebra course, starting with what is a vector?
  3. Practise array operations in the NumPy array tutorial.