KNN SVM Class Reading: October 31, 2017

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

KNN SVM Class Reading

October 31, 2017

For theoretical discussion please refer to theroretical discussion material on LMS. In this note-
book we’ll be implementing KNN and SVM to solve a simple problem [to make it possible to run
in time], same procedure can very well scale to larger problems given enough time to run your
codes.
Problem that we are discussing here pertains to predict which grade a student will belong to
given their height and shoe size.

In [1]: data_file=r'/Users/lalitsachan/Dropbox/March onwards/Python Data Science/Data/Grades.cs

In [2]: import pandas as pd


import numpy as np

In [3]: gd=pd.read_csv(data_file)

In [4]: gd.head(10)

Out[4]: shoe size height class


0 8.5 66.5 seniors
1 10.3 62.5 seniors
2 7.4 67.1 seniors
3 9.5 61.7 seniors
4 10.9 68.6 seniors
5 8.3 69.5 seniors
6 6.8 73.1 seniors
7 8.9 57.1 seniors
8 10.0 59.6 seniors
9 9.2 66.9 seniors

In [5]: gd['class'].value_counts()

Out[5]: seniors 300


fourth 300
Name: class, dtype: int64

In [9]: from sklearn.neighbors import KNeighborsClassifier


from sklearn.cross_validation import KFold,train_test_split

1
Parameters here which we should tune are :
n_neighbors : number of observations which should be used as neighbors. Too low a number
will result in overfitting , where as too high a number will not be able to extract local patterns
which KNN is good at. default is 5
weights : This controls weights to given to each neighbors effect on prediction. Default is
uniform but distance is a good choice to go with. You can anyway treat this as hyperparameter
and see which works out best for your data
metric : unless you have definite knowledge from business process for using a custom distance
function, dont worry too much about it. Minkowski distance is a gneral class of distances as
discussed in the class. You can play around with parameter p for trying out different versions of
minkowski distance. p=2 gives traditional eucledian distance where as p=1 leads to manhattan
distance.

In [11]: train,test=train_test_split(gd,test_size=0.2)

In [12]: x_train=train[['shoe size','height']]


y_train=train['class']

x_test=test[['shoe size','height']]
y_test=test['class']

Lets first visually see how the classes are, this was another reason to choose such simple prob-
lem so that you can see how the data is how KNN performs and where do misclassifications
happen if they happen

In [13]: from ggplot import *

In [14]: %matplotlib inline

In [15]: ggplot(test,aes(x='shoe size',y='height',color='class'))+geom_point()

//anaconda/lib/python3.5/site-packages/matplotlib/__init__.py:872: UserWarning: axes.color_cycl


warnings.warn(self.msg_depr % (key, alt_key))

2
Out[15]: <ggplot: (-9223372036555664668)>

We are not going to get into parameter optimisation, you can use gridsearchCV to tune them.
Procedure remains same as other algorithms

In [16]: knn=KNeighborsClassifier(n_neighbors=5,weights='distance')
knn.fit(x_train,y_train)

Out[16]: KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',


metric_params=None, n_jobs=1, n_neighbors=5, p=2,
weights='distance')

In [17]: test['predicted']=knn.predict(x_test)

//anaconda/lib/python3.5/site-packages/ipykernel/__main__.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html


if __name__ == '__main__':

