The Problem: Every Number Lives in a Tensor
In the training script from the previous lesson, the inputs, the targets, the predictions, the loss and every weight in the model were tensors. A tensor is PyTorch's container for numbers: a block of values arranged along one or more dimensions, all of one type, stored in one place. Most errors in deep learning code are tensor mistakes: the wrong shape, the wrong type of number, or two tensors that cannot be combined. This lesson teaches you to create tensors and to read the three properties that cause those mistakes: shape, dtype and device.
A Bridge from NumPy
If you have used NumPy arrays, tensors will feel familiar. Check yourself before continuing. For the array below, predict the three shapes, then read the answers underneath.
import numpy as np
a = np.arange(12).reshape(3, 4) # 3 rows, 4 columns
a.shape # ?
a[0].shape # ?
a[:, 1:3].shape # ?
(3, 4), then (4,) because one row of four values remains, then (3, 2)
because every row is kept and columns 1 and 2 are selected. If those came
easily, you are ready. If not, practise NumPy indexing first: the next three
lessons build on it.
Shape, dtype and Device

What a tensor carries. The top half shows the three properties; the bottom half shows which tensors share memory with a NumPy array.
Shape lists the size of each dimension. The grid above has shape
(3, 4): dimension 0 has 3 entries (the rows) and dimension 1 has 4 (the
columns). A single number has shape (), a list of five numbers (5,), and
a batch of 64 greyscale images of 28 by 28 pixels (64, 1, 28, 28).
t.shape reports it, t.ndim gives the number of dimensions and
t.numel() the number of values.
dtype is the type of every value in the tensor (S27). Three matter most in this course:
| dtype | Holds | Used for |
|---|---|---|
torch.float32 | Decimal numbers, 32 bits each | Inputs, weights, predictions, losses: PyTorch's default for decimals |
torch.float64 | Decimal numbers, 64 bits each | What NumPy creates by default; occasionally for precise checks |
torch.int64 | Whole numbers | Class labels and counts |
Simple arithmetic between different dtypes is allowed: PyTorch promotes
both to a common type, so int64 + float32 gives float32. Matrix
multiplication, which every layer performs, is stricter and needs matching
dtypes. A model's weights are float32, so its inputs must be too.
device is where the values are stored: cpu means the computer's main
memory. Tensors on a GPU would show a different device, and tensors on
different devices cannot be combined. Everything in the core course stays on
cpu.
Ways to Create a Tensor
| You have | Use | Result |
|---|---|---|
| Python numbers or nested lists | torch.tensor([[0, 1], [2, 3]]) | A new tensor; whole numbers become int64, decimals float32 |
| A size and a fill | torch.zeros(2, 3), torch.ones(4), torch.full((2, 2), 7.0) | A tensor of that shape |
| A range | torch.arange(12) | 0, 1, …, 11 as int64 |
| Random values | torch.rand(5) (between 0 and 1), torch.randn(5) (centred on 0) | float32 |
| A NumPy array | torch.from_numpy(array) or torch.as_tensor(array, dtype=...) | See below |
.reshape(3, 4) rearranges the same values into a new shape; the next
lesson explains it fully (S26).
NumPy arrays need care. torch.from_numpy(array) does not copy the
data: the tensor and the array share the same memory, so changing one
changes the other
(S31).
It also keeps NumPy's dtype, and NumPy's default for decimals is float64.
Going the other way, t.numpy() on a CPU tensor also shares memory
(S32).
Two ways to break the link:
.clone()makes an independent copy with the same dtype.torch.as_tensor(array, dtype=torch.float32)converts tofloat32, which requires a new block of memory.
Exercise: Predict, Then Inspect
Starting state: the course environment active.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/pytorch-practice/tensor-basics cd ~/pytorch-practice/tensor-basicsWindows PowerShell:
mkdir $HOME\pytorch-practice\tensor-basics cd $HOME\pytorch-practice\tensor-basics -
Save this as
tensor_basics.py:"""Create tensors in several ways, then inspect shape, dtype, device and memory.""" import numpy as np import torch grid_a = torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) grid_b = torch.arange(12).reshape(3, 4) array = np.arange(12, dtype=np.float64).reshape(3, 4) grid_c = torch.from_numpy(array) for name, t in [("grid_a", grid_a), ("grid_b", grid_b), ("grid_c", grid_c)]: print(f"{name}: shape {tuple(t.shape)}, dtype {t.dtype}, device {t.device}") print("Python floats:", torch.tensor([1.0, 2.0]).dtype) print("zeros(2, 3):", torch.zeros(2, 3).dtype, tuple(torch.zeros(2, 3).shape)) print("rand(5):", torch.rand(5).dtype) print("class labels:", torch.tensor([0, 2, 1]).dtype) array[0, 0] = 100.0 print("grid_c[0, 0] after changing the array:", grid_c[0, 0].item()) independent = torch.from_numpy(array).clone() array[0, 0] = 0.0 print("clone[0, 0] after changing the array again:", independent[0, 0].item()) converted = torch.as_tensor(array, dtype=torch.float32) print("as_tensor with float32:", converted.dtype, "| shares memory:", converted.data_ptr() == grid_c.data_ptr()) -
Before running, write your predictions for each printed value: the three dtypes of the grids, the four dtypes on the next lines, and the two
[0, 0]values. Then run it:python tensor_basics.pyOutput (exact; these values do not vary between computers):
grid_a: shape (3, 4), dtype torch.int64, device cpu grid_b: shape (3, 4), dtype torch.int64, device cpu grid_c: shape (3, 4), dtype torch.float64, device cpu Python floats: torch.float32 zeros(2, 3): torch.float32 (2, 3) rand(5): torch.float32 class labels: torch.int64 grid_c[0, 0] after changing the array: 100.0 clone[0, 0] after changing the array again: 100.0 as_tensor with float32: torch.float32 | shares memory: False
Success: your predictions match after at most one revision, and you can say why each line printed what it did.
How the Script Works
- Three grids, two dtypes.
grid_acomes from Python whole numbers andgrid_bfromarange, so both areint64.grid_ccomes from a NumPy array made withdtype=np.float64, andfrom_numpykeeps that type. tuple(t.shape)prints the shape as a plain tuple,(3, 4), rather than PyTorch'storch.Size([3, 4]). They mean the same thing.- The four single lines show the defaults: Python decimals become
float32,zerosandrandmakefloat32, Python whole numbers becomeint64. array[0, 0] = 100.0changes the NumPy array, andgrid_c[0, 0]now reads 100.0 too, becausefrom_numpyshared the memory..item()turns a one-value tensor into a Python number.- The clone was taken while the value was 100.0. Setting the array back to 0.0 does not affect it, so it still reads 100.0.
as_tensor(..., dtype=torch.float32)converted the values to 32-bit, which needs new memory.data_ptr()returns the memory address where a tensor's data starts; different addresses mean no sharing.
Your Turn: A Type Mismatch
Save this as layer_input.py in the same folder:
"""Feed NumPy data to a linear layer."""
import numpy as np
import torch
from torch import nn
features = np.random.default_rng(0).normal(size=(4, 3))
layer = nn.Linear(3, 2)
print(layer(torch.from_numpy(features)).shape)
nn.Linear(3, 2) is a layer that turns 3 numbers into 2; its weights are
float32 (S42).
np.random.default_rng(0).normal(size=(4, 3)) makes four rows of three
random NumPy numbers. Run python layer_input.py. It fails, and the
traceback ends with:
RuntimeError: mat1 and mat2 must have the same dtype, but got Double and Float
Fix it with a one-line change so that it prints torch.Size([4, 2]). Then
explain the message: which tensor is Double, and which is Float?
Clean Up
cd ~/pytorch-practice
ls
rm -r tensor-basics
ls
Windows PowerShell:
cd $HOME\pytorch-practice
ls
Remove-Item -Recurse tensor-basics
ls
Check Your Understanding
- You load labels for ten classes with
torch.tensor([3, 7, 1]). What dtype do you get, and is it suitable for labels? - You create
t = torch.from_numpy(a), then normaliseain place witha -= a.mean(). What happens tot? - A batch of 32 colour images of 64 by 64 pixels has three colour channels. Predict its shape in PyTorch's usual layout.
Answer and Reasoning
Your turn
Change the last line to convert the data to float32:
print(layer(torch.from_numpy(features).float()).shape)
torch.as_tensor(features, dtype=torch.float32) works equally well. The
message names the two dtypes in PyTorch's older vocabulary: Double is
float64, from NumPy's default, and Float is float32, the layer's
weights. mat1 and mat2 are the two matrices the layer multiplies: your
input and its weights. A model's inputs must match its weights' dtype, and
converting the data is the usual fix rather than changing the model.
Understanding check
torch.int64, which is what PyTorch's classification losses expect for class labels.tchanges too, becausefrom_numpyshares memory and-=changes the array in place. If you need the original values,clone()before modifying.(32, 3, 64, 64): batch, channels, height, width. PyTorch's image layers expect channels before height and width.