AI

Epoch vs Batch Size vs Iterations: Explained

Epoch vs batch size vs iterations explained with worked numbers: what each means, how they relate, how to choose them and the Keras and PyTorch defaults.

By OmniAI Editorial · Nov 22, 2026 · 13 min read

In epoch vs batch size, the epoch is one full pass of the model through the whole training dataset, while the batch size is how many examples the model looks at before it updates its weights once. An iteration is one of those updates. So if you have 1,000 examples and a batch size of 100, one epoch takes 10 iterations, and training for 5 epochs means 50 weight updates.

This guide explains epoch vs batch size vs iterations with worked numbers, answers what is epoch in machine learning and what is batch size in plain language, shows how batch size and learning rate interact, lists the defaults in Keras, PyTorch and Hugging Face, and gives a practical way to choose values for your own model.

Epoch vs Batch Size vs Iterations at a Glance

TermWhat it meansWhat it controlsTypical values
EpochOne complete pass over every training exampleHow many times the model sees the data1 to 3 for fine-tuning large models, tens to hundreds for small models trained from scratch
Batch sizeNumber of examples processed before one weight updateMemory use, speed per update, noise in each update8 to 512 for most tasks; powers of 2 are common
Iteration (step)One forward pass, backward pass and weight update on one batchTotal number of updatesDataset size divided by batch size, per epoch
Iterations per epochBatches needed to cover the dataset onceLength of one epochceil(dataset size / batch size)

The one formula to remember: iterations per epoch = dataset size ÷ batch size, rounded up if the last batch is smaller. Total iterations = iterations per epoch × number of epochs.

What Is Epoch in Machine Learning?

An epoch is one full cycle through the entire training dataset. During an epoch, every training example is used exactly once to compute errors and update the model. If your dataset has 50,000 images, one epoch means the model has seen all 50,000.

Models almost never learn enough from a single look, so training runs for several epochs. After each one, you typically measure performance on a separate validation set to see whether the model is still improving. Keras's documentation defines it the same way: "An epoch is an iteration over the entire x and y data provided."

The word comes from the idea of a period of time: one epoch is one era of training. It has nothing to do with "Unix epoch" time, which is a different term that shares the word.

The number of epochs is a hyperparameter: you choose it before training. Too few epochs and the model underfits, meaning it hasn't learned the patterns yet. Too many and it can overfit, memorizing the training data instead of learning rules that work on new examples. That trade-off is why most training setups use early stopping, which ends training when validation performance stops improving.

What Is Batch Size?

Batch size is the number of training examples the model processes together before it updates its weights once. Instead of updating after every single example or only after the whole dataset, models usually compromise: they take a small group, compute the average error across that group, and adjust.

There are three classic approaches, named after how much data goes into each update:

ApproachBatch sizeUpdates per epochCharacter
Batch gradient descentThe whole dataset1Smooth, exact gradient; slow and memory-hungry
Stochastic gradient descent (SGD)1Equal to the dataset sizeVery noisy; many cheap updates
Mini-batch gradient descentUsually 8 to 512Dataset size ÷ batch sizeThe standard choice; balances speed and stability

Almost all modern training uses mini-batches. When people say "batch size," they mean the mini-batch size. Confusingly, the optimizer is still often called SGD even when it uses mini-batches.

Why not always use the whole dataset? Because it doesn't fit in memory for real datasets, and because a few thousand slightly noisy updates teach a model far faster than one perfect update. Why not use one example at a time? Because GPUs are built to process many examples in parallel, and a batch of one wastes almost all that capacity.

What Is an Iteration?

An iteration, also called a step, is one weight update: the model takes one batch, makes predictions, measures the error, computes gradients with backpropagation and adjusts its weights. Keras calls these "steps," PyTorch training loops usually count them as batches, and Hugging Face calls them "steps" or "global steps."

The relationship between the three terms is fixed:

  • An epoch is made of iterations.
  • Each iteration processes one batch.
  • The batch size decides how many iterations fit in an epoch.
A light stack of cards on the left, an ink arrow to five small grey blocks in a row with the middle one orange, and a curved ink arrow running from the last block back under to the stack.
One epoch splits the dataset into batches; each batch is one iteration.

Epoch vs Batch Size vs Iterations: Worked Example

Take a dataset of 50,000 training images, the size of the CIFAR-10 training set, and train for 20 epochs. Here's how the batch size changes everything else:

Batch sizeIterations per epochTotal iterations in 20 epochsEffect
163,12562,500Many small, noisy updates; slow on a GPU
321,563 (last batch has 16 images)31,260Common default; good balance
6478215,640Fewer updates, smoother gradients
1283917,820Faster per epoch on a GPU, needs more memory
2561963,920May need a higher learning rate to learn as fast
512981,960Very smooth updates; risk of worse generalization without tuning

Two things to notice. First, 50,000 isn't divisible by 32, so the last batch of each epoch has only 16 images. PyTorch keeps that smaller batch by default; setting drop_last=True on the DataLoader drops it, giving 1,562 iterations instead. Second, doubling the batch size halves the number of updates. If you keep the learning rate and epochs the same, a bigger batch means the model takes fewer steps and may end up less trained, even though each epoch finishes faster.

A second example from fine-tuning: you have 2,000 instruction examples, a per-device batch size of 8 and gradient accumulation of 4 on one GPU. The effective batch size is 8 × 4 = 32, so one epoch is about 63 optimizer steps (62.5 rounded up), and 3 epochs are about 189 steps. That small number is why fine-tuning runs on small datasets finish in minutes.

Batch Size and Learning Rate

Batch size and learning rate are tightly linked, and changing one without the other is the most common reason a training run that worked suddenly doesn't.

The intuition: with a bigger batch, each gradient is an average over more examples, so it's less noisy. But you also take fewer steps per epoch. To cover the same ground, each step needs to move further, which means a larger learning rate.

The best-known rule comes from a Facebook AI Research paper, "Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour" (Goyal et al.). Its linear scaling rule says: when the minibatch size is multiplied by k, multiply the learning rate by k. Combined with a warmup period that starts with a small learning rate and raises it over the first few epochs, the authors trained ResNet-50 with a batch size of 8,192 on 256 GPUs in about an hour while matching the accuracy of a batch size of 256.

The rule has limits. It works up to a point, then breaks down, and adaptive optimizers like Adam often follow a gentler square-root scaling in practice. A Graphcore study, "Revisiting Small Batch Training for Deep Neural Networks" (Masters and Luschi), went the other way: across CIFAR-10, CIFAR-100 and ImageNet experiments, its best results came with batch sizes between 2 and 32, and larger batches narrowed the range of learning rates that trained stably.

Practical takeaways:

  • If you change the batch size, revisit the learning rate.
  • When scaling the batch up a lot, add warmup.
  • If training becomes unstable after raising the batch size, lower the learning rate before anything else.
Two light panels side by side: the left holds rows of many small grey squares under a jagged ink line, with the last square orange; the right holds four large grey blocks under a smooth ink curve.
Small batches give many noisy updates; large batches give fewer, smoother ones.

Small vs Large Batch Size

Small batch (e.g. 8 to 32)Large batch (e.g. 256 and up)
MemoryLowHigh; may not fit on one GPU
Time per epochSlower; GPU under-usedFaster; better hardware use
Gradient noiseHigh, acts as mild regularizationLow
Updates per epochManyFew
GeneralizationOften good out of the boxCan be worse unless learning rate and schedule are tuned
Typical useSmall datasets, fine-tuning on one GPU, limited memoryLarge-scale training on many GPUs

The noise in small batches isn't purely bad. Random variation in each update can help the model avoid settling into narrow solutions that don't generalize. Research on large-batch training (Keskar et al., "On Large-Batch Training for Deep Learning") linked large batches to "sharp minima" with a generalization gap, which is part of why very large batches need careful tuning. Our guide to the bias variance tradeoff explains why a model that fits training data too precisely can do worse on new data.

How to Choose Batch Size and Epochs

Here's a simple process that works for most projects.

Choosing the batch size:

  1. Start with a common default: 32 for small models, or whatever the model's documentation or fine-tuning recipe uses.
  2. Increase it until you run out of GPU memory, then step back, if you want faster epochs.
  3. If you need a larger effective batch than memory allows, use gradient accumulation: process several small batches and sum their gradients before one update.
  4. Whenever you change it a lot, retune the learning rate.

Choosing the number of epochs:

  1. Set a generous upper limit, then use early stopping on a validation set so training ends when validation loss stops improving for a few epochs.
  2. Watch the gap between training and validation loss. If training loss keeps falling while validation loss rises, you're overfitting: stop earlier or add regularization.
  3. For fine-tuning a pretrained model, start with 1 to 3 epochs. More epochs on a small dataset quickly lead to memorization. Our guide on how to fine-tune an LLM covers that case step by step.
  4. For large language model pretraining, the opposite is true: datasets are so large that models often see most data only once, so training is measured in tokens or steps rather than epochs.

These are the defaults you get if you don't set anything, taken from each framework's documentation:

FrameworkDefault batch sizeDefault epochsNotes
Keras model.fit()321steps_per_epoch defaults to dataset size ÷ batch size; data is shuffled before each epoch by default
PyTorch DataLoader1No epochs setting; you write the loopshuffle=False and drop_last=False by default
Hugging Face TrainingArguments8 per device3max_steps overrides epochs; gradient_accumulation_steps defaults to 1; learning rate defaults to 5e-5

Note the PyTorch default of 1: if you forget to set batch_size on a DataLoader, you're doing pure stochastic gradient descent, and training will be very slow. In Hugging Face, the effective batch size is per-device batch size × number of devices × gradient accumulation steps.

A minimal Keras call that sets both:

model.fit(x_train, y_train, batch_size=64, epochs=20, validation_split=0.1)

And the equivalent pieces in PyTorch:

from torch.utils.data import DataLoader

loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
for epoch in range(20):  # one epoch = one pass over loader
    for inputs, labels in loader:  # one iteration per batch
        optimizer.zero_grad()
        loss = loss_fn(model(inputs), labels)
        loss.backward()
        optimizer.step()

Common Mistakes

  • Mixing up epochs and iterations. "Train for 1,000 steps" and "train for 1,000 epochs" differ by a factor of the iterations per epoch, which can be thousands.
  • Raising batch size without touching the learning rate. The run gets faster per epoch but learns less per epoch, and it looks like the model got worse.
  • Comparing runs with different batch sizes by epoch count only. Compare by validation metrics, and keep in mind the number of updates differs.
  • Forgetting to shuffle. Without shuffling, every epoch sees batches in the same order, and if the data is sorted (all cats, then all dogs), each batch is lopsided.
  • Training too many epochs on a small dataset. Validation loss starts climbing while training loss keeps falling: classic overfitting.
  • Assuming the biggest batch that fits is best. It's the fastest per epoch, not necessarily the best model.

If you're new to these ideas, our machine learning for beginners roadmap puts them in the context of the whole training process.

FAQ

What is the difference between epoch and batch size?

An epoch is one full pass over the whole training dataset. Batch size is how many examples are processed before each weight update. The batch size decides how many updates (iterations) one epoch contains.

How many iterations are in one epoch?

Divide the number of training examples by the batch size and round up. With 10,000 examples and a batch size of 64, one epoch has 157 iterations, the last one with only 16 examples unless you drop incomplete batches.

Is a larger batch size better?

Not automatically. Larger batches use the hardware better and finish epochs faster, but they make fewer updates and often need a higher learning rate and warmup to reach the same accuracy. Many models generalize well with batch sizes between 16 and 128.

How many epochs should I train for?

There's no fixed number. Use early stopping on a validation set. As rough starting points, fine-tuning a pretrained model usually needs 1 to 3 epochs, while small models trained from scratch may need dozens or hundreds.

What is steps per epoch vs batch size?

Steps per epoch is the number of iterations in one epoch, and it equals the dataset size divided by the batch size. In Keras you can set steps_per_epoch yourself, for example with an infinitely repeating dataset, but by default it's calculated from the batch size.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog