Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

Data as Arrays: Vectors, Matrices and Shapes

Store a dataset as a NumPy matrix, write a linear model as one matrix product, and predict the shape of every result before you run it, including the broadcasting cases that give wrong answers without an error.

Contentsand lesson path

What you will learn

  • Represent a dataset and a linear model as matrix-vector operations in NumPy, predicting result shapes before running the code.

01. Why it matters

Almost every machine learning model, from linear regression to a large neural network, is built from a few array operations: multiply, add, sum along an axis. Libraries such as scikit-learn and PyTorch hide these operations most of the time, but you meet them as soon as you write a loss function, debug a prediction or read a research paper.

The most common bug in this kind of code is not a crash. It is an operation that runs, returns numbers, and returns the wrong numbers because two arrays had shapes you did not expect. A loss that is quietly averaged over 250,000 pairs instead of 500 residuals still looks like a loss. This lesson gives you the vocabulary (scalar, vector, matrix, shape, axis), shows how a linear model becomes a single matrix product, and teaches the habit that prevents silent shape bugs: predict the shape of every result before you run the line.

The examples use Python 3.12 and NumPy 2.5. Install NumPy with python -m pip install numpy in a virtual environment if you do not have it yet.

02. Scalars, vectors, matrices and tensors

A scalar is a single number, such as a price of 250. A vector is an ordered list of numbers, such as the three facts we know about one house: floor area, number of bedrooms and age. A matrix is a rectangular grid of numbers with rows and columns. A tensor is the general name for an array with any number of dimensions: a colour image is a 3-dimensional tensor (height, width, colour channel), and a batch of images adds a fourth.

In NumPy all of these are ndarray objects. Two attributes describe them. ndim is the number of dimensions, also called axes. shape is a tuple with the size of each axis. A matrix of 4 rows and 3 columns has ndim 2 and shape (4, 3). A vector of 3 numbers has shape (3,): a tuple with one entry. Note that (3,) is not the same as (3, 1), which is a matrix with one column; this difference causes the bug at the end of the lesson.

Machine learning code uses one convention almost everywhere: rows are examples, columns are features. A dataset of n examples with d features is a matrix X of shape (n, d). Row X[i] is the feature vector of example i, and column X[:, j] holds feature j for every example. The targets you want to predict, one per example, form a vector y of shape (n,).

Python · shapes.py
import numpy as np

# Four houses (rows) described by three features (columns):
# floor area in m², number of bedrooms, age in years.
X = np.array([
    [70.0, 2, 15],
    [95.0, 3, 4],
    [120.0, 4, 30],
    [55.0, 1, 8],
])
print("shape:", X.shape, "ndim:", X.ndim)
print("second house (row 1):", X[1])
print("all floor areas (column 0):", X[:, 0])
print("one value is a scalar:", X[2, 1], np.ndim(X[2, 1]))
Expected output
shape: (4, 3) ndim: 2
second house (row 1): [95.  3.  4.]
all floor areas (column 0): [ 70.  95. 120.  55.]
one value is a scalar: 4.0 0

NumPy stores every value of an array with the same type, so the integer bedrooms became floats (3. is 3.0). Indexing with one number removes an axis: X[1] is a vector of shape (3,), and X[2, 1] is a scalar with 0 dimensions.

03. A linear model is one matrix product

A linear model predicts a target as a weighted sum of the features plus a constant. For one house with features x1, x2, x3 it computes w1·x1 + w2·x2 + w3·x3 + b. The numbers w1 to w3 are the weights, one per feature, and b is the bias or intercept. That weighted sum is a dot product of the feature vector with the weight vector.

Doing this for every row at once is exactly what matrix multiplication does. In NumPy the operator is @. For X @ w with X of shape (n, d) and w of shape (d,), NumPy takes the dot product of each row of X with w and returns one number per row: shape (n,). The general rule for two matrices is (n, d) @ (d, k) → (n, k): the inner sizes must be equal, they disappear, and the outer sizes remain. With k columns of weights you get k predictions per row, for example a price and a monthly rent from the same features.

Python · matmul.py
import textwrap

import numpy as np