3
In [18]: ggplot(test,aes(x='shoe size',y='height',color='class',shape='predicted'))+geom_point(

//anaconda/lib/python3.5/site-packages/matplotlib/__init__.py:872: UserWarning: axes.color_cycl


warnings.warn(self.msg_depr % (key, alt_key))

Out[18]: <ggplot: (277646449)>

In [20]: pd.crosstab(test['class'],test['predicted'])

Out[20]: predicted fourth seniors


class
fourth 62 2
seniors 4 52

You can see that missclassification happens in boundry cases where neighbors are of mixed
type

In [21]: from sklearn.metrics import accuracy_score

In [22]: accuracy_score(y_test,knn.predict(x_test))

4
Out[22]: 0.94999999999999996

Now lets see how svm does on the same data

In [23]: from sklearn import svm

In [29]: help(svm.SVC)

Help on class SVC in module sklearn.svm.classes:

class SVC(sklearn.svm.base.BaseSVC)
| C-Support Vector Classification.
|
| The implementation is based on libsvm. The fit time complexity
| is more than quadratic with the number of samples which makes it hard
| to scale to dataset with more than a couple of 10000 samples.
|
| The multiclass support is handled according to a one-vs-one scheme.
|
| For details on the precise mathematical formulation of the provided
| kernel functions and how `gamma`, `coef0` and `degree` affect each
| other, see the corresponding section in the narrative documentation:
| :ref:`svm_kernels`.
|
| Read more in the :ref:`User Guide <svm_classification>`.
|
| Parameters
| ----------
| C : float, optional (default=1.0)
| Penalty parameter C of the error term.
|
| kernel : string, optional (default='rbf')
| Specifies the kernel type to be used in the algorithm.
| It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or
| a callable.
| If none is given, 'rbf' will be used. If a callable is given it is
| used to pre-compute the kernel matrix from data matrices; that matrix
| should be an array of shape ``(n_samples, n_samples)``.
|
| degree : int, optional (default=3)
| Degree of the polynomial kernel function ('poly').
| Ignored by all other kernels.
|
| gamma : float, optional (default='auto')
| Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.
| If gamma is 'auto' then 1/n_features will be used instead.
|
| coef0 : float, optional (default=0.0)
| Independent term in kernel function.

5
| It is only significant in 'poly' and 'sigmoid'.
|
| probability : boolean, optional (default=False)
| Whether to enable probability estimates. This must be enabled prior
| to calling `fit`, and will slow down that method.
|
| shrinking : boolean, optional (default=True)
| Whether to use the shrinking heuristic.
|
| tol : float, optional (default=1e-3)
| Tolerance for stopping criterion.
|
| cache_size : float, optional
| Specify the size of the kernel cache (in MB).
|
| class_weight : {dict, 'balanced'}, optional
| Set the parameter C of class i to class_weight[i]*C for
| SVC. If not given, all classes are supposed to have
| weight one.
| The "balanced" mode uses the values of y to automatically adjust
| weights inversely proportional to class frequencies in the input data
| as ``n_samples / (n_classes * np.bincount(y))``
|
| verbose : bool, default: False
| Enable verbose output. Note that this setting takes advantage of a
| per-process runtime setting in libsvm that, if enabled, may not work
| properly in a multithreaded context.
|
| max_iter : int, optional (default=-1)
| Hard limit on iterations within solver, or -1 for no limit.
|
| decision_function_shape : 'ovo', 'ovr' or None, default=None
| Whether to return a one-vs-rest ('ovr') ecision function of shape
| (n_samples, n_classes) as all other classifiers, or the original
| one-vs-one ('ovo') decision function of libsvm which has shape
| (n_samples, n_classes * (n_classes - 1) / 2).
| The default of None will currently behave as 'ovo' for backward
| compatibility and raise a deprecation warning, but will change 'ovr'
| in 0.18.
|
| .. versionadded:: 0.17
| *decision_function_shape='ovr'* is recommended.
|
| .. versionchanged:: 0.17
| Deprecated *decision_function_shape='ovo' and None*.
|
| random_state : int seed, RandomState instance, or None (default)
| The seed of the pseudo random number generator to use when

6
| shuffling the data for probability estimation.
|
| Attributes
| ----------
| support_ : array-like, shape = [n_SV]
| Indices of support vectors.
|
| support_vectors_ : array-like, shape = [n_SV, n_features]
| Support vectors.
|
| n_support_ : array-like, dtype=int32, shape = [n_class]
| Number of support vectors for each class.
|
| dual_coef_ : array, shape = [n_class-1, n_SV]
| Coefficients of the support vector in the decision function.
| For multiclass, coefficient for all 1-vs-1 classifiers.
| The layout of the coefficients in the multiclass case is somewhat
| non-trivial. See the section about multi-class classification in the
| SVM section of the User Guide for details.
|
| coef_ : array, shape = [n_class-1, n_features]
| Weights assigned to the features (coefficients in the primal
| problem). This is only available in the case of a linear kernel.
|
| `coef_` is a readonly property derived from `dual_coef_` and
| `support_vectors_`.
|
| intercept_ : array, shape = [n_class * (n_class-1) / 2]
| Constants in decision function.
|
| Examples
| --------
| >>> import numpy as np
| >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
| >>> y = np.array([1, 1, 2, 2])
| >>> from sklearn.svm import SVC
| >>> clf = SVC()
| >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE
| SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
| decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
| max_iter=-1, probability=False, random_state=None, shrinking=True,
| tol=0.001, verbose=False)
| >>> print(clf.predict([[-0.8, -1]]))
| [1]
|
| See also
| --------
| SVR

