import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
%matplotlib inline
SVM Kernel
SVM Kernel
= np.array([-2, -1, 0, 1, 2, 3, 4]).reshape(-1, 1)
X = np.array([-1, -1, 1, 1, 1, -1, -1]) y
=y, cmap=cm.Paired) plt.scatter(X.flatten(), np.zeros_like(X), c
<matplotlib.collections.PathCollection at 0x7f8e0b18f490>
def phi(x):
return np.hstack([x, x**2])
phi(X)
array([[-2, 4],
[-1, 1],
[ 0, 0],
[ 1, 1],
[ 2, 4],
[ 3, 9],
[ 4, 16]])
0], phi(X)[:, 1], c = y,cmap = cm.Paired) plt.scatter(phi(X)[:,
<matplotlib.collections.PathCollection at 0x7f8beb7f5fa0>
from sklearn.svm import SVC
= SVC(C=1, kernel='linear') c
c.fit(phi(X), y)
SVC(C=1, kernel='linear')
0], phi(X)[:, 1], c = y, zorder=10, cmap =cm.Paired, edgecolors='k', alpha=1, s=200)
plt.scatter(phi(X)[:, = phi(X)[:, 0].min()-1
x_min = phi(X)[:, 0].max()+1
x_max = phi(X)[:, 1].min()-1
y_min = phi(X)[:, 1].max()+1
y_max
= np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
XX, YY = c.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.6)
plt.pcolormesh(XX, YY, Z =['k', 'k', 'k'],
plt.contour(XX, YY, Z, colors=['--', '-', '--'], levels=[-1, 0, 1])
linestylesr"$x_1 = X$")
plt.xlabel(r"$x_2 = X^2$")
plt.ylabel(r"Decision surface: {:0.1f}*x_1 + {:0.1f}*x_2 + {:0.1f} = 0".format(c.coef_[0, 0], c.coef_[0, 1], c.intercept_[0])) plt.title(
Text(0.5, 1.0, 'Decision surface: 1.3*x_1 + -0.7*x_2 + 1.0 = 0')
# Fit a SVM with polynomial kernel
= SVC(C=1, kernel='poly', degree=2)
c
c.fit(X, y)
SVC(C=1, degree=2, kernel='poly')