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 參數:

# Load the Methods
from sklearn.metrics import mean_absolute_error, make_scorer
# Create a scorer
mae_scorer = make_scorer(mean_absolute_error)
# Use the scorer
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...