PART I — FOUNDATIONS / LESSON 01 / FIELD NOTES

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?

BEGINNER FRIENDLYMATH EXPLAINED2 INTERACTIVE LABSCOPYABLE CODE
INPUT FEATURESHIDDEN LAYERSPREDICTION
FIG 01. A simplified feed-forward network. Animated lines illustrate the direction of information flow; they do not represent measured learned activations.
Learning promise.

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.

01 / FIELD GUIDE

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.

OUTER FIELD

Artificial Intelligence

Rules, search, planning, statistical learning, and more.

SUBFIELD

Machine Learning

Learn a predictive or decision function from data.

SUBFIELD

Deep Learning

Learn layered representations using neural networks.

ARTIFICIAL INTELLIGENCEMACHINE LEARNINGDEEP LEARNING
FIG 02. Containment relationship: Deep Learning ⊂ Machine Learning ⊂ AI.

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).

Interview nuance

Deep learning is not automatically superior. On smaller tabular datasets, simpler models can be cheaper, easier to interpret and highly competitive.

02 / REAL-LIFE MOTIVATION

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.

STORE🚚CUSTOMERDistance → cost?
FIG 03. The task is supervised regression: predict a numeric target using a known input.

For our teaching example, use the following illustrative data (not real market prices):

TRIP A

1 km → ₹40

Observed example.

TRIP B

3 km → ₹80

Observed example.

TRIP C

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.

03 / MODEL MATHEMATICS

One equation is your first model.

LINEAR PREDICTORy^=wx+b

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.

WEIGHT / w

₹20 per km

How strongly increasing distance changes the prediction.

BIAS / b

₹20 base fee

The predicted charge even when the distance is zero.

For a 4 km trip:

WORKED SUBSTITUTIONy^=20×4+20=100
The model predicts ₹100.

Interactive: change the parameters

Move the sliders. The plotted line and prediction update from the actual equation ŷ = wx + b.

12
10
4
WEIGHT12
BIAS10
PREDICTION₹58

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.

Important distinction

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.

04 / THE LEARNING LOOP

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:

1

Read examples. Provide pairs of inputs x and correct targets y.

2

Forward pass. Compute ŷ = wx + b with the current parameters.

3

Calculate loss. Quantify the discrepancy between predictions and targets.

4

Compute gradients. Determine how sensitive the loss is to each parameter.

5

Update parameters. Take a controlled step in a direction expected to decrease loss, then repeat.

DATAx, yPREDICTŷ = wx + bLOSSerror²GRADIENT∂L/∂θUPDATEθ ← θ − η∇Lrepeat the training cycle
FIG 04. The flow of gradient-based training. The gradient step modifies the model parameters, not the target labels.
05 / ERROR MEASUREMENT

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).

MEAN SQUARED ERRORL(w,b)=1N∑i=1N(wxi+b−yi)2

Plain English: predict every example, subtract its true target, square each difference, and take the average.

For three errors of −10, +5 and +5:

WORKED EXAMPLEMSE=(−10)2+52+523=50

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.

06 / OPTIMIZATION DEMYSTIFIED

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.

THE PARAMETER UPDATE RULEθnew=θold−η∇θL
θ = trainable parameter(s) · η = learning rate · ∇L = gradient

Derive one complete gradient step

For a single example with input x = 4, target y = 50, and current w = 8, b = 10:

1

Predict: ŷ = 8×4 + 10 = 42.

2

Error: e = 42 − 50 = −8. Squared loss: L = (−8)² = 64.

3

By the chain rule, dL/dw = 2e×x = 2×(−8)×4 = −64 and dL/db = 2e = −16.

4

With learning rate η = 0.01, new parameters: w = 8−0.01×(−64) = 8.64, b = 10−0.01×(−16) = 10.16.

5

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).

0.20
-1
0 updates
STEP0
CURRENT w-1.00
LOSS16.00

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.

07 / BRIDGE TO DEEP NETWORKS

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.

x = 4× w+ b− ysquarereverse chain rule / gradientsThe reverse pass tracks how the final loss depends on each operation.
FIG 05. A conceptual computational graph. Each node uses local derivatives to propagate gradients backward.
CHAIN RULE FOR COMPOSED FUNCTIONSdLdw=dLdy^×dy^dw

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.

08 / CODE LAB A

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.

01_numpy_gradient_descent.py · runnable Python
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}")  # ~₹100

Why 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.

09 / CODE LAB B

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.

02_pytorch_training.py · runnable Python
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}")
The critical three PyTorch calls

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.

10 / ENGINEERING REALITY

When simple learning does not work as expected.

PROBLEM 01

Overfitting

Training error falls while new-example performance remains poor. Diagnose using held-out data.

PROBLEM 02

Learning rate

Large updates may oscillate or diverge; tiny updates may learn too slowly.

PROBLEM 03

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.

11 / DO THE WORK

Hands-on practice and checkpoints.

Tick each task after you can complete it independently. The checkmarks are stored only in your browser.

0 / 10 complete
12 / INTERVIEW READINESS

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.

13 / PRIMARY SOURCES

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.