Repository navigation
Closed
Description
Description
When LogisticRegressionCV is called on a multi-class dataset with a "low-data" class, some CV folds are forced to drop the rare-class entirely. This propagates through to the neg-log-loss metric as an exception:
Steps/Code to Reproduce
"""
Modify the digits dataset to be very low in 9s, to trigger
an exception in the negative log loss metric.
"""
import sklearn.datasets
import sklearn.linear_model
import numpy as np
X, y = sklearn.datasets.load_digits(return_X_y=True)
n9 = 2
y9 = y[y == 9]
X9 = X[y == 9]
X = X[y != 9]
y = y[y != 9]
X = np.vstack([X, X9[0:n9]])
y = np.hstack([y, y9[0:n9]])
multi_class = "multinomial"
scoring = "neg_log_loss"
random_state = 1
model = sklearn.linear_model.LogisticRegressionCV(multi_class=multi_class, scoring=scoring, random_state=random_state)
model.fit(X, y)Expected Results
I would expect this to run without an exception, or raise an exception before model training is attempted. In particular, if you assume that 0 log(0) -> 0, this should "just work" IMHO.
Actual Results
....env/lib/python3.6/site-packages/sklearn/linear_model/logistic.py in _log_reg_scoring_path(X, y, train, test, pos_class, Cs, scoring, fit_intercept, max_iter, tol, class_weight, verbose, solver, penalty, dual, intercept_scaling, multi_class, random_state, max_squared_sum, sample_weight, l1_ratio)
1195 scores.append(log_reg.score(X_test, y_test))
1196 else:
-> 1197 scores.append(scoring(log_reg, X_test, y_test))
1198
1199 return coefs, Cs, np.array(scores), n_iter
....env/lib/python3.6/site-packages/sklearn/metrics/scorer.py in __call__(self, clf, X, y, sample_weight)
138 **self._kwargs)
139 else:
--> 140 return self._sign * self._score_func(y, y_pred, **self._kwargs)
141
142 def _factory_args(self):
....env/lib/python3.6/site-packages/sklearn/metrics/classification.py in log_loss(y_true, y_pred, eps, normalize, sample_weight, labels)
2164 "y_true: {2}".format(transformed_labels.shape[1],
2165 y_pred.shape[1],
-> 2166 lb.classes_))
2167 else:
2168 raise ValueError('The number of classes in labels is different '
ValueError: y_true and y_pred contain different number of classes 9, 10. Please provide the true labels explicitly through the labels argument. Classes found in y_true: [0 1 2 3 4 5 6 7 8]
Versions
System:
python: 3.6.7 | packaged by conda-forge | (default, Jul 2 2019, 02:07:37) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]
executable: miniconda3/envs/eda/bin/python
machine: Darwin-18.7.0-x86_64-i386-64bit
Python deps:
pip: 19.3.1
setuptools: 41.4.0
sklearn: 0.21.3
numpy: 1.17.2
scipy: 1.3.1
Cython: None
pandas: 0.25.2
One workaround that I've been able to implement is using functools.partial to create a custom loss function that takes the output of predict_proba() and expands it by filling zeros into the missing label. This approach assumes that the missing label is always at the end of the array, which I think is reasonable but needs to be tested.
Activity
glemaitre commentedon Aug 11, 2020
So we should improve the error message such that it is obvious that we want the following:
But even with this code, we get an error. So there is clearly a bug inlog_lossmetric.Edit: actually not, I forgot
needs_proba=Truewhen creating the scorer.glemaitre commentedon Aug 11, 2020
So we need to some documentation and an error message which is more explicit to come up with the solution.
Human gold patch for scikit-learn__scikit-learn-32828