Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Machine Learning by (19k points)

I read this thread about the difference between SVC() and LinearSVC() in scikit-learn.

Now I have a data set of binary classification problem(For such a problem, the one-to-one/one-to-rest strategy difference between both functions could be ignore.)

I want to try under what parameters would these 2 functions give me the same result. First of all, of course, we should set kernel='linear' for SVC() However, I just could not get the same result from both functions. I could not find the answer from the documents, could anybody help me to find the equivalent parameter set I am looking for?

I modified the following code from an example of the scikit-learn website, and apparently they are not the same:

import numpy as np

import matplotlib.pyplot as plt

from sklearn import svm, datasets

iris = datasets.load_iris()

X = iris.data[:, :2]              

y = iris.target

for i in range(len(y)):

    if (y[i]==2):

        y[i] = 1

h = .02  

C = 1.0  

svc = svm.SVC(kernel='linear', C=C).fit(X, y)

lin_svc = svm.LinearSVC(C=C, dual = True, loss = 'hinge').fit(X, y)

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1

y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1

xx, yy = np.meshgrid(np.arange(x_min, x_max, h),

                     np.arange(y_min, y_max, h))

titles = ['SVC with linear kernel',

          'LinearSVC (linear kernel)']

for i, clf in enumerate((svc, lin_svc)):

    plt.subplot(1, 2, i + 1)

    plt.subplots_adjust(wspace=0.4, hspace=0.4)

    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)

    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)

    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired)

    plt.xlabel('Sepal length')

    plt.ylabel('Sepal width')

    plt.xlim(xx.min(), xx.max())

    plt.ylim(yy.min(), yy.max())

    plt.xticks(())

    plt.yticks(())

    plt.title(titles[i])

plt.show()

1 Answer

0 votes
by (33.1k points)
edited by

In machine learning,

SVC(kernel='linear', **kwargs) # by default uses RBF kernel

LinearSVC(loss='hinge', **kwargs) 

Another element, that can't be easily fixed is increasing intercept_scaling in LinearSVC, as in this implementation bias is regularized - consequently, they will never be exactly equal (unless bias=0 for your problem), but they assume two different models.

SVC : 1/2||w||^2 + C SUM xi_i

LinearSVC: 1/2||[w b]||^2 + C SUM xi_i

After increasing intercept scaling (to 10.0)

Hope this answer helps you!

If you want to know more about Machine Learning Algorithms and undergo a Machine Learning Certification then watch this video:

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...