4
4

More than 1 year has passed since last update.

Scikit-learnのall_estimators()関数の活用:全モデルでの精度を一括比較する

Last updated at Posted at 2023-08-02

Scikit-learnは多機能で広く使われているPythonの機械学習ライブラリですが、提供されている多数のモデルをどれが一番性能が良いのか比較するのは一苦労です。そこで役立つのがall_estimators()関数です。

all_estimators()とは?

all_estimators()はScikit-learnが提供する全ての推定器(モデル)のリストを返す関数です。特に引数type_filterを指定することで特定の種類('classifier'、'regressor'等)のモデルだけを取得することが可能です。

実際に使ってみる

以下のコードでは、カリフォルニア住宅価格データセットを用いてall_estimators()で取得した全ての回帰モデルを一度に評価し、その中で最も良いモデルを見つける例を示します。
今回はall_estimators()の使用例にのみフォーカスするため、前処理や特徴量選択は省略しています。

import warnings
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import cross_val_score
from sklearn.utils import all_estimators
from sklearn.exceptions import NotFittedError

california_housing = datasets.fetch_california_housing()
X = pd.DataFrame(california_housing.data, columns=california_housing.feature_names)
y = pd.Series(california_housing.target)

estimators = all_estimators(type_filter='regressor')

warnings.filterwarnings('ignore')

best_score = 0
best_model = None

for name, E in estimators:
    try:
        model = E()
        score = cross_val_score(model, X, y, cv=3).mean()
        print(f"{name}: {score}")
        if score > best_score:
            best_score = score
            best_model = name
    except:
        print(f"{name}: erorr")

print(f'Best model: {best_model}, Score: {best_score}')

コードの解説

まず、必要なライブラリをインポートし、データセットを取得しています。ここではScikit-learnから提供されているカリフォルニアの住宅価格データセットを使用しています。

import warnings
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import cross_val_score
from sklearn.utils import all_estimators
from sklearn.exceptions import NotFittedError

california_housing = datasets.fetch_california_housing()
X = pd.DataFrame(california_housing.data, columns=california_housing.feature_names)
y = pd.Series(california_housing.target)

次に、all_estimators(type_filter='regressor')を使って全ての回帰モデルを取得します。

estimators = all_estimators(type_filter='regressor')

続いて、各モデルに対して3分割の交差検証を行い、その平均スコアを計算します。そのスコアが今までのものよりも高ければ、そのスコアとモデルの名前を更新します。モデルによっては、このままのデータでは使用できないものもあるため、今回はerrorというメッセージを出力します。

warnings.filterwarnings('ignore')

best_score = 0
best_model = None

for name, E in estimators:
    try:
        model = E()
        score = cross_val_score(model, X, y, cv=3).mean()
        print(f"{name}: {score}")
        if score > best_score:
            best_score = score
            best_model = name
    except:
        print(f"{name}: erorr")

print(f'Best model: {best_model}, Score: {best_score}')

以上のコードを実行すると、以下のような結果が出力されます。(モデルには乱数が含まれているものもあるため、精度は実行ごとに異なります。)

ARDRegression: 0.5723824917716036
AdaBoostRegressor: 0.33048366807523344
BaggingRegressor: 0.616501269465403
BayesianRidge: 0.576258148067912
CCA: erorr
DecisionTreeRegressor: 0.31688626547202653
DummyRegressor: -0.013261448503657366
ElasticNet: 0.40444100575688857
ElasticNetCV: 0.55673973154539
ExtraTreeRegressor: 0.28103009473775714
ExtraTreesRegressor: 0.6839895276578902
GammaRegressor: 0.13644777714303416
GaussianProcessRegressor: -2.9758393330165567
GradientBoostingRegressor: 0.6800063110192864
HistGradientBoostingRegressor: 0.6832313500928516
HuberRegressor: -1.7792780300141129
IsotonicRegression: erorr
KNeighborsRegressor: 0.05292671098955367
KernelRidge: 0.5134438688954565
Lars: 0.558055082776185
LarsCV: 0.558055082776185
Lasso: 0.26296756684870987
LassoCV: 0.5608824384115452
LassoLars: 0.2629669521308365
LassoLarsCV: 0.5722362636543111
LassoLarsIC: 0.5762820158960716
LinearRegression: 0.5762820158960736
LinearSVR: -2.2860952598124746
MLPRegressor: 0.28395853565282136
MultiOutputRegressor: erorr
MultiTaskElasticNet: erorr
MultiTaskElasticNetCV: erorr
MultiTaskLasso: erorr
MultiTaskLassoCV: erorr
NuSVR: -0.023127703069969474
OrthogonalMatchingPursuit: -0.016149574068156387
OrthogonalMatchingPursuitCV: 0.4651939433233627
PLSCanonical: erorr
PLSRegression: 0.4826330447681779
PassiveAggressiveRegressor: -2.4856691998570337
PoissonRegressor: 0.2407851128648719
QuantileRegressor: erorr
RANSACRegressor: -4.21645892176356
RadiusNeighborsRegressor: nan
RandomForestRegressor: 0.6546425367147917
RegressorChain: erorr
Ridge: 0.5762781352184145
RidgeCV: 0.576204954276622
SGDRegressor: -4.201018195468885e+29
SVR: -0.05147757666204519
StackingRegressor: erorr
TheilSenRegressor: -11.457423940135671
TransformedTargetRegressor: 0.5762820158960736
TweedieRegressor: 0.46071587322897295
VotingRegressor: erorr
Best model: ExtraTreesRegressor, Score: 0.6839895276578902

出力結果の解釈

出力結果から、ExtraTreesRegressorが最も高いスコア(約0.684)を出していることが分かります。それ以外のモデルでも良い結果を出しているものもありますが、一部のモデルではエラーが発生しています。このようにall_estimators()を使用することで、複数のモデルを一括で評価し、最もパフォーマンスが良いモデルを選択することが可能です。


以上がScikit-learnのall_estimators()関数の利用についての説明となります。様々なモデルを一度に試すことで、最適なモデル選択に役立つことを覚えておきましょう。
実際に使用する際には、前処理や特徴量選択、ハイパーパラメータチューニングなどの工夫が必要となります。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4