scikit-learn - Sklearn 投票集成与使用不同特征的模型并使用 k 折交叉验证进行测试
问题描述
我有一个包含 4 组不同特征的数据框。
我需要用这四个不同的特征组创建 4 个不同的模型,并将它们与集成投票分类器结合起来。此外,我需要使用 k 折交叉验证来测试分类器。
但是,我发现很难将不同的特征集、投票分类器和 k 折交叉验证与 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 个模型使用相同的功能。我如何改进这个程序以实现我的目标?
解决方案
我确实设法使用管道实现了这一点,
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))
请参考sklearn Pipeline:如果您在使用 ColumnTransforms 时收到 TypeError,则“ColumnTransformer”类型的参数不可迭代。
推荐阅读
- monetdb - 使用 WITH 的 UPDATE 语句在 MonetDB 中不起作用
- javascript - 我为带有 csp 和烧瓶的内联 js 实现 nonce 有什么问题?
- python - Pandas:如何用其他列上的数学条件替换一个值?
- javascript - 在 service.ts 文件中进行更改时 Nest.js 中的编译问题
- mongodb - MongoDb 未正确添加
- opengl - 为什么 glBlitNamedFramebuffer() 不能正常工作?
- rust - 不在 Rocket 0.5+ 中使用异步?
- asp.net - 我在我的服务器上使用 excel 但我收到很多错误
- laravel - 如何运行工匠命令在后台 laravel 中工作
- node.js - 是否可以在每个请求中自动发送渲染数据?