LoginSignup
1
2

More than 3 years have passed since last update.

Python機械学習プログラミング第3章冒頭のソース解説

Posted at

はじめに

「Python機械学習プログラミング第二版」を現在勉強中で、かなり心折れそうです。
一回2時間ぐらい取ってるんですが、一回毎の進捗が少なく、達成感を感じづらい為です。
めげずに、ゴリゴリ進めていきます。

後で、振り返った時に復習しやすいようにアウトプットを残しておきます。

ソースコードの解説

中身をみてみる

Python機械学習プログラミング第3章冒頭のソース解説です。ソースコード全文



>>> iris = datasets.load_iris()
>>> X = iris.data[:, [2, 3]]
>>> y = iris.target
>>> print('Class labels:', np.unique(y))
Class labels: [0 1 2]

X = iris.data[:, [2, 3]]

データセットの全ての行の2〜3コラムを取ってくる。行列のスライスの仕方
scikit-learnに付属しているデータセットirisを読み込みます。
scikit-learnには機械学習やデータマイニングをすぐ試せるように、
いくつかの実験用データセットが同梱されているようです。

データセットの詳細

レコード数 カラム数 主な用途 データセットの詳細
150 4 分類(Classfication) UCI Machine Learning Repository: Iris Data Set

各カラムの構成

sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
がく片の長さ がく片の幅 花弁の長さ 花弁の幅

データセットの中身の見方

70%の訓練データと30%のテストデータに分ける。


>>> from sklearn.model_selection import train_test_split
>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.3, random_state=1, stratify=y)
>>> print('Labels counts in y:', np.bincount(y))
Labels counts in y: [50 50 50]
>>> print('Labels counts in y_train:', np.bincount(y_train))
Labels counts in y_train: [35 35 35]
>>> print('Labels counts in y_test:', np.bincount(y_test))
Labels counts in y_test: [15 15 15]

X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.3, random_state=1, stratify=y)

train_test_split関数の引数stratifyは公式によると、

stratify : array-like or None (default=None)
If not None, data is split in a stratified fashion, using this as the class labels.
Stratified Sampling (層化サンプリング) を行なう場合に、クラスを示す行列を設定します。 (デフォルト値: None)

つまり、yの行列がそのままクラスになりますよ〜〜って意味っぽい。

bincount関数は、0以上の整数の数を数えるらしい

Standardizing the features:


sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

StandardScalerインスタンスの中身の説明については、公式リファレンスが英語しかない〜〜
でもまあ、中身はちょっと難しそうなので、このへんで視覚的に理解して、このへんで整理できました。

Training a perceptron via scikit-learn

Redefining the plot_decision_region function from chapter 2:


ppn = Perceptron(n_iter=40, eta0=0.1, random_state=1)
ppn.fit(X_train_std, y_train)

y_pred = ppn.predict(X_test_std)
print('Misclassified samples: %d' % (y_test != y_pred).sum())
print('Accuracy: %.2f' % accuracy_score(y_test, y_pred))
print('Accuracy: %.2f' % ppn.score(X_test_std, y_test))

def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):

    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    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.3, 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=colors[idx],
                    marker=markers[idx],
                    label=cl,
                    edgecolor='black')

    # highlight test samples
    if test_idx:
        # plot all samples
        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')

xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
np.meshgridとnp.arrangeの説明はこれ参照しました。

Training a perceptron model using the standardized training data:


X_combined_std = np.vstack((X_train_std, X_test_std))
y_combined = np.hstack((y_train, y_test))

plot_decision_regions(X=X_combined_std, y=y_combined,
                      classifier=ppn, test_idx=range(105, 150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')

plt.tight_layout()
#plt.savefig('images/03_01.png', dpi=300)
plt.show()
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2