Repository navigation
Labels
Description
Describe the bug
ClassifeirChain fails when trying to make scoring predictions. The reason is: ClassifeirChain's attribute classes_ is a list and not a np.array as the _get_response_values function expects.
Steps/Code to Reproduce
from sklearn.multioutput import ClassifierChain
from sklearn.metrics._scorer import get_scorer
from sklearn.datasets import make_multilabel_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.multioutput import ClassifierChain
X, Y = make_multilabel_classification(n_samples=72, n_classes=3, random_state=0)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0)
base_lr = LogisticRegression(solver='lbfgs', random_state=0)
chain = ClassifierChain(base_lr, order='random', random_state=0)
y_pred = chain.fit(X_train, Y_train).predict(X_test)
print(get_scorer("average_precision")(chain, X_test, Y_test))Expected Results
No error thrown.
Actual Results
File "C:\Users\Mavs\Documents\Python\ATOM\test.py", line 204, in <module>
print(get_scorer("average_precision")(chain, Y_test, y_pred))
File "C:\Users\Mavs\Documents\Python\ATOM\venv310\lib\site-packages\sklearn\metrics\_scorer.py", line 266, in __call__
return self._score(partial(_cached_call, None), estimator, X, y_true, **_kwargs)
File "C:\Users\Mavs\Documents\Python\ATOM\venv310\lib\site-packages\sklearn\metrics\_scorer.py", line 466, in _score
y_pred = method_caller(clf, "predict_proba", X, pos_label=pos_label)
File "C:\Users\Mavs\Documents\Python\ATOM\venv310\lib\site-packages\sklearn\metrics\_scorer.py", line 86, in _cached_call
result, _ = _get_response_values(
File "C:\Users\Mavs\Documents\Python\ATOM\venv310\lib\site-packages\sklearn\utils\_response.py", line 77, in _get_response_values
if pos_label is not None and pos_label not in classes.tolist():
AttributeError: 'list' object has no attribute 'tolist'
Versions
System:
python: 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)]
executable: C:\Users\Mavs\Documents\Python\ATOM\venv310\Scripts\python.exe
machine: Windows-10-10.0.19045-SP0
Python dependencies:
sklearn: 1.3.0
pip: 23.1.2
setuptools: 59.8.0
numpy: 1.23.5
scipy: 1.10.1
Cython: 0.29.30
pandas: 1.5.3
matplotlib: 3.7.2
joblib: 1.3.1
threadpoolctl: 3.1.0
Built with OpenMP: True
threadpoolctl info:
user_api: blas
internal_api: openblas
prefix: libopenblas
filepath: C:\Users\Mavs\Documents\Python\ATOM\venv310\Lib\site-packages\numpy\.libs\libopenblas.FB5AE2TYXYH2IJRDKGDGQ3XBKLKTF43H.gfortran-win_amd64.dll
version: 0.3.20
threading_layer: pthreads
architecture: Zen
num_threads: 16
user_api: openmp
internal_api: openmp
prefix: vcomp
filepath: C:\Users\Mavs\Documents\Python\ATOM\venv310\Lib\site-packages\sklearn\.libs\vcomp140.dll
version: None
num_threads: 16
user_api: blas
internal_api: openblas
prefix: libopenblas
filepath: C:\Users\Mavs\Documents\Python\ATOM\venv310\Lib\site-packages\scipy.libs\libopenblas-802f9ed1179cb9c9b03d67ff79f48187.dll
version: 0.3.18
threading_layer: pthreads
architecture: Zen
num_threads: 16
user_api: openmp
internal_api: openmp
prefix: libiomp
filepath: C:\Users\Mavs\Documents\Python\ATOM\venv310\Lib\site-packages\torch\lib\libiomp5md.dll
version: None
num_threads: 8
user_api: openmp
internal_api: openmp
prefix: libiomp
filepath: C:\Users\Mavs\Documents\Python\ATOM\venv310\Lib\site-packages\torch\lib\libiompstubs5md.dll
version: None
num_threads: 1
Activity
betatim commentedon Jul 11, 2023
Thanks for reporting this. I can reproduce the problem.
A slight complication is that
ClassifierChain.classes_is defined as a list of the classes for each estimator in the chain. This is a bit different from whatclasses_should be IMHO. I think it makes sense to fix this and stick to the uniform interface forclasses_. This might need some deprecation notice/warning. Maybe we need a new attribute that stores the individual classes seen by each estimator?Would you be interested in submitting a Pull Request for this?
sqali commentedon Jul 11, 2023
Hi @betatim ,
I would love to work on the proposed solution.
tvdboom commentedon Jul 11, 2023
I am willing to give it a try as well, although I'll probably need some guidance about the deprecation/warning part.
I also noticed that
MultiOutputClassifierexperiences the same issue, and the docstring for theclasses_attribute is wrong. It saysclasses_: ndarray of shape (n_classes,)but the code is the same as ClassifierChain.scikit-learn/sklearn/multioutput.py
Line 539 in 7f9bad9
Is it possible for the base estimators to have different
classes_? If not, it would make sense to let the attribute of the meta-estimator return the classes from the first base estimator.betatim commentedon Jul 12, 2023
It seems unlikely that they'd have different classes, but not impossible? I think the same data is passed to all estimators in the chain, but maybe if the estimator in the chain does some splitting of the data at random during its learning it would see different classes? I'm not sure if this is realistic or not. I think I'd go for the chain's
classes_attribute being the union of all the individual estimator'sclasses_?I'm not very familiar with the
ClassifierChainmethodology, so for me this would be a case where doing the research takes more time than making the change.@tvdboom and @sqali regarding making a PR: maybe one of you can make a PR and the other can help review it?
ps. it might be worth making one PR for
ClassifierChainand in it mentioning thatMultiOutputClassifierhas the same problem, but holding off with changing its code. Once there is consensus around the solution forClassifierChainyou can then add on theMultiOutputClassifieror make a second PR to deal with it.sqali commentedon Jul 12, 2023
Hi @betatim ,
Sure, I and @tvdboom would love to work on it together.
I will do my research and update it here.
glemaitre commentedon Jul 12, 2023
So there are some puzzling stuff here.
First, it seems that the
ClassifierChainaccepts multiclass-multioutput while it should not. This is not the purpose of the original paper. The idea is to have a set of binary classifiers that can learn a label correlation. So I would think that we should run atype_of_targetand reject if we are not in themultilabel-indicatorcase.Secondly, for the classes, we expect each binary classifier to be trained on
[0, 1]. The current version of theclasses_is actually not informative at all. Making the union would already be more aligned with our own API but I don't think this is informative as well.As a user, I would expect
classes_to refer to the label's name which in the simple case would berange(Y.shape[1])(that corresponds as well tonp.unique(LabelBinarizer().inverse_transform(Y)). In a world thatY, could be a dataframe, I would therefore expectY.columns.glemaitre commentedon Jul 12, 2023
And I lost track of the original problem:
_get_response_valuesis not written to handle multilabel classification. We can decide if we want to change the API ofclasses_for the multilabel but otherwise we should fix:scikit-learn/sklearn/utils/_response.py
Lines 73 to 75 in fa3ca7a
If
estimator.classes_is actually a list, then we can fork in a branch to handle this case. There is no problem withpos_labelbut I would need to check if there are any metrics supporting the output ofdecision_functionorpredict_probain this case.predictshould work like a charm just by returning directly the output.tvdboom commentedon Jul 12, 2023
Feel free to make the pr @sqali and add me to the reviewers
sqali commentedon Jul 12, 2023
Hi @glemaitre @betatim ,
I can confirm that the estimator.classes_ is actually a list. I ran the below code and got the output.
Ouput:-
I am new to open source. I require some guidance here. I understand that I need to make changes in the multioutput.py file in the fit function of classes MultiOutputClassifier and ClassifierChain by introducing a new attribute to store the individual classes seen by each estimator. Kindly confirm if this would be the right approach.
betatim commentedon Jul 13, 2023
If you are new to open-source @sqali it might be better to start with a good first issue. Those are meant for newcomers compared to issues like this.
sqali commentedon Jul 13, 2023
Hi @betatim ,
I am new to open source but I have proficiency in Python and used Scikit Learn for several use cases, I could use your help in this. I would be grateful if you can please confirm if the above-mentioned solution would work.
betatim commentedon Jul 14, 2023
@sqali "good first issues" are exactly for people who are new to open-source.
@glemaitre the same exception gets raised for a binary classification problem:
So I think we should have one PR that fixes the problem of
chain.classes_being a list. There is an example of it being a list, but in that case it is a multi-output problem.I don't think there is anything that needs changing in
_get_response_values. The bug is in theClassifierChainI think. The attribute is computed here and I think it should be the union of the labels of the individual estimators (just in case that one of them sees different class labels).glemaitre commentedon Jul 14, 2023
From your example, it is not a binary problem, this is a multilabel-indicator:
A binary classifier will be a 1-D array with 0/1. But it does not make sense for
ClassifierChainsince it tries to find an association between labels (columns inY).This is one of the reasons I think that we should only accept
multilabel-indicatoras a type of target.glemaitre commentedon Jul 15, 2023
While working on #26840 which required to simplify #26120, I needed to solve the current bug here.
NB: the line
is wrong because the signature of a scorer is
scorer(estimator, X_test, y_test).As mentioned in #26817 (comment), I don't particularly find useful the representation of
classes_but it seems that we are consistent across estimator handling multilabel-indicator. I don't know if it is worth changing this representation for the moment.glemaitre commentedon Jul 15, 2023
@sqali Sorry to have taken over here. To be honest, the private code of the scorers is not beginner friendly, with some caching mechanism (that I had to think about). I would have let this issue open if I would not have a need to solve it in #26840.
sqali commentedon Jul 15, 2023
Hi @glemaitre,
It is okay, no problem!! I will go ahead with some issues that are less difficult than this.