サポートベクターマシンによる分類

Python3.5でやってみた

サポートベクターマシン

データと境界線との距離の最大化を戦略とする手法。

非線形変換により線形分離ができないものでも分類可能。

かなり精度が良く、いろんなところに使われている。

コード

# coding:utf-8

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
from sklearn import cross_validation

# データセット
X = np.c_[
          (1.3, .8),
          (1.2, .5),
          (1.3, 2.1),
          (-1.5, -1),
          (-1.4, -.9),
          (-1.3, -1.2),
          (-1.1, -.2),
          (-1.2, -.4),
          # --
          (1, -1),
          (.2, -2),
          (.5, -2.4),
          (.2, -2.3),
          (0, -2.7),
          (.4, -.7),
          (-.5, 1.2),
          (-1.5, 2.1),].T
# 正解ラベル
Y = [0] * 8 + [1] * 8

# 画面の数
fignum = 1

# 学習と描画
for kernel in ('linear', 'poly', 'rbf'):

    # SVMでの学習
    clf = svm.SVC(kernel=kernel, gamma=2)
    clf.fit(X, Y)

    # クリア
    plt.figure(fignum, figsize=(4, 3))
    plt.clf()

    # データセットのプロット
    plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
                facecolors='none', zorder=10)
    plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired,s=100)

    # maxとmin
    plt.axis('tight')
    x_min = -3
    x_max = 3
    y_min = -3
    y_max = 3

    # 等高線を書くための準備
    XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
    Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
    Z = Z.reshape(XX.shape)
    plt.figure(fignum, figsize=(4, 3))
    plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired)

    # 描画画面の設定
    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)
    plt.xticks(())
    plt.yticks(())
    fignum = fignum + 1


# plt.scatter(X[:8,0],X[:8,1],c="blue",s=100)
# plt.scatter(X[8:,0],X[8:,1],c="red",s=100)

plt.show()

f:id:carumisu:20160518155459p:plain

f:id:carumisu:20160518155506p:plain

f:id:carumisu:20160518155511p:plain

こんな感じです