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
| Resource | Link |
|---|---|
| Previous | First Keras model |
| Next | CNNs introduction |
| Prerequisites | First 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 totalWHY 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 size | Effect |
|---|---|
| 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:
- Train loss keeps falling — model learning
- Validation loss rises — model memorising noise
| Signal | Diagnosis |
|---|---|
| Train ↓, val ↓ | Healthy learning |
| Train ↓, val flat | May 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:
patience=5— wait 5 epochs without val improvement before stoprestore_best_weights=True— roll back to best epoch, not lastepochs=200— upper cap; early stop usually finishes sooner
Use this when: any .fit() on data under ~50k rows without a fixed epoch budget.
Other regularisation knobs
| Technique | What it does |
|---|---|
EarlyStopping | Stop when val metric stalls |
Dropout(0.3) | Randomly zero 30% of neurons during training |
| Smaller network | Fewer Dense units |
| More data | Best regulariser when possible |
| L2 on weights | kernel_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
- Fix architecture small (16–32 units)
- Train with early stopping — note stopping epoch
- If underfit (train & val both high loss) — add units or train longer
- If overfit (val ↑) — dropout, L2, or fewer units
- Final evaluate on test once
Same discipline as GridSearchCV — don't tune on test.
Epochs vs sklearn
| sklearn | Keras |
|---|---|
.fit() once | .fit(epochs=N) iterative |
| Trees have implicit depth limit | Epochs need explicit limit or early stop |
max_depth controls complexity | Layers + epochs + dropout |
Essential commands
| Command / action | What it does |
|---|---|
epochs=50 | Max training passes |
batch_size=32 | Mini-batch size |
validation_split=0.2 | Internal val set during fit |
EarlyStopping(patience=5) | Stop on val plateau |
restore_best_weights=True | Keep 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