🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEtensorflow

tensorflow Documentation

LOADING ENGINE...

model.compile()

AI & DATA SCIENCE // model-compile

model.compile() configures a Keras model for training, specifying the optimizer, loss function, and metrics to track.

Syntax

model.compile(optimizer='adam', loss=None, metrics=None)

Deep Dive Course

compile() must be called before fit(), since it's where the model is told how to learn — which optimizer will update its weights, which loss function measures how wrong its predictions are, and which additional metrics, like accuracy, should be tracked and reported during training without directly influencing the weight updates. Optimizer and loss can be passed either as string shortcuts, like 'adam' and 'sparse_categorical_crossentropy', or as actual configured objects, like tf.keras.optimizers.Adam(learning_rate=0.001), when you need to customize their settings.

1Understanding model.compile()

compile() must be called before fit(), since it's where the model is told how to learn — which optimizer will update its weights, which loss function measures how wrong its predictions are, and which additional metrics, like accuracy, should be tracked and reported during training without directly influencing the weight updates. Optimizer and loss can be passed either as string shortcuts, like 'adam' and 'sparse_categorical_crossentropy', or as actual configured objects, like tf.keras.optimizers.Adam(learning_rate=0.001), when you need to customize their settings.

💡

Pass an actual optimizer object like tf.keras.optimizers.Adam(learning_rate=0.001) instead of the string shortcut 'adam' whenever you need to customize settings like the learning rate — the string shortcut always uses that optimizer's default configuration.

editor.html
import tensorflow as tf
from tensorflow.keras import layers, Sequential

model = Sequential([layers.Dense(10, activation='softmax', input_shape=(32,))])
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
print(model.optimizer.__class__.__name__)
localhost:3000

2Practical Example

Here is a real-world application of model.compile() showing how it is used in production TensorFlow code.

editor.html
import tensorflow as tf
from tensorflow.keras import layers, Sequential

model = Sequential([layers.Dense(10, activation='softmax', input_shape=(32,))])
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005),
    loss='sparse_categorical_crossentropy'
)
print(model.optimizer.learning_rate.numpy())
localhost:3000

3Best Practices

Follow these guidelines when working with model.compile():

1. Match the loss function to the label format: sparse_categorical_crossentropy for integer class labels, categorical_crossentropy for one-hot encoded labels

2. Pass a configured optimizer object instead of a string shortcut whenever you need a non-default learning rate or other optimizer setting

3. Include metrics like 'accuracy' in compile() to get them tracked and reported automatically during fit(), instead of computing them manually after training

⚠️

Tip: Pass an actual optimizer object like tf.keras.optimizers.Adam(learning_rate=0.001) instead of the string shortcut 'adam' whenever you need to customize settings like the learning rate — the string shortcut always uses that optimizer's default configuration.

editor.html
import tensorflow as tf
from tensorflow.keras import layers, Sequential

model = Sequential([layers.Dense(10, activation='softmax', input_shape=(32,))])
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
print(model.optimizer.__class__.__name__)
localhost:3000

Examples

Example 01Basic Usage
import tensorflow as tf
from tensorflow.keras import layers, Sequential

model = Sequential([layers.Dense(10, activation='softmax', input_shape=(32,))])
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
print(model.optimizer.__class__.__name__)
Example 02Advanced Example
import tensorflow as tf
from tensorflow.keras import layers, Sequential

model = Sequential([layers.Dense(10, activation='softmax', input_shape=(32,))])
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005),
    loss='sparse_categorical_crossentropy'
)
print(model.optimizer.learning_rate.numpy())

Best Practices

  • Match the loss function to the label format: sparse_categorical_crossentropy for integer class labels, categorical_crossentropy for one-hot encoded labels
  • Pass a configured optimizer object instead of a string shortcut whenever you need a non-default learning rate or other optimizer setting
  • Include metrics like 'accuracy' in compile() to get them tracked and reported automatically during fit(), instead of computing them manually after training

Interview Question

Why does Keras distinguish between the loss function and the metrics passed to compile(), when both are often computed from the same predictions and labels?

Hint: Think about which one actually drives weight updates and which is purely informational.

The loss function is the single value that backpropagation actually differentiates with respect to the model's weights, making it the quantity that directly drives every weight update during training — it must be a differentiable function of the predictions. Metrics, in contrast, are computed purely for the developer's own monitoring, reported after each batch or epoch to track progress like accuracy, but they never feed into the gradient computation and don't need to be differentiable at all, which is exactly why a metric like accuracy, a non-differentiable step-function-like comparison, can be tracked during training even though it could never work as the loss function driving the optimization itself.

Exercises

MediumPractice using model.compile() in a real scenario.
View Solution
import tensorflow as tf
from tensorflow.keras import layers, Sequential

model = Sequential([layers.Dense(10, activation='softmax', input_shape=(32,))])
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
print(model.optimizer.__class__.__name__)

Frequently Asked Questions

Why does Keras distinguish between the loss function and the metrics passed to compile(), when both are often computed from the same predictions and labels?

The loss function is the single value that backpropagation actually differentiates with respect to the model's weights, making it the quantity that directly drives every weight update during training — it must be a differentiable function of the predictions. Metrics, in contrast, are computed purely for the developer's own monitoring, reported after each batch or epoch to track progress like accuracy, but they never feed into the gradient computation and don't need to be differentiable at all, which is exactly why a metric like accuracy, a non-differentiable step-function-like comparison, can be tracked during training even though it could never work as the loss function driving the optimization itself.

Related Functions

model-fittf-keras-sequentiallosses-categoricalcrossentropy