Scope: This article focuses on perceptrons and fully connected feedforward neural networks (multilayer perceptrons, or MLPs). It deliberately does not cover CNNs, RNNs, or Transformers. Numerical tables labeled illustrative are teaching examples, not reported experiment results.
The big idea: learning is a repeated correction
A neural network is not a collection of mysterious rules. It is a mathematical function with adjustable parameters—primarily weights and biases. During training, it makes a prediction, measures how far that prediction is from the correct answer, and adjusts its parameters to improve future predictions.
The essential cycle is:
Input features
↓
Linear layers (weights + biases)
↓
Activation functions
↓
Prediction (forward pass)
↓
Loss function: how wrong was it?
↓
Backpropagation: compute gradients
↓
Optimizer: update weights and biases
↺ Repeat with more training data
There are three distinct jobs worth remembering:
- The loss function measures prediction error.
- Backpropagation calculates how changing each trainable parameter would affect that error.
- The optimizer uses those gradients to update the parameters.
Keeping those jobs separate makes almost every later training concept easier to understand.
1. From one perceptron to one prediction
Start with a single artificial neuron. It takes input values, multiplies them by weights, adds a bias, and applies an activation function.
For two features:
Here,
Let's calculate a simple example:
| Value | Number |
|---|---|
| First input, |
1 |
| Second input, |
0 |
| First weight, |
0.6 |
| Second weight, |
−0.2 |
| Bias, |
−0.3 |
With the classic perceptron's step activation—output 1 when
x1, x2 = 1, 0
w1, w2 = 0.6, -0.2
bias = -0.3
z = x1 * w1 + x2 * w2 + bias
output = 1 if z >= 0 else 0
print(z, output) # 0.3 1
This simple model introduces the ingredients of larger networks. One important distinction: the classic perceptron uses a step function, whereas modern networks generally use activations suitable for gradient-based training.
2. What changes when we add layers?
A feedforward neural network connects many neurons in successive layers. Information moves from the input toward the output:
- Input features describe an example, such as house size, bedrooms, and property age.
- Hidden layers learn intermediate transformations.
- The output layer produces the value or score required by the task.
Consider this small PyTorch model:
import torch.nn as nn
model = nn.Sequential(
nn.Linear(3, 8), # Three inputs → eight hidden neurons
nn.ReLU(), # Nonlinear activation
nn.Linear(8, 4), # Eight neurons → four
nn.ReLU(),
nn.Linear(4, 1), # Four neurons → one output
)
Its architecture is 3 → 8 → 4 → 1. It has two hidden layers, with 8 and 4 neurons. The ReLU() operations are activations, not extra groups of neurons.
Each nn.Linear layer has weights and biases. For a layer with
| Layer | Calculation | Parameters |
|---|---|---|
Linear(3, 8) |
32 | |
Linear(8, 4) |
36 | |
Linear(4, 1) |
5 | |
| Total | 73 |
The network is not specifically a house-price model. Its purpose depends on the training data, target, output design, and loss function. Three numerical inputs and one output could describe house-price regression, a student's predicted score, delivery time, or a binary-classification logit.
Why not just stack linear layers?
If there are no nonlinear activations between them, a stack of linear layers is still equivalent to one linear transformation. Activations allow the network to represent more complex relationships.
Common choices are:
| Activation | What it does | Typical role |
|---|---|---|
| ReLU | Hidden layers | |
| Sigmoid | Maps values into (0, 1) | Convert binary logits to probabilities |
| Tanh | Maps values into (−1, 1) | Some hidden-layer designs |
| Softmax | Converts a vector of logits to class probabilities | Multiclass predictions |
An important PyTorch detail: BCEWithLogitsLoss expects a raw logit, so do not put a sigmoid immediately before that loss. Likewise, CrossEntropyLoss normally receives raw multiclass logits, not probabilities already passed through softmax. For ordinary regression, the final linear layer often has no activation.
3. Forward pass, loss, and backpropagation
A forward pass is simply the computation that produces a prediction. With one linear neuron:
The prediction
For regression, a common choice is mean squared error (MSE):
If an actual value is 10 and the prediction is 8, the squared error for that one example is
| Problem | Common loss | PyTorch example |
|---|---|---|
| Predict a continuous number | Mean squared error | nn.MSELoss() |
| Predict one of two classes | Binary cross-entropy from logits | nn.BCEWithLogitsLoss() |
| Predict one of several classes | Multiclass cross-entropy | nn.CrossEntropyLoss() |
The loss tells us how wrong the prediction is, but it does not update the model. To change parameters, we need gradients.
Backpropagation applies the chain rule of calculus to calculate how the loss depends on each weight and bias. For one neuron with squared-error loss,
we get:
These derivatives are gradients. A basic stochastic gradient descent (SGD) optimizer updates the parameters using a learning rate
In PyTorch, loss.backward() computes the gradients and optimizer.step() applies the update. The learning rate determines the scale of that update: excessively small updates can make training slow, while excessively large ones can overshoot or destabilize it.
4. Watch a neuron learn: three real numerical iterations
The formulas become clearer when we follow the same neuron through three updates. Use a single training example and deliberately simple starting values:
| Setting | Value |
|---|---|
| Input |
1 |
| Actual target |
2 |
| Initial weight |
0 |
| Initial bias |
0 |
| Learning rate |
0.1 |
| Loss | |
| Optimizer | SGD |
Iteration 1. Starting with
Both gradients are
Iteration 2. With
Iteration 3. With
| Iteration | Prediction before update | Loss before update | Weight after update | Bias after update |
|---|---|---|---|---|
| 1 | 0.00 | 4.0000 | 0.400 | 0.400 |
| 2 | 0.80 | 1.4400 | 0.640 | 0.640 |
| 3 | 1.28 | 0.5184 | 0.784 | 0.784 |
After the third update, the next prediction—before another update—would be
That progression is the heart of training: predict → calculate loss → compute gradients → update parameters → predict again. The weight and bias happen to change equally here because
You can reproduce every number without installing any machine-learning library:
x = 1.0
y = 2.0
weight = 0.0
bias = 0.0
learning_rate = 0.1
for iteration in range(1, 4):
prediction = weight * x + bias
loss = (y - prediction) ** 2
grad_weight = 2 * (prediction - y) * x
grad_bias = 2 * (prediction - y)
weight -= learning_rate * grad_weight
bias -= learning_rate * grad_bias
print(
f"Iteration {iteration}: prediction={prediction:.2f}, "
f"loss={loss:.4f}, weight={weight:.3f}, bias={bias:.3f}"
)
This is a deliberately controlled teaching example with one data point. Real training uses many examples and must be evaluated on data not used to fit the model.
5. Translating the learning cycle into PyTorch
The PyTorch equivalent of that learning loop is short:
# Assumes model, train_loader, loss_fn, and optimizer are defined.
for epoch in range(num_epochs):
model.train()
for X_batch, y_batch in train_loader:
optimizer.zero_grad() # Clear previous gradients
predictions = model(X_batch) # Forward pass
loss = loss_fn(predictions, y_batch) # Measure error
loss.backward() # Compute gradients
optimizer.step() # Update weights and biases
Four terms are easy to confuse:
| Term | Meaning |
|---|---|
| Parameter | A learned value, such as a weight or bias |
| Hyperparameter | A chosen setting, such as learning rate or layer width |
| Batch | The examples processed for one optimizer update |
| Epoch | One full pass through the training dataset |
An iteration usually means one optimizer update. With 1,000 training examples and batch size 100, one epoch typically contains 10 iterations.
A small, complete example: learning XOR
XOR has the targets 0, 1, 1, 0 for the binary input pairs (0,0), (0,1), (1,0), and (1,1). One classic linear perceptron cannot learn that pattern, but a multilayer network with a nonlinear activation can.
import torch
from torch import nn
torch.manual_seed(0)
X = torch.tensor([
[0., 0.],
[0., 1.],
[1., 0.],
[1., 1.],
])
y = torch.tensor([[0.], [1.], [1.], [0.]])
model = nn.Sequential(
nn.Linear(2, 8),
nn.Tanh(),
nn.Linear(8, 1),
)
loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)
for epoch in range(1000):
optimizer.zero_grad()
logits = model(X)
loss = loss_fn(logits, y)
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
probabilities = torch.sigmoid(model(X))
print(probabilities)
Notice that the model returns logits and sigmoid is applied after training, for interpretation. This four-example exercise demonstrates training mechanics, not real-world generalization: it evaluates the same examples used for learning.
6. How many hidden layers and neurons should a network have?
In PyTorch you can define deeper models simply by adding layers:
model = nn.Sequential(
nn.Linear(3, 64),
nn.ReLU(),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 16),
nn.ReLU(),
nn.Linear(16, 8),
nn.ReLU(),
nn.Linear(8, 1),
)
That architecture is 3 → 64 → 32 → 16 → 8 → 1 and contains four hidden layers. You choose the depth and width, but more layers are not automatically better. Larger models can express more complex patterns while also consuming more computation and potentially fitting noise in the training data.
There is no universal formula for the ideal layer count. Start with a reasonable small model, compare validation results, and increase capacity only when the evidence supports it.
A useful practical distinction:
- Underfitting: Both training and validation performance remain poor; investigate the data, feature quality, optimization setup, and model capacity.
- Overfitting: Training loss improves while validation performance worsens; investigate regularization, data quality, model size, and when to stop training.
The training set teaches the model. A validation set helps select model settings. A separate test set, held back from tuning, is used for the final performance assessment.
7. The hyperparameters that actually matter
Hyperparameter tuning means selecting settings that govern the model's structure and training process. The network learns its weights and biases; you choose or search over settings such as layer widths and learning rate.
| Area | Hyperparameter | What it controls | Illustrative starting choices |
|---|---|---|---|
| Architecture | Hidden layers | Network depth | 1–4 in small experiments |
| Architecture | Hidden units | Neurons per layer | 8, 16, 32, 64, 128 |
| Architecture | Activation | Nonlinearity | ReLU, Tanh, GELU |
| Training | Learning rate | Parameter-update scale | 0.01, 0.001, 0.0001 |
| Training | Optimizer | Update algorithm | SGD, Adam, AdamW |
| Training | Batch size | Examples per update | 16, 32, 64, 128 |
| Training | Epochs | Maximum complete data passes | 50, 100, 200 |
| Training | Loss function | Which error to minimize | MSE, BCE-with-logits, cross-entropy |
| Regularization | Dropout | Fraction of activations dropped during training | 0.1, 0.2, 0.3 |
| Regularization | Weight decay | Penalty/discouragement for large weights | 0.0001 as an experiment |
| Stability | Gradient clipping | Limit gradient magnitude | max_norm=1.0 when needed |
| Training control | Early-stopping patience | Bad validation epochs tolerated before stopping | 5–10 |
| Training control | Scheduler patience | Bad epochs before an LR adjustment | 2–3 |
| Evaluation | Validation split | Data reserved for tuning/monitoring | 0.2 as a simple starting point |
| Reproducibility | Random seed | Helps reproduce initialization and shuffling | 42 |
These are examples to test, not universal defaults. Some settings (such as class weights, label smoothing, and probability thresholds) apply particularly to classification tasks rather than continuous regression. Normalization layers such as BatchNorm or LayerNorm are additional architecture choices when appropriate.
Dropout: reducing dependence on particular activations
model = nn.Sequential(
nn.Linear(3, 32),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(32, 16),
nn.ReLU(),
nn.Linear(16, 1),
)
nn.Dropout(0.2) randomly zeroes approximately 20% of the activations on each training pass. It may reduce overfitting by discouraging dependence on particular activations. Too much dropout can make a small model underfit.
Use model.train() during training. model.eval() turns dropout off for validation and inference. PyTorch handles the training-time scaling internally.
Weight decay and gradient clipping serve different purposes
optimizer = torch.optim.AdamW(
model.parameters(),
lr=0.001,
weight_decay=0.0001,
)
# In a training step, after loss.backward():
# torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
Weight decay is a regularization technique. Gradient clipping is primarily a training-stability measure; it is not an interchangeable cure for overfitting.
8. A learning-rate scheduler is not early stopping
As training progresses, the learning rate that worked initially might become too large for fine adjustments. A scheduler can reduce it when a monitored metric stops improving.
A common PyTorch choice is ReduceLROnPlateau:
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer,
mode="min", # Lower validation loss is better
factor=0.5, # Halve the learning rate
patience=3,
min_lr=1e-6,
)
# After computing validation loss at the end of each epoch:
# scheduler.step(val_loss)
A sequence of reductions might be 0.001 → 0.0005 → 0.00025, but only when the plateau condition is met; these are not changes that automatically happen every three epochs.
One subtle detail: With PyTorch's ReduceLROnPlateau, patience=3 means it tolerates three bad epochs and normally reduces the learning rate when the bad-epoch count exceeds three—typically on the fourth bad epoch. If the goal is a reduction right after the third consecutive bad epoch, patience=2 is a closer match to that behavior.
Early stopping does something different: it ends training when validation results fail to improve sufficiently. A typical setup might have scheduler patience 3 and early-stopping patience 10, giving the scheduler time to make an adjustment before training stops.
| Feature | Learning-rate scheduler | Early stopping |
|---|---|---|
| Watches validation performance | Often | Often |
| Changes the learning rate | Yes | No |
| Stops training | No | Yes |
| Useful when | Progress plateaus but further improvement may be possible | Continued training no longer seems useful |
When implementing early stopping, track the best validation metric, count consecutive insufficient improvements, and save the best model weights for restoration. A min_delta threshold defines what counts as meaningful improvement. The scheduler may use its own different threshold rules.
9. Tuning architectures: grid search, random search, and Optuna
Neural-network tuning follows the same general logic as GridSearchCV and RandomizedSearchCV in scikit-learn: choose trial configurations, train on training data, compare on validation data, and select the best configuration.
| Approach | Strategy | Tradeoff |
|---|---|---|
| Grid search | Try every specified combination | Simple, but gets expensive as choices multiply |
| Random search | Sample combinations | Covers larger spaces within a fixed trial budget |
| Optuna | Adaptively suggest configurations | Flexible for conditional choices and neural-network experiments |
For example, Optuna can choose the number of hidden layers and neurons per layer:
import optuna
import torch.nn as nn
def objective(trial):
n_layers = trial.suggest_int("layers", 1, 4)
n_units = trial.suggest_categorical("units", [8, 16, 32, 64])
modules = []
in_features = 3
for _ in range(n_layers):
modules += [nn.Linear(in_features, n_units), nn.ReLU()]
in_features = n_units
modules.append(nn.Linear(in_features, 1))
candidate = nn.Sequential(*modules)
# Your own training/validation function must be implemented.
return train_and_evaluate(candidate)
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=30)
print(study.best_params)
This Optuna snippet is an integration pattern, not standalone runnable code: train_and_evaluate is intentionally undefined. It must train the candidate and return a validation loss. For scikit-learn-style wrappers around PyTorch, skorch is another possibility; SciKeras is for Keras rather than native PyTorch networks.
Avoid using the final test set to pick your hyperparameters. Otherwise it becomes another validation set, and the reported final result is less meaningful.
10. Quantization: optimizing the trained model
Training and deployment have different concerns. After you have a useful model, you may want to reduce its memory footprint or improve inference performance. Quantization represents some weights and/or activations using lower-precision formats, such as INT8 rather than FP32.
| Representation | Bits per value | Approximate raw storage for 1 million values |
|---|---|---|
| FP32 | 32 | 4 MB |
| FP16 / BF16 | 16 | 2 MB |
| INT8 | 8 | 1 MB |
| INT4 | 4 | 0.5 MB |
FP16 and BF16 are lower-precision floating-point formats, not integer quantization. These storage figures omit scales, metadata, packing, padding, and other implementation overhead.
Three useful quantization terms:
- Post-training quantization (PTQ): Apply quantization after training.
- Quantization-aware training (QAT): Simulate quantization effects during training so the model can adapt.
- Dynamic quantization: Quantize some values dynamically during inference, depending on the backend and method.
A version-dependent illustration of weight-only INT8 with torchao looks like this:
from torchao.quantization import quantize_, Int8WeightOnlyConfig
# 'model' must already be trained; backend/version compatibility varies.
model.eval()
quantize_(model, Int8WeightOnlyConfig())
That example is not guaranteed to work on every torchao version or hardware backend and does not imply all activations run in INT8. Benchmark inference accuracy, memory, and latency on the actual target device before accepting a quantized model.
Also, the earlier 3 → 8 → 4 → 1 network has only 73 trainable parameters: reducing their precision saves almost nothing in absolute terms. Quantization becomes more compelling when model size and deployment constraints justify it. The underlying principle also appears in LLM quantization, though methods such as GPTQ and AWQ are more specialized.
11. A complete training example: fit a small regression network
The following self-contained educational example ties together layers, nonlinearities, batch training, validation, dropout, AdamW, gradient clipping, a plateau scheduler, and early stopping. It creates synthetic data with three features and one continuous target; it does not download a real dataset or call an external API.
For clarity, this version separates training, validation, and test data, and restores the best validation checkpoint before evaluating the held-out test set.
import copy
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
torch.manual_seed(42)
# Synthetic nonlinear regression: three features, one target.
X = torch.randn(1000, 3)
y = (
2.0 * X[:, :1]
- 1.5 * X[:, 1:2]
+ 0.8 * X[:, 2:3].square()
+ 0.1 * torch.randn(1000, 1)
)
# Keep the test set separate from the training/tuning decisions.
indices = torch.randperm(len(X))
train_idx = indices[:800]
val_idx = indices[800:900]
test_idx = indices[900:]
train_loader = DataLoader(
TensorDataset(X[train_idx], y[train_idx]),
batch_size=32,
shuffle=True,
)
val_loader = DataLoader(
TensorDataset(X[val_idx], y[val_idx]), batch_size=64
)
test_loader = DataLoader(
TensorDataset(X[test_idx], y[test_idx]), batch_size=64
)
model = nn.Sequential(
nn.Linear(3, 32),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(32, 16),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(16, 1),
)
loss_fn = nn.MSELoss()
optimizer = torch.optim.AdamW(
model.parameters(), lr=0.001, weight_decay=0.0001
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, mode="min", factor=0.5, patience=3, min_lr=1e-6
)
def evaluate(data_loader):
model.eval() # Disables dropout
total_loss, total_count = 0.0, 0
with torch.no_grad():
for xb, yb in data_loader:
batch_loss = loss_fn(model(xb), yb)
total_loss += batch_loss.item() * len(xb)
total_count += len(xb)
return total_loss / total_count
best_val_loss = float("inf")
best_state = copy.deepcopy(model.state_dict())
bad_epochs = 0
early_stopping_patience = 10
min_delta = 0.001
for epoch in range(100):
model.train()
for xb, yb in train_loader:
optimizer.zero_grad()
predictions = model(xb)
loss = loss_fn(predictions, yb)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
val_loss = evaluate(val_loader)
scheduler.step(val_loss)
if val_loss < best_val_loss - min_delta:
best_val_loss = val_loss
best_state = copy.deepcopy(model.state_dict())
bad_epochs = 0
else:
bad_epochs += 1
current_lr = optimizer.param_groups[0]["lr"]
print(f"Epoch {epoch + 1:3d} | Val MSE {val_loss:.5f} | LR {current_lr:.6f}")
if bad_epochs >= early_stopping_patience:
print("Early stopping triggered")
break
model.load_state_dict(best_state)
test_mse = evaluate(test_loader)
print(f"Held-out test MSE: {test_mse:.5f}")
Run it with Python and PyTorch installed:
pip install torch
python neural_network_example.py
The test MSE printed by this script is a result of your own run; no specific score is promised here. Real applications also require representative data, leakage-safe preprocessing, task-appropriate metrics, and evaluation of the conditions in which predictions will be used.
12. A practical checklist for diagnosing training
When a model performs poorly, the most productive first question is not always "Should I add more layers?" Look at the pattern in the training and validation metrics.
| What you observe | What to investigate first |
|---|---|
| Training loss barely decreases | Input scaling, target quality, learning rate, gradients, model capacity |
| Training loss oscillates or diverges | Learning rate, data values, batch size, gradient stability |
| Training improves, validation worsens | Overfitting, data quality, dropout, weight decay, smaller architecture |
| Both training and validation remain poor | Underfitting, features, optimization settings, training duration |
| Validation loss stops improving | LR scheduler, early-stopping patience, whether more capacity helps |
| Model is too large or slow for deployment | Size/latency profiling, then quantization if supported |
A reasonable workflow is to define the supervised task → split the data → prepare features without leakage → build a simple network → train and validate → tune deliberately → test on held-out data → optimize deployment if necessary.
Closing thought
A neural network makes more sense once its components stop looking like separate buzzwords. Layers and activations determine what it can represent. Loss and gradients explain what it needs to change. Optimizers and learning rates control how it changes. Validation, regularization, and training controls help determine whether it learned something useful rather than merely memorizing the examples.
Start with one neuron and three parameter updates. Once that is intuitive, the larger PyTorch architecture is the same fundamental learning process repeated across many parameters.

