← Advanced Data Science
TopBottomRead ChapterDownload Notebook

Chapter 1 · Foundations

Tensors and Computational Linear Algebra

How can shape, axes, and operations preserve—or quietly change—the meaning of data?

Deep-learning systems represent observations, parameters, and intermediate calculations as tensors. Before studying gradients or models, you need to read a tensor as structured data: what each axis means, which operations preserve that meaning, and which operations can silently change it.

Learning objectives

  • Interpret scalar, vector, matrix, and higher-order tensor shapes.
  • Create and inspect PyTorch tensors.
  • Predict the results of indexing and shape transformations.
  • Use reductions, broadcasting, and matrix multiplication correctly.
  • Write and check a model input contract.

Essential practice

Use small, visible tensors. Predict each output shape before running code, then connect the result to observations, features, channels, or time.

Further study

Trace a batch × time × features tensor through slicing, permutation, reduction, and a linear transformation while documenting every axis.

Tensor language

Numbers gain meaning from their arrangement

A tensor is a multidimensional array. Its rank in this chapter is the number of axes, and its shape lists the size of each axis in order. A scalar has shape (); a vector might have shape (5,); a matrix might have shape (32, 5). Higher-order tensors let us describe images, sequences, and batches without changing the underlying idea.

Common tensor structures
StructureExample shapePossible meaning
Scalar()One loss value
Vector(5,)Five features for one observation
Matrix(32, 5)Thirty-two observations by five features
Three axes(32, 12, 5)Batch by time by features
Four axes(32, 3, 28, 28)Batch by channels by height by width
Optional mathematics: notation

A matrix \(X\in\mathbb{R}^{n\times p}\) contains \(n\) rows and \(p\) columns. In a typical tabular dataset, \(n\) is the number of observations and \(p\) is the number of features. For a tensor with shape \((n_1,\ldots,n_d)\), the number of stored values is:

\[N_{\mathrm{values}}=\prod_{j=1}^d n_j.\]

Interactive explorer

Give every axis a name

Choose a data type and adjust its dimensions. The diagram and interpretation update together.

Shape
Values
Axis meaning

Indexing and slicing

Select values without losing the story

PyTorch follows zero-based indexing. In a matrix x, x[1, :] selects the second row and every column; x[:, 0] selects every row and the first column. An integer index removes an axis, while a range such as 1:2 preserves it.

\[X[i,j]\quad\text{selects row }i\text{ and column }j.\]

Ellipsis (...) stands for the axes not written explicitly. Negative indices count backward from the end, so -1 selects the final position.

Selected values
Result shape

Shape operations

Reshape, transpose, and permute answer different questions

Reshape

Groups the same sequence of values into new axis sizes. The total number of values must remain constant.

Transpose

Exchanges two axes. For a matrix, it changes rows × columns into columns × rows.

Permute

Reorders several axes, such as converting batch × height × width × channels into batch × channels × height × width.

Original shape
Requested shape

Optional detail: view versus copy

Some shape operations can return a view that shares storage with the original tensor; others may require a copy. For this chapter, use reshape when you need a particular shape and do not build conclusions around storage sharing. Memory layout and contiguity are deferred.

Reductions

State which axis is being summarized

A reduction combines several values. On a matrix shaped observations × features, x.mean(dim=0) produces one mean per feature, while x.mean(dim=1) produces one mean per observation. Omitting dim combines every value into one scalar.

\[\bar x_j=\frac{1}{n}\sum_{i=1}^n x_{ij}.\]

Why keepdim matters

x.mean(dim=1, keepdim=True) retains a size-one axis. The result can be subtracted from the original matrix to center every row with an explicit broadcast-compatible shape.

Broadcasting

Compatibility is checked from the final axis backward

For elementwise operations, PyTorch compares shapes from right to left. Two axis sizes are compatible when they are equal or one of them is 1. Missing leading axes are treated as size 1. Broadcasting avoids manual copying, but it cannot decide whether the alignment is meaningful.

