|
Pythonの機械学習用のライブラリであるScikit-learnを取り上げて、実際の課題に挑戦します。scikit-learnライブラリの使用をするにあたっては、パーセプトロン・モデルに学習させる課題を取り上げることが便利である。scikit-learnにはirisデータセットや手書き数字のデータなど便利なデータベースが含まれているいます。
Scitkit-learnはPythonで書かれているので、Pythonの基礎的な知識を持っている人を想定します。なお、anaconda等でPythonのモジュール一式がインストールされていることも前提とします。scikit-learnの公式ホームページはhttp://scikit-learn.org/stable/index.htmlです。このサイトには使用方法の詳しいドキュメントが掲載されています。
Last updated: 2018.4.22
$ conda update scikit-learnscikit-learnの機能はsklearnという名称のライブラリに組み込まれます。sklearnの中身を見てみると、以下のようになっています。
MacBook-Air:sklearn koichi$ ls __check_build kernel_approximation.py __init__.py kernel_ridge.py __pycache__ learning_curve.py _build_utils linear_model _isotonic.cpython-36m-darwin.so manifold base.py metrics calibration.py mixture cluster model_selection covariance multiclass.py cross_decomposition multioutput.py cross_validation.py naive_bayes.py datasets neighbors decomposition neural_network discriminant_analysis.py pipeline.py dummy.py preprocessing ensemble random_projection.py exceptions.py semi_supervised externals setup.py feature_extraction svm feature_selection tests gaussian_process tree grid_search.py utils isotonic.pyこの中で、datasetsというモジュールには、機械学習で必須のアヤメの標本データ及び手書き数字のデータが収められています。実際に、これらのデータを読み込んで見ましょう。loads.digitsは手書き数字のデータ、loads.irisはアヤメのデータを読み込みます。ipythonを起動した後、以下の順番でコマンドを入力してください。
$ ipython Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 6 2017, 12:04:38) Type 'copyright', 'credits' or 'license' for more information IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from sklearn import datasets In [2]: iris = datasets.load_iris() In [3]: x = iris.data In ]4]: y = iris.targetアヤメのデータセットを見て見ましょう。アヤメのデータセットには150枚のアヤメの計測データが収録されています。特徴量は4種類で、がくの長さと幅の大きさ、花びらの長さと幅の大きさ、となっています。iris.dataの中身を見てみると
IN [5]: print(x) [[ 5.1 3.5 1.4 0.2] [ 4.9 3. 1.4 0.2] [ 4.7 3.2 1.3 0.2] [ 4.6 3.1 1.5 0.2] [ 5. 3.6 1.4 0.2] --- [ 6.7 3. 5.2 2.3] [ 6.3 2.5 5. 1.9] [ 6.5 3. 5.2 2. ] [ 6.2 3.4 5.4 2.3] [ 5.9 3. 5.1 1.8]]のように4つのデータの配列になっています。iris.targetには各計測データに対応するアヤメの種類が収納されています。アヤメの種類はsetosa、 versicolor、 virginicaの3つに分類されます。
In [6]: import numpy as np
In [7]: print('Class labels:", np.unique(y))
Class labels: [0 1 2]
となっていることがわかります。unique(y)は異なる数字のみからなる配列に変換する。
In [8]: digits = datasets.load_digits() In [9]: print(digits.data) [[ 0. 0. 5. ..., 0. 0. 0.] [ 0. 0. 0. ..., 10. 0. 0.] [ 0. 0. 0. ..., 16. 9. 0.] ..., [ 0. 0. 1. ..., 6. 0. 0.] [ 0. 0. 2. ..., 12. 0. 0.] [ 0. 0. 10. ..., 12. 1. 0.]] In [10]: digits.target Out [10]: array([0, 1, 2, ..., 8, 9, 8]) In [11]: x=digits.data In [12]: y=digits.traget In [13]: print(x.shape) (1797, 64) In [14]: print(y.shape) (1797,)データの個数は1797個です。手書き数字の特徴データは8x8=64ピクセルの特徴量から構成されています。ターゲットは手書き数字の正解なので、データの個数と同じです。
from sklearn import datasets
import numpy as np
from sklearn.linear_model import Perceptron
iris = datasets.load_iris()
x = iris.data[:, [2, 3]]
y = iris.target
print('Class labels:', np.unique(y))
ppn = Perceptron(max_iter=10000, tol=0.00001, random_state=1)
#ppn = Perceptron(n_iter=400, eta0=0.00001, random_state=0)
ppn.fit(x,y)
y_pred = ppn.predict(x)
print('Misclassified samples: %d' % (y != y_pred).sum())
from sklearn.metrics import accuracy_score
print('Accuracy: %.2f' % accuracy_score(y, y_pred)
from sklearn.linear_model import Perceptron
from sklearn import datasets
import numpy as np
from sklearn.neural_network import MLPClassifier
iris = datasets.load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
mlp = MLPClassifier(hidden_layer_sizes=(100, ), max_iter=10000, tol=0.0001, random_state=1)
#mlp = MLPClassifier(hidden_layer_sizes=(100, ), max_iter=10000, tol=0.00001, random_state=None)
mlp.fit(X, y)
y_pred = mlp.predict(X)
from sklearn.metrics import accuracy_score
print('Class labels:', np.unique(y))
print('Misclassified samples: %d' % (y != y_pred).sum())
print('Accuracy: %.2f' % accuracy_score(y, y_pred))
このトレーニングから得られるモデルの予測をデータに適用した時の予測の正解率は