Skip to content
Visual explainer 3h to learn 5 steps

Linear algebra for machine learning with NumPy

Compute dot products, norms and matrix-vector predictions in NumPy and explain each array shape against a feature table.

By Invicly Tech, , in AI and Machine Learning with Python. About 10 minutes to read.

Topic 4 of 34

In short

A feature table is a matrix: each row is one example and each column is one feature, so a row is a vector of numbers. A linear model's prediction is the dot product of that row with a weight vector, plus a bias, and NumPy computes it for every row at once with a matrix-vector product. Reading array shapes, such as (rows, features), is the skill that catches most bugs before they happen.

Think of it like this: A dot product is like a shopping bill: quantities times prices, added up into one total.

Explained simply

Linear algebra sounds scary, but in machine learning it mostly means working with lists and tables of numbers. A vector is a list, like the size, bedrooms and age of one house. A matrix is a table, like many houses stacked as rows. Your dataset is already a matrix.

A linear model gives each feature a weight. To predict one house's price, you multiply each feature by its weight and add the results, then add a fixed starting amount called the bias. Multiplying matching entries and adding them up is called a dot product.

NumPy, the main Python library for numbers, can do this for every row at once. You write X @ w and get one prediction per row. This is fast because NumPy runs the loop in optimised compiled code instead of slow Python.

The most useful habit is checking shapes. A shape like (100, 3) means 100 rows and 3 columns. Before multiplying, ask whether the sizes line up. Most beginner bugs in NumPy are shape mistakes that run without errors but give nonsense.

Press Play on a diagram to walk through it one step at a time.

FlowFrom feature table to predictions
  1. 1
    Feature matrix X

    Shape (n, d): n rows, d features.

  2. 2
    Weight vector w

    Shape (d,): one weight per feature.

  3. 3
    X @ w

    Each row dotted with w gives shape (n,).

  4. 4
    Add bias b

    A single number broadcast to every row.

  5. 5
    Predictions

    Shape (n,): one value per example.

MapCommon NumPy operations by job
NumPy for ML
  • Create
    • np.array(list)
    • np.zeros((n, d))
    • rng.normal(size=(n, d))
  • Inspect
    • a.shape
    • a.ndim
    • a.dtype
  • Combine
    • a @ b
    • a * b (element-wise)
    • np.dot(a, b)
  • Summarise
    • a.mean(axis=0)
    • a.sum(axis=1)
    • np.linalg.norm(a)
  • Reshape
    • a.reshape(-1, 1)
    • a.ravel()
    • a.T

In depth

Shapes: the grammar of NumPy

Every array has a shape. A feature matrix X with 1,000 rows and 5 features has shape (1000, 5). One row, X[0], has shape (5,). One column, X[:, 0], has shape (1000,). A weight vector for 5 features has shape (5,).

Matrix multiplication A @ B needs the last size of A to equal the first size of B. (1000, 5) @ (5,) works and returns (1000,). (1000, 5) @ (1000,) raises a ValueError, which is good: NumPy caught the mistake. Multiplying two matrices, (1000, 5) @ (5, 3), gives (1000, 3), for example three outputs per row. Print shapes often, and add assert X.shape[1] == w.shape[0] in code you reuse.

  • (n, d) @ (d,) gives (n,)
  • (n, d) @ (d, k) gives (n, k)
  • X.T flips (n, d) into (d, n)
  • reshape(-1, 1) turns (n,) into (n, 1)

Dot products, norms and distance

The dot product of a and b is the sum of a[i] times b[i]. It is large when two vectors point the same way, zero when they are at right angles, and negative when they point in opposite directions. Dividing it by both lengths gives cosine similarity, used later for recommenders and text embeddings.

A norm is a vector's length. The L2 norm is the square root of the sum of squares, np.linalg.norm(v). The L1 norm is the sum of absolute values, np.linalg.norm(v, ord=1). The distance between two rows is the norm of their difference. Models such as k-nearest neighbours rely on that distance, which is why a feature measured in thousands will swamp one measured in units unless you scale first.

CompareTwo ways to measure a vector
L2 norm
  • Square root of sum of squares
  • Straight-line length
  • np.linalg.norm(v)
  • Used by ridge regularisation
L1 norm
  • Sum of absolute values
  • City-block length
  • np.linalg.norm(v, ord=1)
  • Used by lasso regularisation

Broadcasting without surprises

Broadcasting lets NumPy combine arrays of different shapes. It compares shapes from the right. Two sizes are compatible when they are equal or one of them is 1; the size-1 dimension is stretched. So X (1000, 5) minus X.mean(axis=0) (5,) subtracts each column's mean from every row, which is exactly how standardisation works.

The danger is shapes (n,) and (n, 1). Subtracting them gives (n, n), every value minus every other value, with no error. This often appears when y comes from a DataFrame column as (n, 1) and predictions are (n,). A mean squared error computed on that (n, n) array is a meaningless number. Flatten with ravel() or check shapes before arithmetic.

Predictions as matrix-vector products

A linear regression prediction for row i is X[i] @ w + b. For all rows, it is X @ w + b, where b is broadcast. A logistic regression uses the same score and then squeezes it into a probability with the sigmoid function, 1 / (1 + e to the minus score). A neural network layer is X @ W + b with W a matrix, followed by a simple non-linear function, stacked several times.

