TATECHATLAS
◎ English
Math & models / Tip

Passing Regression Metrics to cross_val_score and GridSearchCV with the neg_ Convention

scikit-learn scorers must return higher-is-better values, so error metrics are registered as neg_-prefixed strings that cross_val_score and GridSearchCV maximize. Negate the returned scores to recover the original loss.

On this page

Pass the regression metric as a neg_-prefixed string to the scoring argument: scoring="neg_mean_absolute_error" for MAE, "neg_mean_squared_error" for MSE, "neg_root_mean_squared_error" for RMSE, and "r2" or "explained_variance" for metrics that are already higher-is-better. All scorer objects in scikit-learn follow the convention that higher return values are better, so distance-style losses are exposed with their sign flipped. cross_val_score then returns one negated loss per fold, and GridSearchCV ranks parameter sets by the largest mean of those negated values and stores it in best_score_. Recover the ordinary loss with a single negation, for example MAE = -grid.best_score_. Use sklearn.metrics.get_scorer_names() to enumerate the registered names in your installed version instead of guessing, because an unrecognized name raises an error whose class varies by release.

Context and Recommendation

Cross-validation utilities that evaluate estimators internally, including cross_val_score, cross_validate and GridSearchCV, accept a scoring parameter. It can be omitted, in which case the estimator's own score method is used, or supplied as a string name, a callable, or a collection of metrics when several must be tracked at once. For regression the recommendation is to name the metric explicitly: most regressors default to R-squared from their score method, which is rarely the quantity you want to optimize when the business cost is an absolute or squared prediction error.

Error metrics are non-negative losses whose best value is 0.0, so they cannot be returned directly by a scorer that must reward larger numbers. scikit-learn therefore registers them under a neg_ string: 'neg_mean_absolute_error' calls metrics.mean_absolute_error and returns its negation. Passing that string is the shortest correct way to select models by MAE in both cross_val_score and GridSearchCV.

Reasoning and Trade-offs

The mechanism is a maximization contract. Every scorer object follows the rule that higher return values are better, and the selection tools pick the candidate with the largest mean score. Negating a loss is a strictly monotone transformation, so the ranking of models and the identity of the best parameter set are unchanged; only the sign of the reported number differs. The cost is sign handling: best_score_ and the fold array are negative, and a reader who forgets the convention will conclude that a worse model won. Convert once at the reporting boundary and keep the raw value only for audit.

Keep the metric formula separate from what the fitted model estimates and from any inference claim. Absolute loss is aligned with the conditional median, squared loss with the conditional mean when the relevant finite-moment conditions hold; neither is a confidence statement. RMSE is not generally the standard deviation of errors, because that equality needs zero-mean errors and a matching divisor. Also note that MAE gives each absolute error a linear, unbounded contribution, so it is less dominated by outliers than squared loss without being immune to extreme errors.

Discovery matters more than memorizing names: get_scorer_names() returns the registered scorers for the installed version. A wrong name raises an error whose class depends on the release, InvalidParameterError in recent versions and ValueError earlier, so validate against get_scorer_names() rather than catching one specific exception type.

Concrete Illustration

Prerequisites: Python 3.9 or newer with scikit-learn 1.0 or newer, since get_scorer_names was added in 1.0; install with pip install scikit-learn. The example builds a deterministic synthetic regression problem, scores a gradient-boosting regressor with five folds, tunes two hyperparameters, and checks the sign contract. The fold count, the two boolean sign checks and the registered-scorer check are observed outputs of this code; the final list is an illustrative conversion of fixed sample fold scores, not a measured result, because actual MAE values depend on the library version and data.

The important reading is that every reported scorer value is non-positive, while the negated values are the MAE you would quote to a stakeholder. GridSearchCV's best_score_ follows the same rule, so the negation is applied uniformly to fold scores and to the selected score.

from sklearn.datasets import make_regression
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import get_scorer_names
from sklearn.model_selection import GridSearchCV, cross_val_score

X, y = make_regression(n_samples=200, n_features=8, random_state=0)
model = GradientBoostingRegressor(random_state=0)

scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_absolute_error")
print("fold count:", len(scores))
print("every fold is non-positive:", bool((scores <= 0).all()))

grid = GridSearchCV(
    model,
    {"n_estimators": [100, 200], "learning_rate": [0.01, 0.1]},
    cv=5,
    scoring="neg_mean_absolute_error",
)
grid.fit(X, y)
print("best score is non-positive:", bool(grid.best_score_ <= 0))
print("scorer registered:", "neg_mean_absolute_error" in get_scorer_names())

illustrative_fold_scores = [-3.25, -4.1, -2.8, -5.0, -3.7]
print("MAE from negated scores:", [-value for value in illustrative_fold_scores])

# Illustrative output:
# fold count: 5
# every fold is non-positive: True
# best score is non-positive: True
# scorer registered: True
# MAE from negated scores: [3.25, 4.1, 2.8, 5.0, 3.7]

Applicability Limits

The neg_ convention is specific to scikit-learn and does not transfer to libraries that expect a positive loss or a minimize flag, so translate the sign when moving code across ecosystems. It also says nothing about classification scorers, where precision, recall and false-positive rate have their own directions and where the false-positive count is an absolute workload rather than a rate; regression scorer tables do not establish classification behavior.

Some regression metrics have no registered string because they require user-set parameters, for example mean_pinball_loss with alpha and mean_tweedie_deviance with power. Wrap them with make_scorer and set greater_is_better=False when the underlying function is a loss, so the scorer still satisfies the higher-is-better contract. When a custom callable is used with n_jobs greater than 1, define it in an importable module rather than inline, which is more robust across joblib backends.

For multiple metrics, pass a dict or list to scoring and, in GridSearchCV, set refit to the key of the metric that should choose the final model; refit=False skips refitting entirely. Finally, the neg_ strings assume the estimator exposes predict; scorers that need predict_proba or decision_function are unavailable for regressors that provide neither.

Applicability

  • Does the installed scikit-learn version include the scorer name returned by get_scorer_names()?
  • Is the metric a registered string scorer, or does it need a parameter such as alpha or power and therefore make_scorer?
  • Will the consumer of best_score_ negate it before reporting the loss in original units?
  • Is greater_is_better set so that a custom loss still follows the higher-is-better contract?
  • Are you comparing results with another library that may not use the neg_ sign convention?
  • For multiple metrics, does refit name exactly one key of the scoring mapping?

The neg_ prefix and get_scorer_names are scikit-learn conventions, so the same strings and sign handling may not apply elsewhere. Named scorers cover only metrics that need no extra arguments; parameterized losses require make_scorer, and custom callables need care with parallel backends. The example uses synthetic data and reports structural sign checks, not accuracy figures, and the numeric MAE values shown are illustrative rather than measured. Metric choice also depends on the target functional and moment conditions, which no scorer name encodes.

Sources

  1. scikit-learn: model evaluation ↗
  2. scikit-learn: mean_absolute_error ↗
Back to top ↑