X = np.array([[70.0, 2, 15], [95.0, 3, 4], [120.0, 4, 30], [55.0, 1, 8]])
w = np.array([2.0, 10.0, -0.5])  # one weight per feature, shape (3,)
b = 30.0                         # the bias (intercept), a scalar

y_hat = X @ w + b
print("y_hat:", y_hat, "shape:", y_hat.shape)

# The same prediction for house 0, written out by hand
print("by hand:", 70.0 * 2.0 + 2 * 10.0 + 15 * -0.5 + 30.0)

# Two outputs at once: price and monthly rent, one column of weights each
W = np.array([[2.0, 0.010], [10.0, 0.100], [-0.5, -0.004]])  # shape (3, 2)
B = np.array([30.0, 0.2])                                     # shape (2,)
print("X @ W + B shape:", (X @ W + B).shape)

try:
    X @ W.T  # (4, 3) @ (2, 3): the inner sizes 3 and 2 differ
except ValueError as error:
    print(textwrap.fill(f"ValueError: {error}", width=80))  # wrap for the page
Expected output
y_hat: [182.5 248.  295.  146. ] shape: (4,)
by hand: 182.5
X @ W + B shape: (4, 2)
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with
gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)

The error message is long, but its last part is the useful one: "size 2 is different from 3" names the two inner sizes that should match. (The script wraps the message with textwrap to fit the page; NumPy prints it on one line.) When you see this error, write the two shapes side by side and look at the inner pair.

The * operator is a different operation. X * w multiplies element by element: every column of X is multiplied by its own weight, and nothing is summed. With these shapes it does not fail, because NumPy stretches w over the rows (the next section explains how), so you get a (4, 3) array of scaled features instead of four predictions.

Python · star_vs_at.py
import numpy as np

X = np.array([[70.0, 2, 15], [95.0, 3, 4], [120.0, 4, 30], [55.0, 1, 8]])
w = np.array([2.0, 10.0, -0.5])

scaled = X * w            # element-wise: every column multiplied by its weight
print(scaled.shape)
print(scaled[0])
print(scaled.sum(axis=1)) # summing each row gives the same numbers as X @ w
print(X @ w)
Expected output
(4, 3)
[140.   20.   -7.5]
[152.5 218.  265.  116. ]
[152.5 218.  265.  116. ]

04. Broadcasting: how NumPy combines different shapes

In X @ w + b the bias is a scalar, yet it was added to all four predictions. With W and B above, a vector of shape (2,) was added to a (4, 2) matrix. This is broadcasting: the NumPy rule for element-wise operations between arrays of different shapes. It compares the two shapes from the right, one axis at a time. Two sizes are compatible when they are equal or when one of them is 1 (a missing axis on the left counts as 1). A size-1 axis is stretched to match the other array, without copying data. If any pair of sizes differs and neither is 1, NumPy raises an error.

Work through two cases. (4, 3) with (3,): the right-most sizes are 3 and 3, and the missing axis on the left counts as 1, so the vector is reused for every row. This is how you standardise features: subtract the column means, shape (3,), and divide by the column standard deviations. (4, 3) with (4,): the right-most sizes are 3 and 4, so this fails. To work on rows you need the row statistics as a column of shape (4, 1); keepdims=True keeps the reduced axis with size 1 for exactly this purpose.

Python · broadcasting.py
import numpy as np

X = np.array([[70.0, 2, 15], [95.0, 3, 4], [120.0, 4, 30], [55.0, 1, 8]])

means = X.mean(axis=0)           # one mean per column: shape (3,)
stds = X.std(axis=0)
Z = (X - means) / stds           # (4, 3) with (3,): stretched over the rows
print("means:", means.round(2), means.shape)
print("column means after:", Z.mean(axis=0).round(6) + 0.0)
print("column stds after:", Z.std(axis=0).round(6))

# Centring each ROW needs the row means as a column, shape (4, 1)
row_means = X.mean(axis=1, keepdims=True)
print("row means shape:", row_means.shape, "->", (X - row_means).shape)
try:
    X - X.mean(axis=1)           # (4, 3) with (4,): trailing sizes 3 and 4 clash
