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

TensorFlow · Module

model.compile

Configures a Keras model for training by specifying its optimizer, loss, and metrics. Optional settings control weighting, execution mode, batches per function call, XLA compilation, and mixed-precision loss scaling.

How it works

Calling compile configures a Keras model for training by selecting an optimizer, loss calculation, and optional metrics. It can also control weighted metrics, eager execution, batches processed per traced call, XLA compilation, and automatic loss scaling before fit is used.

Syntax

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
optimizerstr or keras.optimizers.OptimizerOptimizer name or optimizer instance used for training.
lossstr, keras.losses.Loss, or callableLoss name, Loss instance, or callable taking y_true and y_pred.
loss_weightslist, dict, or NoneOptional scalar or per-output loss weighting.
metricslist, dict, or NoneMetrics reported during training and evaluation.
weighted_metricslist, dict, or NoneMetrics calculated with sample weighting.
run_eagerlyboolWhether to execute the training step eagerly.
steps_per_executionintNumber of batches processed per tf.function call.
jit_compilebool or strWhether to use XLA compilation; auto chooses based on support.
auto_scale_lossboolWhether to wrap the optimizer with loss scaling for mixed precision.

Returns

None; configures the model in place.

Key points

  • Use compile after constructing the model and before calling fit to establish its training configuration.
  • The optimizer accepts either a registered optimizer name or an optimizer object.
  • A custom loss callable receives true targets first and model predictions second.
  • jit_compile selects whether the training computation should use XLA compilation.
  • The auto JIT mode enables XLA when supported by the JAX or TensorFlow model.
  • steps_per_execution determines how many batches are processed by one function invocation.

Common mistakes

  • The automatic JIT setting can turn XLA on or off depending on whether the model supports it, so behavior is not guaranteed to be identical across models.
  • steps_per_execution groups multiple batches into each traced function call; choose it with care because callbacks may not run once per individual batch.

Example: Compile a binary classifier

import tensorflow as tf

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

Creates a binary-classification model and configures its optimizer, loss, and accuracy metric.

When to use it

Set the training objective

Supervised classification or regression

Balance output losses

Multi-output networks

Enable automatic loss scaling

Mixed-precision training

Control execution and XLA

Performance experimentation

Interview questions

QWhat does Model.compile do?

compile configures a model for training. Its main choices are the optimizer, loss, and metrics; after configuration, training is typically performed with fit.

Follow-up: How would you configure different losses for multiple outputs? Pass a loss structure matching the model outputs and use loss_weights to control each output's contribution.

QWhat are the primary compile arguments?

optimizer may be an optimizer name or instance, while loss may be a loss name, Loss instance, or callable receiving y_true and y_pred. Metrics can be supplied to report evaluation measures during training and evaluation.

Follow-up: What is the distinction between metrics and weighted_metrics? weighted_metrics applies sample weights to metric calculations, whereas ordinary metrics do not use those weights in the same way.

QHow does jit_compile interact with compile?

jit_compile controls XLA compilation of the model's training step. With the TensorFlow backend, auto enables XLA when the model supports it and otherwise disables it.

Follow-up: When would run_eagerly help? It can make debugging easier by executing the training step eagerly, at the cost of graph execution optimizations.

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

Source: tf.keras.Model | TensorFlow v2.16.1. Checked 2026-10-15.