\[a_j=b_j\quad\text{or}\quad a_j=1\quad\text{or}\quad b_j=1.\]
Compatible?
Result

Computational linear algebra

Elementwise multiplication is not matrix multiplication

If \(A\in\mathbb{R}^{m\times k}\) and \(B\in\mathbb{R}^{k\times n}\), then \(AB\in\mathbb{R}^{m\times n}\). The shared inner size \(k\) is combined; the two outer sizes remain.

\[(AB)_{ij}=\sum_{r=1}^k A_{ir}B_{rj}.\]

A dot product combines two vectors into a scalar. A matrix–vector product transforms one feature vector. A matrix–matrix product transforms a batch or composes linear maps. These operations will become the computational core of linear regression and neural-network layers.

Vector norms: measuring size

The \(L_1\) norm adds absolute values, while the Euclidean or \(L_2\) norm is the square root of the sum of squares:

\[\lVert x\rVert_1=\sum_i |x_i|,\qquad \lVert x\rVert_2=\sqrt{\sum_i x_i^2}.\]

For x = torch.tensor([3., 4.]), torch.linalg.vector_norm(x, ord=1) is 7 and torch.linalg.vector_norm(x) is 5. Norms later help quantify errors, parameter size, and changes in gradients.

A reusable debugging habit

Write the input contract before the model

  1. 1.Name the observation unit and every axis.
  2. 2.Write the expected shape using both words and numbers.
  3. 3.Verify dtype and device deliberately.
  4. 4.Inspect one observation, one feature, or one time step.
  5. 5.Check the observed tensor against the model's expected final dimension.
  6. 6.Record every shape-changing operation.

Example input contract

meaning: batch × time × features
expected shape: (32, 12, 5)
dtype: torch.float32
device: cpu
model expects: 5 features at the final axis
checked slice: x[0, -1, :]

Minimal Python

Predict, run, and explain

Each example is independent and bounded. Predict the shape and output before selecting Run.

Create and inspect a feature matrix

import torch

features = torch.tensor(
    [[18, 2, 7], [21, 1, 5]],
    dtype=torch.float32,
)
print(f"shape={tuple(features.shape)}")
print(f"dtype={features.dtype}, device={features.device}")
output

Click Run to see the results.

Select one observation

import torch

x = torch.arange(12).reshape(3, 4)
second_observation = x[1, :]
print(second_observation.tolist())
print(f"shape={tuple(second_observation.shape)}")
output

Click Run to see the results.

Reshape without changing the values

import torch

x = torch.arange(24).reshape(2, 3, 4)
y = x.reshape(6, 4)
print(f"{tuple(x.shape)} -> {tuple(y.shape)}")
print(f"same values={torch.equal(x.flatten(), y.flatten())}")
output

Click Run to see the results.

Reduce along the observation axis

import torch

x = torch.tensor([[1., 2., 3.], [4., 5., 6.]])
column_means = x.mean(dim=0)
print(column_means.tolist())
print(f"shape={tuple(column_means.shape)}")
output

Click Run to see the results.

Add a feature-specific shift

import torch

x = torch.tensor([[1., 2.], [3., 4.]])
shift = torch.tensor([10., 20.])
print((x + shift).tolist())
output

Click Run to see the results.

Compare elementwise and matrix multiplication

import torch

A = torch.tensor([[1., 2.], [3., 4.]])
B = torch.tensor([[2., 0.], [1., 2.]])
print("A * B =", (A * B).tolist())
print("A @ B =", (A @ B).tolist())
output

Click Run to see the results.

Common mistakes

Code can run while the data meaning is wrong

Swapped axes

Symptom: a model receives features × observations.

Check: inspect one row and state what it represents.

Invalid reshape story

Symptom: the element count matches, but unrelated values are grouped as one observation.

Check: name the new axes before reshaping.

Accidental broadcast

Symptom: an operation succeeds along an unintended axis.

Check: align shapes from the right on paper.

