硬投票

如何训练多数规则分类器(硬投票):
#训练多数规则分类器: from sklearn import datasets from sklearn.model_selection import
cross_val_score from sklearn.linear_model import LogisticRegression from
sklearn.naive_bayes import GaussianNB from sklearn.ensemble import
RandomForestClassifier from sklearn.ensemble import VotingClassifier iris =
datasets.load_iris() X,y = iris.data[:,1:3],iris.target clf1 =
LogisticRegression(solver='lbfgs',multi_class='multinomial',random_state=1) #
solver:逻辑回归损失函数的优化方法,拟牛顿法的一种。利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。 clf2 =
RandomForestClassifier(n_estimators=50,random_state=1) clf3 = GaussianNB() eclf
=
VotingClassifier(estimators=[('lr',clf1),('rf',clf2),('gnb',clf3)],voting='hard')
for clf,label in zip([clf1,clf2,clf3,eclf],['Logistic Regression','Random
Forest','Naive Bayes','Ensemble']): scores =
cross_val_score(clf,X,y,cv=5,scoring='accuracy')
print("Accuracy:均值:%0.2f,标准差:%0.2f [%s]" %(scores.mean(),scores.std(),label))
Out:

Accuracy:均值:0.95,标准差:0.04 [Logistic Regression]
Accuracy:均值:0.94,标准差:0.04 [Random Forest]
Accuracy:均值:0.91,标准差:0.04 [Naive Bayes]
Accuracy:均值:0.95,标准差:0.04 [Ensemble]

软投票

下边的示例程序说明了当软投票分类器(soft VotingClassifier)是基于线性支持向量机(linear SVM)、决策树(Decision
Tree)、K 近邻(K-nearest)分类器时,决策域可能的变化情况:

Plot the decision boundaries of a VotingClassifier
from sklearn import datasets import numpy as np from sklearn.tree import
DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from
sklearn.svm import SVC from itertools import product from sklearn.ensemble
import VotingClassifier import matplotlib.pyplot as plt iris =
datasets.load_iris() X,y = iris.data[:,[0,2]],iris.target #???data[:,[0,2]]
#Training clf1 = DecisionTreeClassifier(max_depth=4) clf2 =
KNeighborsClassifier(n_neighbors=7) clf3 =
SVC(gamma='scale',kernel='rbf',probability=True) #gamma:核函数系数 #
kernel:算法中采用的核函数类型,‘rbf’:径像核函数/高斯核 # probability:是否启用概率估计 eclf =
VotingClassifier(estimators=[('dt',clf1),('knn',clf2),('svc',clf3)],
voting='soft',weights=[2,1,2]) clf1 = clf1.fit(X,y) clf2 = clf2.fit(X,y) clf3 =
clf3.fit(X,y) eclf = eclf.fit(X,y) # Plotting decision regions x_min,x_max =
X[:,0].min() - 1,X[:,0].max() + 1 y_min,y_max = X[:,1].min() - 1,X[:,1].max() +
1 xx,yy = np.meshgrid(np.arange(x_min, x_max, 0.1),np.arange(y_min, y_max,
0.1)) # 生成网格点坐标矩阵: # 坐标矩阵——横坐标矩阵XX中的每个元素,与纵坐标矩阵YY中对应位置元素,共同构成一个点的完整坐标。 #
如B点坐标(X12,Y12)=(1,1)(X12​,Y12​)=(1,1) f, axarr = plt.subplots(2, 2,
sharex='col', sharey='row', figsize=(10, 8)) # sharey‘row’ 时,每一行的子图会共享 x 或者 y 轴
for idx,clf,tt in zip(product([0,1],[0,1]), [clf1,clf2,clf3,eclf], ['Decison
Tree(depth=4)','KNN(k=7)','Kernel SVM','Soft Voting']): Z =
clf.predict(np.c_[xx.ravel(),yy.ravel()]) '''
numpy中的ravel()、flatten()、squeeze()都有将多维数组转换为一维数组的功能,区别:
ravel():如果没有必要,不会产生源数据的副本 flatten():返回源数据的副本 squeeze():只能对维数为1的维度降维
另外,reshape(-1)也可以“拉平”多维数组 ''' ''' np.r_ 是按列连接两个矩阵,就是把两矩阵上下相加,要求列数相等,类似于 pandas
中的 concat()。 np.c_ 是按行连接两个矩阵,就是把两矩阵左右相加,要求行数相等,类似于pandas中的merge()。 ''' Z =
Z.reshape(xx.shape) axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.4) #
contourf绘制等高线的,contour和contourf都是画三维等高线图的,不同点在于contour() 是绘制轮廓线,contourf()会填充轮廓
axarr[idx[0], idx[1]].scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor='k')
axarr[idx[0], idx[1]].set_title(tt) plt.show()
Figure:

投票回归器

投票回归器背后的思想是将概念上不同的机器学习回归器组合起来,并返回平均预测值。这样一个回归器对于一组同样表现良好的模型是有用的,以便平衡它们各自的弱点。

下面的例子展示了如何匹配投票回归器:

Plot individual and voting regression predictions
import matplotlib.pyplot as plt from sklearn import datasets from
sklearn.ensemble import GradientBoostingRegressor from sklearn.ensemble import
RandomForestRegressor from sklearn.linear_model import LinearRegression from
sklearn.ensemble import VotingRegressor #loading some example data boston =
datasets.load_boston() X,y = boston.data,boston.target #training classifier
reg1 = GradientBoostingRegressor(random_state=1,n_estimators=10) reg2 =
RandomForestRegressor(random_state=1,n_estimators=10) reg3 = LinearRegression()
ereg = VotingRegressor([('gb',reg1),('rf',reg2),('lr',reg3)]) reg1.fit(X,y)
reg2.fit(X,y) reg3.fit(X,y) ereg.fit(X,y) xt = X[:20] plt.figure()
plt.plot(reg1.predict(xt),'gd',label
='GradientBoostingRegressor')#''中的字母代表了散点图中的表示样式,gd为绿色菱形,g代表绿色
plt.plot(reg2.predict(xt),'b^',label='RandomForestRegressor')
plt.plot(reg3.predict(xt),'ys',label='LinearRegression')#样式为黄色正方形,y代表黄色
plt.plot(ereg.predict(xt),'r*',label='VotingRegressor')
plt.tick_params(axis='y',which='both',bottom=False,top=False,labelbottom=False)
plt.ylabel('predicted') plt.xlabel('training samples') plt.legend('Comparison
of individual predictions with averaged') plt.show()
Figure:

 

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信