Skip to content

SVC and OneVsOneClassifier decision_function inconsistent on sub-sample #9174

Closed

Description

@nimrodta

Hi,

I'm seeing inconsistent numerical results with SVC's decision_function.
When estimated over an entire batch of samples ( (n_samples, n_features) matrix ) compared to analyzing sample-by-sample, the results are not the same.
This is true for both the individual numerical values per sample and the overall distribution of the results.

The model is SVC with RBF kernel, for a 3-class classification:

SVC(C=1.0, gamma=0.007, class_weight = new_class_weight, probability = True, random_state = 30, 
decision_function_shape = 'ovr')

The models are loaded from file:

ML = joblib.load("model.pkl")

Option A, analyze a matrix:

distances = ML.decision_function(X)

Option B, analyze individual samples:

distances = numpy.zeros([X.shape[0], 3])
for i in range(X.shape[0]):     
    distances[i,:]` = ML.decision_function(X[i,:].reshape(1,-1))

Output for first two samples:
Option A:
sample 1: [ 0.90835588, -0.17305875, 2.26470288]
sample 2: [ 1.10437313, -0.2371539 , 2.13278077]

Option B:
sample 1: [ 0.82689247, -0.32689247, 2.5 ]
sample 2: [ 1.22005359, -0.5 , 2.27994641]

I couldn't find any indication for this behavior in the documentation.

Windows-10-10.0.15063-SP0
Python 3.5.2 |Anaconda 4.2.0 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)]
NumPy 1.12.1
SciPy 0.18.1
Scikit-Learn 0.18.1

Thanks!

Activity

  1. DanaAverbuch commented on Jun 20, 2017

    @DanaAverbuch

    Hi sklearn owners,
    Is it posible the problam is in lines 422 and 423?

    max_confidences = sum_of_confidences.max()
    min_confidences = sum_of_confidences.min()
    

    It seems the lack of axis argument is influencing the downstream calculations.

    Should this function cope with a single sample array?

  2. amueller commented on Jun 20, 2017

    @amueller
    Member

    Could you please provide a self-contained example that generates the model from built-in or synthetic data?

  3. DanaAverbuch commented on Jun 20, 2017

    @DanaAverbuch

    Here you go:

    import numpy as np
    from sklearn.datasets import load_iris
    data = load_iris()
    y=data.target
    X = data.data
    from sklearn.svm import SVC
    from sklearn.multiclass import OneVsRestClassifier
    clf = SVC(decision_function_shape='ovr').fit(X, y)
    dfall = clf.decision_function(X)
    same = list()
    for i in range(X.shape[0]):
        dfone = clf.decision_function(X[i, :].reshape(1, -1))
        same.append(np.all(dfone == dfall[i, :]))
    
    print(same)
    
  4. jnothman commented on Jun 20, 2017

    @jnothman
    Member
  5. albertcthomas commented on Jul 6, 2017

    @albertcthomas
    Contributor

    Is someone working on this? I dont really know what the expected result is in this case. It is 'normal' that the results are not the same given that we use the max and the min of sum_of_confidences which are different for X[i] and X.

  6. jnothman commented on Jul 6, 2017

    @jnothman
    Member
  7. jnothman commented on Jan 8, 2018

    @jnothman
    Member

    This messes with a lot. The current behaviour is clearly problematic. I think we should:

    • have a common test (or if it exists, make sure some OvO classifiers are tested) to ensure that prediction of a sub-sample is identical to prediction of a whole sample (now Add common test to ensure all(predict(X[mask]) == predict(X)[mask]) #10420)
    • determine the scale used in _ovr_decision_function from the entire training set or a sample. But I'm not sure whether we then need to clip to ensure the score stays in (-.5, +.5) or whether doing so should be avoided as it would break ties differently, i.e. without regards to the outlying distance.
  8. changed the title [-]SVC decision_function inconsistent numerical values[/-] [+]SVC and OneVsOneClassifier decision_function inconsistent on sub-sample[/+] on Jan 8, 2018
  9. Johayon commented on Jan 9, 2018

    @Johayon
    Contributor

    I would like to propose a PR for this issue. I think the scale should be done sample by sample as this would ensure that the score always stays in (-.5, +.5) for every sample.

  10. jnothman commented on Jan 9, 2018

    @jnothman
    Member

    No, the point of the current implementation is that the rank across columns of the decision function should be meaningful as well as the rank across rows.

  11. Johayon commented on Jan 9, 2018

    @Johayon
    Contributor

    ok, I did not understand that.

  12. Johayon commented on Jan 9, 2018

    @Johayon
    Contributor

    maybe we can apply a sigmoid to map the confidence from (-inf,+inf) to (-.5,+.5) which respect the order.
    (exp(x) - 1)/2(exp(x) + 1)
    this will respect the rank across columns and rows of the decision function and can be computed sample by sample.

  13. jnothman commented on Jan 9, 2018

    @jnothman
    Member
  14. Johayon commented on Jan 9, 2018

    @Johayon
    Contributor

    the test_ovr_decision_function seems to test the current logic well enough.

    def test_ovr_decision_function():
    # One point from each quadrant represents one class
    X_train = np.array([[1, 1], [-1, 1], [-1, -1], [1, -1]])
    y_train = [0, 1, 2, 3]
    # First point is closer to the decision boundaries than the second point
    base_points = np.array([[5, 5], [10, 10]])
    # For all the quadrants (classes)
    X_test = np.vstack((
    base_points * [1, 1], # Q1
    base_points * [-1, 1], # Q2
    base_points * [-1, -1], # Q3
    base_points * [1, -1] # Q4
    ))
    y_test = [0] * 2 + [1] * 2 + [2] * 2 + [3] * 2
    clf = svm.SVC(kernel='linear', decision_function_shape='ovr')
    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    # Test if the prediction is the same as y
    assert_array_equal(y_pred, y_test)
    deci_val = clf.decision_function(X_test)
    # Assert that the predicted class has the maximum value
    assert_array_equal(np.argmax(deci_val, axis=1), y_pred)
    # Get decision value at test points for the predicted class
    pred_class_deci_val = deci_val[range(8), y_pred].reshape((4, 2))
    # Assert pred_class_deci_val > 0 here
    assert_greater(np.min(pred_class_deci_val), 0.0)
    # Test if the first point has lower decision value on every quadrant
    # compared to the second point
    assert_true(np.all(pred_class_deci_val[:, 0] < pred_class_deci_val[:, 1]))

  15. jnothman commented on Jan 9, 2018

    @jnothman
    Member
  16. harold-jeffreys commented on Dec 4, 2018

    @harold-jeffreys

    I wonder if anyone can comment if this is related to an issue I'm having. The decision_function in SVC is returning different values depending on the number of observations it is provided with. I've attempted to give a short example below (using only synthetic data). For me the results of the first line in the array is different in each case.

    import numpy as np
    from sklearn.svm import SVC
    
    X_train = np.vstack((np.random.randn(10,2), np.random.randn(10,2)+np.array([2,2]) ,  np.random.randn(10,2)+np.array([2,0])))
    y_train = np.hstack( (np.zeros(10),np.ones(10), np.ones(10)*2 ) )
    
    svm = SVC()
    svm.fit(X_train, y_train)
    
    X_tt = np.array([[-1,-2],[-1,-3], [2,2], [1,3]])
    print("Just as for the decision function of the first point:")
    print(svm.decision_function(X_tt[0,:].reshape(1,-1)))
    print("\n\nTry asking for all the points together")
    print(svm.decision_function(X_tt))
    
  17. jnothman commented on Dec 9, 2018

    @jnothman
    Member

    Sounds like the same issue. Does #10440 get more consistent results?

  18. glemaitre commented on Jan 28, 2019

    @glemaitre
    Member

    #10440 give consistent results.

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