compile, fit, evaluate & predict
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Every Keras model, whether built with the Sequential API, the Functional API or by subclassing, exposes the same four built-in training methods: compile() declares what to optimize and what to report, fit() runs the training loop, evaluate() measures a trained model on held-out data and predict() produces outputs. This page covers their arguments, the data formats they accept, validation, weighting, the History object and the pitfalls that cause silent mistakes. How callbacks plug into fit() is on Callbacks; replacing what happens inside one step is on Customizing fit() with train_step; writing the loop yourself is on Writing a Training Loop from Scratch. Model building is on Sequential & Functional Models; the individual losses, metrics and optimizers are on Losses, Metrics and Optimizers & Learning-Rate Schedules.
It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming and not covered) and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31; the signature listings match inspect.signature of the installed keras.Model. Snippets that continue an earlier example, or use names such as model and x_batch defined elsewhere, were run with small synthetic stand-ins. The general theory of the training loop is in Training Deep Networks; the equivalent PyTorch hand-written loop is on the PyTorch training loop page.
The big picture
fit() is a loop over epochs and batches. For each batch it calls an internal train_step: a forward pass, a loss computation, a gradient computation, an optimizer update and a metric update. After each epoch it optionally runs validation, then lets callbacks react (checkpointing, early stopping, learning-rate changes). evaluate() and predict() use the same machinery without the gradient part.
The same compiled model can be reused: evaluate() and predict() do not touch the weights, and calling fit() again continues from the current weights and optimizer state (use initial_epoch to keep epoch numbering consistent).
A complete example
import numpy as np
import keras
from keras import layers
# Python 3.13, TensorFlow 2.21, Keras 3.15
rng = np.random.default_rng(0)
x = rng.normal(size=(2000, 20)).astype("float32")
y = (x[:, :3].sum(axis=1) > 0).astype("float32") # binary labels
x_train, x_val = x[:1600], x[1600:]
y_train, y_val = y[:1600], y[1600:]
model = keras.Sequential([
keras.Input(shape=(20,)),
layers.Dense(64, activation="relu"),
layers.Dense(1, activation="sigmoid"),
])
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=1e-3),
loss=keras.losses.BinaryCrossentropy(),
metrics=[keras.metrics.BinaryAccuracy(name="acc"),
keras.metrics.AUC(name="auc")],
)
history = model.fit(
x_train, y_train,
batch_size=64,
epochs=10,
validation_data=(x_val, y_val),
verbose=2,
)
print(list(history.history)) # ['acc', 'auc', 'loss', 'val_acc', 'val_auc', 'val_loss'] (order may differ)
results = model.evaluate(x_val, y_val, batch_size=256, return_dict=True)
print(results) # {'acc': ..., 'auc': ..., 'loss': ...}
probs = model.predict(x_val[:5], verbose=0) # NumPy array, shape (5, 1)
single = model(x_val[:5], training=False) # a tensor, preferred for small inputs
compile()
The signature in Keras 3.15 is:
Model.compile(
optimizer="rmsprop",
loss=None,
loss_weights=None,
metrics=None,
weighted_metrics=None,
run_eagerly=False,
steps_per_execution=1,
jit_compile="auto",
auto_scale_loss=True,
)
| Argument | Meaning |
|---|---|
|
An optimizer instance or a string alias such as |
|
A loss instance, a string alias or a plain function |
|
Scalar coefficients (list or dict by output name) that weight each output’s loss in the total, for multi-output models. |
|
Values reported but not optimized. They are computed without sample weights. |
|
Metrics that are evaluated using |
|
Run Python step by step instead of in a compiled graph. Useful for debugging with |
|
Number of batches run per compiled call. See below. |
|
Whether to use XLA/JIT compilation. |
|
With the |
Details that matter in practice:
-
The loss is the single scalar that
fit()minimizes. Any regularization penalties attached to layers (for examplekernel_regularizer) and anyadd_loss()terms are added to it automatically. The reportedlosstherefore includes them, while a metric built from the same loss does not. -
Pick the loss form to match the output.
BinaryCrossentropyfor one sigmoid unit,CategoricalCrossentropyfor one-hot labels,SparseCategoricalCrossentropyfor integer labels. If the last layer has no softmax or sigmoid, passfrom_logits=Trueto the loss; mixing the two up is the most common cause of a model that trains badly without any error. See Information Theory and Losses for why. -
A string alias such as
"accuracy"is resolved from the loss and output shape, which is convenient but can pick a different metric than you intended. When it matters, pass an explicit metric object. -
Trainable variables are collected when you call
compile(). If you changelayer.trainableafterwards, callcompile()again before the nextfit(), otherwise the change is not picked up. This is exactly the freezing and unfreezing pattern used in Transfer Learning & Fine-Tuning. -
Calling
compile()again replaces the optimizer, so its accumulated state (such as Adam moments) is reset.
Multiple outputs, losses and metrics
inputs = keras.Input(shape=(20,))
h = layers.Dense(32, activation="relu")(inputs)
cls = layers.Dense(3, activation="softmax", name="cls")(h)
reg = layers.Dense(1, name="reg")(h)
model = keras.Model(inputs, [cls, reg])
model.compile(
optimizer="adam",
loss={"cls": keras.losses.SparseCategoricalCrossentropy(),
"reg": keras.losses.MeanSquaredError()},
loss_weights={"cls": 1.0, "reg": 0.2},
metrics={"cls": ["accuracy"], "reg": ["mae"]},
)
x = np.random.rand(512, 20).astype("float32")
y_cls = np.random.randint(0, 3, size=(512,))
y_reg = np.random.rand(512, 1).astype("float32")
model.fit(x, {"cls": y_cls, "reg": y_reg}, epochs=2, batch_size=64, verbose=0)
Dictionaries are keyed by output layer names, so name your outputs. The history then contains keys such as cls_accuracy and reg_mae, with val_ variants when validation is used. Check history.history.keys() instead of guessing metric names; the same names are what monitor= in callbacks expects.
steps_per_execution and jit_compile
steps_per_execution=N runs N batches inside one compiled function call. It reduces Python and host-device overhead, which helps on TPUs and for small models where each step is cheap. At most one epoch runs per call and N larger than the epoch is truncated. The side effect is that on_train_batch_begin and on_train_batch_end fire only every N batches, so batch-level callbacks see coarser information. The Keras documentation notes that this option is not supported with the PyTorch backend.
jit_compile="auto" lets Keras compile the step with XLA on the TensorFlow and JAX backends when the model supports it. If a model contains an operation XLA cannot compile, set jit_compile=False rather than debugging cryptic errors. With the PyTorch backend "auto" means eager execution, and True uses torch.compile with the inductor backend. More about XLA is on Performance, XLA & Profiling.
fit()
The signature is:
Model.fit(
x=None, y=None, batch_size=None, epochs=1, verbose="auto", callbacks=None,
validation_split=0.0, validation_data=None, shuffle=True,
class_weight=None, sample_weight=None, initial_epoch=0,
steps_per_epoch=None, validation_steps=None,
validation_batch_size=None, validation_freq=1,
)
Accepted inputs
x can be a NumPy array, a TensorFlow tensor, a list or dict of those for multi-input models, a tf.data.Dataset, a keras.utils.PyDataset (a Sequence-like object), a generator, or (with the PyTorch backend) a DataLoader. For datasets, PyDatasets and generators the y argument must be omitted because the targets are part of each yielded element: a tuple (inputs, targets) or (inputs, targets, sample_weights).
Two rules decide behaviour for non-array inputs:
-
batch_sizemust not be given for datasets, PyDatasets and generators; they are already batched. -
shuffleis ignored for those inputs. Shuffle inside the pipeline, for example withDataset.shuffle(); see Input Pipelines with tf.data and tf.data Performance.
import tensorflow as tf
ds = (tf.data.Dataset.from_tensor_slices((x_train, y_train))
.shuffle(10_000)
.batch(64)
.prefetch(tf.data.AUTOTUNE))
val_ds = tf.data.Dataset.from_tensor_slices((x_val, y_val)).batch(256)
history = model.fit(ds, epochs=5, validation_data=val_ds)
Validation
-
validation_split=0.2holds out the last 20 percent of the arrays before shuffling. It works only for array-like inputs, and because the split is positional, sorted data (for example grouped by class) gives a biased validation set. Shuffle the arrays yourself first. -
validation_datatakes(x_val, y_val)or(x_val, y_val, val_sample_weights), or a dataset, PyDataset or generator. It overridesvalidation_splitwhen both are given. -
validation_freq=Nvalidates every N epochs only; useful when validation is expensive. -
validation_stepslimits how many validation batches are drawn. If only part of the dataset is consumed each time, validation restarts from the beginning, so the same samples are used in every epoch. For an infinitely repeating validation dataset it is required. -
validation_batch_sizedefaults tobatch_sizeand can be larger because no gradients are stored.
During validation the layers run in inference mode: dropout is off and batch normalization uses its moving statistics. The metrics prefixed val_ are therefore not directly comparable to the training metrics, which are running averages over the epoch computed while the weights were still changing. For why the gap between them matters, see Generalization and Regularization and Model Evaluation.
Epochs, steps and infinite datasets
epochs counts passes over the data. initial_epoch is the epoch index to start from, which matters when resuming so that logs and callbacks such as TensorBoard continue the numbering; it does not restore weights or optimizer state by itself. steps_per_epoch defines an epoch as a fixed number of batches. It defaults to the number of samples divided by the batch size when that is known. It is required when the dataset repeats forever (dataset.repeat() without a count): without it training would never finish the first epoch.
infinite = (tf.data.Dataset.from_tensor_slices((x_train, y_train))
.shuffle(10_000).repeat().batch(64).prefetch(tf.data.AUTOTUNE))
model.fit(infinite, epochs=10, steps_per_epoch=len(x_train) // 64,
validation_data=val_ds)
Class weights and sample weights
For imbalanced classification you can make errors on rare classes cost more.
-
class_weight={0: 1.0, 1: 5.0}maps a class index to a weight and applies during training only (validation metrics are unweighted). When the targets have rank 2 or more, they must be one-hot or have a last dimension of 1. -
sample_weightis a per-sample array of shape(samples,), or(samples, timesteps)for per-timestep weights. Fortf.data.Dataset, PyDataset, DataLoader and generator inputs it is not accepted as an argument; return it as the third element of each yielded tuple instead. -
Weights scale the contribution to the loss. They do not affect the plain
metricslist; put metrics inweighted_metricsto have them use the weights.
weights = np.where(y_train == 1, 5.0, 1.0).astype("float32")
# arrays: sample_weight argument
model.fit(x_train, y_train, sample_weight=weights, epochs=3, verbose=0)
# datasets: third tuple element
ds_w = (tf.data.Dataset.from_tensor_slices((x_train, y_train, weights))
.batch(64))
model.fit(ds_w, epochs=3, verbose=0)
model.compile(optimizer="adam", loss="binary_crossentropy",
weighted_metrics=["accuracy"])
Re-weighting is one of several ways to handle imbalance; resampling and threshold selection are discussed in Model Evaluation.
Verbosity and the History object
verbose is 0 (silent), 1 (progress bar) or 2 (one line per epoch); "auto" means 1 for most cases. Use 2 in notebooks that log to files and on batch systems, since the progress bar produces huge logs.
fit() returns a History callback object. Its history attribute maps each metric name to a list with one value per epoch, params holds the fit configuration and epoch the epoch indices. Because the same object is attached automatically, you rarely need to create one.
import matplotlib.pyplot as plt
h = history.history
plt.plot(h["loss"], label="train")
plt.plot(h["val_loss"], label="validation")
plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend()
plt.show()
evaluate()
Model.evaluate(
x=None, y=None, batch_size=None, verbose="auto", sample_weight=None,
steps=None, callbacks=None, return_dict=False, **kwargs,
)
evaluate() runs the model in inference mode over the data and returns the loss and the compiled metrics. By default the result is a scalar (single output, no metrics) or a list; map list values by the order the metrics were given in compile(). Passing return_dict=True is more robust, and the keys match the names you used in compile(). The Keras reference warns that a list result can contain more entries than model.metrics_names shows when compiled metrics have several sub-metrics, which is another reason to prefer the dictionary.
Never evaluate on data that influenced decisions: use a held-out test set that was not used for early stopping, checkpoint selection or hyperparameter search, otherwise the number is optimistic. A comparable procedure for scikit-learn models is described in Model Evaluation.
predict()
Model.predict(x, batch_size=None, verbose="auto", steps=None, callbacks=None)
predict() iterates over x in batches and returns NumPy arrays: one array for a single output, or a list or dict of arrays for several outputs. It does not need targets. Points to remember:
-
The output is the raw model output. For a classifier whose last layer is
Dense(10)without an activation, the result is logits; applysoftmaxor takeargmaxyourself. -
For one small batch that fits in memory, calling the model directly,
model(x, training=False), avoids the per-call overhead ofpredict()and returns a tensor. Keras documentation recommends this for small inputs. Be sure to passtraining=Falseexplicitly, so that Dropout and similar layers run in inference mode. -
stepsis needed for infinite datasets. -
The batch order is deterministic; with a dataset that shuffles on each iteration, the predictions will not line up with your label array. Build a separate, non-shuffled dataset for prediction.
Batch-level methods
For incremental or online learning, or when integrating Keras into a custom loop, use the single-batch helpers:
loss = model.train_on_batch(x_batch, y_batch, return_dict=True)
vals = model.test_on_batch(x_val_batch, y_val_batch, return_dict=True)
out = model.predict_on_batch(x_batch)
train_on_batch() performs one gradient update and returns the loss and metrics; it accepts sample_weight and class_weight. test_on_batch() takes sample_weight but has no class_weight. Metric state accumulates across consecutive calls, so reset it (for example with model.reset_metrics()) before starting a fresh measurement. These methods do not run callbacks, do not shuffle and do not track epochs, which is why most training should use fit() instead.
Reproducibility
Training results change from run to run because of weight initialization, shuffling, dropout and non-deterministic GPU kernels. Call keras.utils.set_random_seed(42) once at the start; it seeds Python, NumPy and the backend. On TensorFlow, tf.config.experimental.enable_op_determinism() makes ops deterministic at some cost in speed. Even then, exact reproducibility across hardware and library versions is not guaranteed. For tracking runs see Experiment Tracking and MLOps.
Common mistakes
-
Forgetting
from_logits=Truewhen the last layer outputs logits, or applying it when it outputs probabilities. -
Using
sparse_categorical_crossentropywith one-hot labels, or the reverse; the shape error is usually clear, but for a single output class it may run and train nonsense. -
Passing
shuffle=Truewith atf.data.Datasetand expecting it to shuffle; it is ignored. -
Expecting
validation_splitto shuffle first. It does not. -
Changing
trainablewithout callingcompile()again. -
Reading
history.history["acc"]when the metric was named"accuracy". Print the keys. -
Using
verbose=1in a non-interactive log; use 2. -
Treating a
model.fit()second call as a fresh training: weights and optimizer state continue. -
Comparing the training loss to the validation loss when the training loss includes regularization terms and a running average over the epoch.
-
Reusing code from older tutorials that relies on
tf.kerasbeing Keras 2: in TensorFlow 2.21tf.kerasis Keras 3. The behaviour differences are on Migrating from Keras 2 to Keras 3.