-
-
Notifications
You must be signed in to change notification settings - Fork 25.8k
TST check equivalence sample_weight in CalibratedClassifierCV #21179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ogrisel
merged 10 commits into
scikit-learn:main
from
glemaitre:is/calibrated_sample_weight
Oct 1, 2021
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
cf1fdce
TST check equivalence sample_weight in CalibratedClassifierCV
glemaitre aaa1bde
iter
glemaitre 017bfe2
iter
glemaitre caed3bb
iter
glemaitre 2c844b3
iter
glemaitre bec6ed4
iter
glemaitre 2a71374
Grant co-authorship to Julien
glemaitre e5a406f
iter
glemaitre c1a18be
Update sklearn/calibration.py
glemaitre f7ed498
pep8
glemaitre File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,7 +6,7 @@ | |
from numpy.testing import assert_allclose | ||
from scipy import sparse | ||
|
||
from sklearn.base import BaseEstimator | ||
from sklearn.base import BaseEstimator, clone | ||
from sklearn.dummy import DummyClassifier | ||
from sklearn.model_selection import LeaveOneOut, train_test_split | ||
|
||
|
@@ -784,3 +784,97 @@ def test_calibration_display_ref_line(pyplot, iris_data_binary): | |
|
||
labels = viz2.ax_.get_legend_handles_labels()[1] | ||
assert labels.count("Perfectly calibrated") == 1 | ||
|
||
|
||
@pytest.mark.parametrize("method", ["sigmoid", "isotonic"]) | ||
@pytest.mark.parametrize("ensemble", [True, False]) | ||
def test_calibrated_classifier_cv_double_sample_weights_equivalence(method, ensemble): | ||
"""Check that passing repeating twice the dataset `X` is equivalent to | ||
passing a `sample_weight` with a factor 2.""" | ||
X, y = load_iris(return_X_y=True) | ||
# Scale the data to avoid any convergence issue | ||
X = StandardScaler().fit_transform(X) | ||
# Only use 2 classes | ||
X, y = X[:100], y[:100] | ||
sample_weight = np.ones_like(y) * 2 | ||
|
||
# Interlace the data such that a 2-fold cross-validation will be equivalent | ||
# to using the original dataset with a sample weights of 2 | ||
X_twice = np.zeros((X.shape[0] * 2, X.shape[1]), dtype=X.dtype) | ||
X_twice[::2, :] = X | ||
X_twice[1::2, :] = X | ||
y_twice = np.zeros(y.shape[0] * 2, dtype=y.dtype) | ||
y_twice[::2] = y | ||
y_twice[1::2] = y | ||
|
||
base_estimator = LogisticRegression() | ||
calibrated_clf_without_weights = CalibratedClassifierCV( | ||
base_estimator, | ||
method=method, | ||
ensemble=ensemble, | ||
cv=2, | ||
) | ||
calibrated_clf_with_weights = clone(calibrated_clf_without_weights) | ||
|
||
calibrated_clf_with_weights.fit(X, y, sample_weight=sample_weight) | ||
calibrated_clf_without_weights.fit(X_twice, y_twice) | ||
|
||
# Check that the underlying fitted estimators have the same coefficients | ||
for est_with_weights, est_without_weights in zip( | ||
calibrated_clf_with_weights.calibrated_classifiers_, | ||
calibrated_clf_without_weights.calibrated_classifiers_, | ||
): | ||
assert_allclose( | ||
est_with_weights.base_estimator.coef_, | ||
est_without_weights.base_estimator.coef_, | ||
) | ||
|
||
# Check that the predictions are the same | ||
y_pred_with_weights = calibrated_clf_with_weights.predict_proba(X) | ||
y_pred_without_weights = calibrated_clf_without_weights.predict_proba(X) | ||
|
||
assert_allclose(y_pred_with_weights, y_pred_without_weights) | ||
|
||
|
||
@pytest.mark.parametrize("method", ["sigmoid", "isotonic"]) | ||
@pytest.mark.parametrize("ensemble", [True, False]) | ||
def test_calibrated_classifier_cv_zeros_sample_weights_equivalence(method, ensemble): | ||
"""Check that passing removing some sample from the dataset `X` is | ||
equivalent to passing a `sample_weight` with a factor 0.""" | ||
X, y = load_iris(return_X_y=True) | ||
# Scale the data to avoid any convergence issue | ||
X = StandardScaler().fit_transform(X) | ||
# Only use 2 classes and select samples such that 2-fold cross-validation | ||
# split will lead to an equivalence with a `sample_weight` of 0 | ||
X = np.vstack((X[:40], X[50:90])) | ||
y = np.hstack((y[:40], y[50:90])) | ||
sample_weight = np.zeros_like(y) | ||
sample_weight[::2] = 1 | ||
|
||
base_estimator = LogisticRegression() | ||
calibrated_clf_without_weights = CalibratedClassifierCV( | ||
base_estimator, | ||
method=method, | ||
ensemble=ensemble, | ||
cv=2, | ||
) | ||
calibrated_clf_with_weights = clone(calibrated_clf_without_weights) | ||
|
||
calibrated_clf_with_weights.fit(X, y, sample_weight=sample_weight) | ||
calibrated_clf_without_weights.fit(X[::2], y[::2]) | ||
|
||
# Check that the underlying fitted estimators have the same coefficients | ||
for est_with_weights, est_without_weights in zip( | ||
calibrated_clf_with_weights.calibrated_classifiers_, | ||
calibrated_clf_without_weights.calibrated_classifiers_, | ||
): | ||
assert_allclose( | ||
est_with_weights.base_estimator.coef_, | ||
est_without_weights.base_estimator.coef_, | ||
) | ||
|
||
# Check that the predictions are the same | ||
y_pred_with_weights = calibrated_clf_with_weights.predict_proba(X) | ||
y_pred_without_weights = calibrated_clf_without_weights.predict_proba(X) | ||
|
||
assert_allclose(y_pred_with_weights, y_pred_without_weights) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice and much needed new test! |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Very informative, thanks!