import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
%matplotlib inline
SVM with RBF kernel
SVM with RBF kernel
Let us now understand how the gamma parameter works. For that, we will look at a different dataset
from sklearn import datasets
= datasets.load_iris()
iris = iris.data
X = iris.target
y
= X[y != 0, :2]
X = y[y != 0] y
0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired,
plt.scatter(X[:, ='k', s=100) edgecolor
<matplotlib.collections.PathCollection at 0x7ff4422b1e50>
from sklearn import svm
def plot_contour(clf, X, y):
0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired,
plt.scatter(X[:, ='k', s=100)
edgecolor
'tight')
plt.axis(= X[:, 0].min()-1
x_min = X[:, 0].max()+1
x_max = X[:, 1].min()-1
y_min = X[:, 1].max()+1
y_max
= np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
XX, YY = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
Z
# Put the result into a color plot
= Z.reshape(XX.shape)
Z > 0, cmap=plt.cm.Paired, alpha=0.2)
plt.pcolormesh(XX, YY, Z
=['k', 'k', 'k'],
plt.contour(XX, YY, Z, colors=['--', '-', '--'], levels=[-.5, 0, .5]) linestyles
# Fit linear SVM
= svm.SVC(kernel='linear')
clf
clf.fit(X, y) plot_contour(clf, X, y)
# Fit polynomial SVM of degree 2, 3, 4
for degree in range(3, 7):
= svm.SVC(kernel='poly', degree=degree)
clf
clf.fit(X, y)
plt.figure()'degree = {}'.format(degree))
plt.title( plot_contour(clf, X, y)
= X
X_train = y
y_train = 'rbf'
kernel # Store kernel matrix
= []
kms for fig_num, gamma in enumerate([0.01, 0.1, 1, 10, 100, 1000]):
= svm.SVC(kernel=kernel, gamma=gamma)
clf
clf.fit(X_train, y_train)
plt.figure(fig_num)
plt.clf()
"gamma = {}".format(gamma))
plt.title( plot_contour(clf, X_train, y_train)