Skip to content

Scorer not working on ClassifierChain #26817

Description

@tvdboom

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

  1. added
    Needs Triage
    on Jul 11, 2023
  2. betatim commented on Jul 11, 2023

    @betatim
    Member

    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 what classes_ should be IMHO. I think it makes sense to fix this and stick to the uniform interface for classes_. 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?

  3. added and removed
    Needs Triage
    on Jul 11, 2023
  4. sqali commented on Jul 11, 2023

    @sqali
    Contributor

    Hi @betatim ,

    I would love to work on the proposed solution.

  5. tvdboom commented on Jul 11, 2023

    @tvdboom
    ContributorAuthor

    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 MultiOutputClassifier experiences the same issue, and the docstring for the classes_ attribute is wrong. It says classes_: ndarray of shape (n_classes,) but the code is the same as ClassifierChain.

    self.classes_ = [estimator.classes_ for estimator in self.estimators_]

    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.

  6. betatim commented on Jul 12, 2023

    @betatim
    Member

    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.

    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's classes_?

    I'm not very familiar with the ClassifierChain methodology, 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 ClassifierChain and in it mentioning that MultiOutputClassifier has the same problem, but holding off with changing its code. Once there is consensus around the solution for ClassifierChain you can then add on the MultiOutputClassifier or make a second PR to deal with it.

  7. sqali commented on Jul 12, 2023

    @sqali
    Contributor

    Hi @betatim ,

    Sure, I and @tvdboom would love to work on it together.

    I will do my research and update it here.

  8. glemaitre commented on Jul 12, 2023

    @glemaitre
    Member

    So there are some puzzling stuff here.

    First, it seems that the ClassifierChain accepts 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 a type_of_target and reject if we are not in the multilabel-indicator case.

    Secondly, for the classes, we expect each binary classifier to be trained on [0, 1]. The current version of the classes_ 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 be range(Y.shape[1]) (that corresponds as well to np.unique(LabelBinarizer().inverse_transform(Y)). In a world that Y, could be a dataframe, I would therefore expect Y.columns.

  9. glemaitre commented on Jul 12, 2023

    @glemaitre
    Member

    And I lost track of the original problem: _get_response_values is not written to handle multilabel classification. We can decide if we want to change the API of classes_ for the multilabel but otherwise we should fix:

    prediction_method = _check_response_method(estimator, response_method)
    classes = estimator.classes_
    target_type = "binary" if len(classes) <= 2 else "multiclass"

    If estimator.classes_ is actually a list, then we can fork in a branch to handle this case. There is no problem with pos_label but I would need to check if there are any metrics supporting the output of decision_function or predict_proba in this case. predict should work like a charm just by returning directly the output.

  10. tvdboom commented on Jul 12, 2023

    @tvdboom
    ContributorAuthor

    Feel free to make the pr @sqali and add me to the reviewers

  11. sqali commented on Jul 12, 2023

    @sqali
    Contributor

    Hi @glemaitre @betatim ,

    I can confirm that the estimator.classes_ is actually a list. I ran the below code and got the output.

    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(chain.classes_)
    print(type(chain.classes_))
    

    Ouput:-

    [array([0, 1]), array([0, 1]), array([0, 1])]
    <class 'list'>
    

    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.

  12. betatim commented on Jul 13, 2023

    @betatim
    Member

    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.

  13. sqali commented on Jul 13, 2023

    @sqali
    Contributor

    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.

  14. betatim commented on Jul 14, 2023

    @betatim
    Member

    @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:

    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, Y_test, y_pred))

    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 the ClassifierChain I 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).

  15. glemaitre commented on Jul 14, 2023

    @glemaitre
    Member

    binary classification problem

    From your example, it is not a binary problem, this is a multilabel-indicator:

    In [3]: from sklearn.datasets import make_multilabel_classification
    
    In [4]: X, Y = make_multilabel_classification(n_samples=72, n_classes=3, random_state=0)
    
    In [5]: from sklearn.utils.multiclass import type_of_target
    
    In [6]: type_of_target(Y)
    Out[6]: 'multilabel-indicator'

    A binary classifier will be a 1-D array with 0/1. But it does not make sense for ClassifierChain since it tries to find an association between labels (columns in Y).
    This is one of the reasons I think that we should only accept multilabel-indicator as a type of target.

  16. glemaitre commented on Jul 15, 2023

    @glemaitre
    Member

    While working on #26840 which required to simplify #26120, I needed to solve the current bug here.

    NB: the line

    get_scorer("average_precision")(chain, Y_test, y_pred)

    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.

  17. glemaitre commented on Jul 15, 2023

    @glemaitre
    Member

    @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.

  18. sqali commented on Jul 15, 2023

    @sqali
    Contributor

    Hi @glemaitre,

    It is okay, no problem!! I will go ahead with some issues that are less difficult than this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions