Skip to content

ovr decision_function calculation from ovo case #6416

Closed

Description

@btdai

Dear scikit-learn developers,

I found a small bug in sklearn/svm/base.py, function decision_function, line 545. The first argument passed to multiclass._ovr_decision_function in sklearn/multiclass.py does not much with the implementation of _ovr_decision_function. The first argument from svm.decision_function is a boolean ndarray, while line 603, 604 in multiclass.py actually check if the values are 0 or 1. So the vote matrix is always zero, no matter what the first argument is from svm.decision_function.

I understand that the ovo will be replaced by ovr in version 0.18, so not sure if this function will be still valid in 0.18. Just point out just in case that, you actually wanted to check True/False, but became 0/1.

Thank you for all your effort, sklearn is very helpful!

Activity

  1. yenchenlin commented on Feb 22, 2016

    @yenchenlin
    Contributor

    Hello @btdai ,
    Can you provide a minimum example script to reproduce the error?

    By the way, you can use:
    https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/base.py#L545
    to refer to particular line of code in sklearn.

  2. btdai commented on Feb 23, 2016

    @btdai
    ContributorAuthor

    Thank you, Yen.

    Do you still need me to write a piece of code to demonstrate this?

  3. yenchenlin commented on Feb 23, 2016

    @yenchenlin
    Contributor

    Yes please

  4. btdai commented on Feb 23, 2016

    @btdai
    ContributorAuthor

    Hi, Yen,

    I think i was wrong, even if I changed the variable (as 0-1 ndarrays)
    passed to multiclass_ovr_decision_function, I still don't get what I
    wanted. So this is not a bug between 0-1 to boolean varaible.

    Please run the attached python file. The darker the color is, the higher
    confidence score it should be. So we should see extreme values far from the
    separating plane. However, from the visualization, the darkest and lightest
    color are just beside the hyperplane. I'm thinking why this happens.

    On Tue, Feb 23, 2016 at 11:02 AM, Yen [email protected] wrote:

    Yes please

    —
    Reply to this email directly or view it on GitHub
    #6416 (comment)
    .

  5. btdai commented on Feb 23, 2016

    @btdai
    ContributorAuthor

    Hi, All,

    After another round of investigation, I suspect there is a bug at sklearn/svm/base.py at line 545 https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/base.py#L545 , I suggest to change it from
    return _ovr_decision_function(dec < 0, dec, len(self.classes_))
    to
    return _ovr_decision_function(dec < 0, -dec, len(self.classes_))

    The picture below shows the decision_function of ovr of the current implementation (first row), and the decision_function of ovr after modification (second row). Our intuition is this, if a point is further away from the separating hyperplane, the value of decision function should be more extreme (lighter and darker in the picture). However, the three plots in the first row are against this intuition, the points nearer to the hyperplane is darker or lighter.
    ovr_decision_function
    So I think there is a bug at line 545 in sklearn/svm/base.py If we were to give multiclass._ovr_decision_function dec<0 to vote, we ought to give the negative of decision_function too. Therefore, I suggested to change as the above.

    import numpy as np
    from sklearn import datasets, svm, multiclass
    import matplotlib.pyplot as plt
    
    def my_linspace (min_value, max_value, steps):
        diff = max_value - min_value
        return np.linspace (min_value - 1.0 * diff, max_value + 1.0 * diff, steps)
    
    iris = datasets.load_iris()
    x = iris.data[:,:2]
    y = iris.target
    
    ovo = svm.SVC(kernel='linear')
    ovr = svm.SVC(kernel='linear', decision_function_shape='ovr')
    ovo.fit(x, y)
    ovr.fit(x, y)
    
    steps = 200
    x0 = my_linspace(min(x[:,0]), max(x[:,0]), steps)
    x1 = my_linspace(min(x[:,1]), max(x[:,1]), steps)
    xx0, xx1 = np.meshgrid(x0, x1)
    mesh_data = np.c_[xx0.ravel(), xx1.ravel()]
    ovo_deci = ovo.decision_function(mesh_data)
    ovr_deci = ovr.decision_function(mesh_data)
    
    new_deci = multiclass._ovr_decision_function(ovo_deci < 0, -ovo_deci, 3).reshape(steps, steps, 3)
    ovo_deci = ovo_deci.reshape(steps, steps, 3)
    ovr_deci = ovr_deci.reshape(steps, steps, 3)
    
    color = ['red', 'green', 'blue']
    y_color = [color[i] for i in y]
    
    plt.figure(figsize = (18, 12))
    contour_color = [plt.cm.Reds, plt.cm.Greens, plt.cm.Blues]
    
    for i in range(3):
        plt.subplot(2, 3, i + 1)
        plt.scatter(x[:,0], x[:,1], c=y_color)
        plt.contourf(xx0, xx1, ovr_deci[:,:,i], 20, cmap=contour_color[i], alpha=0.5)
        plt.subplot(2, 3, i + 4)
        plt.scatter(x[:,0], x[:,1], c=y_color)
        plt.contourf(xx0, xx1, new_deci[:,:,i], 20, cmap=contour_color[i], alpha=0.5)
    
    plt.show()
  6. btdai commented on Mar 4, 2016

    @btdai
    ContributorAuthor

    Hi, All,

    Is there anyway to get attentions from contributors for this post? I'm new to this community, thank you.

  7. amueller commented on Oct 8, 2016

    @amueller
    Member

    @btdai sorry, there is a huge backlog of issues.

  8. amueller commented on Oct 8, 2016

    @amueller
    Member

    I find it extremely hard to judge what you're saying from the hues. Can you maybe provide a simple numeric example?

  9. jnothman commented on Oct 8, 2016

    @jnothman
    Member

    decision_function's value should be greater if farther from separating hyperplane. Is that what you're suggesting here?

  10. btdai commented on Oct 8, 2016

    @btdai
    ContributorAuthor

    Dear Andreas and Joel,

    I really appreciate your replies on this issue, and understand the huge
    backlog of issues.

    What Joel said is right. In the case of binary classification, the
    decision_function should give 0 at the separating hyperplane, and the
    further it is from the hyperplane, the greater the absolute value of
    decision_function gives.

    For the decision_function in ovr (one vesus rest) case, it should be a sum
    from decision_function from various ovo (one vesus one) cases, so the
    property that values near to hyperplane should be closer to zero, should be
    preserved. However, I found the output from decision_function is not
    intuitive.

    If you see the figure below, you will see the darkest and lightest area is
    just next to the intersections of hyperplanes, that's why I said it's not
    intuitive. What I expected to see is that darkest and lightest area are
    furthest from the intersection of hyperplanes.

    [image: Inline image 1]

    The code for generating the plot is as attached.

    Thank you very much.

    Bing Tian

    On Sat, Oct 8, 2016 at 9:39 PM, Joel Nothman [email protected]
    wrote:

    decision_function's value should be greater if farther from separating
    hyperplane. Is that what you're suggesting here?

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub
    #6416 (comment),
    or mute the thread
    https://github.com/notifications/unsubscribe-auth/AQmGoBrklbLl0S3PA8U3B6Lb9cGm8kpJks5qx5z2gaJpZM4HfS_Z
    .

  11. amueller commented on Oct 8, 2016

    @amueller
    Member

    I don't see any code attached. It would be great if you could provide a numerical example with like 5 data points. Arguing about hues is tricky.

  12. btdai commented on Oct 10, 2016

    @btdai
    ContributorAuthor

    Hi, Andreas,

    I used the iris dataset, which is about 150 data points. There are three classes, so there are two ovo for each class. For example, if we are looking at the red class, there are two ovo, which are Red v.s. Green and Red v.s. Blue, so the ovr classifier actually combines these two binary classifier, however, for points that are further from the hyperplane, we shall see the value further from zero, i.e., either lightest or darkest.

    Please run the code below with matplotlib.

    -- Bing Tian

    import numpy as np
    from sklearn import datasets, svm, multiclass
    import matplotlib.pyplot as plt
    
    def my_linspace (min_value, max_value, steps):
        diff = max_value - min_value
        return np.linspace (min_value - 1.0 * diff, max_value + 1.0 * diff, steps)
    
    iris = datasets.load_iris()
    x = iris.data[:,:2]
    y = iris.target
    
    ovo = svm.SVC(kernel='linear')
    ovr = svm.SVC(kernel='linear', decision_function_shape='ovr')
    ovo.fit(x, y)
    ovr.fit(x, y)
    
    steps = 200
    x0 = my_linspace(min(x[:,0]), max(x[:,0]), steps)
    x1 = my_linspace(min(x[:,1]), max(x[:,1]), steps)
    xx0, xx1 = np.meshgrid(x0, x1)
    mesh_data = np.c_[xx0.ravel(), xx1.ravel()]
    ovo_deci = ovo.decision_function(mesh_data)
    ovr_deci = ovr.decision_function(mesh_data)
    
    new_deci = multiclass._ovr_decision_function(ovo_deci < 0, -ovo_deci, 3).reshape(steps, steps, 3)
    ovo_deci = ovo_deci.reshape(steps, steps, 3)
    ovr_deci = ovr_deci.reshape(steps, steps, 3)
    
    color = ['red', 'green', 'blue']
    y_color = [color[i] for i in y]
    
    plt.figure(figsize = (18, 12))
    contour_color = [plt.cm.Reds, plt.cm.Greens, plt.cm.Blues]
    
    for i in range(3):
        plt.subplot(2, 3, i + 1)
        plt.scatter(x[:,0], x[:,1], c=y_color)
        plt.contourf(xx0, xx1, ovr_deci[:,:,i], 20, cmap=contour_color[i], alpha=0.5)
        plt.subplot(2, 3, i + 4)
        plt.scatter(x[:,0], x[:,1], c=y_color)
        plt.contourf(xx0, xx1, new_deci[:,:,i], 20, cmap=contour_color[i], alpha=0.5)
    
    plt.show()
  13. btdai commented on Oct 10, 2016

    @btdai
    ContributorAuthor

    the 3 figures in the top row is what ovr decision function gives

    the 3 figures in the bottom row is what I think is intuitive.

  14. 3 remaining items

  15. btdai commented on Oct 19, 2016

    @btdai
    ContributorAuthor

    Thank you @jnothman

  16. btdai commented on Oct 19, 2016

    @btdai
    ContributorAuthor

    Hi, Andreas, @amueller

    I created this 6-points test dataset with choosing 2 points for each class (each of red, green, blue), one nearer to the decision boundaries, and the other further from the decision boundaries.

    The 6 points are labelled by the values from decision functions, for the respective ovr classifier, e.g., the values in the two figures of the first column represent the decision functions of the red-vs-rest classifier. We do expect the further the points are away from the decision boundaries, the values from decision functions should be higher (of coz values should be positive, since points belong to that class)

    The values in the 3 figures on the upper row reveal the decision function from build-in decision_function when the SVC is set to 'ovr'. While the values in the 3 figures on the lower row reveal the decision function from my own calculation, where I did a simple modification to change the sign of decision function values from ovo classifiers.

    I believe what I did is right, because, while calling
    return _ovr_decision_function(dec < 0, dec, len(self.classes_))

    we take neg decision values as class 0, pos decision values as class 1, so the second argument should be consistent with the first, by changing its sign, so it should be
    return _ovr_decision_function(dec < 0, -dec, len(self.classes_))

    6_points

    import numpy as np
    from sklearn import datasets, svm, multiclass
    import matplotlib.pyplot as plt
    
    iris = datasets.load_iris()
    x = iris.data[:,:2]
    y = iris.target
    
    ovo = svm.SVC(kernel='linear')
    ovr = svm.SVC(kernel='linear', decision_function_shape='ovr')
    ovo.fit(x, y)
    ovr.fit(x, y)
    
    test_pts = [()] * 6
    test_pts[0] = (5.0, 3.1) # red class nearer to decision boundaries
    test_pts[1] = (4.5, 3.5) # red class further from decision boundaries
    test_pts[2] = (5.5, 2.6) # green class nearer to decision boundaries
    test_pts[3] = (5.0, 2.0) # green class further from decision boundaries
    test_pts[4] = (6.5, 3.0) # blue class nearer to decision boundaries
    test_pts[5] = (7.5, 3.0) # blue class further from decision boundaries
    test_pts = np.array(test_pts)
    
    ovo_deci = ovo.decision_function(test_pts)
    ovr_deci = ovr.decision_function(test_pts)
    # the line above actually calls multiclass._ovr_decision_function(ovo_deci < 0, ovo_deci, 3)
    # I personally believe we should change the sign of ovo_deci as the next line
    new_deci = multiclass._ovr_decision_function(ovo_deci < 0, -ovo_deci, 3)
    
    color = ['red', 'green', 'blue']
    y_color = [color[i] for i in y]
    
    text_pos = [(5.0,4.5),(5.0,4.8),(7.5,2.1),(7.5,1.8),(7.5,4.8),(7.5,4.5)]
    
    plt.figure(figsize = (18, 12))
    for i in range(3):
        plt.subplot(2, 3, i + 1)
        plt.scatter(x[:,0], x[:,1], c=y_color, marker='+')
        plt.scatter(test_pts[2*i:2*i+2,0], test_pts[2*i:2*i+2,1], c=color[i], s = 80)
        for j in range(2*i, 2*i+2):
            plt.annotate('%.3f' % ovr_deci[j,i], xy=test_pts[j], xytext=text_pos[j],arrowprops=dict(facecolor='black', shrink=0.05))
        plt.subplot(2, 3, i + 4)
        plt.scatter(x[:,0], x[:,1], c=y_color, marker='+')
        plt.scatter(test_pts[2*i:2*i+2,0], test_pts[2*i:2*i+2,1], c=color[i], s = 80)
        for j in range(2*i, 2*i+2):
            plt.annotate('%.3f' % new_deci[j,i], xy=test_pts[j], xytext=text_pos[j],arrowprops=dict(facecolor='black', shrink=0.05))
    
    plt.show()
  17. modified the milestones: 0.18.1, 0.19 on Oct 19, 2016
  18. btdai commented on Oct 21, 2016

    @btdai
    ContributorAuthor

    Hi, All,

    I have made a pull request here: https://github.com/btdai/scikit-learn/pull/1

    Do I get an approval from somewhere?

    Thank you.

  19. maniteja123 commented on Oct 21, 2016

    @maniteja123
    Contributor

    Hi @btdai , thanks for the contribution, but I suppose you intended to create a PR for scikit-learn main repo, instead of your forked repository. Also I think, a non-regression test would be helpful as suggested by @amueller to show that the change has the intended effect. Thanks !
    Also, I believe a better name for the PR would be helpful, something like BUG: Fix ovr decision_function calculation from ovo case and tag it with [MRG] at the beginning in case you have completed the fix and would like it to be reviewed.

  20. maniteja123 commented on Oct 21, 2016

    @maniteja123
    Contributor

    Hi, I am not sure why you can't see the dropdown, but you could go to your fork and change the branch to btdai_patch_ovr_decision_function and then select Compare which would lead to comparison from where you can create a PR.

    Also it seems you accidentally inverted the logic and the second PR is to merge changes from scikit-learn upstream to your fork. It should be the other way around.

    Hope it helps.

  21. amueller commented on Oct 21, 2016

    @amueller
    Member

    @btdai I think your PR was closed because it contained many unrelated changes and had no message saying what it was about.

  22. btdai commented on Oct 22, 2016

    @btdai
    ContributorAuthor

    @amueller @maniteja123
    Hi, Andreas and Maniteja,

    I created this PR: #7724
    Hope it is right this time.

    Thank you for your help!

  23. lesteve commented on Oct 22, 2016

    @lesteve
    Member

    Hope it is right this time.

    Your PR looks good (just talking about the form not the actual content which I haven't looked at yet), congrats for sticking to it despite the difficulties! The good thing is that it will be way easier for your next PRs ;-) !

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions