ランダムフォレストの実装
メニューを表示するにはスワイプしてください
この章では、scikit-learnライブラリを使用してランダムフォレストモデルの学習、評価、および解釈方法について学びます。ランダムフォレストの仕組み、実データを用いた構築方法、パフォーマンスの評価方法、モデル結果から有益な洞察を抽出する方法について解説します。
RandomForestClassifierのパラメータ
RandomForestClassifierのscikit-learnには、フォレストの構築や性能に影響する複数のパラメータがあります。
n_estimators:- フォレスト内の決定木の本数を設定;
- 値を大きくすると安定性と性能が向上する傾向があるが、計算コストも増加。
max_features:- 各木で最適な分割を探す際に考慮する特徴量の数を指定;
- 値を小さくすると木の多様性が増し過学習を抑制しやすく、値を大きくすると木同士が似やすくなる。
max_depth:- 各木の最大深さを制限;
- 浅い木は過学習を防ぎやすいが複雑なデータには不十分な場合があり、深い木は詳細を捉えやすいが過学習のリスクが高まる。
random_state:- 乱数生成のシードを設定;
- ブートストラップサンプリングや特徴量選択のランダム性を制御し、再現性を確保。
これらのパラメータを調整することで、モデルの精度、堅牢性、計算効率のバランスを取ることが可能です。
ランダムフォレストにおける特徴量重要度
ランダムフォレストの特徴量重要度は、各特徴量が全ての木において不純度をどれだけ減少させてモデルの予測精度を向上させたかを測定します。これにより、
- 予測に最も影響を与える特徴量の特定;
- 重要度の低い特徴量を除外してモデルを簡素化;
- データの主要な要因の把握。
一般的な指標には、不純度減少の平均や、特徴量を入れ替えた際の精度減少の平均などがあります。
12345678910111213141516171819202122232425262728293031323334353637from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, confusion_matrix, RocCurveDisplay import matplotlib.pyplot as plt import numpy as np # Step 1: Load the Iris dataset data = load_iris() X = data.data y = data.target feature_names = data.feature_names # Step 2: Split into train and test sets X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y ) # Step 3: Train a RandomForestClassifier clf = RandomForestClassifier(n_estimators=100, random_state=42) clf.fit(X_train, y_train) # Step 4: Evaluate with accuracy y_pred = clf.predict(X_test) acc = accuracy_score(y_test, y_pred) print(f"Accuracy: {acc:.2f}") # Step 5: Plot feature importances importances = clf.feature_importances_ indices = np.argsort(importances)[::-1] plt.figure(figsize=(6, 4)) plt.title("Feature Importances") plt.bar(range(X.shape[1]), importances[indices], align="center") plt.xticks(range(X.shape[1]), [feature_names[i] for i in indices], rotation=45) plt.tight_layout() plt.show()
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 6
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 6