Sub topic 3
Choosing the metric you optimize
This chapter assumes you can run GridSearchCV and know what cross-validation is. The tuner picks the setting with the best score, so the metric you choose defines what "best" means.
The metric is the objective
Tuning compares settings by one number. If that number does not match what you care about, the search finds a model that is good at the wrong thing. Choose the metric before you start, and write down why.
Training loss and the tuning metric are different things. A model trains by minimizing a loss such as log loss. You tune and report with a metric such as F1 or mean absolute error. The two can disagree. For example, a setting can have a lower log loss and a worse F1.
Matching the metric to the problem
| Situation | Poor choice | Better choice |
|---|---|---|
| Rare positive class (fraud, disease) | Accuracy | Average precision, F1, recall at a set precision |
| You need calibrated probabilities | Accuracy | Log loss, Brier score |
| Large errors cost much more than small ones | Mean absolute error | Root mean squared error |
| Outliers should not dominate | Mean squared error | Median absolute error |
| Classes matter equally | Micro-averaged F1 | Macro-averaged F1 |
With a 95% negative class, a model that always predicts "negative" scores 95% accuracy. A grid search on accuracy will hardly separate good settings from useless ones.
Scoring in scikit-learn
Pass scoring to the search. Scikit-learn always maximizes the score, so error metrics appear negated, for example "neg_mean_squared_error". A "best" value of -4.2 is better than -9.0.
You can track several metrics at once. With more than one, you must say which one picks the winner by setting refit.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
X, y = make_classification(
n_samples=2000, weights=[0.95, 0.05], 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
)
search = GridSearchCV(
LogisticRegression(max_iter=1000),
{"C": [0.01, 0.1, 1, 10]},
cv=5,
scoring={"accuracy": "accuracy", "f1": "f1", "ap": "average_precision"},
refit="ap",
)
search.fit(X_train, y_train)
print(search.best_params_)
for name in ["accuracy", "f1", "ap"]:
score = search.cv_results_[f"mean_test_{name}"][search.best_index_]
print(name, round(score, 3))Here ap (average precision) chooses the setting. Accuracy and F1 are reported alongside it. Compare the three columns in cv_results_. If accuracy barely moves while average precision changes a lot, that confirms accuracy was hiding the differences.
Common errors
- Changing the metric after seeing results. Picking the metric that makes your best model look good is a form of tuning on the test data. Fix it first.
- Optimizing a threshold-dependent metric without handling the threshold. F1 uses a 0.5 cutoff by default. If the deployed system uses another cutoff, tune the one you will deploy, or use a threshold-free metric such as average precision.
- Reading negated scores as bad.
neg_*values closer to zero are better. - Using a different metric to report than to tune. The final test score should use the same metric the search optimized, plus any others you declared in advance.
Exercise
A search with scoring="negmeanabsoluteerror" reports bestscore_ = -3.1 for setting A and -4.8 for setting B. Which setting wins, and what is A's actual mean absolute error?
Show answer
Setting A wins, because -3.1 is higher than -4.8 and scikit-learn maximizes the score. Its mean absolute error is 3.1.