「あやめ」の種類判別(その1)

iris(菖蒲:アヤメ)データセットを使って進める
 (その1)は行番号1~27までを解説する

#
#   1.データの読み込み
#
import pandas as pd
import numpy  as np
import matplotlib.pyplot as plt
import seaborn as sns
#
from sklearn import datasets
#      
%matplotlib inline
#
iris_datasets =  datasets.load_iris()
#
#
#print("***詳細*****",flush=True)
#print(iris_datasets.DESCR)
#print("********",flush=True)
#
#
#   2.データの確認
#
iris = pd.DataFrame(iris_datasets.data,columns = iris_datasets.feature_names)
iris['target'] = iris_datasets.target
#
iris.head()
#
#
#   3.モデルの学習
#
target = iris['target']
data = iris[iris_datasets.feature_names]
#
from sklearn import model_selection
data_train,data_test,target_train,target_test = \
        model_selection.train_test_split(data,target,train_size=0.8)
#
print(target_train.shape,target_test.shape)
print(data_train.shape,data_test.shape)
#
from sklearn.svm import SVC
model = SVC(gamma='scale')
model.fit(data_train,target_train)
#
target_predict = model.predict(data_test)
#
print(target_predict)
print(np.array(target_test))
#
model.score(data_test,target_test)
#
#
#   4.モデルの評価
#
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
#
precision = precision_score(target_test,target_predict,average='micro')
recall = recall_score(target_test,target_predict,average='micro')
f1 = f1_score(target_test,target_predict,average='micro')
#
print('適合率(precision)',precision)
print('再現率(recall)',recall)
print('F値(F-measure)',f1)
#
#
#
# データの先頭
#print("***先頭****",flush=True)
#iris.head()
#print("********",flush=True)
#
# データの概要
#print("***概要****",flush=True)
#iris.info()
#print("********",flush=True)
#
# データの要約統計量
#print("***統計*****")
#iris.describe()
#print("********")
#
# データの形状
#print("***形状*****")
#iris.shape
#print("********")
#
# データ要素の取り出し
#print("***要素*****")
#iris.iloc[:10]
#print("********")
#
# 条件に合う行の取得
#print("***条件*****")
#iris.query("target==1")
#print("********")
#
#

以下はサンプルコードと解説

1.データの読み込み

#
import pandas as pd
import numpy  as np
import matplotlib.pyplot as plt
import seaborn as sns

 必要なライブラリを読込む
   ライブラリ内のモジュールを読み込むこともできる
   読み込んだら処理しやすいように「as」を使って名前を付与する
   同一名になる場合は互いに異なる名前を付与する

 各ライブラリの説明 
   pandas・・・データの確認や抽出に適したライブラリ
   numpy・・・行列計算用ライブラリー
   matplotlib.pyplot・・・グラフ描画ライブラリーのpyplot部分
   seaborn・・・見た目の優れたグラフ描画ライブラリー

#
from sklearn import datasets

 サンプルデータを使用する準備
   sklearn・・・機械学習用のモデルやサンプルデータ
          分類や回帰などの機械学習に使えるdatasets群
   sklearnモジュールからdatasetsオブジェクトを取り出す

 「scikit-learn」は「サイキット・ラーン」と読み
   Pythonの機械学習ライブラリ(アルゴリズム)で構成されている

#         
%matplotlib inline

 グラフ 表示の設定
   %はインタラクティブサポートを有効化するためのコマンド
   「inline」とはその場(環境や状態)で表示する意味
     (注)グラフが書けない実行環境だとこの行はエラーになる

#
iris_datasets =  datasets.load_iris()

 irisのサンプルデータセットを読み込む

"""
print("***詳細*****",flush=True)
print(iris_datasets.DESCR)
print("********",flush=True)
"""

  irisのサンプルデータセットの内容を出力する
     ※コメントアウト(#)を外すと出力される
   50件づつ3つのクラスに分かれており全部で150件
   4つの数値データで構成されている

   詳細の確認をする
     目的変数 target 品種(3種類)
     説明変数 data  花びらの属性(長さと幅)

     説明変数名は「feature_names」に列名として存在する

   以下はprint文による出力例

***詳細*****
.. _iris_dataset:

Iris plants dataset
--------------------

**Data Set Characteristics:**

    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
                
    :Summary Statistics:

    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)
    ============== ==== ==== ======= ===== ====================

    :Missing Attribute Values: None
    :Class Distribution: 33.3% for each of 3 classes.
    :Creator: R.A. Fisher
    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
    :Date: July, 1988

The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.

This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.

.. topic:: References

   - Fisher, R.A. "The use of multiple measurements in taxonomic problems"
     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
     Mathematical Statistics" (John Wiley, NY, 1950).
   - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.
     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
     Structure and Classification Rule for Recognition in Partially Exposed
     Environments".  IEEE Transactions on Pattern Analysis and Machine
     Intelligence, Vol. PAMI-2, No. 1, 67-71.
   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions
     on Information Theory, May 1972, 431-433.
   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II
     conceptual clustering system finds 3 classes in the data.
   - Many, many more ...
********

2.データの確認

#
iris = pd.DataFrame(iris_datasets.data,columns = iris_datasets.feature_names)
iris['target'] = iris_datasets.target

 Pandasの「DataFrame」を使って列名を決める
   第一引数・・・元になるデータ
   第二引数・・・元になるデータが持っている列名を指定する

  「DataFrame」に列を追加するために、列名とデータを指定する
   5カラム目として「target」を追加する
     ※単なる数字データが列名を付けた配列データになる

#
print(iris.head())

 先頭(head)の5行を表示する例・・・行数は指定可
   print文を使って出力する
   先頭の5行、5列のデータが出力される

 以下はprint文による出力例

   sepal length (cm)  sepal width (cm)  ...  petal width (cm)  target
0                5.1               3.5  ...               0.2       0
1                4.9               3.0  ...               0.2       0
2                4.7               3.2  ...               0.2       0
3                4.6               3.1  ...               0.2       0
4                5.0               3.6  ...               0.2       0

[5 rows x 5 columns]

3.その他

 データの内容を詳細に確認する
    行番号69~97までの処理、コメントアウトを外すと出力される
   参照 「あやめ」の種類判別(その4)