【问题标题】:Sklearn Voting ensemble with models using different features and testing with k-fold cross validationSklearn Voting ensemble 与使用不同特征的模型并使用 k 折交叉验证进行测试
【发布时间】:2020-09-15 19:22:49
【问题描述】:

我有一个包含 4 组不同特征的数据框。

我需要用这四个不同的特征组创建 4 个不同的模型,并将它们与集成投票分类器结合起来。 此外,我需要使用 k 折交叉验证来测试分类器。

但是,我发现很难将不同的特征集、投票分类器和 k-fold 交叉验证与 sklearn 中可用的功能结合起来。以下是我到目前为止的代码。

y = df1.index
x = preprocessing.scale(df1)

SVM = svm.SVC(kernel='rbf', C=1)
rf=RandomForestClassifier(n_estimators=200)
ann = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(25, 2), random_state=1)
neigh = KNeighborsClassifier(n_neighbors=10)

models = list()
models.append(('facial', SVM))
models.append(('posture', rf))
models.append(('computer', ann))
models.append(('physio', neigh))

ens = VotingClassifier(estimators=models)

cv = KFold(n_splits=10, random_state=None, shuffle=True)
scores = cross_val_score(ens, x, y, cv=cv, scoring='accuracy')

如您所见,该程序对所有 4 个模型使用相同的功能。我该如何改进这个计划以实现我的目标?

【问题讨论】:

  • 你的代码有错误吗?
  • 这很好用,但我的目标是为每个模型使用不同的功能组。这里所有模型都使用了我的数据集中可用的所有特征。
  • 我已经提到了这个,但是,发布的答案不使用 k 折交叉验证
  • 您需要在每个估算器之前附加一个列选择。见the example here。所以你最终的VotingClassifier 将有一个管道列表(每个列选择器和估计器一个)。尝试并实施这种方法。如果仍然无法解决,我会发布答案。

标签: scikit-learn classification voting ensemble-learning k-fold


【解决方案1】:

我确实设法使用管道实现了这一目标,

y = df1.index
x = preprocessing.scale(df1)

phy_features = ['A', 'B', 'C']
phy_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
phy_processer = ColumnTransformer(transformers=[('phy', phy_transformer, phy_features)])

fa_features = ['D', 'E', 'F']
fa_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
fa_processer = ColumnTransformer(transformers=[('fa', fa_transformer, fa_features)])


pipe_phy = Pipeline(steps=[('preprocessor', phy_processer ),('classifier', SVM)])
pipe_fa = Pipeline(steps=[('preprocessor', fa_processer ),('classifier', SVM)])

ens = VotingClassifier(estimators=[pipe_phy, pipe_fa])

cv = KFold(n_splits=10, random_state=None, shuffle=True)
for train_index, test_index in cv.split(x):
    x_train, x_test = x[train_index], x[test_index]
    y_train, y_test = y[train_index], y[test_index]
    ens.fit(x_train,y_train)
    print(ens.score(x_test, y_test))

如果您在使用 ColumnTransforms 时收到 TypeError,请参考 sklearn Pipeline: argument of type 'ColumnTransformer' is not iterable

【讨论】:

    猜你喜欢
    • 2016-02-11
    • 2020-02-06
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2016-02-01
    • 2017-02-06
    • 1970-01-01
    相关资源
    最近更新 更多