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

Keras · Module

model.compile

Configures a Keras model for training by selecting its optimizer, loss, metrics, and execution behavior. After compilation, the model can be trained and evaluated with the standard Keras APIs.

How it works

Model.compile() stores the optimizer, objective, metrics, and execution settings that Keras uses for training and evaluation. Losses may be named functions or loss objects, metrics can be named or instantiated, and options such as JIT compilation and eager execution control how the training step runs.

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 optimizer instanceOptimizer name or optimizer instance used to update model weights.
lossstring, loss instance, or callableLoss function name, loss object, or callable receiving y_true and y_pred.
loss_weightslist, tuple, or dictionaryOptional scalar weighting factors for combining multiple losses.
metricslistMetrics evaluated during training and testing.
weighted_metricslistMetrics evaluated with sample weighting.
run_eagerlybooleanWhether to run the training step eagerly.
steps_per_executionintegerNumber of batches executed per compiled function call.
jit_compileboolean or "auto"Whether to use XLA compilation for the training step; "auto" selects backend-dependent behavior.
auto_scale_lossbooleanWhether to automatically wrap the optimizer for loss scaling under mixed precision.

Returns

None

Key points

  • Call compile() after constructing a model and before using the standard training APIs.
  • Use weighted_metrics for metrics that should account for sample weights.
  • steps_per_execution controls how many batches run inside one compiled function call.
  • When enabled with mixed-float16, Keras dynamically scales the loss to reduce numerical underflow risk.

Common mistakes

  • Changing a layer's trainable property after compilation does not affect fit() until the model is compiled again.
  • With mixed-float16 and jit_compile=True, Keras automatically applies loss scaling to the optimizer.
  • The default automatic JIT behavior depends on the backend and whether the model supports XLA compilation.

Example: Compile a model for regression

import keras

model = keras.Sequential([
    keras.layers.Dense(1, input_shape=(1,))
])
model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
    loss=keras.losses.MeanSquaredError(),
    metrics=[keras.metrics.MeanAbsoluteError()],
)

Creates a one-output model and configures its optimizer, loss, and metric before training.

When to use it

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

Supervised learning

Register task-appropriate metrics for training and testing reports.

Regression or classification evaluation

Enable or automatically select XLA compilation where the backend and model support it.

Accelerated execution

Use automatic loss scaling with a mixed-float16 dtype policy.

Mixed-precision training

Interview questions

QWhat does Model.compile() do?

compile() configures a model for training by selecting an optimizer, loss, metrics, and execution options. It prepares the model so methods such as fit() and evaluate() can use that configuration.

Follow-up: Why must compilation be repeated after changing layer trainability? Because trainable variables are captured when compile() runs, so later changes are not applied during fit().

QWhich forms can the optimizer and loss take?

The optimizer may be given by name or as an optimizer instance. The loss may likewise be a registered name or a Loss object, and a loss callable receives y_true and y_pred.

Follow-up: When would an optimizer instance be preferable? When explicit optimizer settings, such as a learning rate, must be controlled rather than using defaults.

QHow does jit_compile affect compilation?

jit_compile controls XLA compilation of the model's training step. With the default "auto", JAX and TensorFlow enable XLA when supported, while the Torch backend uses its Inductor path by default.

Follow-up: What should be checked if automatic JIT fails? Disable JIT compilation or identify unsupported operations in the model's training step.

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

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