Wrong reduction

Symptom: one mean per observation is reported as one mean per feature.

Check: describe what disappears and what remains.

Dtype mismatch

Symptom: an operation fails or silently represents data inappropriately.

Check: print dtype and preserve integer class labels where required.

* versus @

Symptom: a plausible-shaped result implements the wrong calculation.

Check: say “corresponding entries” or “row by column” before coding.

Summary

Shape reasoning is part of model reasoning

  • A tensor combines values, shape, dtype, and device.
  • Axis names come from the data-generating process, not from PyTorch.
  • Indexing selects; reshape regroups; transpose and permute reorder axes.
  • Reductions require an interpretation of the axis being combined.
  • Broadcasting checks compatibility, not substantive meaning.
  • Elementwise multiplication and matrix multiplication implement different mathematical operations.
  • A written input contract catches many errors before training begins.

Next: Chapter 2 adds derivatives and automatic differentiation to the tensor operations established here.

Review

Review questions

1A tensor has shape \((32, 5)\). Give one plausible interpretation of both axes.

One plausible interpretation is 32 observations by 5 features. Shape alone does not establish that meaning; the data contract must name the axes.

2What is the difference between a scalar, vector, matrix, and a three-axis tensor?

They have zero, one, two, and three axes respectively. These names describe structure, not the substantive meaning of the values.

3Why can two tensors with the same shape still represent different kinds of data?

Shape records axis sizes, but not whether an axis means people, features, channels, time steps, or something else.

4What does `x[:, -1, :]` select from a tensor shaped batch × time × features?

It keeps every observation, selects the final time step, and keeps every feature. The result is shaped batch × features.

5When is `reshape` valid?

The original and requested shapes must contain the same total number of values. Semantic validity also requires that the new axes have an intended meaning.

6How does `keepdim=True` help after a reduction?

It retains the reduced axis with size one, which can make later broadcasting explicit and less error-prone.

7Are shapes \((4,3)\) and \((3,)\) broadcast-compatible for addition? Explain.

Yes. Alignment starts from the right, so the size-3 vector matches the final size-3 axis of the matrix and is reused across four rows.

8Why are `A * B` and `A @ B` different?

`A * B` multiplies corresponding entries and normally preserves shape. `A @ B` performs row-by-column multiplication and requires compatible inner dimensions.

9Why should integer class labels usually not be converted automatically to floating-point inputs?

Labels and model inputs play different roles. Many classification losses expect integer class indices even though model inputs and parameters use floating-point values.

10Write four checks for a tensor before it enters a model.

Name the axes, inspect the shape, verify the dtype and device, and inspect a small slice or range for plausible values. Also compare the observed shape with the model's declared input contract.

Terminology

Glossary

Tensor
A multidimensional array whose values share a data type.
Scalar
A tensor with no axes; it contains one value.
Vector
A one-dimensional tensor.
Matrix
A two-dimensional tensor arranged by rows and columns.
Axis
One direction of variation in a tensor.
Shape
The ordered sizes of all tensor axes.
Dimension
A term often used for either an axis or the size of an axis; state the intended meaning.
Rank
In this chapter, the number of tensor axes; this differs from matrix rank.
Dtype
The numeric representation shared by a tensor's values.
Device
The processor and memory location holding a tensor.
Index
A position used to select a value or slice along an axis.
Slice
A selected range of positions from a tensor.
Reshape
A rearrangement of the same number of values into a new shape.
Transpose
An exchange of two axes; for a matrix, rows and columns are exchanged.
Permute
A reordering of three or more axes.
Reduction
An operation such as sum or mean that combines values along one or more axes.
Broadcasting
Automatic alignment of compatible shapes for an elementwise operation.
Elementwise operation
An operation applied to corresponding positions.
Matrix multiplication
A row-by-column operation that contracts a shared inner dimension.
Norm
A nonnegative measure of the size of a vector or tensor.
Batch
A group of observations processed together.

Sources

Key references