投票分类器VotingClassfier的使用

投票分类器有硬投票和软投票两种,硬投票是对结果进行投票,软投票是对多种结果的预测精度加权后取最高值投票。
这里使用硬投票举个例子

from sklearn.model_selection import train_test_split
from sklearn.datasets import make_moons
x,y=make_moons(n_samples=1000,noise=0.25,random_state=42)
xtr,xte,ytr,yte=train_test_split(x,y,test_size=0.2,random_state=42)#获得数据
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
rfc=RandomForestClassifier(n_estimators=10, random_state=42)
logit=LogisticRegression(solver="liblinear", random_state=42)
svc=SVC(gamma="auto", random_state=42)

voting=VotingClassifier(estimators=[('rf',rfc),('log',logit),('svc',svc)],voting='hard')
#使用硬投票
voting.fit(xtr,ytr)
for clf in (logit,rfc,svc,voting):
    clf.fit(xtr,ytr)
    yp=clf.predict(xte)
    print(clf.__class__.__name__,accuracy_score(yte,yp))

LogisticRegression 0.835
RandomForestClassifier 0.94
SVC 0.94
VotingClassifier 0.943

修改VotingClassifier的参数voting为soft可以获得软投票,但是需要保证估算器都有predict_probe方法,SVC分类器是没有的,需要对SVC的超参数probability设置为True,当然这会导致SVC使用交叉验证时候的速度降低,但是会获得predict_probe方法。

rfc=RandomForestClassifier(n_estimators=10, random_state=42)
logit=LogisticRegression(solver="liblinear", random_state=42)
svc=SVC(gamma="auto", random_state=42,probability=True)#修改参数probability=True
voting=VotingClassifier(estimators=[('rf',rfc),('log',logit),('svc',svc)],voting='soft')
voting.fit(xtr,ytr)
for clf in (logit,rfc,svc,voting):
    clf.fit(xtr,ytr)
    yp=clf.predict(xte)
    print(clf.__class__.__name__,accuracy_score(yte,yp))

LogisticRegression 0.835
RandomForestClassifier 0.94
SVC 0.94
VotingClassifier 0.945

上面使用软投票获得的预测精度又比硬投票提升了一些。

猜你喜欢

转载自blog.csdn.net/lisenby/article/details/108631496
今日推荐