Rana Maninder Singh
Lesson 4 of 8Deep Learning

Epochs, Batch Size, Early Stopping & Overfitting

Lesson opener

In one line: What an epoch and batch size mean in practice.

Why it matters: Mini-batches add noise that often helps generalisation vs full-batch on small data.

Before this lesson: First Keras model / Applied ML statistics

Before you start

ResourceLink
PreviousFirst Keras model
NextCNNs introduction
PrerequisitesFirst Keras model, Applied ML statistics
Time~50 minutes

What you will learn

  • What an epoch and batch size mean in practice
  • How to read train vs validation loss curves
  • Early stopping — stop training before memorisation
  • Overfitting in neural nets — connection to bias-variance

Epochs and batches — training schedule

Epoch = one complete pass through the training dataset.

Batch size = number of rows per gradient update before weights change.

Dataset: 800 training customers
Batch size: 32
→ 800 ÷ 32 = 25 gradient updates per epoch
50 epochs → 50 × 25 = 1,250 updates total

WHY Mini-batches add noise that often helps generalisation vs full-batch on small data.

WHEN Default batch_size=32 for tabular; try 16 or 64 if memory allows.

Batch sizeEffect
Small (8–16)Noisier updates, slower per epoch
Medium (32–64)Common default
Large (256+)Smoother, needs more memory

Indian workplace example: Training on overnight batch scores for 2 lakh Delhi users — larger batches on GPU; 300-row churn notebook — batch 32 is fine on laptop CPU.


Overfitting — memorising the training set

From Applied ML statistics:

SignalDiagnosis
Train ↓, val ↓Healthy learning
Train ↓, val flatMay need more capacity or features
Train ↓, val ↑Overfitting — stop or regularise

WHY Unlimited epochs on small tabular data often hurts test performance.

WHEN Always plot history.history['loss'] vs val_loss.

import matplotlib.pyplot as plt

# After model.fit(...)
plt.plot(history.history["loss"], label="train")
plt.plot(history.history["val_loss"], label="val")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()
plt.title("Churn model — watch val_loss")
plt.show()

Early stopping — automatic brake

EarlyStopping monitors validation loss and stops when it stops improving.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.callbacks import EarlyStopping

df = pd.read_csv("data/customers.csv")
X = pd.get_dummies(df[["tenure_months", "monthly_spend", "support_tickets", "segment"]], drop_first=True)
y = df["churned"].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)

model = keras.Sequential([
    layers.Input(shape=(X_train_s.shape[1],)),
    layers.Dense(32, activation="relu"),
    layers.Dense(16, activation="relu"),
    layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["AUC"])

early_stop = EarlyStopping(
    monitor="val_loss",
    patience=5,
    restore_best_weights=True,
)

history = model.fit(
    X_train_s, y_train,
    validation_split=0.2,
    epochs=200,
    batch_size=32,
    callbacks=[early_stop],
    verbose=0,
)

print(f"Stopped at epoch {len(history.history['loss'])}")
print(f"Test AUC: {model.evaluate(X_test_s, y_test, verbose=0)[1]:.3f}")

Breaking it down:

Use this when: any .fit() on data under ~50k rows without a fixed epoch budget.


Other regularisation knobs

TechniqueWhat it does
EarlyStoppingStop when val metric stalls
Dropout(0.3)Randomly zero 30% of neurons during training
Smaller networkFewer Dense units
More dataBest regulariser when possible
L2 on weightskernel_regularizer=keras.regularizers.l2(0.001)
layers.Dense(16, activation="relu", kernel_regularizer=keras.regularizers.l2(0.001))
layers.Dropout(0.3),

WHY Tabular churn rarely needs huge nets — regularise before adding layers.

WHEN Val loss diverges from train loss after epoch 10.


Tuning workflow

  1. Fix architecture small (16–32 units)
  2. Train with early stopping — note stopping epoch
  3. If underfit (train & val both high loss) — add units or train longer
  4. If overfit (val ↑) — dropout, L2, or fewer units
  5. Final evaluate on test once

Same discipline as GridSearchCV — don't tune on test.


Epochs vs sklearn

sklearnKeras
.fit() once.fit(epochs=N) iterative
Trees have implicit depth limitEpochs need explicit limit or early stop
max_depth controls complexityLayers + epochs + dropout

Essential commands

Command / actionWhat it does
epochs=50Max training passes
batch_size=32Mini-batch size
validation_split=0.2Internal val set during fit
EarlyStopping(patience=5)Stop on val plateau
restore_best_weights=TrueKeep best epoch weights

Practice

Do this now: Train the churn Keras model with and without EarlyStopping. Plot train vs val loss for both. Record test AUC — did early stopping help? Relate overfitting to bias-variance in two sentences.

Checklist

  • [ ] Epoch vs batch size explained with row counts
  • [ ] Train vs validation loss interpreted
  • [ ] EarlyStopping with restore_best_weights=True
  • [ ] Test set evaluated after tuning on validation only
  • [ ] Next: CNNs introduction