Compiling a model sets up how it learns and measures success. It tells the model how to improve and how to check its progress.
Compiling models (optimizer, loss, metrics) in TensorFlow
Start learning this pattern below
Jump into concepts and practice - no test required
model.compile(optimizer='optimizer_name_or_object', loss='loss_function_name_or_object', metrics=['metric1', 'metric2', ...])
optimizer controls how the model learns (e.g., 'adam', 'sgd').
loss is the function that measures how wrong the model is (e.g., 'sparse_categorical_crossentropy').
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01), loss='mse', metrics=['mse'])
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy', 'Precision'])
This code builds a small neural network, compiles it with Adam optimizer and sparse categorical crossentropy loss, then trains it on random data for 3 epochs. It prints the accuracy after each epoch.
import tensorflow as tf # Create a simple model model = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='relu', input_shape=(5,)), tf.keras.layers.Dense(3, activation='softmax') ]) # Compile the model with optimizer, loss, and metrics model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) # Create some dummy data import numpy as np x_train = np.random.random((20, 5)) y_train = np.random.randint(0, 3, 20) # Train the model history = model.fit(x_train, y_train, epochs=3, verbose=0) # Print training accuracy for each epoch for i, acc in enumerate(history.history['accuracy'], 1): print(f'Epoch {i} accuracy: {acc:.4f}')
You must compile the model before training it.
Choosing the right optimizer and loss depends on your problem type (classification, regression, etc.).
Metrics help you understand how well the model is doing during training.
Compiling sets how the model learns and measures success.
Optimizer controls learning steps, loss measures error, metrics track performance.
Always compile before training your model.
Practice
compile() method in a TensorFlow model?Solution
Step 1: Understand the role of
Thecompile()compile()method prepares the model for training by specifying how it learns and how performance is measured.Step 2: Identify what
It sets the optimizer (how the model updates weights), the loss function (how error is calculated), and metrics (how performance is tracked).compile()setsFinal Answer:
To set the optimizer, loss function, and metrics before training -> Option AQuick Check:
Compile sets optimizer, loss, metrics = A [OK]
- Confusing compile with training or prediction
- Thinking compile saves the model
- Assuming compile runs the training process
Solution
Step 1: Check optimizer and loss names
The Adam optimizer is specified as 'adam' and categorical crossentropy loss as 'categorical_crossentropy'.Step 2: Verify metrics format
Metrics must be passed as a list, so ['accuracy'] is correct, not a string.Final Answer:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) -> Option CQuick Check:
Correct optimizer, loss, and metrics list = D [OK]
- Passing metrics as a string instead of list
- Using wrong loss function for classification
- Choosing wrong optimizer name
model.compile(optimizer='sgd', loss='mse', metrics=['mae']) history = model.fit(x_train, y_train, epochs=2) print(history.history['mae'])
What will be printed?
Solution
Step 1: Understand metrics in compile and fit
The model is compiled with 'mae' (mean absolute error) as a metric, so it will track this during training.Step 2: Check what history.history['mae'] contains
It stores a list of metric values for each epoch, so printing it shows a list of MAE values per epoch.Final Answer:
A list of mean absolute error values for each epoch -> Option DQuick Check:
Metrics list stores per-epoch values = B [OK]
- Expecting a single float instead of list
- Confusing loss with metric values
- Thinking 'mae' is invalid metric
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics='accuracy')
What is the problem?
Solution
Step 1: Check metrics argument type
Metrics must be passed as a list or tuple, e.g., ['accuracy'], not a string.Step 2: Confirm other arguments are correct
Optimizer 'adam' and loss 'categorical_crossentropy' are valid names, so the issue is due to metrics format.Final Answer:
Metrics should be a list, not a string -> Option AQuick Check:
Metrics argument must be list = A [OK]
- Passing metrics as a string
- Misnaming loss or optimizer
- Compiling after training instead of before
Solution
Step 1: Identify task type
Binary classification means two classes, so the loss should be 'binary_crossentropy'.Step 2: Choose suitable optimizer and metrics
Adam optimizer is widely used and effective; accuracy is a good metric for classification.Step 3: Check other options
Options B and D use categorical losses for multi-class, and A uses regression losses, so they are less suitable.Final Answer:
optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] -> Option BQuick Check:
Binary task needs binary_crossentropy loss = C [OK]
- Using categorical loss for binary tasks
- Choosing regression loss for classification
- Ignoring metric suitability
