Hikaru's notes

A collection of notes and resources

View the Project on GitHub HikaruMizoe/notes

2.3 モデルのパフォーマンスを分析する

タスクステートメント

モデルのパフォーマンスを分析する

対象知識

モデル評価手法とメトリクス

分類問題のメトリクス

混同行列(Confusion Matrix)
              予測
          Positive  Negative
実際 Positive   TP        FN
     Negative   FP        TN
F1 スコア
正解率(Accuracy)
適合率(Precision)
再現率(Recall / Sensitivity)
ROC 曲線(Receiver Operating Characteristic)
AUC(Area Under the Curve)
ヒートマップ

回帰問題のメトリクス

二乗平均平方根誤差(RMSE: Root Mean Squared Error)
平均絶対誤差(MAE: Mean Absolute Error)
R² スコア(決定係数)

パフォーマンスベースラインを作成する方法

モデルのオーバーフィットとアンダーフィットを特定する方法

オーバーフィット(過学習)の兆候

アンダーフィット(学習不足)の兆候

学習曲線の分析

import matplotlib.pyplot as plt

plt.plot(history['train_loss'], label='Training Loss')
plt.plot(history['val_loss'], label='Validation Loss')
plt.legend()
plt.show()

ML のトレーニングデータとモデルに関するインサイトを得るために SageMaker Clarify で使用可能なメトリクス

バイアスメトリクス

説明可能性メトリクス

収束の問題

対象スキル

1. 評価メトリクスを選択および解釈し、モデルのバイアスを検出する

不均衡データの場合

from sklearn.metrics import classification_report, f1_score

# F1スコアを重視
f1 = f1_score(y_true, y_pred, average='weighted')
print(f"F1 Score: {f1}")

# 詳細レポート
report = classification_report(y_true, y_pred)
print(report)

ROC-AUC の使用

from sklearn.metrics import roc_auc_score, roc_curve
import matplotlib.pyplot as plt

# AUC スコア
auc = roc_auc_score(y_true, y_pred_proba)

# ROC 曲線のプロット
fpr, tpr, thresholds = roc_curve(y_true, y_pred_proba)
plt.plot(fpr, tpr, label=f'AUC = {auc:.2f}')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend()
plt.show()

2. モデルのパフォーマンス、トレーニング時間、コスト間のトレードオフを評価する

要素 高性能モデル 高速/低コストモデル
モデル複雑度 高い(Deep NN) 低い(Linear)
トレーニング時間 長い 短い
インスタンスタイプ GPU CPU
コスト 高い 低い
精度 高い 中程度

3. AWS のサービスを使用して再現可能な実験を行う

SageMaker Experiments

from sagemaker.experiments import Run

# 実験の実行
with Run(
    experiment_name='customer-churn-experiment',
    run_name='xgboost-v1',
    sagemaker_session=session
) as run:
    # ハイパーパラメータをログ
    run.log_parameters({
        'max_depth': 5,
        'eta': 0.2,
        'num_round': 100
    })
    
    # モデルのトレーニング
    estimator.fit({'train': train_data})
    
    # メトリクスをログ
    run.log_metric(name='auc', value=0.85)
    run.log_metric(name='accuracy', value=0.82)

4. シャドウバリアントのパフォーマンスと本番稼働用バリアントのパフォーマンスを比較する

from sagemaker.model_monitor import DataCaptureConfig

# データキャプチャ設定
data_capture_config = DataCaptureConfig(
    enable_capture=True,
    sampling_percentage=100,
    destination_s3_uri=f's3://{bucket}/data-capture'
)

# シャドウバリアントでデプロイ
predictor = model.deploy(
    initial_instance_count=1,
    instance_type='ml.m5.xlarge',
    data_capture_config=data_capture_config
)

# 本番バリアントとシャドウバリアントを比較
predictor.update_endpoint(
    initial_instance_count=1,
    instance_type='ml.m5.xlarge',
    variant_name='production-variant',
    initial_variant_weight=90
)

predictor.update_endpoint(
    initial_instance_count=1,
    instance_type='ml.m5.xlarge',
    variant_name='shadow-variant',
    initial_variant_weight=10
)

5. SageMaker Clarify を使用してモデルの出力を解釈する

from sagemaker import clarify

# Clarify プロセッサーの作成
clarify_processor = clarify.SageMakerClarifyProcessor(
    role=role,
    instance_count=1,
    instance_type='ml.m5.xlarge',
    sagemaker_session=session
)

# SHAP 分析の実行
explainability_config = clarify.SHAPConfig(
    baseline=[baseline_data],
    num_samples=100,
    agg_method='mean_abs'
)

clarify_processor.run_explainability(
    data_config=data_config,
    model_config=model_config,
    explainability_config=explainability_config
)

6. SageMaker モデルデバッガーを使用してモデル収束をデバッグする

from sagemaker.debugger import Rule, rule_configs, DebuggerHookConfig

# デバッガールールの設定
rules = [
    Rule.sagemaker(rule_configs.vanishing_gradient()),
    Rule.sagemaker(rule_configs.overfit()),
    Rule.sagemaker(rule_configs.overtraining()),
    Rule.sagemaker(rule_configs.loss_not_decreasing())
]

# デバッガー設定
debugger_hook_config = DebuggerHookConfig(
    s3_output_path=f's3://{bucket}/debugger-output'
)

# Estimator にデバッガーを追加
estimator = TensorFlow(
    entry_point='train.py',
    role=role,
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    framework_version='2.12',
    debugger_hook_config=debugger_hook_config,
    rules=rules
)

estimator.fit(train_data)

# デバッガーの結果を確認
for rule in estimator.latest_training_job.rule_job_summary():
    print(f"{rule['RuleConfigurationName']}: {rule['RuleEvaluationStatus']}")

実践的な評価パターン

クロスバリデーション

from sklearn.model_selection import cross_val_score

# 5-fold クロスバリデーション
scores = cross_val_score(model, X, y, cv=5, scoring='f1_weighted')
print(f"F1 scores: {scores}")
print(f"Mean F1: {scores.mean():.3f} (+/- {scores.std() * 2:.3f})")

層化 K-Fold

from sklearn.model_selection import StratifiedKFold

skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

for train_idx, val_idx in skf.split(X, y):
    X_train, X_val = X[train_idx], X[val_idx]
    y_train, y_val = y[train_idx], y[val_idx]
    # トレーニングと評価

重要なポイント

メトリクス選択のガイドライン

ユースケース 推奨メトリクス 理由
不均衡データの分類 F1, AUC-ROC 正解率だけでは不十分
偽陽性を避けたい Precision スパムフィルタなど
偽陰性を避けたい Recall 疾病診断など
回帰(外れ値あり) MAE RMSEは外れ値に敏感
回帰(外れ値なし) RMSE, R² 標準的な評価

モデル診断チェックリスト

関連リンク