Skip to content

Different results depending on data type of class labels using svm.SVC #11263

Open

Description

@danjgale

Hi All,

I'm getting different results using sklearn.svm.SVC depending on whether I use strings or integers for my class labels during multiclassification. I would expect that the data type for class labels shouldn't matter (unless I am missing something). I've narrowed this down to SVC (i.e. this doesn't happen with LogisticRegression() or LinearSVC()). I've also not been able to reproduce this issue with a toy dataset made from scratch, but below I've provided a sample (n = 20) of the dataset I am working with, along with code, that produces this issue.

Link to the data:
https://www.dropbox.com/s/tgx02j5nfvc860q/test.csv?dl=0

The first 5 rows and 7 columns look like this (columns 0 and 1 are class labels, either as string or int, respectively):

0  LL  0  0.728522 -0.649361  3.853140 -0.903645 -1.551013 -0.080372   
1  LL  0  1.601109 -4.050748 -0.429045 -3.481833  2.344579 -0.615784   
2  LL  0  3.829118  1.465271  3.090473 -4.780373  1.583611  3.498092   
3  LL  0 -0.535664  1.090892  3.537763 -1.333069  0.273352  2.050236   
4  LL  0 -0.413857  0.795902  1.273712  0.621104  2.638997  2.792364

Steps/Code to Reproduce

import pandas as pd
from sklearn.svm import SVC
from sklearn.cross_validation import cross_val_score

data = pd.read_csv('test.csv')

x = data.iloc[:, 2:].values # features with shape (20, 44)
class_str = data.iloc[:, 0]  # contains class labels 'LL', 'LR', 'GL', 'GR'
class_int = data.iloc[:, 1] # contains class labels 0 1 2 3 

# run a simple 3-fold CV on the data with each type of class label
clf = SVC(C=1.0, kernel='linear')
print(cross_val_score(clf, x, class_int))
print(cross_val_score(clf, x, class_str))

Expected Results

Same cross validation accuracies. E.g.,

[0.625 0.25  0.25 ]
[0.625 0.25  0.25 ]

Actual Results

Different cross validation accuracies:

[0.625 0.25  0.25 ]
[0.625 0.375 0.5  ]

So, the results differ based on the label type. But, critically, the int and str labels properly correspond to one another so we wouldn't expect there to be a mismatch.

Any help would be appreciated, thanks!

Versions

Darwin-17.4.0-x86_64-i386-64bit
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:14:23) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]
NumPy 1.14.2
SciPy 1.0.1
Scikit-Learn 0.19.1

Activity

  1. albertcthomas commented on Jun 15, 2018

    @albertcthomas
    Contributor

    Actually just a fit gives different results on class_int and class_str. For instance clf.dual_coef_ and clf.intercept_ are different and one is not even a permutation of the other one because of small differences.

  2. albertcthomas commented on Jun 15, 2018

    @albertcthomas
    Contributor

    When the following transformation is performed on the labels

    cls, y = np.unique(y_, return_inverse=True)

    we obtain

    cls = array(['GL', 'GR', 'LL', 'LR'], dtype=object)
    y = array([2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], dtype=int64)

    I wonder if this can be the cause of small differences in the results

  3. danjgale commented on Jun 15, 2018

    @danjgale
    Author

    ^Using LabelEncoder returns the same results.

    from sklearn.preprocessing import LabelEncoder
    
    LabelEncoder().fit_transform(class_str)

    produces:

    array([2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
    

    That could be it. But, the labels themselves shouldn't have an effect on performance though, correct?

  4. albertcthomas commented on Jun 15, 2018

    @albertcthomas
    Contributor

    I'm not sure but the bug might come from libsvm and which label is mapped to -1 and which label is mapped to +1. A smaller reproducible example showing that we don't exactly obtain the same intercept in such a case

    import numpy as np
    from sklearn.svm import SVC
    
    rng = np.random.RandomState(37)
    
    X = rng.randn(100, 2)
    y_int = np.array([-1] * 50 + [1] * 50)
    y_str = np.array([1] * 50 + [-1] * 50)
    
    clf_1 = SVC()
    clf_1.fit(X, y_int)
    
    clf_2 = SVC()
    clf_2.fit(X, y_str)
    
    print(np.abs(clf_1.intercept_))
    print(np.abs(clf_2.intercept_))

    returns

    [ 0.26214191]
    [ 0.26186368]
    
  5. jnothman commented on Jun 17, 2018

    @jnothman
    Member

    The variation definitely comes down to the order of the mapping between class strings and numbers: scikit-learn will map to numbers in sorted order.

    However, something else I notice is that every sample but 15 is a support vector, which probably means that it's a bad fit (although I'm not particularly expert on SVMs so I'm not certain that's a correct interpretation). I wonder if that's true for your larger dataset too.

    clf = SVC(C=1.0, kernel='linear')
    clf.fit(x, class_int)
    print(clf.support_)
    clf.fit(x, class_str)
    print(clf.support_)
  6. albertcthomas commented on Jun 18, 2018

    @albertcthomas
    Contributor

    @jnothman Should there be a common test for classifiers checking that flipping the labels roughly gives the same results?

  7. jnothman commented on Jun 18, 2018

    @jnothman
    Member
  8. danjgale commented on Jun 18, 2018

    @danjgale
    Author

    This doesn't add too much, but FWIW I rebuilt my procedure using R and the e1071 package and reanalyzed my actual dataset. I was able to replicate the results, either using integers or string labels in R, of class_int, but not class_str. Should users default to setting class labels as integers, rather than string just to be safe?

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