Sub topic 3
Choosing the metric you optimize
This chapter assumes you can train a scikit-learn classifier, know what GridSearchCV is at a basic level, and understand train, validation, and test splits. Every tuning method in this tutorial does the same thing: it picks the setting with the best score. If the score measures the wrong thing, the search finds the wrong model efficiently.
The metric defines "best"
A tuning run compares candidate settings using one number, computed on validation data. That number is your objective. Changing it can change the winner, even with the same data, model, and search space.
Two kinds of metric are involved:
- Training loss is what the model minimizes while it fits its parameters, such as log loss for logistic regression. It must be differentiable, or at least convenient to optimize.
- Selection metric is what you maximize or minimize when comparing hyperparameter settings. It can be anything you can compute from predictions, such as F1, recall at a fixed precision, or expected cost.
These do not have to match. A model trained with log loss can be selected by average precision, because the selection metric should reflect what you care about in use. The training loss only has to be something the algorithm can optimize.
Common metrics and when they mislead
| Metric | Uses | Typical problem |
|---|---|---|
| Accuracy | Balanced classes, equal error costs | A model that always predicts the majority class scores 95% when 95% of rows are negative |
| F1 | One number balancing precision and recall | Depends on a decision threshold, ignores true negatives |
| ROC AUC | Ranking quality across all thresholds | Can look good on heavily imbalanced data because false positives are diluted by many negatives |
| Average precision | Ranking quality when positives are rare | Baseline equals the positive rate, so values are hard to compare across datasets |
| Log loss | Quality of predicted probabilities | Penalizes confident mistakes sharply, so it can be dominated by a few rows |
| RMSE | Regression where large errors matter most | Sensitive to outliers |
| MAE | Regression with outliers present | Treats all error sizes the same |
| R² | Regression, relative to predicting the mean | Not comparable across datasets with different variance |
Threshold-based metrics (accuracy, F1, precision, recall) score hard labels. Threshold-free metrics (ROC AUC, average precision, log loss) score probabilities or rankings. If you tune with a threshold-free metric and later pick a threshold, you are making a second decision that also needs validation data.
Match the metric to the cost of errors
Start from the decision the model supports, not from a metric name.
- State what a false positive costs and what a false negative costs. In fraud screening a missed fraud may cost far more than a manual review.
- Decide whether you act on labels or on ranked scores. A review queue that handles the top 100 cases wants a ranking metric. An automatic block wants a thresholded one.
- Check class balance. If one class is under about 10% of rows, treat accuracy with suspicion.
- Pick the simplest metric that encodes steps 1 to 3, and report others alongside it.
Seeing the metric change the winner
The next example tunes the regularization strength C of a logistic regression on a dataset where only about 5% of rows are positive. GridSearchCV accepts a dictionary of scorers and computes all of them for every setting. The refit argument names the one used to pick the best setting and to retrain the final model.
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=5000, n_features=20, n_informative=5,
weights=[0.95, 0.05], flip_y=0.01, random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
param_grid = {"logisticregression__C": [0.001, 0.01, 0.1, 1, 10, 100]}
scoring = {
"accuracy": "accuracy",
"f1": "f1",
"average_precision": "average_precision",
}
search = GridSearchCV(
pipe, param_grid, cv=5, scoring=scoring, refit="average_precision"
)
search.fit(X_train, y_train)
results = pd.DataFrame(search.cv_results_)
cols = [
"param_logisticregression__C",
"mean_test_accuracy",
"mean_test_f1",
"mean_test_average_precision",
]
print(results[cols].round(3).to_string(index=False))
print("Best by average precision:", search.best_params_)Read the table column by column. Accuracy will sit near 0.95 or higher for every row and barely separate the settings, because the majority class dominates it. F1 and average precision vary more, and their best rows may not agree. Whichever column you name in refit decides the final model.
Custom metrics
When errors have different costs, write the cost as a scorer. make_scorer wraps a function with the signature f(y_true, y_pred). Scikit-learn always maximizes scores, so for a loss set greater_is_better=False and the library negates it internally.
import numpy as np
from sklearn.metrics import confusion_matrix, fbeta_score, make_scorer
def expected_cost(y_true, y_pred):
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
return (10 * fn + 1 * fp) / len(y_true)
cost_scorer = make_scorer(expected_cost, greater_is_better=False)
f2_scorer = make_scorer(fbeta_score, beta=2)
y_true = np.array([0, 0, 1, 1, 0, 1])
y_pred = np.array([0, 1, 1, 0, 0, 1])
print("cost:", expected_cost(y_true, y_pred))
print("F2:", fbeta_score(y_true, y_pred, beta=2))Pass cost_scorer or f2_scorer as scoring= in a search. Here a missed positive costs 10 times a false alarm. F2 weights recall more heavily than precision. Scores from a scorer made with greater_is_better=False appear negated in cv_results_, so a result of -0.12 means a cost of 0.12.
Probability-based metrics need response_method set correctly. For average_precision and roc_auc, scikit-learn uses predict_proba or decision_function for you. For a custom scorer on probabilities, use make_scorer(func, response_method="predict_proba").
Common errors
- Optimizing accuracy on imbalanced data. The search rewards models that ignore the minority class. Switch to average precision, F1, or a cost metric.
- Tuning on one metric and reporting another. If you select by F1 and report ROC AUC, the reported value is not the one you optimized. State which metric chose the model, and report others as secondary.
- Selecting on the test set. The metric must be computed on validation folds. The test set gets one evaluation at the end.
- Ignoring the threshold. A model tuned for F1 at the default 0.5 threshold may do better at another threshold. If the threshold matters, tune it with the same cross-validation, not on the test set.
- Metric noise treated as signal. Differences of 0.002 between settings are often smaller than the fold-to-fold spread. Check
std_test_<metric>incv_results_before concluding one setting is better. - Averaging across folds hides class differences. Macro-averaged metrics treat every class equally, while micro-averaged ones favor frequent classes. Choose the average that matches the importance of each class.
Multi-objective situations
Sometimes you care about two things, such as accuracy and prediction latency. Two options keep the search simple:
- Optimize one metric and set a hard constraint on the other. For example, maximize recall among settings whose precision is at least 0.9. You can implement this as a custom scorer that returns the recall when precision meets the bound and zero otherwise.
- Combine them into a single weighted score, which requires you to justify the weights.
A weighted sum hides trade-offs. Prefer the constraint form when a requirement is a firm limit. Libraries such as Optuna also support true multi-objective studies that return a set of non-dominated settings, but that adds complexity you should take on only when you cannot state a constraint.
Exercise
A fraud model is tuned on a dataset where 1% of transactions are fraud. A grid search with scoring="accuracy" reports 0.99 for every candidate. Why is this uninformative, which metric would you switch to if you rank transactions for a review team, and what must you pass to GridSearchCV if you compute several metrics at once?
Show answer
A model that predicts "not fraud" for every row already scores 0.99, so accuracy cannot separate the candidates. For a ranked review queue with rare positives, use average precision (scoring="averageprecision"). When scoring is a dictionary of several metrics, pass refit="averageprecision" (or another scorer name) so the search knows which metric selects the best setting and retrains the final model.
Exercise
You build a scorer with makescorer(expectedcost, greaterisbetter=False), and cvresults shows meantestscore values of -0.14 and -0.09 for two settings. Which setting is better, and what is its expected cost?
Show answer
The setting with -0.09 is better. Scikit-learn negates the loss so that higher is always better, so -0.09 means an expected cost of 0.09, which is lower than 0.14.