from sklearn.base import TransformerMixin, BaseEstimator
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import VotingClassifier
class ColumnExtractor(TransformerMixin, BaseEstimator):
def __init__(self, cols):
self.cols = cols
def transform(self, X):
col_list = []
for c in self.cols:
col_list.append(X[:, c:c+1])
return np.concatenate(col_list, axis=1)
def fit(self, X, y=None):
return self
data = load_iris()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y)
pipe1 = Pipeline([
('col_extract', ColumnExtractor( cols=range(0,2) )),
('clf', LogisticRegression())
])
pipe1.fit(X_train, y_train)
pipe1.score(X_test,y_test)
pipe2 = Pipeline([
('col_extract', ColumnExtractor( cols=range(2,4) )),
('clf', SVC(probability=True))
])
pipe2.fit(X_train, y_train)
pipe2.score(X_test,y_test)
eclf = VotingClassifier(estimators=[('df1-clf1', pipe1), ('df2-clf2', pipe2)], voting='soft', weights= [1, 0.5])
eclf.fit(X_train, y_train)
eclf.score(X_test,y_test)