Tensor
Tensors are the fundamental building block of machine learning in PyTorch — learn what they are, how to manipulate them, and how to use them on a GPU.
Goal of the lesson
By the end of this 3-hour session you should be able to:
- explain what a tensor is and why machine learning frameworks are built around it,
- create tensors from Python data, NumPy arrays, and built-in factories,
- inspect and reshape tensors confidently,
- write small numerical programs using broadcasting and matrix multiplication,
- move computation to a GPU,
- read and write
[C, H, W]image tensors and apply simple filters to them.
The tensor is the only data structure deep learning really has. Every model input, every weight, every gradient, every output is a tensor. Spending three hours getting comfortable with them pays off in every chapter that follows.
Suggested timing
| Block | Topic |
|---|---|
| 30 min | Setup, what a tensor is, scalar/vector/matrix/n-dim |
| 30 min | Attributes (shape, dtype, device), factory functions |
| 45 min | Operations: arithmetic, broadcasting, matmul, reshape, indexing |
| 30 min | NumPy interop and GPU |
| 45 min | Capstone — image manipulation with pure tensor ops |
Setup
This series targets Windows with uv as the Python project manager.
If you don’t have uv yet, install it from PowerShell:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Create the project:
uv init --python 3.12 tensor
cd tensor
uv add torch torchvision matplotlib pillow numpyOn Windows the default torch and torchvision wheels from PyPI are CPU-only. That is fine for everything in this chapter.
If you have an NVIDIA GPU and want CUDA, see Using uv with PyTorch and the CUDA page. You will need to point uv at the PyTorch CUDA wheel index.
Check the install:
You're reading a preview.
Sign in to read the full article. Any account opens 10 free articles a month; students and teachers read their course pages without limit.
Sign in