我有两个不同的特征集(因此,具有相同数量的行且标签相同),在我的情况下是DataFrames
:
df1
:
| A | B | C |-------------| 1 | 4 | 2 || 1 | 4 | 8 || 2 | 1 | 1 || 2 | 3 | 0 || 3 | 2 | 5 |
df2
:
| E | F |---------| 6 | 1 || 1 | 3 || 8 | 1 || 2 | 8 || 5 | 2 |
labels
:
| labels |----------| 5 || 5 || 1 || 7 || 3 |
我想使用它们来训练一个VotingClassifier
。但是在拟合步骤中只能指定一个特征集。目标是用df1
拟合clf1
,用df2
拟合clf2
。
eclf = VotingClassifier(estimators=[('df1-clf', clf1), ('df2-clf', clf2)], voting='soft')eclf.fit(...)
在这种情况下我应该如何操作?有没有简单的解决方案?
回答:
创建自定义函数来实现你想要的目标是相当容易的。
导入所需的库:
import numpy as npfrom sklearn.preprocessing import LabelEncoderdef fit_multiple_estimators(classifiers, X_list, y, sample_weights = None): # 使用LabelEncoder转换标签`y`,因为预测方法使用基于索引的指针 # 这些将在稍后转换回原始数据。 le_ = LabelEncoder() le_.fit(y) transformed_y = le_.transform(y) # 使用各自的特征数组拟合所有估计器 estimators_ = [clf.fit(X, y) if sample_weights is None else clf.fit(X, y, sample_weights) for clf, X in zip([clf for _, clf in classifiers], X_list)] return estimators_, le_def predict_from_multiple_estimator(estimators, label_encoder, X_list, weights = None): # 使用概率进行'soft'投票预测 pred1 = np.asarray([clf.predict_proba(X) for clf, X in zip(estimators, X_list)]) pred2 = np.average(pred1, axis=0, weights=weights) pred = np.argmax(pred2, axis=1) # 将整数预测转换为原始标签: return label_encoder.inverse_transform(pred)
逻辑取自VotingClassifier源码。
现在测试上述方法。首先获取一些数据:
from sklearn.datasets import load_irisdata = load_iris()X = data.datay = []#将整数类别转换为字符串标签for x in data.target: if x==0: y.append('setosa') elif x==1: y.append('versicolor') else: y.append('virginica')
将数据分为训练集和测试集:
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y)
将X划分为不同的特征数据:
X_train1, X_train2 = X_train[:,:2], X_train[:,2:]X_test1, X_test2 = X_test[:,:2], X_test[:,2:]X_train_list = [X_train1, X_train2]X_test_list = [X_test1, X_test2]
获取分类器列表:
from sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVC# 确保这里的估计器数量与不同特征数据的数量相等classifiers = [('knn', KNeighborsClassifier(3)), ('svc', SVC(kernel="linear", C=0.025, probability=True))]
使用数据拟合分类器:
fitted_estimators, label_encoder = fit_multiple_estimators(classifiers, X_train_list, y_train)
使用测试数据进行预测:
y_pred = predict_from_multiple_estimator(fitted_estimators, label_encoder, X_test_list)
获取预测的准确性:
from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_test, y_pred))
如果有任何疑问,请随时提问。