BaggingClassifier:重點與細節

Python 的 Ensemble 方法

Román de las Heras

Data Scientist, Appodeal

異質 vs 同質函式

異質集成函式

het_est = HeterogeneousEnsemble(
    estimators=[('est1', est1), ('est2', est2), ...],
    # additional parameters
)

同質集成函式

hom_est = HomogeneousEnsemble(
    est_base,
    n_estimators=chosen_number,
    # additional parameters
)
Python 的 Ensemble 方法

BaggingClassifier

Bagging 分類器範例:

# Instantiate the base estimator ("weak" model)
clf_dt = DecisionTreeClassifier(max_depth=3)
# Build the Bagging classifier with 5 estimators
clf_bag = BaggingClassifier(
    clf_dt,
    n_estimators=5
)
# Fit the Bagging model to the training set
clf_bag.fit(X_train, y_train)
# Make predictions on the test set
y_pred = clf_bag.predict(X_test)
Python 的 Ensemble 方法

BaggingRegressor

Bagging 迴歸器範例:

# Instantiate the base estimator ("weak" model)
reg_lr = LinearRegression()
# Build the Bagging regressor with 10 estimators
reg_bag = BaggingRegressor(
    reg_lr
)
# Fit the Bagging model to the training set
reg_bag.fit(X_train, y_train)
# Make predictions on the test set
y_pred = reg_bag.predict(X_test)
Python 的 Ensemble 方法

袋外分數(Out-of-bag)

  • 對每個樣本未被抽中的估計器,分別計算其預測
  • 彙整個別預測
  • 以這些預測計算評估指標:
    • 分類:accuracy(正確率)
    • 迴歸:R^2
clf_bag = BaggingClassifier(
    clf_dt,
    oob_score=True
)
clf_bag.fit(X_train, y_train)
print(clf_bag.oob_score_)
0.9328125
pred = clf_bag.predict(X_test)
print(accuracy_score(y_test, pred))
0.9625
Python 的 Ensemble 方法

換你動手試試!

Python 的 Ensemble 方法

Preparing Video For Download...