compile, fit, evaluate & predict Explained
The Four Steps
| Method | Purpose |
|---|---|
compile() | Choose optimizer, loss and metrics |
fit() | Train the model |
evaluate() | Test the model on new data and get loss and metrics |
predict() | Get the model outputs for new samples |
compile()
python
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
- optimizer: how to update the weights
- loss: what to minimize
- metrics: extra numbers to display (they do not change training)
fit()
python
history = model.fit(
x_train, y_train,
epochs=10,
batch_size=64,
validation_split=0.2, # use 20% of the data for validation
shuffle=True,
verbose=1
)
| Argument | Meaning |
|---|---|
epochs | How many times to go through the whole dataset |
batch_size | Samples per weight update (32 or 64 are typical) |
validation_split or validation_data | Data used to check performance during training |
shuffle | Mix the data each epoch (recommended) |
verbose | 0 silent, 1 progress bar, 2 one line per epoch |
callbacks | Extra actions during training |
The History Object
fit() returns a history with the loss and metrics of each epoch. This is how you draw learning curves.
python
print(history.history.keys())
# dict_keys(['accuracy', 'loss', 'val_accuracy', 'val_loss'])
import matplotlib.pyplot as plt
plt.plot(history.history["accuracy"], label="train")
plt.plot(history.history["val_accuracy"], label="validation")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
evaluate()
python
loss, acc = model.evaluate(x_test, y_test, verbose=0)
print(f"Test loss: {loss:.4f}, Test accuracy: {acc:.4f}")
Important: Never evaluate on the training data and report that as your final result. The test data must be data the model has never seen.
predict()
python
probs = model.predict(x_test[:3])
print(probs.shape) # (3, 10)
print(probs[0].round(3)) # probabilities for each digit
print(probs[0].argmax()) # most likely digit
Training Data as a Dataset
Besides NumPy arrays, fit() accepts tf.data.Dataset objects, which we will learn soon.
Choosing Epochs and Batch Size
- Start with 10 epochs and look at the validation curve
- If validation loss starts rising while training loss falls, you are overfitting. Use fewer epochs or
EarlyStopping - Smaller batches give noisier but sometimes better results. Larger batches are faster
Conclusion
The compile, fit, evaluate, predict cycle is the heart of Keras. Learn the main arguments and use the history to understand what happened.
Quick Summary: compile chooses the learning setup, fit trains, evaluate tests, predict gives outputs, and history shows the learning curves.

