Machine-learning-with-python-implementing-svm-in-python

提供:Dev Guides
移動先:案内検索

ML-PythonでのSVMの実装

PythonでSVMを実装するには、次のように標準ライブラリのインポートから始めます-

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns; sns.set()

次に、SVMを使用して分類するために、sklearn.dataset.sample_generatorから線形に分離可能なデータを持つサンプルデータセットを作成します-

from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples = 100, centers = 2, random_state = 0, cluster_std = 0.50)
plt.scatter(X[:, 0], X[:, 1], c = y, s = 50, cmap = 'summer');

以下は、100個のサンプルと2つのクラスターを持つサンプルデータセットを生成した後の出力です-

PythonでのSVMの実装

SVMは識別分類をサポートしていることを知っています。 2次元の場合は線を、複数次元の場合は多様体を見つけるだけで、クラスを互いに分割します。 次のように上記のデータセットに実装されています-

xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c = y, s = 50, cmap = 'summer')
plt.plot([0.6], [2.1], 'x', color = 'black', markeredgewidth = 4, markersize = 12)
for m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:
plt.plot(xfit, m *xfit + b, '-k')
plt.xlim(-1, 3.5);

出力は次のとおりです-

出力

上記の出力から、上記のサンプルを完全に識別する3つの異なるセパレーターがあることがわかります。

前述のように、SVMの主な目標は、データセットをクラスに分割して最大周辺超平面(MMH)を見つけることです。したがって、クラス間にゼロ線を引くのではなく、各線の周りにある幅のマージンを最も近い点まで描画できます。 それは次のように行うことができます-

xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c = y, s = 50, cmap = 'summer')

for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:
   yfit = m* xfit + b
   plt.plot(xfit, yfit, '-k')
   plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none',
   color = '#AAAAAA', alpha = 0.4)
plt.xlim(-1, 3.5);

最大周辺超平面

出力の上記の画像から、判別分類器内の「マージン」を簡単に観察できます。 SVMはマージンを最大化するラインを選択します。

次に、Scikit-Learnのサポートベクトル分類子を使用して、このデータでSVMモデルをトレーニングします。 ここでは、線形カーネルを使用して、次のようにSVMに適合しています-

from sklearn.svm import SVC # "Support vector classifier"
model = SVC(kernel = 'linear', C = 1E10)
model.fit(X, y)

出力は次のとおりです-

SVC(C=10000000000.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma='auto_deprecated',
kernel='linear', max_iter=-1, probability=False, random_state=None,
shrinking=True, tol=0.001, verbose=False)

さて、より良い理解のために、以下は2D SVCの決定関数をプロットします-

def decision_function(model, ax = None, plot_support = True):
   if ax is None:
      ax = plt.gca()
   xlim = ax.get_xlim()
   ylim = ax.get_ylim()

モデルを評価するには、次のようにグリッドを作成する必要があります-

x = np.linspace(xlim[0], xlim[1], 30)
y = np.linspace(ylim[0], ylim[1], 30)
Y, X = np.meshgrid(y, x)
xy = np.vstack([X.ravel(), Y.ravel()]).T
P = model.decision_function(xy).reshape(X.shape)

次に、次のように決定境界とマージンをプロットする必要があります-

ax.contour(X, Y, P, colors = 'k', levels = [-1, 0, 1], alpha = 0.5, linestyles = ['--', '-', '--'])

今、次のようにサポートベクターを同様にプロットします-

if plot_support:
   ax.scatter(model.support_vectors_[:, 0],
   model.support_vectors_[:, 1], s = 300, linewidth = 1, facecolors = 'none');
ax.set_xlim(xlim)
ax.set_ylim(ylim)

さて、この関数を使用して、次のようにモデルを適合します-

plt.scatter(X[:, 0], X[:, 1], c = y, s = 50, cmap = 'summer')
decision_function(model);

SVMモデルの実装

上記の出力から、SVM分類器がマージンのあるデータに適合していることがわかります。 破線とサポートベクトル、このフィットの重要な要素、破線に触れます。 これらのサポートベクトルポイントは、次のように分類子の_support_vectors__属性に格納されます-

model.support_vectors_

出力は次のとおりです-

array([[