C.W.K.
Stream
Lesson 01 of 06 · published

model.compile() — Wiring Optimizer, Loss, Metrics

~9 min · compile, optimizer, loss

Level 0Level 0
0 XP0/78 lessons0/17 achievements
0/100 XP to next level100 XP to go0% complete

The configuration step that makes fit() work

Before you can call model.fit(), you must compile() the model. This wires together the optimizer (how weights update), the loss (what we minimize), and metrics (what we monitor). Three choices that determine whether your training works at all.

Use string shortcuts ('adam', 'sparse_categorical_crossentropy') for fast experiments. Use instance objects when you need to tune hyperparameters — learning rate, optimizer beta values, loss class weights, etc.

Code

Compile — string vs instance·python
import tensorflow as tf
from tensorflow import keras

# Quick — string shortcuts
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'],
)

# Tunable — explicit instances
model.compile(
    optimizer=keras.optimizers.Adam(
        learning_rate=1e-3, beta_1=0.9, beta_2=0.999, epsilon=1e-7,
    ),
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=[
        keras.metrics.SparseCategoricalAccuracy(name='accuracy'),
        keras.metrics.TopKCategoricalAccuracy(k=5, name='top5_accuracy'),
    ],
    jit_compile='auto',   # XLA compilation
)

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.