Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Keras · Function

compile

Configures a Keras model for training by selecting its optimizer, loss, metrics, and execution settings. Call it before fit(), evaluate(), or other built-in training methods.

How it works

Call compile() after building a model and before training it. It stores the optimizer, loss calculation, metrics, execution settings, and related training configuration that Keras uses during methods such as fit().

Syntax

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)

Parameters

NameTypeDescription
optimizerstring or keras.optimizers.OptimizerOptimizer name or optimizer instance used to update model weights.
lossstring, keras.losses.Loss, or callableLoss name, loss instance, or compatible callable used to calculate training loss.
loss_weightslist, tuple, or dictionaryOptional coefficients for combining multiple loss values.
metricslist or dictionaryMetrics to report during training and evaluation.
weighted_metricslist or dictionaryMetrics that should receive sample weights.
run_eagerlybooleanWhether to execute the training step eagerly instead of using compiled execution.
steps_per_executionintegerNumber of batches executed in one compiled function call.
jit_compileboolean or "auto"Whether to use XLA compilation, or let Keras choose automatically.
auto_scale_lossbooleanWhether to wrap the optimizer with automatic loss scaling when appropriate.

Returns

Returns None; the model is configured in place.

Key points

  • Compilation prepares the model to work with Keras's built-in training workflow.
  • optimizer accepts either a registered optimizer name or an optimizer object.
  • loss can identify a built-in loss by name or provide a loss object.
  • steps_per_execution groups batches into each compiled call to reduce per-call overhead.
  • jit_compile selects whether Keras uses XLA while compiling the model.
  • On the Torch backend, automatic JIT mode uses eager execution by default.

Common mistakes

  • Changing a layer's trainable property after compilation does not affect fit() until the model is compiled again.
  • With JAX or TensorFlow, automatic JIT compilation is enabled when the model supports it; unsupported models fall back to disabled JIT.
  • Increasing steps_per_execution can improve performance, but execution is capped at one full epoch and truncated when it exceeds the epoch size.

Example: Compile a binary classifier

import keras

model = keras.Sequential([
    keras.layers.Dense(1, activation="sigmoid")
])
model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
    loss=keras.losses.BinaryCrossentropy(),
    metrics=[keras.metrics.BinaryAccuracy()],
)

Configures a model's optimizer, loss, and metrics before training.

When to use it

Set the optimizer and objective before calling `fit()`.

Supervised learning

Register accuracy, error, or custom metrics for training and evaluation.

Monitoring training

Use `steps_per_execution` to batch multiple training steps into one compiled call.

Performance tuning

Control automatic or explicit XLA compilation with `jit_compile`.

Backend compilation

Interview questions

QWhat does Model.compile() configure?

compile() configures a model for training by selecting an optimizer, loss, and optional metrics. It also accepts execution controls such as eager execution, steps per execution, JIT compilation, and automatic loss scaling.

Follow-up: How can compilation affect later layer changes? Trainable variables are captured at compilation time, so changing a layer's trainable setting requires compiling again before calling fit().

QWhat forms can the optimizer and loss take?

The optimizer may be supplied by name or as an optimizer instance. The loss may similarly be a recognized string, a loss object, or a callable compatible with Keras's loss interface.

Follow-up: When would an optimizer instance be preferable? Use one when explicit settings such as learning rate or momentum need to be configured rather than relying on the named default.

QHow does jit_compile behave across backends?

jit_compile controls XLA compilation and accepts True, False, or "auto". With JAX and TensorFlow, "auto" enables XLA when supported; with the Torch backend, automatic mode defaults to eager execution.

Follow-up: What is the practical trade-off of run_eagerly=True? It makes debugging easier by executing operations eagerly, but sacrifices the performance benefits of compiled execution.

  • Model.fit
  • Model.evaluate
  • Model.predict
  • keras.optimizers
  • keras.losses
  • keras.metrics

Source: Model training APIs. Checked 2026-10-15.