sklearn の cross_val_score()

Python によるモデル検証

Kasey Jones

Data Scientist

cross_val_score()

from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier()

estimator: 使用するモデル

X: 説明変数データセット

y: 目的変数配列

cv: 交差検証の分割数

cross_val_score(estimator=rfc, X=X, y=y, cv=5)
Python によるモデル検証

scoring と make_scorer の使用

cross_val_score の scoring 引数:

# メソッドを読み込む
from sklearn.metrics import mean_absolute_error, make_scorer
# スコアラーを作成
mae_scorer = make_scorer(mean_absolute_error)
# スコアラーを使用
cross_val_score(<estimator>, <X>, <y>, cv=5, scoring=mae_scorer)
Python によるモデル検証

sklearn のメソッドを読み込む

from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_error, make_scorer

モデルとスコアラーを作成

rfc = RandomForestRegressor(n_estimators=20, max_depth=5, random_state=1111)
mse = make_scorer(mean_squared_error)

cross_val_score() を実行

cv_results = cross_val_score(rfc, X, y, cv=5, scoring=mse)
Python によるモデル検証

結果の参照

print(cv_results)
[196.765, 108.563, 85.963, 222.594, 140.942]

平均と標準偏差を出力:

print('The mean: {}'.format(cv_results.mean()))
print('The std: {}'.format(cv_results.std()))
The mean: 150.965
The std: 51.676
Python によるモデル検証

演習に進みましょう!

Python によるモデル検証

Preparing Video For Download...