旅行好きなソフトエンジニアの備忘録

プログラミングや技術関連のメモを始めました

【Python】 KNNによるデータの分類

書籍「PYTHON機械学習プログラミング」のKNNによるデータの分類例をメモします。

# -*- coding: utf-8 -*-

import numpy as np
from matplotlib.colors import ListedColormap
from matplotlib import pyplot as plt
from sklearn.neighbors import KNeighborsClassifier

def plot_decision_regions(X, y, classifier, resolution=0.02):
    # マーカーとカラーマップの準備
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # 領域の最大最小値
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1

    # グリッドポイントの生成
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))

    # 予測を実行する
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)

    # 予測結果をプロットする
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)

    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    for i, cls in enumerate(np.unique(y)):
        plt.scatter(X[y==cls, 0], X[y==cls, 1], alpha=0.8, c=cmap(i), marker=markers[i], label=cls)

    plt.show()

if __name__ == '__main__':
    # データの生成
    np.random.seed(0)
    X1 = np.random.randn(50, 2)
    y1 = np.ones(50)
    X2 = np.random.randn(50, 2) + 10
    y2 = np.ones(50)*2
    X3 = np.random.randn(50, 2)
    X3[:, 1] += 10
    y3 = np.ones(50)*3
    X4 = np.random.randn(50, 2)
    X4[:, 0] += 10
    y4 = np.ones(50)*4 
    X = np.concatenate((X1, X2, X3, X4))
    y = np.concatenate((y1, y2, y3, y4))

    # KNNによる分類
    knn = KNeighborsClassifier(n_neighbors=4)
    knn.fit(X, y)

    # 分類結果を表示する
    plot_decision_regions(X, y, knn)

f:id:ni4muraano:20170219221457j:plain