What is
Deep Learning?
Before using sophisticated neural networks, we need to answer one deceptively simple question: how can a computer improve its predictions by seeing examples?
By the end, you will derive a model's prediction, manually calculate one gradient step, build a trainable linear model from scratch, and explain the same training loop in PyTorch.
AI, machine learning, and deep learning are not the same thing.
Artificial intelligence is the broad field of making systems perform tasks associated with intelligence. Machine learning learns patterns or mappings from data. Deep learning is a class of machine learning models based on neural networks with multiple processing layers.
Artificial Intelligence
Rules, search, planning, statistical learning, and more.
Machine Learning
Learn a predictive or decision function from data.
Deep Learning
Learn layered representations using neural networks.
Example: A shopping site can use hand-written recommendations (rules), a decision tree trained on purchase history (ML), or a neural network that learns from customers' browsing sequences and product embeddings (DL).
Deep learning is not automatically superior. On smaller tabular datasets, simpler models can be cheaper, easier to interpret and highly competitive.
Imagine predicting delivery cost.
You operate a local delivery service. Longer trips typically cost more. Suppose you observe several trips with distance and actual cost. You want a model that can predict the cost of a new trip.
For our teaching example, use the following illustrative data (not real market prices):
1 km → ₹40
Observed example.
3 km → ₹80
Observed example.
5 km → ₹120
Observed example.
We suspect a linear relationship: a fixed base fee plus an additional amount per kilometre. In real systems we would also consider traffic, weather, demand, vehicle type, and other factors.
One equation is your first model.
Read it aloud: predicted cost = (cost per kilometre × distance) + base fee. The letter x is an input, w and b are adjustable parameters, and ŷ is the predicted outcome.
₹20 per km
How strongly increasing distance changes the prediction.
₹20 base fee
The predicted charge even when the distance is zero.
For a 4 km trip:
Interactive: change the parameters
Move the sliders. The plotted line and prediction update from the actual equation ŷ = wx + b.
Points are the three example trips (1,40), (3,80), (5,120). The line represents your chosen parameters; adjust them until they align with the examples.
Linear regression is a useful way to learn training mechanics, but a single linear model is not a deep neural network. Deep networks compose many learned transformations, usually with nonlinear activations.
How does a model actually learn?
Training means changing parameters to reduce a numerical objective computed from training examples. A typical gradient-based process consists of five recurring steps:
Read examples. Provide pairs of inputs x and correct targets y.
Forward pass. Compute ŷ = wx + b with the current parameters.
Calculate loss. Quantify the discrepancy between predictions and targets.
Compute gradients. Determine how sensitive the loss is to each parameter.
Update parameters. Take a controlled step in a direction expected to decrease loss, then repeat.
How do we measure “wrong”?
Suppose the actual delivery cost is ₹100 but our model predicts ₹90. The signed error is 90 − 100 = −10. If we average signed errors, positive and negative errors can cancel. A common regression loss is mean squared error (MSE).
Plain English: predict every example, subtract its true target, square each difference, and take the average.
For three errors of −10, +5 and +5:
The squared loss has units of currency squared in this example. The root mean squared error (RMSE) restores the original units. MSE is particularly sensitive to large errors; it is not universally the best loss.
Gradient descent is controlled trial and improvement.
A gradient tells us the local direction in which loss increases most rapidly. To decrease the loss, subtract a multiple of that gradient.
Derive one complete gradient step
For a single example with input x = 4, target y = 50, and current w = 8, b = 10:
Predict: ŷ = 8×4 + 10 = 42.
Error: e = 42 − 50 = −8. Squared loss: L = (−8)² = 64.
By the chain rule, dL/dw = 2e×x = 2×(−8)×4 = −64 and dL/db = 2e = −16.
With learning rate η = 0.01, new parameters: w = 8−0.01×(−64) = 8.64, b = 10−0.01×(−16) = 10.16.
New prediction: 8.64×4+10.16=44.72. New loss: (44.72−50)²=27.8784, less than 64.
Interactive: change the learning rate and watch the updates
This simulator minimizes the actual function L(w) = (w − 3)². Its gradient is 2(w − 3), so the precise update is w ← w − η·2(w − 3).
Observe: for this particular quadratic, learning rates between 0 and 1 converge; η = 1 alternates between two points; η > 1 increases the distance from the optimum. This threshold is specific to this objective, not a universal learning-rate rule.
What is backpropagation?
When a network has many layers, computing each parameter gradient independently would be wasteful. Backpropagation efficiently applies the chain rule through the computational graph in reverse, reusing intermediate derivatives.
For our single-example squared error, the pieces are dL/dŷ = 2(ŷ−y) and dŷ/dw = x. Multiplying gives dL/dw = 2(ŷ−y)x. In deeper networks, this multiplication continues backward through every differentiable layer.
Implement training from scratch with NumPy.
We create a tiny, noiseless dataset with y = 20x + 20, intentionally start with incorrect parameters, and optimize them using full-batch gradient descent. Every line has a purpose.
import numpy as np
# Create a reproducible dataset: 1 km costs 40, 3 km costs 80, etc.
# Float64 gives us predictable numerical precision for this tiny experiment.
x = np.array([1., 3., 5., 7.], dtype=np.float64)
y = np.array([40., 80., 120., 160.], dtype=np.float64)
# The model starts out NOT knowing the correct weight and bias.
w = 0.0
b = 0.0
# The learning rate controls how large a parameter update we take.
learning_rate = 0.01
num_epochs = 10000
n = len(x)
for epoch in range(num_epochs):
# FORWARD PASS: calculate a price prediction for each distance.
prediction = w * x + b
# ERROR: positive means overprediction, negative underprediction.
error = prediction - y
# LOSS: a single number measuring average squared error.
loss = np.mean(error ** 2)
# GRADIENTS: exact derivatives of the mean squared error.
# Multiplying by x applies the chain rule to the weight.
dw = (2.0 / n) * np.sum(error * x)
db = (2.0 / n) * np.sum(error)
# PARAMETER UPDATE: move against the loss gradient.
w -= learning_rate * dw
b -= learning_rate * db
if epoch % 2000 == 0:
print(f"Epoch {epoch:5d} | MSE: {loss:.6f}")
print(f"Learned weight: {w:.4f}") # Approximately 20
print(f"Learned bias: {b:.4f}") # Approximately 20
# INFERENCE: use learned parameters for an unseen 4 km trip.
new_distance = 4.0
new_price = w * new_distance + b
print(f"Predicted cost for 4 km: ₹{new_price:.2f}") # ~₹100Why each part exists
Why use arrays instead of calculating each example separately?
NumPy performs vectorized operations for the whole batch. The expression w*x+b predicts multiple examples together; this approach generalizes naturally to matrices in neural networks.
Why does the gradient contain 2/N?
Squaring the error produces a factor of 2 when differentiated, and averaging N squared errors contributes a factor of 1/N.
Why use 10,000 epochs on such a tiny dataset?
We are illustrating convergence toward the exact parameters from a simple initialization. Real applications use held-out validation, stopping criteria, mini-batches and more careful optimization.
Does low training loss guarantee a useful model?
No. This toy dataset was constructed to match a perfect line. Real data contain noise and may be nonlinear. Evaluate on unseen data and look for leakage, data shifts and overfitting.
Build the same model with PyTorch.
PyTorch replaces manual gradient formulas with automatic differentiation. We will use nn.Linear to represent the equation, MSELoss to measure error and SGD to update parameters.
import torch
from torch import nn
# Ensure repeatable parameter initialization where supported.
torch.manual_seed(42)
# Each example has one input feature: delivery distance.
# The shape is (4 samples, 1 feature).
X = torch.tensor([[1.], [3.], [5.], [7.]])
y = torch.tensor([[40.], [80.], [120.], [160.]])
# A linear layer learns one weight and one bias.
# Under the hood it computes a transformed input + bias.
model = nn.Linear(in_features=1, out_features=1)
# MSE is suitable for this numerical regression demonstration.
loss_function = nn.MSELoss()
# SGD updates the learnable parameters using computed gradients.
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(10000):
model.train() # Training mode (important for some layer types).
predictions = model(X) # 1. Forward pass
loss = loss_function(predictions, y) # 2. Calculate loss
optimizer.zero_grad() # 3. Clear old gradients
loss.backward() # 4. Autograd gradients
optimizer.step() # 5. Update parameters
if epoch % 2000 == 0:
print(f"Epoch {epoch:5d} | MSE: {loss.item():.6f}")
# Switch to evaluation mode before predicting on new inputs.
model.eval()
with torch.no_grad():
new_trip = torch.tensor([[4.]])
predicted_price = model(new_trip).item()
print("Learned weight:", model.weight.item())
print("Learned bias:", model.bias.item())
print(f"Predicted 4 km cost: ₹{predicted_price:.2f}")zero_grad() clears accumulated gradients; backward() calculates gradients using the computation graph; step() changes the model's parameters. torch.no_grad() disables gradient recording during this inference example.
Install PyTorch using the environment-specific instructions in the official PyTorch installation selector ↗. This webpage displays code you can copy; Python execution itself happens in your Python environment, not inside the browser.
When simple learning does not work as expected.
Overfitting
Training error falls while new-example performance remains poor. Diagnose using held-out data.
Learning rate
Large updates may oscillate or diverge; tiny updates may learn too slowly.
Bad assumptions
Distance alone cannot capture traffic, route difficulty or demand in a real delivery price model.
Neural networks become valuable when we want to learn more complex nonlinear relationships, representations and dependencies. But architecture is only one part of quality: problem framing, data quality, evaluation and operational constraints matter too.
Hands-on practice and checkpoints.
Tick each task after you can complete it independently. The checkmarks are stored only in your browser.
Explain, don't just memorize.
Practice answering each question out loud, then reveal the model answer.
1. How does machine learning differ from traditional programming?
Traditional programming often uses explicitly authored rules, while ML learns parameterized relationships or decision functions from examples according to an objective. Hybrid systems can combine both.
2. What is a weight, and what is a bias?
A weight controls how an input contributes to a transformation. A bias supplies an adjustable offset. In a linear model, prediction is wx+b.
3. What is the difference between loss and a metric?
A loss is an optimization objective used to update parameters. A metric assesses performance, often in a form useful to the problem. They may coincide (e.g. MSE), but need not.
4. Explain the forward pass, backward pass, and optimizer step.
The forward pass computes outputs and loss; backpropagation calculates parameter gradients; the optimizer modifies parameters according to an update rule.
5. Why is gradient descent called a first-order method?
Because it uses first derivatives (gradients) of the objective, rather than higher-order derivative information such as a full Hessian.
6. Can training loss reach zero but the model still be poor?
Yes. A model may memorize examples, exploit leakage or fail under distribution shift. Held-out evaluation and task-relevant metrics are essential.
7. What happens with a very high learning rate?
Updates can overshoot low-loss regions, oscillate or diverge. The exact behavior depends on objective curvature and the optimizer.
8. What is the chain rule and why does backprop need it?
For a composition L(f(w)), dL/dw=(dL/df)(df/dw). Backprop applies this repeatedly through network operations to compute gradients efficiently.
9. Why use a neural network instead of linear regression?
A multilayer network with nonlinear activations can represent nonlinear relationships that a single linear function cannot. However, added model complexity is not always justified.
10. How would you detect that your model is not learning?
Check inputs and targets, baseline predictions, shapes, finite loss, learning rate, gradient values, whether parameters update, and train/validation behavior.
Go back to official documentation.
Our explanations are original teaching material. Use the following first-party references to validate behavior and explore the full APIs.
PyTorch — Learn the Basics ↗
Official beginner learning pathway · Training, tensors, model building, optimization and saving models.
PyTorch — Automatic Differentiation ↗
Autograd tutorial · How gradients are recorded and computed.
PyTorch — Optimization ↗
Optimization tutorial · A standard training loop.
NumPy — Quickstart ↗
Official NumPy user guide · Arrays, arithmetic and vectorization.
Google — Machine Learning Crash Course ↗
Official ML foundations course · Interactive conceptual exercises.
Dive into Deep Learning ↗
Open deep learning textbook · Mathematical derivations and implementations.