ランダムフォレストのPythonサンプルコード
概要
アイリスデータセットを用いた分類機を作成
サンプルコード
# 必要なライブラリのインポート from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, classification_report # データの読み込み iris = load_iris() X = iris.data y = iris.target # 訓練データとテストデータに分割 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # ランダムフォレスト分類器のインスタンス作成 clf = RandomForestClassifier(n_estimators=100, random_state=42) # 分類器の訓練 clf.fit(X_train, y_train) # テストデータを使って予測 y_pred = clf.predict(X_test) # 評価 accuracy = accuracy_score(y_test, y_pred) report = classification_report(y_test, y_pred) print(f"Accuracy: {accuracy:.2f}") print("Classification Report:") print(report)
実行結果
Accuracy: 1.00 Classification Report: precision recall f1-score support 0 1.00 1.00 1.00 19 1 1.00 1.00 1.00 13 2 1.00 1.00 1.00 13 accuracy 1.00 45 macro avg 1.00 1.00 1.00 45 weighted avg 1.00 1.00 1.00 45