except ValueError as error:
    print("ValueError:", error)
Expected output
means: [85.    2.5  14.25] (3,)
column means after: [0. 0. 0.]
column stds after: [1. 1. 1.]
row means shape: (4, 1) -> (4, 3)
ValueError: operands could not be broadcast together with shapes (4,3) (4,)

The axis argument names the axis that is reduced (removed). X.mean(axis=0) collapses the rows and leaves one value per column; X.mean(axis=1) collapses the columns and leaves one value per row. The + 0.0 in the print only turns a printed -0. into 0.: tiny rounding errors can make a mean of zero come out as a negative zero.

05. The silent (n, 1) versus (n,) bug

Broadcasting is convenient, and it is also the source of the most expensive shape bug in ML code. Many functions return predictions as a column of shape (n, 1): a matrix product with a (d, 1) weight matrix, a neural network layer with one output, or model.predict in some libraries. Targets loaded from a table column usually have shape (n,). Subtracting them looks harmless.

Apply the rule from the right: (n, 1) against (n,) becomes (n, 1) against (1, n). Both size-1 axes stretch, and the result has shape (n, n): every prediction minus every target. No error is raised, the mean of that array is a number, and training code will happily minimise it. The example below uses four rows so you can see the effect.

Python · silent_bug.py
import numpy as np

y = np.array([3.0, 5.0, 4.0, 6.0])              # targets, shape (4,)
pred = np.array([[2.5], [5.5], [4.0], [5.0]])   # model output, shape (4, 1)

diff = pred - y
print("diff shape:", diff.shape)                # (4, 4), not (4,)
print("wrong MSE:", np.mean(diff ** 2))
print("right MSE:", np.mean((pred.ravel() - y) ** 2))
assert pred.ravel().shape == y.shape            # a one-line guard against the bug
Expected output
diff shape: (4, 4)
wrong MSE: 2.625
right MSE: 0.375

The wrong value is seven times the right one here, but with real data the two can be close enough to go unnoticed. Three habits keep you safe:

  • Write the expected shape next to the line, as the comments above do, and check it the first time the code runs.
  • Make shapes explicit with .ravel() or .reshape(-1) to get (n,), or .reshape(-1, 1) to get (n, 1). The -1 asks NumPy to work out that size.
  • Assert shapes at function boundaries, for example assert y_hat.shape == y.shape, before you compute a loss.

Predicting shapes becomes quick with practice. For each operation, ask three questions: is it a matrix product (inner sizes must match and vanish) or element-wise (broadcast from the right)? Which axis does a reduction remove? Did an index remove an axis?

06. Check your understanding

Practice check · 3 questions

Predict the shape

Work out each answer on paper before you look at the options.

Q1. `X` has shape (1000, 12): 1,000 customers and 12 features. What is the shape of `X.mean(axis=0)`?
Q2. To centre each row of `X` (shape (100, 3)) on its own mean, a learner writes `X - X.mean(axis=1)`. What happens?
Q3. `A` has shape (3, 4) and `B` has shape (5, 4): 3 queries and 5 documents with 4 features each. Which expression gives one dot-product score for every query–document pair?
Practice only: not graded, not saved, not evidence.

07. Apply it

This skill ends with a practice project: fit linear regression in pure NumPy on a real dataset and compare it with scikit-learn. Prepare its data layer now.

  1. Load the diabetes dataset that ships with scikit-learn: from sklearn.datasets import load_diabetes and X, y = load_diabetes(return_X_y=True). Write down the shapes you expect, then print them.
  2. Standardise X with broadcasting, as in this lesson, and check that every column mean is close to 0 with np.allclose.
  3. Create a random weight vector with np.random.default_rng(0).normal(size=X.shape[1]), compute predictions and a mean squared error, and add an assert on the prediction shape before the loss.

08. Review prompt

Without looking back, explain in your own words: what the shape (n, d) of a dataset means; why X @ w gives one number per row while X * w does not; the broadcasting rule, using (4, 3) with (3,) and (4, 3) with (4,) as examples; and why subtracting a (500,) target vector from (500, 1) predictions gives a wrong loss instead of an error.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check