Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

From Logistic Regression to a Neural Network

See logistic regression as a single neuron, find out why stacking linear layers alone adds nothing, add a hidden layer with a non-linear activation to fit data a straight line cannot, and run the four moves of every training step (forward pass, loss, backward pass, optimizer step) in PyTorch.

Contentsand lesson path

What you will learn

  • Explain how a forward pass, a loss, backpropagation and an optimizer step update the weights, and inspect gradients with PyTorch autograd.

Prerequisites: Machine Learning Fundamentals, Linear Algebra & Calculus for ML

01. Why it matters

Neural networks can sound like a new kind of model, but the first step from what you already know is small. Logistic regression, from the ML fundamentals lessons, computes a weighted sum of the inputs and squashes it into a probability. A neural network does the same thing many times over, in layers, with a non-linear function between the layers. That one change lets it fit curved decision boundaries and, with enough layers and data, images, sound and text.

This lesson builds that bridge with code you can run. You will compute a single neuron by hand in NumPy, show that two linear layers without anything between them collapse into one, and train a small network in PyTorch on data that logistic regression cannot separate. Along the way you meet the four moves that every training step repeats, which the rest of this skill takes apart one by one.

You need: Python 3.12, PyTorch 2 (the CPU build is enough: pip install torch --index-url https://download.pytorch.org/whl/cpu) and scikit-learn 1.9.

02. Logistic regression is one neuron

A neuron takes an input vector x, multiplies it by a weight vector w, adds a bias b and passes the result through an activation function. The weighted sum z = w · x + b is called the pre-activation. With the sigmoid activation σ(z) = 1 / (1 + e^(−z)), the output lies between 0 and 1 and can be read as a probability. That is exactly logistic regression.

To train it you need a loss: one number that says how wrong the predictions are. For yes/no labels the usual choice is binary cross-entropy, the average of −log(p) for positive examples and −log(1 − p) for negative ones. It punishes confident mistakes hard: predicting 0.01 for a true positive costs −log(0.01) ≈ 4.6, while predicting 0.9 costs only 0.11.

Python · neuron.py
import numpy as np

# One neuron = logistic regression: weighted sum, then a squashing function
w = np.array([0.8, -0.5])
b = -0.1
X = np.array([[1.0, 0.0], [0.0, 2.0], [2.0, 1.0]])
y = np.array([1, 0, 1])

z = X @ w + b                      # pre-activation, one number per example
p = 1 / (1 + np.exp(-z))           # sigmoid turns it into a probability
loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))  # binary cross-entropy
print("z    =", z.round(3))
print("p    =", p.round(3))
print(f"loss = {loss:.4f}")
Terminal
python neuron.py
Expected output
z    = [ 0.7 -1.1  1. ]
p    = [0.668 0.25  0.731]
loss = 0.3346

The first example has z = 0.8 × 1 − 0.5 × 0 − 0.1 = 0.7 and a probability of 0.668. All three predictions lean the right way, so the loss is modest. Training means changing w and b so that this loss falls, which needs the slope of the loss with respect to each weight: its gradient.

03. Layers, and why they need a non-linearity

A layer is many neurons side by side, each with its own weights, all reading the same input. In PyTorch, nn.Linear(2, 16) is a layer of 16 neurons with 2 inputs each: a 16 × 2 weight matrix plus 16 biases. A multilayer perceptron (MLP) chains such layers: the outputs of one layer are the inputs of the next. The layers between input and output are hidden layers.

Chaining is only useful if something non-linear sits between the layers. Without it, two linear layers compute W₂(W₁x + b₁) + b₂, which is one matrix times x plus one bias: a single linear layer in disguise. The script below checks this numerically.

Python · stacked.py
import torch
from torch import nn

torch.manual_seed(0)
two_linear = nn.Sequential(nn.Linear(2, 16), nn.Linear(16, 1))
with torch.no_grad():
    W1, b1 = two_linear[0].weight, two_linear[0].bias
    W2, b2 = two_linear[1].weight, two_linear[1].bias
    W, b = W2 @ W1, W2 @ b1 + b2          # the same map as ONE linear layer
    x = torch.tensor([[0.5, -1.0], [2.0, 3.0]])
    print("two layers:", two_linear(x).squeeze().round(decimals=4))
    print("one layer: ", (x @ W.T + b).squeeze().round(decimals=4))
Terminal
python stacked.py
Expected output
two layers: tensor([-0.0257,  0.0055])
one layer:  tensor([-0.0257,  0.0055])

The two outputs are identical, so the extra layer added nothing. An activation function between the layers breaks this collapse. Three are common. Sigmoid squashes to (0, 1), tanh to (−1, 1), and ReLU (rectified linear unit) returns max(0, z). Their slopes matter as much as their values, because training multiplies slopes together, as you will see in the next lesson.

Python · activations.py
import torch

z = torch.tensor([-4.0, -1.0, 0.0, 1.0, 4.0], requires_grad=True)
print("z        ", z.detach().numpy())
functions = {"sigmoid": torch.sigmoid, "tanh": torch.tanh, "relu": torch.relu}
for name, fn in functions.items():
    out = fn(z)
    (slope,) = torch.autograd.grad(out.sum(), z)  # derivative at each z
    value, slope = out.detach().numpy().round(2), slope.numpy().round(2)
    print(f"{name:<8} ", value, " slope", slope)
