前提・実現したいこと
決定領域を描写するコードがあるのですがこの意味がわかりません。
該当のソースコード
以下のものが該当のコードになります。ここでわからないのは2つの配列を meshgrid
で変換しているのと、plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
でグラフに描写しているところです。
こちらのサイトにも等高線を引く時にも meshgrid
と countourf
の二つを使ってグラフを書いていました。
http://ailaby.com/contour/
なぜこれで決定領域が引けるのかがわかりません。
python
1from matplotlib.colors import ListedColormap 2 3def plot_decision_regions(X, y, classifier, resolution=0.02): 4 # マーカーとカラーマップの準備 5 markers = ('s', 'x', 'o', '^', 'v') 6 colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') 7 cmap = ListedColormap(colors[:len(np.unique(y))]) 8 9 #決定領域のプロット 10 x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 11 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 12 13 #グリッドポイントの生成 14 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), 15 np.arange(x2_min, x2_max, resolution)) 16 #各特徴量を一次元配列に変換して予測を実行 17 Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) 18 #予想結果を元のグリッドポイントのデータサイズに変換 19 Z = Z.reshape(xx1.shape) 20 # グリッドポイントの等高線のプロット 21 plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) 22 plt.xlim(xx1.min(), xx1.max()) 23 plt.ylim(xx2.min(), xx2.max()) 24 25 # plot class samples 26 for idx, cl in enumerate(np.unique(y)): 27 plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], 28 alpha=0.8, c=cmap(idx), 29 edgecolor='black', 30 marker=markers[idx], 31 label=cl)
試したこと
meshgrid
meshgrid(X,Y)
メソッドはこちらのサイトによるとマス目を作るそうですがよくわかりませんでした。実際に試して見るとこのようになり、第一引数の配列は横一列にして縦に並べるようになり、第二引数の配列は縦一列に並べて横に並べる形になりました。
python
1X = np.array([[1,2], 2 [3,4]]) 3 4 5Y = np.array([[5,6], 6 [7,8]]) 7 8xx1, xx2 = np.meshgrid(X,Y) 9 10print(xx1) 11# 12#[[1 2 3 4] 13# [1 2 3 4] 14# [1 2 3 4] 15# [1 2 3 4]] 16 17print(xx2) 18 19#[[5 5 5 5] 20# [6 6 6 6] 21# [7 7 7 7] 22# [8 8 8 8]]
countour
countour
これに関してはなんのことかわかりません。ただ、先ほどのサイトのコードを試してみると1、2引数の配列を元に第三引数のグラフへと代入しているようです。
python
1import numpy as np 2import matplotlib.pyplot as plt 3 4n = 100 5x = np.linspace(-1, 1, n) 6y = np.linspace(-1, 1, n) 7 8X, Y = np.meshgrid(x, y) 9Z = np.sqrt(X**2 + Y**2) 10 11# 12# meshgrid で作った X と Y、そして高さ Z を contour に渡す 13# 14plt.contour(X, Y, Z) 15 16plt.gca().set_aspect('equal') 17plt.show()
補足情報(FW/ツールのバージョンなど)
python機械学習プログラミング p30
github
https://github.com/rasbt/python-machine-learning-book/blob/master/code/ch02/ch02.ipynb
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。