The Keras counterpart to PyTorch's manual validation loop from PyTorch Validation Loop โ .evaluate() for computing metrics on held-out data, and .predict() for generating raw predictions.
model.evaluate() โ Computing Loss and Metrics
test_loss, test_accuracy = model.evaluate(x_test, y_test)
print(f"Test loss: {test_loss:.4f}, Test accuracy: {test_accuracy:.4f}")
This directly returns whatever loss and metrics were specified in .compile(), computed over the entire provided dataset โ internally handling exactly the same batched evaluation loop, gradient-tracking disabling, and averaging logic covered manually in PyTorch Validation Loop.
model.predict() โ Getting Raw Predictions
predictions = model.predict(x_test)
print(predictions.shape) # (num_samples, num_classes) -- raw output probabilities, not a scalar metric
predicted_classes = predictions.argmax(axis=1) # convert probabilities to actual class predictions
Unlike .evaluate() (which requires true labels and returns aggregate metrics), .predict() only needs input data and returns the model's raw output for every example โ used when you need the actual predictions themselves, not just a summary performance number.
Custom Metrics
from tensorflow.keras.metrics import Precision, Recall
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy', Precision(), Recall()]
)
results = model.evaluate(x_test, y_test) # returns [loss, accuracy, precision, recall]
Common Mistakes
- Confusing
.evaluate()(needs true labels, returns aggregate metrics) with.predict()(needs only inputs, returns raw per-example predictions) โ using the wrong one for a given need is a common mix-up. - Forgetting that
.predict()returns raw model output (e.g. softmax probabilities), not final class labels โ an explicit.argmax()(or similar post-processing) step is usually still needed to get actual predicted classes.
Interview Relevance
Q: "When would you use model.predict() instead of model.evaluate()?" .predict() is used when you need the model's actual raw predictions for each individual example โ for making real inferences, further processing, or inspection โ and only requires input data, no true labels. .evaluate() is used specifically to compute aggregate performance metrics (loss, accuracy, etc.) against known true labels, summarizing performance rather than returning individual predictions.
Practice Question
After calling model.predict(x_test) on a multi-class classification model, what additional step is needed to get the actual predicted class label for each example?