sklearn GridSearchCV not using sample_weight in score function
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
By default, scikit-learn's GridSearchCV passes sample_weight to the estimator's fit method but does not pass it to the scoring function during evaluation. This means the model trains with weighted samples, but the cross-validation score treats all samples equally. To fix this, create a custom scorer using make_scorer that accepts sample_weight, or use the fit_params approach combined with a custom scoring callable. Since scikit-learn 1.4+, you can also use metadata routing to pass sample_weight to both fit and score.
The Problem
GridSearchCV calls estimator.fit(X_train, y_train, sample_weight=sw_train) correctly, but during scoring it calls scorer(estimator, X_val, y_val) without passing sample_weight.
Fix 1: Custom Scorer with make_scorer
Create a scorer that accepts and uses sample_weight:
Fix 2: Custom Scoring Callable
Write a scoring function that extracts the correct sample_weight for each fold:
Fix 3: Manual Cross-Validation (Most Control)
For full control over sample_weight in both fit and score:
Fix 4: Metadata Routing (scikit-learn 1.4+)
Scikit-learn 1.4 introduced metadata routing, which allows sample_weight to flow to both fit and score:
This is the cleanest solution but requires scikit-learn 1.4 or later.
When Sample Weight Matters
Common Pitfalls
- Assuming
GridSearchCVpassessample_weightto the scorer automatically: It does not (before metadata routing). The scorer receives only(estimator, X, y).sample_weightinfit_paramsonly affectsestimator.fit(), not the evaluation score. - Using
make_scorerwith a fixedsample_weightarray: Passing the fullsample_weightarray tomake_scoreruses all weights on every fold's validation set, not just the weights for the validation indices. This produces incorrect scores when fold sizes differ from the full dataset. - Forgetting that
class_weightin the estimator is different fromsample_weightin the scorer:class_weight='balanced'on the estimator adjusts training, but the scorer still evaluates unweighted unless explicitly configured. Both mechanisms serve different purposes. - Not using
StratifiedKFoldwith imbalanced data: DefaultKFoldmay create folds where the minority class is absent. Always useStratifiedKFold(the default for classification inGridSearchCV) when working with imbalanced datasets and sample weights. - Expecting metadata routing to work without
set_config: In scikit-learn 1.4+, metadata routing must be explicitly enabled withsklearn.set_config(enable_metadata_routing=True). Without this,sample_weightis silently ignored in the scorer.
Summary
GridSearchCVdoes not passsample_weightto the scoring function by default- For scikit-learn 1.4+, use metadata routing with
set_score_request(sample_weight=True) - For older versions, write a manual cross-validation loop for full control over weighted scoring
- Use
compute_sample_weight('balanced', y)to create weights for imbalanced datasets - Always verify that both training (fit) and evaluation (score) use
sample_weightfor consistent model selection
Related reading
- SKLearn how to get decision probabilities for LinearSVC classifier
- sklearn How to reset a Regressor or classifier object in sknn
- sklearn ImportError cannot import name plot_roc_curve
- sklearn LabelBinarizer returns vector when there are 2 classes
- sklearn LinearRegression, why only one coefficient returned by the model?
- sklearn LinearSVC - X has 1 features per sample; expecting 5
- Sklearn list of algorithms
- sklearn LogisticRegression and changing the default threshold for classification
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.