ランダムフォレストとブースティング系でアンサンブル学習で多クラス分類するサンプルコード
以下は、Pythonのscikit-learnライブラリを使用して、ランダムフォレストと勾配ブースティングを組み合わせて多クラス分類を行うアンサンブル学習のサンプルコードです。
python
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.metrics import accuracy_score import numpy as np # データセットを読み込み 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.2, random_state=42) # ランダムフォレストと勾配ブースティングのモデルを定義 rf_model = RandomForestClassifier(n_estimators=100, random_state=42) gb_model = GradientBoostingClassifier(n_estimators=100, random_state=42) # モデルをトレーニング rf_model.fit(X_train, y_train) gb_model.fit(X_train, y_train) # それぞれのモデルで予測を行う rf_pred = rf_model.predict(X_test) gb_pred = gb_model.predict(X_test) # 各モデルの精度を出力 print("Random Forest Accuracy:", accuracy_score(y_test, rf_pred)) print("Gradient Boosting Accuracy:", accuracy_score(y_test, gb_pred)) # アンサンブル学習: 両方のモデルの予測を平均化して多数決を取る ensemble_pred = np.round((rf_pred + gb_pred) / 2) # アンサンブル学習の精度を出力 print("Ensemble Accuracy:", accuracy_score(y_test, ensemble_pred))
このコードでは、Irisデータセットを使用して、ランダムフォレストと勾配ブースティングのモデルを個別にトレーニングし、それらの予測を平均化してアンサンブル学習を行っています。最後に、アンサンブル学習の精度を出力しています。
関連記事

cp932もできる?
はい、Pythonのソースコードの冒頭に # coding: cp932 と指定 ...

バイクに関するYOUTUBEを取得して、TwitterにPOSTしたいんだ。
その場合、まずはYouTube APIを使用してバイクに関する動画を取得し、次に ...

直近の12か月のデータの平均値を、来月の売上として説明変数を渡すのは、ありなの?
直近12か月のデータの平均値を来月の売上として説明変数として渡すことは、一般的な ...

itemPriceMin1__gt=min_price_records.values(‘min_price’)).values(‘original_product_code’).annotate(next_min_price=Min(‘itemPriceMin1’))
itemPriceMin1__gt=min_price_records.valu ...
ディスカッション
コメント一覧
まだ、コメントがありません