So the same few operations power most models in this path. When scikit-learn fits a LinearRegression, the learned weights are in coef_ and the bias in intercept_, and you can reproduce predict yourself with X @ model.coef_ + model.intercept_. Doing that once is a good way to make the maths concrete.

LayersThe same operation, growing in size
  1. 1
    Neural layer

    X @ W + b, then a non-linear function.

  2. 2
    Logistic regression

    sigmoid(X @ w + b) gives probabilities.

  3. 3
    Linear regression

    X @ w + b gives numbers.

  4. 4
    Dot product

    One row times one weight vector.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Represent rows and features as vectors~35m
  2. 2
    Multiply matrices and check shapes~35m
  3. 3
    Compute dot products and norms~35m
  4. 4
    Use broadcasting safely~35m
  5. 5
    Turn weights and features into predictions~35m

Key points

  • Rows are examples and columns are features; X.shape tells you (rows, features).
  • Matrix multiplication needs the inner sizes to match: (n, d) @ (d,) gives (n,).
  • A dot product multiplies matching entries and adds them; a norm measures a vector's length.
  • Broadcasting stretches size-1 dimensions automatically, which is handy and also a source of silent bugs.
  • A linear model's predictions are simply X @ w + b.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import numpy as np

# 3 houses x 2 features: size in m2, bedrooms
X = np.array([[50.0, 1], [80.0, 2], [120.0, 3]])
w = np.array([3000.0, 10000.0])   # price per m2, per bedroom
b = 20000.0                        # base price

print(X.shape, w.shape)            # (3, 2) (2,)
pred = X @ w + b                   # shape (3,)
print(pred)                        # [180000. 280000. 410000.]
print(np.linalg.norm(w))           # length of the weight vector

Each prediction is one row dotted with the weights, plus the bias.

Reproducing scikit-learn's predictions by hand

Step 1: fit a LinearRegression on synthetic data with known weights. Step 2: read coef_ and intercept_. Step 3: compute X @ coef_ + intercept_ yourself. Step 4: compare with model.predict(X). Expected evidence: the learned weights are close to [2, -1, 0.5], the bias close to 4, and np.allclose prints True.

python
import numpy as np
from sklearn.linear_model import LinearRegression

rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))
y = X @ np.array([2.0, -1.0, 0.5]) + 4 + rng.normal(scale=0.1, size=200)

m = LinearRegression().fit(X, y)
print(m.coef_.round(2), round(m.intercept_, 2))
manual = X @ m.coef_ + m.intercept_
print(np.allclose(manual, m.predict(X)))   # True

Catching the (n,) versus (n, 1) bug

Step 1: create y_true with shape (4, 1), as you get from df[["price"]].to_numpy(). Step 2: create predictions with shape (4,). Step 3: subtract them and look at the shape: (4, 4). Step 4: fix it with ravel() and recompute. The wrong mean squared error is silently different from the right one.

python
import numpy as np

y_true = np.array([[3.0], [5.0], [7.0], [9.0]])   # (4, 1)
y_pred = np.array([2.5, 5.0, 7.5, 9.0])            # (4,)

wrong = ((y_true - y_pred) ** 2).mean()
print((y_true - y_pred).shape, round(wrong, 3))    # (4, 4) and a nonsense value

right = ((y_true.ravel() - y_pred) ** 2).mean()
print(round(right, 3))                             # 0.125

Quick reference

  • Rows are examples, columns are features: X.shape == (n_rows, n_features)
  • (n, d) @ (d,) gives (n,); inner sizes must match
  • a @ b is matrix multiplication; a * b is element by element
  • np.linalg.norm(v) is the L2 length; ord=1 gives the L1 length
  • axis=0 goes down columns (per feature); axis=1 goes across rows (per example)
  • Shapes (n,) and (n, 1) broadcast to (n, n): flatten with ravel() first
  • Linear prediction: X @ model.coef_ + model.intercept_

Common mistakes

  • Mixing shapes (n,) and (n, 1): subtracting them broadcasts to an (n, n) matrix without any error.
  • Using * when you mean @: * multiplies element by element, @ does matrix multiplication.
  • Forgetting which axis is which: axis=0 works down columns, axis=1 works across rows.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1X has shape (200, 4). Which weight shape lets you compute X @ w?

Question 2

2What is the L2 norm of the vector [3, 4]?

Question 3

3What does X.mean(axis=0) return for a (1000, 5) array?

Question 4

4Which operation does element-wise multiplication in NumPy?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Compute the dot product of [2, 0, 1] and [4, 5, 3] by hand and with NumPy.

  2. Exercise 2medium

    Standardise a (100, 3) random matrix column by column using broadcasting, and check each column now has mean about 0 and standard deviation about 1.

  3. Exercise 3hard

    Write a function that returns the index of the training row closest (L2 distance) to a query vector, using broadcasting and no Python loop.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How much linear algebra do I need for machine learning?
To use classical models well you need vectors, matrices, dot products, norms and shapes. Deeper topics such as eigenvectors help with PCA and research, but you can learn them when you need them.
What is the difference between @ and * in NumPy?
The @ operator does matrix multiplication, combining rows with columns. The * operator multiplies entries in matching positions, after broadcasting.
Why does NumPy not raise an error when my shapes are wrong?
Broadcasting is a feature: shapes like (n,) and (n, 1) are compatible, so NumPy produces an (n, n) result. Check shapes with print or assert before doing arithmetic.

Go deeper

ShareXLinkedInWhatsApp