I want to build a stacking classifier for the three label following dataset:
from sklearn.datasets import make_classification
# Define dataset
def get_dataset():
X, y = make_classification(
n_samples=1000,
n_features=20,
n_informative=15,
n_redundant=5,
random_state=2022,
n_classes=3,
)
return X, y
I want to use sklearn models plus a dummy model of my own:
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.utils.multiclass import unique_labels
class DummyClassifier(BaseEstimator, ClassifierMixin):
def __init__(self):
pass
def fit(self, X, y, **kwargs):
if y is None:
raise ValueError("requires y to be passed, but the target y is None")
X, y = check_X_y(X, y)
self.n_features_in_ = X.shape[1]
self.classes_ = np.unique(y)
self.is_fitted_ = True
self.X_ = X
self.y_ = y
return self
def predict(self, X):
check_is_fitted(self, ["is_fitted_", "X_", "y_"])
X = check_array(X)
return self.y_[np.ones(X.shape[0], dtype=np.int64)]
def is_classifier():
return True
combined:
from sklearn.ensemble import StackingClassifier
def get_stacking():
# Base models
level0 = list()
level0.append(("logistic reg", LogisticRegression()))
level0.append(("knn", KNeighborsClassifier()))
level0.append(("cart", DecisionTreeClassifier()))
level0.append(("svm", SVC()))
level0.append(("random", DummyClassifier()))
# Meta learner
level1 = LogisticRegression()
# Stacking ensemble
model = StackingClassifier(estimators=level0, final_estimator=level1, cv=5)
return model
I get interpretability through the final_estimator's coefficients:
stack = get_stacking()
stack.fit(X, y)
for i in range(3):
print(stack.final_estimator_.classes_[i])
print(stack.final_estimator_.coef_[i])
I understand that for 3 classes and 4 models, I get 12 coefficients for each final output class. In my case I have 5 models but 13 coefficients:
0
[ 0.12169113 -0.00882275 -0.10934588 1.39370271 -0.647395 -0.7427852
0.28413927 0.05880896 -0.33942572 0.17350847 -0.71793331 -0.62128377
-0.01146239]
1
[ 0.05118664 0.07307435 -0.12623659 -0.7132075 1.22529472 -0.51406282
-0.16767687 -0.00635399 0.17205527 -0.27319447 0.6866465 -0.47218785
0.09065114]
2
[-0.17287777 -0.06425161 0.23558246 -0.68049521 -0.57789973 1.25684802
-0.1164624 -0.05245497 0.16737045 0.099686 0.03128681 1.09347161
-0.07918875]
Where's the problem with my DummyClassifier?