集成学习 Python-随机森林、SVM、KNN

时间:2021-05-14 17:22:37

标签: python scikit-learn svm random-forest knn

我正在尝试集成分类器随机森林、SVM 和 KNN。 在这里,我将 VotingClassifier 与 GridSearchCV 结合使用。 如果我尝试使用逻辑回归、随机森林和高斯,代码运行良好

clf11 = LogisticRegression(random_state=1)
clf12 = RandomForestClassifier(random_state=1)
clf13 = GaussianNB()

但是我不知道我在下面的代码中做错了什么,因为我是初学者。 这是我尝试使用随机森林、KNN 和 SVM

from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import VotingClassifier

clf11 = RandomForestClassifier(n_estimators=100,criterion="entropy")
clf12 = KNeighborsClassifier(n_neighbors=best_k)
clf13 = SVC(kernel='rbf', probability=True)
eclf1 = VotingClassifier(estimators=[('lr', clf11), ('rf', clf12), ('gnb', clf13)],voting='hard')

params = {'lr__C': [1.0, 100.0], 'rf__n_estimators': [20, 200]}

grid1 = GridSearchCV(estimator=eclf1, param_grid=params, cv=30)
grid1.fit(X_train,y_train)
grid1_predicted = grid1.predict(X_test)
print('Accuracy score : {}%'.format(accuracy_score(y_test,grid1_predicted)*100))
scores_dict['Logistic-Random-Gaussian'] = accuracy_score(y_test,grid1_predicted)*100

每当我运行这个我得到

Invalid parameter estimator VotingClassifier.

这些是我遇到的错误。enter image description here enter image description here

是否可以集成随机森林、svm 和 KNN?

或者,有没有其他方法可以做到?

1 个答案:

答案 0 :(得分:0)

发布的代码如下:

clf11 = RandomForestClassifier(n_estimators=100,criterion="entropy")
clf12 = KNeighborsClassifier(n_neighbors=best_k)
clf13 = SVC(kernel='rbf', probability=True)
eclf1 = VotingClassifier(estimators=[('lr', clf11), ('rf', clf12), ('gnb', clf13)],voting='hard')

params = {'lr__C': [1.0, 100.0], 'rf__n_estimators': [20, 200]}

在这里,您对 RandomForestClassifier 使用了 hiperparameters C,这将不起作用。

您必须使用对正在使用的分类器有效的 hiperparameters。也许估计器的名称“lr”、“rf”和“gnb”被其他更合适的替代,然后选择对不同类型分类器有效的超参数

以下方法可行:

clf11 = RandomForestClassifier(n_estimators=100,criterion="entropy")
clf12 = KNeighborsClassifier(n_neighbors=best_k)
clf13 = SVC(kernel='rbf', probability=True)
eclf1 = VotingClassifier(estimators=[('rf', clf11), ('knn', clf12), ('svc', clf13)],voting='hard')

params = {'svc__C': [1.0, 100.0], 'rf__n_estimators': [20, 200]}