Terminal
python activations.py
Expected output
z         [-4. -1.  0.  1.  4.]
sigmoid   [0.02 0.27 0.5  0.73 0.98]  slope [0.02 0.2  0.25 0.2  0.02]
tanh      [-1.   -0.76  0.    0.76  1.  ]  slope [0.   0.42 1.   0.42 0.  ]
relu      [0. 0. 0. 1. 4.]  slope [0. 0. 0. 1. 1.]

The sigmoid slope is at most 0.25 and almost zero for large |z|; tanh is steeper near zero but also flattens out. ReLU has slope 1 for every positive input and 0 for negative ones, which is one reason it is the default in hidden layers today. Sigmoid survives at the output of yes/no models, where you want a probability.

04. Training a small network: the four moves

The two-moons dataset has two interleaved crescents. No straight line separates them, so logistic regression has a ceiling. The network below has one hidden layer of 16 ReLU neurons and one output neuron. Its training loop repeats four moves:

  1. Forward pass: run the inputs through the network to get predictions, here logits (raw scores before the sigmoid).
  2. Loss: compare predictions with the labels. BCEWithLogitsLoss applies the sigmoid and the binary cross-entropy in one numerically stable step.
  3. Backward pass: loss.backward() computes the gradient of the loss with respect to every weight.
  4. Optimizer step: opt.step() moves each weight a little against its gradient. Plain SGD (stochastic gradient descent) subtracts the learning rate times the gradient. opt.zero_grad() clears the previous gradients first, for a reason the next lesson shows.
Python · moons.py
import torch
from sklearn.datasets import make_moons
from sklearn.linear_model import LogisticRegression
from torch import nn

X, y = make_moons(n_samples=1000, noise=0.2, random_state=0)
X_tr, X_te, y_tr, y_te = X[:800], X[800:], y[:800], y[800:]
logreg = LogisticRegression().fit(X_tr, y_tr)
print(f"logistic regression test accuracy: {logreg.score(X_te, y_te):.3f}")

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 1))
opt = torch.optim.SGD(model.parameters(), lr=0.5)
loss_fn = nn.BCEWithLogitsLoss()  # sigmoid + binary cross-entropy, computed stably
Xt = torch.tensor(X_tr, dtype=torch.float32)
yt = torch.tensor(y_tr, dtype=torch.float32)
for step in range(1, 2001):
    logits = model(Xt).squeeze(1)  # 1. forward pass
    loss = loss_fn(logits, yt)     # 2. loss
    opt.zero_grad()
    loss.backward()                # 3. backward pass: gradients of every weight
    opt.step()                     # 4. update the weights
    if step in (1, 10, 100, 500, 2000):
        print(f"step {step:4d}  training loss {loss.item():.4f}")
with torch.no_grad():
    pred = model(torch.tensor(X_te, dtype=torch.float32)).squeeze(1) > 0
acc = (pred.numpy() == y_te).mean()
print(f"neural network test accuracy: {acc:.3f}")
print("parameters:", sum(p.numel() for p in model.parameters()))
Terminal
python moons.py
Expected output
logistic regression test accuracy: 0.855
step    1  training loss 0.6792
step   10  training loss 0.4676
step  100  training loss 0.2797
step  500  training loss 0.1363
step 2000  training loss 0.0797
neural network test accuracy: 0.960
parameters: 65

Logistic regression stops at 0.855 because its decision boundary is a straight line, whatever its weights. The network reaches 0.960 with only 65 parameters: (2 × 16 + 16) in the hidden layer and (16 + 1) in the output layer. Each hidden ReLU neuron contributes a bend, and the output neuron combines the bends into a curved boundary. Note that this loop uses all 800 rows in every step, which is full-batch gradient descent; real training uses small random mini-batches, as the lab later in this skill does.

For other tasks only the last layer and the loss change. For a numeric target (a price, a duration), the output neuron has no activation and the loss is usually mean squared error (nn.MSELoss). For k classes, the output layer has k neurons producing logits, and nn.CrossEntropyLoss applies the softmax and the cross-entropy together, so you feed it the raw logits and the class indices.

05. Check your understanding

Practice check · 3 questions

Neurons and layers

Use the scripts and outputs of this lesson.

Q1. In `stacked.py`, two `nn.Linear` layers give exactly the same outputs as a single matrix and bias. What does that show?
Q2. How many trainable parameters does `nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 3))` have?
Q3. On the two-moons data, logistic regression stops at 0.855 test accuracy. Why would training it for longer not get it near the network's 0.960?
Practice only: not graded, not saved, not evidence.

06. Apply it

The practice project for this skill trains an MLP in plain PyTorch. Before you start it, extend moons.py.

  1. Replace nn.ReLU() with nothing (two linear layers) and confirm that accuracy falls to the logistic-regression level.
  2. Try 2, 4 and 64 hidden units and write down the test accuracy and parameter count of each.
  3. Write two sentences on what the hidden layer adds and why the number of parameters alone does not tell you how well a network will do.

07. Review prompt

Without looking back, write the computation of one neuron with a sigmoid activation; explain why two linear layers without an activation equal one; state the largest slope of the sigmoid and the slope of ReLU for positive inputs; name the four moves of a training step and what each does; and say which output layer and loss you would use for a price, a yes/no label and a 10-class label.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check