7
| Support Vector Machine for Regression implemented using libsvm.
|
| LinearSVC
| Scalable Linear Support Vector Machine for classification
| implemented using liblinear. Check the See also section of
| LinearSVC for more comparison element.
|
| Method resolution order:
| SVC
| sklearn.svm.base.BaseSVC
| abc.NewBase
| sklearn.svm.base.BaseLibSVM
| abc.NewBase
| sklearn.base.BaseEstimator
| sklearn.base.ClassifierMixin
| builtins.object
|
| Methods defined here:
|
| __init__(self, C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, shrinking=True, prob
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from sklearn.svm.base.BaseSVC:
|
| decision_function(self, X)
| Distance of the samples X to the separating hyperplane.
|
| Parameters
| ----------
| X : array-like, shape (n_samples, n_features)
|
| Returns
| -------
| X : array-like, shape (n_samples, n_classes * (n_classes-1) / 2)
| Returns the decision function of the sample for each class
| in the model.
| If decision_function_shape='ovr', the shape is (n_samples,
| n_classes)
|
| predict(self, X)
| Perform classification on samples in X.
|

8
| For an one-class model, +1 or -1 is returned.
|
| Parameters
| ----------
| X : {array-like, sparse matrix}, shape (n_samples, n_features)
| For kernel="precomputed", the expected shape of X is
| [n_samples_test, n_samples_train]
|
| Returns
| -------
| y_pred : array, shape (n_samples,)
| Class labels for samples in X.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from sklearn.svm.base.BaseSVC:
|
| predict_log_proba
| Compute log probabilities of possible outcomes for samples in X.
|
| The model need to have probability information computed at training
| time: fit with attribute `probability` set to True.
|
| Parameters
| ----------
| X : array-like, shape (n_samples, n_features)
| For kernel="precomputed", the expected shape of X is
| [n_samples_test, n_samples_train]
|
| Returns
| -------
| T : array-like, shape (n_samples, n_classes)
| Returns the log-probabilities of the sample for each class in
| the model. The columns correspond to the classes in sorted
| order, as they appear in the attribute `classes_`.
|
| Notes
| -----
| The probability model is created using cross validation, so
| the results can be slightly different than those obtained by
| predict. Also, it will produce meaningless results on very small
| datasets.
|
| predict_proba
| Compute probabilities of possible outcomes for samples in X.
|
| The model need to have probability information computed at training
| time: fit with attribute `probability` set to True.
|

9
| Parameters
| ----------
| X : array-like, shape (n_samples, n_features)
| For kernel="precomputed", the expected shape of X is
| [n_samples_test, n_samples_train]
|
| Returns
| -------
| T : array-like, shape (n_samples, n_classes)
| Returns the probability of the sample for each class in
| the model. The columns correspond to the classes in sorted
| order, as they appear in the attribute `classes_`.
|
| Notes
| -----
| The probability model is created using cross validation, so
| the results can be slightly different than those obtained by
| predict. Also, it will produce meaningless results on very small
| datasets.
|
| ----------------------------------------------------------------------
| Methods inherited from sklearn.svm.base.BaseLibSVM:
|
| fit(self, X, y, sample_weight=None)
| Fit the SVM model according to the given training data.
|
| Parameters
| ----------
| X : {array-like, sparse matrix}, shape (n_samples, n_features)
| Training vectors, where n_samples is the number of samples
| and n_features is the number of features.
| For kernel="precomputed", the expected shape of X is
| (n_samples, n_samples).
|
| y : array-like, shape (n_samples,)
| Target values (class labels in classification, real numbers in
| regression)
|
| sample_weight : array-like, shape (n_samples,)
| Per-sample weights. Rescale C per sample. Higher weights
| force the classifier to put more emphasis on these points.
|
| Returns
| -------
| self : object
| Returns self.
|
| Notes

10
| ------
| If X and y are not C-ordered and contiguous arrays of np.float64 and
| X is not a scipy.sparse.csr_matrix, X and/or y may be copied.
|
| If X is a dense array, then the other methods will not support sparse
| matrices as input.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from sklearn.svm.base.BaseLibSVM:
|
| coef_
|
| ----------------------------------------------------------------------
| Methods inherited from sklearn.base.BaseEstimator:
|
| __repr__(self)
| Return repr(self).
|
| get_params(self, deep=True)
| Get parameters for this estimator.
|
| Parameters
| ----------
| deep: boolean, optional
| If True, will return the parameters for this estimator and
| contained subobjects that are estimators.
|
| Returns
| -------
| params : mapping of string to any
| Parameter names mapped to their values.
|
| set_params(self, **params)
| Set the parameters of this estimator.
|
| The method works on simple estimators as well as on nested objects
| (such as pipelines). The former have parameters of the form
| ``<component>__<parameter>`` so that it's possible to update each
| component of a nested object.
|
| Returns
| -------
| self
|
| ----------------------------------------------------------------------
| Data descriptors inherited from sklearn.base.BaseEstimator:
|
| __dict__

11
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Methods inherited from sklearn.base.ClassifierMixin:
|
| score(self, X, y, sample_weight=None)
| Returns the mean accuracy on the given test data and labels.
|
| In multi-label classification, this is the subset accuracy
| which is a harsh metric since you require for each sample that
| each label set be correctly predicted.
|
| Parameters
| ----------
| X : array-like, shape = (n_samples, n_features)
| Test samples.
|
| y : array-like, shape = (n_samples) or (n_samples, n_outputs)
| True labels for X.
|
| sample_weight : array-like, shape = [n_samples], optional
| Sample weights.
|
| Returns
| -------
| score : float
| Mean accuracy of self.predict(X) wrt. y.

Parameters to tune here are :


C : this is penaly on errors
kernel : this variable transformation which is used for making cases linearly separable . ’rbf’
is good enough and fits very fast. You can also try ’linear’, ’poly’, ’rbf’, ’sigmoid’ or your own
methods. These kernels will have their own parameters to tune.
degree : this is degree for polynomial kernel , defaults to 3. doesnt matter if you are using rbf
kernel
gamma : parameter for rbf, poly and sigmoid . default 1/n_features
coef0 : independent term in kernel function.It is only significant in ’poly’ and ’sigmoid’.
class_weight : generally it is a good idea to keep it as ’balanced’ as discussed for other algo-
rithms.

In [24]: clf=svm.SVC(verbose=True,cache_size=2000,C=20,
class_weight='balanced')
clf.fit(x_train,y_train)

12
[LibSVM]

Out[24]: SVC(C=20, cache_size=2000, class_weight='balanced', coef0=0.0,


decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=True)

In [25]: test['predicted_svm']=clf.predict(x_test)

//anaconda/lib/python3.5/site-packages/ipykernel/__main__.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html


if __name__ == '__main__':

In [26]: pd.crosstab(test['class'],test['predicted_svm'])

Out[26]: predicted_svm fourth seniors


class
fourth 63 1
seniors 2 54

In [27]: accuracy_score(y_test,clf.predict(x_test))

Out[27]: 0.97499999999999998

You can see that svm gives a huge boost in the accuracy , lets see visually where it has out-
smarted KNN

In [28]: ggplot(test,aes(x='shoe size',y='height',color='class',shape='predicted'))+geom_point(

//anaconda/lib/python3.5/site-packages/matplotlib/__init__.py:872: UserWarning: axes.color_cycl


warnings.warn(self.msg_depr % (key, alt_key))

13
Out[28]: <ggplot: (-9223372036577130352)>

You can see that , again missclassification at the boundry, but the reason is different from KNN.
This is because of classes being not entirlely linearly separable. We saw in theoretical discussion
that SVM allows some missclassification with penlaty . These missclassification are under the
penalty limit according to training data.
Also this can probably be avoided or performance can be imporved if you tuned parameters
We’ll conclude our discussion here. Please do the practice exercises . If you face any issue we’ll
discuss that either in class or QA forum on LMS.
Prepared By : Lalit Sachan ([email protected])
In case of any doubts or errata alert; please take to QA forum for discussion.
Doubts will be discussed in live class sessions too. [This doesnt apply for self paced students]

14

You might also like