Skip to content

DummyClassifier bug with putting arrays into lists #10786

Closed

Description

@lrossert

Description

/site-packages/sklearn/dummy.py

In sklearn.dummy the class DummyClassifier has an issue when the predict function is called when the attribute n_outputs_ is 1. The error is around line 223 of dummy.py

               y = np.tile([classes_[k][class_prior_[k].argmax()] for
                             k in range(self.n_outputs_)], [n_samples, 1])

Since earlier around line 189 the attibute classes_ and class_prior_ are converted to lists:

               classes_ = [classes_]
               class_prior_ = [class_prior_]

I think this gives rise to the issue where an error is returned as argmax() does not work on lists. Here argmax() is not called on an array but on a list. This is because the array is put into a list in line 189.

A hotfix I've used locally is to change the source code on line 223 to unlist/use the first element of a list for classes_ and n_outputs_. This looks like:

               y = np.tile([classes_[0][k][class_prior_[0][k].argmax()] for
                             k in range(self.n_outputs_)], [n_samples, 1])

This error occurs when the DummyClassifier strategy variable is set to mose_frequent:

DummyClassifier(strategy='most_frequent')

But may also occur on some of the other DummyClassifier strategy options.

Steps/Code to Reproduce

import pandas as pd
from sklearn import datasets
from math import floor

from sklearn.dummy import DummyClassifier

############## Get the test train split #############
# Load the breast_cancer dataset
breast_cancer = datasets.load_breast_cancer()

# data
feature_names = pd.Series(breast_cancer.feature_names)
breast_cancer_data = breast_cancer.data
breast_cancer_data = pd.DataFrame(breast_cancer_data)
breast_cancer_data = breast_cancer_data.rename(columns=feature_names)

# response
breast_cancer_response = breast_cancer.target
breast_cancer_response = pd.DataFrame(breast_cancer_response)
breast_cancer_response = breast_cancer_response.rename(columns={0:'response'})

# since the data is randomly shuffled we take the last 20 values as out test 
#set
# note that for more rigourous testing we couls use SKLearn's train_test_split
# function. But we are not focussing on cleaning here

# we split into 70%, 30% test train
length = len(breast_cancer_data)
train_length = floor(length*0.3)

# Split the data into training/testing sets
breast_cancer_data_train = breast_cancer_data[:-train_length ]
breast_cancer_data_test = breast_cancer_data[-train_length :]

# Split the targets into training/testing sets
breast_cancer_response_train = breast_cancer_response[:-train_length ]
breast_cancer_response_test = breast_cancer_response[-train_length :]

##################### DummyClassifier Issue ################

dummy = DummyClassifier(strategy='most_frequent')
dummy.fit(X=breast_cancer_data_train, y=breast_cancer_response_train)

# error occurs on the following line
dummy_pred = dummy.predict(breast_cancer_data_test)

#dummy.n_outputs_
#[dummy.classes_][0][0][[dummy.class_prior_][0][0].argmax()]

Expected Results

Expect an array. In this case an array made up of only [1]s:

array([[1],
       .
       .
       .
       [1]])

Actual Results

  File "C:/Users/lancelot.rossert/Documents/Keyrus/Blog posts/dummy_issue.py", line 53, in <module>
    dummy_pred = dummy.predict(breast_cancer_data_test)

  File "C:\Users\lancelot.rossert\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\dummy.py", line 224, in predict
    k in range(self.n_outputs_)], [n_samples, 1])

  File "C:\Users\lancelot.rossert\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\dummy.py", line 224, in <listcomp>
    k in range(self.n_outputs_)], [n_samples, 1])

AttributeError: 'list' object has no attribute 'argmax'

Versions

Windows-7-6.1.7601-SP1
Python 3.6.2 |Anaconda custom (64-bit)| (default, Sep 19 2017, 08:03:39) [MSC v.1900 64 bit (AMD64)]
NumPy 1.13.3
SciPy 1.0.0
Scikit-Learn 0.19.0

