集成學習的投票機制(Voting mechanism about ensemble learning)

硬投票

如何訓練多數規則分類器(硬投票):

#訓練多數規則分類器:
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:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章