Skip to content

SGDClassifier never has the attribute "predict_proba" (even with log or modified_huber loss) #10113

Closed

Description

@jhays006

Description

SGDClassifier's predict_proba() is not compatible with MultiOutputClassifier's predict_proba() (even when it has the proper loss functions: log or modified_huber).

The incompatibility occurs because estimators implementing SGDClassifier do not have the attribute "predict_proba"; thus, when wrapped by MultiOutputClassifier, predict_proba() raises an error.
The error occurs in this file:
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/multioutput.py

At this condition:

        if not hasattr(self.estimator, "predict_proba"):
            raise ValueError("The base estimator should implement"
                             "predict_proba method")

Just for the overly simplified example below, LogisticRegression classifiers do have the attribute, and those work correctly.

Steps/Code to Reproduce

from sklearn.linear_model import SGDClassifier as online
from sklearn.linear_model import LogisticRegression as log

# use either one because they allow predict_proba() with SGDClassifier alone:
clf_test = online(loss="log", penalty="l2")
#clf_test = online(loss="modified_huber", penalty="l2")

# The problematic condition in MultiOutputClassifier's predict_proba():
if not hasattr(clf_test, "predict_proba"):
    print("Don't allow predict_proba() when wrapped by MultiOutputClassifier.")
else:
    print("Allow predict_proba() when wrapped by MultiOutputClassifier.")

# By contrast, the logistic regression classifier would work.
clf_test = log()
if not hasattr(clf_test, "predict_proba"):
    print("Don't allow predict_proba() when wrapped by MultiOutputClassifier.")
else:
    print("Allow predict_proba() when wrapped by MultiOutputClassifier.")

Expected Results

Allow predict_proba() when wrapped by MultiOutputClassifier.
Allow predict_proba() when wrapped by MultiOutputClassifier.

Actual Results

Don't allow predict_proba() when wrapped by MultiOutputClassifier.
Allow predict_proba() when wrapped by MultiOutputClassifier.

Versions

Windows-10-10.0.15063
('Python', '2.7.11 |Anaconda custom (32-bit)| (default, Mar 4 2016, 15:18:41) [MSC v.1500 32 bit (Intel)]')
('NumPy', '1.10.4')
('SciPy', '0.17.0')
('Scikit-Learn', '0.19.1')

Activity

  1. changed the title [-]SDGClassifier never has the attribute "predict_proba" (even with log or modified_huber loss)[/-] [+]SGDClassifier never has the attribute "predict_proba" (even with log or modified_huber loss)[/+] on Nov 11, 2017
  2. jhays006 commented on Nov 11, 2017

    @jhays006
    Author

    Alright, it has something to do with predict_proba being a property in SGDClassifier.

    A simple workaround (which will work before or after there's a fix) is to make a simple subclass that implements predict_proba (not a property) by calling the super's predict_proba. In case it isn't obvious, the data is made-up here.

    from sklearn.linear_model import SGDClassifier as online
    from sklearn.multioutput import MultiOutputClassifier as moc
    
    class Simple(online):
        # be sure to add the rest of the parameters if you need them
        def __init__(self, loss='log'):
            super(Simple, self).__init__(loss=loss, penalty="l2")
        
        def predict_proba(self, X):
            return super(Simple, self).predict_proba(X)
    
    # Subclass works
    clf_test = moc(Simple())
    clf_test.partial_fit([[0,1], [1,0]], [[0,1], [1,0]], [[0,1], [0,1]])
    print clf_test.predict_proba([[0,1]])
    
    # main class fails
    clf_test = moc(online(loss="log", penalty="l2"))
    clf_test.partial_fit([[0,1], [1,0]], [[0,1], [1,0]], [[0,1], [0,1]])
    print clf_test.predict_proba([[0,1]])
  3. jnothman commented on Nov 11, 2017

    @jnothman
    Member

    predict_proba, for some estimators, is only available after fitting.

    yes, MultiOutputClassifier is incorrectly checking whether predict_proba is available on self.estimator rather than self.estimators_[0]. Fix welcome.

  4. jnothman commented on Nov 11, 2017

    @jnothman
    Member

    Perhaps MultiOutputClassifier should also use the same property mechanism to only make predict_proba available after fitting.

  5. added
    Easy
    on Nov 11, 2017
  6. jhays006 commented on Nov 11, 2017

    @jhays006
    Author

    But, predict_proba isn't available even after fitting.

  7. jnothman commented on Nov 11, 2017

    @jnothman
    Member

    The problem is that MultiOutputClassifier is checking the before-fitting estimator for whether it supports predict_proba, not the after-fitting estimator.

    SGDClassifier, after fitting, should support predict_proba with an appropriate loss:

    >>> from sklearn.linear_model import SGDClassifier
    >>> sgd = SGDClassifier(loss="log", penalty="l2")
    >>> sgd.fit([[0], [1]], [0, 1])
    /Users/joel/repos/scikit-learn/sklearn/linear_model/stochastic_gradient.py:128: FutureWarning: max_iter and tol parameters have been added in <class 'sklearn.linear_model.stochastic_gradient.SGDClassifier'> in 0.19. If both are left unset, they default to max_iter=5 and tol=None. If tol is not None, max_iter defaults to max_iter=1000. From 0.21, default max_iter will be 1000, and default tol will be 1e-3.
      "and default tol will be 1e-3." % type(self), FutureWarning)
    SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1,
           eta0=0.0, fit_intercept=True, l1_ratio=0.15,
           learning_rate='optimal', loss='log', max_iter=None, n_iter=None,
           n_jobs=1, penalty='l2', power_t=0.5, random_state=None,
           shuffle=True, tol=None, verbose=0, warm_start=False)
    >>> sgd.predict_proba([[0]])
    array([[ 0.99285523,  0.00714477]])
  8. jhays006 commented on Nov 11, 2017

    @jhays006
    Author

    Oh, it's checking too early. Alright, thanks for looking into it so fast.

  9. jnothman commented on Nov 11, 2017

    @jnothman
    Member
  10. FinLouarn commented on Jul 16, 2018

    @FinLouarn

    @srajanpaliwal it seems your are not going to close this issue soon, but correct me if I'm wrong?
    I'm taking over it, and will try to push something soon.

  11. FinLouarn commented on Jul 16, 2018

    @FinLouarn

    'Fix SGDClassifier never has the attribute "predict_proba" ' #10389 seems to fix #10113, but not yet reviewed and closed. @jnothman do you agree that #10389 fixed #10113 ?

  12. jnothman commented on Jul 16, 2018

    @jnothman
    Member

    @FinLouarn, yes, it's the right solution, but lacks a test.

  13. jnothman commented on Jul 16, 2018

    @jnothman
    Member

    Please do complete it.

  14. rebekahkim commented on Sep 29, 2018

    @rebekahkim
    Contributor

    I'll work on the test

  15. jnothman commented on Feb 25, 2019

    @jnothman
    Member

    I can't reproduce this issue at master actually. Running the code under "steps to reproduce" I get the expected results. Close?

  16. rebekahkim commented on Feb 27, 2019

    @rebekahkim
    Contributor

    @jnothman, I think @TomDLT also suggested the same thing but as @amueller pointed out, it would still fail for certain (obscure) cases.

    Here's an edge case I came up with in #12222

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

    Easyhelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions