ML使用Sklearn投票分类器详细指南

2021年5月4日22:57:20 发表评论 883 次浏览

投票分类器是一种机器学习模型, 它在众多模型的整体上进行训练, 并根据其将选定类别作为输出的最高概率来预测输出(类别)。

它只是汇总传递给"投票分类器"的每个分类器的结果, 并根据最高的投票预测输出类别。我们的想法不是创建单独的专用模型并为每个模型寻找准确性, 而是创建一个模型来训练这些模型, 并根据它们对每种输出类别的总投票多数来预测输出。

投票分类器支持两种类型的投票。

  1. 硬投票:在硬投票中, 预测的输出类别是具有最高投票多数的类别, 即, 每个分类器预测的可能性最高的类别。假设三个分类器预测了输出类别(A, A, B), 因此大多数人预测一种作为输出。因此一种将是最终的预测。
  2. 软投票:在软投票中, 输出类别是基于赋予该类别的概率的平均值进行的预测。假设给三个模型一些输入, 对类的预测概率A =(0.30, 0.47, 0.53)和B =(0.20, 0.32, 0.40)。所以上课的平均水平A是0.4333和B是0.3067, 赢家显然是一流的一种因为它具有每个分类器平均的最高概率。

注意:

确保包括多种模型以供投票分类器使用, 以确保由一个模型产生的错误可以由另一个模型解决。

代码:实现投票分类器的Python代码

# importing libraries
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
  
# loading iris dataset
iris = load_iris()
X = iris.data[:, : 4 ]
Y = iris.target
  
# train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.20 , random_state = 42 )
  
# group /ensemble of models
estimator = []
estimator.append(( 'LR' , LogisticRegression(solver = 'lbfgs' , multi_class = 'multinomial' , max_iter = 200 )))
estimator.append(( 'SVC' , SVC(gamma = 'auto' , probability = True )))
estimator.append(( 'DTC' , DecisionTreeClassifier()))
  
# Voting Classifier with hard voting
vot_hard = VotingClassifier(estimators = estimator, voting = 'hard' )
vot_hard.fit(X_train, y_train)
y_pred = vot_hard.predict(X_test)
  
# using accuracy_score metric to predict accuracy
score = accuracy_score(y_test, y_pred)
print ( "Hard Voting Score % d" % score)
  
# Voting Classifier with soft voting
vot_soft = VotingClassifier(estimators = estimator, voting = 'soft' )
vot_soft.fit(X_train, y_train)
y_pred = vot_soft.predict(X_test)
  
# using accuracy_score
score = accuracy_score(y_test, y_pred)
print ( "Soft Voting Score % d" % score)

输出:

Hard Voting Score 1
Soft Voting Score 1

例子:

Input  :4.7, 3.2, 1.3, 0.2 
Output :Iris Setosa

实际上, 对于软投票而言, 输出精度会更高, 因为它是所有估算器组合的平均概率, 至于我们已经拟合过度的基本虹膜数据集, 因此输出不会有太大差异。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: