Instead of picking one best model, stacking learns a second-level model that decides when each base model should be trusted. It works well when base learners make different kinds of errors.
# Create data with 20 featuresn_features=20X,y=make_classification(n_samples=2500,n_features=n_features,n_informative=10,n_classes=2,n_redundant=0,n_clusters_per_class=4,random_state=777,)X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.33,random_state=777)
# Models used in base learnerestimators=[("dt1",DecisionTreeClassifier(max_depth=3,random_state=777)),("dt2",DecisionTreeClassifier(max_depth=4,random_state=777)),("dt3",DecisionTreeClassifier(max_depth=5,random_state=777)),("dt4",DecisionTreeClassifier(max_depth=6,random_state=777)),]# Number of models included in base learnern_estimators=len(estimators)# aggregation modelfinal_estimator=DecisionTreeClassifier(max_depth=3,random_state=777)# train base-learner and aggregation modelclf=StackingClassifier(estimators=estimators,final_estimator=final_estimator)clf.fit(X_train,y_train)# evaluatey_pred=clf.predict(X_test)clf_score=roc_auc_score(y_test,y_pred)print("ROC-AUC")print(f"Decision Tree Stacking={clf_score}, Random Forest={rf_score}")
ROC-AUC
Decision Tree Stacking=0.7359716965608031, Random Forest=0.855797033310609