Activity

  1. lesteve commented on Mar 9, 2018

    @lesteve
    Member

    Thanks for the standalone snippet reproducing the problem! It looks like a bug indeed. Quickly playing with it it seems like the problem does not happen when feeding numpy arrays (rather than pandas.Dataframe/pandas.Series). Can you confirm this?

    In any case a PR with a test would be more than welcome! The fix you are proposing is unlikely to be generic enough I am afraid.

  2. added
    Easy
    on Mar 9, 2018
  3. lesteve commented on Mar 9, 2018

    @lesteve
    Member

    Looking at it just a bit more, for some reason it looks like you are feeding y as a DataFrame, feeding y as a Series works. I am not sure whether calling check_X_y would just fix this.

  4. lrossert commented on Mar 9, 2018

    @lrossert
    Author

    Hi,
    Thanks for getting back to me with help. You are correct with this working with y being a numpy array or a pandas series.
    Also it does look like calling check_X_y as you suggested helps. y is converted to an array and the rest of the process goes smoothly:

    from sklearn.utils import check_X_y
    ##################### DummyClassifierIssue ######################
    
    dummy = DummyClassifier(strategy='most_frequent')
    
    X_converted, y_converted = \
                     check_X_y(X=breast_cancer_data_test, y=breast_cancer_response_test)
    dummy.fit(X=X_converted, y=y_converted)
    
    dummy_pred = dummy.predict(X_converted)

    ^This no longer returns an error

  5. mohamed-ali commented on Mar 17, 2018

    @mohamed-ali
    Contributor

    I think this can be closed.

  6. lesteve commented on Mar 19, 2018

    @lesteve
    Member

    I am not 100% sure but it feels like a check_X_y could be added inside DummyClassifier.fit?

    I have to say I am not an expert on the extent of the pandas support inside scikit-learn and my feeling is that passing in a y which is a one-column DataFrame may be outside of it.

  7. nsorros commented on Apr 5, 2018

    @nsorros

    @lesteve @lrossert is this issue being addressed with a PR?

  8. qinhanmin2014 commented on Apr 5, 2018

    @qinhanmin2014
    Member

    Feel free to submit a PR if you think there's a reasonable solution :)

  9. nsorros commented on Apr 6, 2018

    @nsorros

    As suggested above, check_X_y fixes the issue because it calls column_or_1d under the hood which is what other classifiers do as well to deal with dataframes y. I opened a PR about it #10926. Any comment and help are more than welcome since this is my first PR.

  10. lrossert commented on Apr 6, 2018

    @lrossert
    Author

    @nsorros Looks good to me but I've not got any PR experience

  11. mloning commented on Aug 21, 2018

    @mloning
    Contributor

    I'm assuming this is the same problem.

    from sklearn.dummy import DummyClassifier
    import numpy as np
    
    # generate data
    N_OBS = 20
    y = np.random.choice([0, 1], size=(N_OBS, 1))
    X = np.random.normal(size=(N_OBS, 1))
    
    dummy = DummyClassifier()
    dummy.fit(X, y)
    
    dummy.predict_proba(X)
    
    dummy.predict(X)
    

    predict_proba() works fine, but predict() gives the following error when running the above code:

    ------------------------------------------------------------------------
    AttributeError                         Traceback (most recent call last)
    <ipython-input-48-54eaa77c7dab> in <module>()
         10 dummy.fit(X, y)
         11 dummy.predict_proba(X)
    ---> 12 dummy.predict(X)
    
    ~/.conda/envs/egym/lib/python3.6/site-packages/sklearn/dummy.py in predict(self, X)
        225             elif self.strategy == "stratified":
        226                 y = np.vstack(classes_[k][proba[k].argmax(axis=1)] for
    --> 227                               k in range(self.n_outputs_)).T
        228 
        229             elif self.strategy == "uniform":
    
    ~/.conda/envs/egym/lib/python3.6/site-packages/numpy/core/shape_base.py in vstack(tup)
        232 
        233     """
    --> 234     return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
        235 
        236 def hstack(tup):
    
    ~/.conda/envs/egym/lib/python3.6/site-packages/numpy/core/shape_base.py in <listcomp>(.0)
        232 
        233     """
    --> 234     return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
        235 
        236 def hstack(tup):
    
    ~/.conda/envs/egym/lib/python3.6/site-packages/sklearn/dummy.py in <genexpr>(.0)
        225             elif self.strategy == "stratified":
        226                 y = np.vstack(classes_[k][proba[k].argmax(axis=1)] for
    --> 227                               k in range(self.n_outputs_)).T
        228 
        229             elif self.strategy == "uniform":
    
    AttributeError: 'list' object has no attribute 'argmax'
    
  12. swainshashwat commented on Mar 4, 2019

    @swainshashwat

    I'm facing the exact issue. check_X_y does not solve the issue for me. I'm using the sklearn version from pip.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugEasy

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions