Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 16.13 — Tensors and PyTorch: A First Look
Python · Example 1 of 3

Gradient descent for a line, in NumPy

Change learning_rate to 0.2, then to 0.5, and watch what happens to the loss. Too large a step overshoots.

A tensor is a NumPy-like array that can run on a GPU and remember how it was computed, so PyTorch can find gradients automatically. Training a neural network is five repeated steps: forward pass, loss, gradients, update, repeat. You can run the whole idea with plain NumPy first.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write mse(y_true, y_pred) using NumPy.

02

Write gradient_step(w, grad, learning_rate) and use it three times to minimise w squared from w = 10.

03

Write linear_forward(batch, W, b) and check the output shape for a batch of 4 with 3 features and 2 outputs.

Explain it without notes

01

What are the five steps of a training loop?

02

What is a tensor, and how does it differ from a NumPy array?

03

What does autograd do, and why do we need it?

04

Your PyTorch model gives different outputs for the same input on repeated calls, and memory grows during evaluation. What are the likely causes and fixes?

Gradient descent for a line, in NumPy
Sign in to run this example in your browser.

Expected output

step   1: loss  33.0000  w 1.400  b 0.500
step  10: loss   0.0137  w 2.069  b 0.804
step  50: loss   0.0012  w 2.020  b 0.942
step 200: loss   0.0000  w 2.000  b 0.999