二次元の分類結果を plot
機械学習の結果、2 個の特徴の座標と分類結果をわかりやすく図で出力している
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def plot_dicision_regions(X, y, classifier, test_idx=None, resolusions=0.02): """ 二次元の X について、分類がわかるよう plot する """ # マーカーとカラーマップの準備 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, resolusions), np.arange(x2_min, x2_max, resolusions) ) 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 idx, cl in enumerate(np.unique(y)): plt.scatter( x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl, edgecolor='black') if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter( X_test[:, 0], X_test[:, 1], c='', edgecolor='black', alpha=1.0, linewidth=1, marker='o', s=100, label='test set' )