メインコンテンツへスキップ

【完全無料・連載第7回】Pythonでモデルの精度を徹底評価!scikit-learnによる評価指標入門

    はじめに

    本記事は、Pythonの機械学習ライブラリ scikit-learn を使い、不均衡なデータセット(病気の発生率が低いデータなど)を用いて、適合率・再現率・F1値・ROC曲線を算出・描画するハンズオンガイドです。

    1. サンプルプログラム(Python)

    以下のコードをコピーして Google Colab で実行してみてください!

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from sklearn.datasets import make_classification
    from sklearn.model_selection import train_test_split
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.metrics import (
        confusion_matrix, 
        classification_report, 
        roc_curve, 
        roc_auc_score
    )
    
    # ==========================================
    # 1. 不均衡データの生成 (陽性が全体の10%のみ)
    # ==========================================
    X, y = make_classification(
        n_samples=1000, 
        n_features=10, 
        weights=[0.9, 0.1], # 9:1 の不均衡データ
        random_state=42
    )
    
    # データを分割
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.3, random_state=42, stratify=y
    )
    
    # ==========================================
    # 2. モデルの作成と学習
    # ==========================================
    model = RandomForestClassifier(random_state=42)
    model.fit(X_train, y_train)
    
    # 予測値(0か1)と、陽性になる確率値を取得
    y_pred = model.predict(X_test)
    y_prob = model.predict_proba(X_test)[:, 1] # 陽性(1)の確率
    
    # ==========================================
    # 3. 評価レポート(適合率・再現率・F1値が一発で出る!)
    # ==========================================
    print("=== 分類評価レポート (Classification Report) ===")
    print(classification_report(y_test, y_pred, target_names=['Normal(0)', 'Disease(1)']))
    
    # ==========================================
    # 4. ROC曲線とAUCの算出・可視化
    # ==========================================
    fpr, tpr, thresholds = roc_curve(y_test, y_prob)
    auc_val = roc_auc_score(y_test, y_prob)
    
    plt.figure(figsize=(7, 5))
    plt.plot(fpr, tpr, color='blue', lw=2, label=f'ROC Curve (AUC = {auc_val:.3f})')
    plt.plot([0, 1], [0, 1], color='gray', linestyle='--', label='Random Chance (AUC = 0.500)')
    plt.xlabel('False Positive Rate (1 - Specificity)')
    plt.ylabel('True Positive Rate (Recall)')
    plt.title('ROC Curve & AUC Score')
    plt.legend()
    plt.grid(True)
    plt.show()

    3. コードの解説

    1. classification_report: 各クラスにおける「Precision」「Recall」「F1-score」を一覧で綺麗に表示してくれる超強力関数です。

    2. predict_proba: 単なる判定(0か1)だけでなく、「陽性である確率(0.0〜1.0)」を出力します。ROC曲線の描画にはこの確率データを使います。

    3. roc_curve & roc_auc_score: 閾値を変化させた際の過誤率と検出率の変化をプロットし、モデルの識別能力をAUCスコア(最大1.0)として定量評価します。

    次回の【第8回】では、機械学習モデルのパラメータ調整の基本!「ハイパーパラメータチューニング(GridSearchCV)」に挑戦します!

     
     

    kaoru

     
     
    文系ビジネスマン向けのデータ統計学・機械学習特化ブログの公式noteです。 Excelテンプレートや、コピペで動くPythonコードなどを発信・配布しています。 💻 公式ブログはこちら:[https://world-info.sakura.ne.jp/everyone/]

    あなたへのおすすめ