1. 程式人生 > 實用技巧 >sklearn.ensemble 整合學習理論

sklearn.ensemble 整合學習理論

目錄

一、什麼是整合學習

整合學習是一種技術框架,它本身不是一個單獨的機器學習演算法,而是通過構建並結合多個機器學習器來完成學習任務,一般結構是:先產生一組“個體學習器”,再用某種策略將它們結合起來,目前,有三種常見的整合學習框架(策略):bagging,boosting和stacking

也就是說,整合學習有兩個主要的問題需要解決,第一是如何得到若干個個體學習器,第二是如何選擇一種結合策略,將這些個體學習器集合成一個強學習器

二、Bagging演算法

Bagging(裝袋演算法)的整合學習方法非常簡單,假設我們有一個數據集D,使用Bootstrap sample(有放回的隨機取樣)
的方法取了k個數據子集(子集樣本數都相等):D1,D2,…,Dk,作為新的訓練集,我們使用這k個子集分別訓練一個分類器(使用分類、迴歸等演算法),最後會得到k個分類模型。我們將測試資料輸入到這k個分類器,會得到k個分類結果,比如分類結果是0和1,那麼這k個結果中誰佔比最多,那麼預測結果就是誰。
我們使用葡萄酒資料集進行建模(資料處理):
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 10:12:48 2020

@author: Admin
"""
## 我們使用葡萄酒資料集進行建模(資料處理)
import pandas as pd 
df_wine 
= pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data',header=None) df_wine.columns = ['Class label', 'Alcohol','Malic acid', 'Ash','Alcalinity of ash','Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols','Proanthocyanins','Color intensity
', 'Hue','OD280/OD315 of diluted wines','Proline'] df_wine['Class label'].value_counts() ''' 2 71 1 59 3 48 Name: Class label, dtype: int64 ''' df_wine = df_wine[df_wine['Class label'] != 1] # drop 1 class y = df_wine['Class label'].values X = df_wine[['Alcohol','OD280/OD315 of diluted wines']].values from sklearn.model_selection import train_test_split # 切分訓練集與測試集 from sklearn.preprocessing import LabelEncoder # 標籤化分類變數 le = LabelEncoder() y = le.fit_transform(y) #吧y值改為0和1 ,原來是2和3 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=1,stratify=y) #2、8分 ## 我們使用單一決策樹分類: from sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(criterion='entropy',random_state=1,max_depth=None) #選擇決策樹為基本分類器 from sklearn.metrics import accuracy_score #計算準確率 tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train,y_train_pred) #訓練集準確率 tree_test = accuracy_score(y_test,y_test_pred) #測試集準確率 print('Decision tree train/test accuracies %.3f/%.3f' % (tree_train,tree_test)) #Decision tree train/test accuracies 1.000/0.833 ## 我們使用BaggingClassifier分類: from sklearn.ensemble import BaggingClassifier tree = DecisionTreeClassifier(criterion='entropy',random_state=1,max_depth=None) #選擇決策樹為基本分類器 bag = BaggingClassifier(base_estimator=tree,n_estimators=500,max_samples=1.0,max_features=1.0,bootstrap=True, bootstrap_features=False,n_jobs=1,random_state=1) from sklearn.metrics import accuracy_score bag = bag.fit(X_train,y_train) y_train_pred = bag.predict(X_train) y_test_pred = bag.predict(X_test) bag_train = accuracy_score(y_train,y_train_pred) bag_test = accuracy_score(y_test,y_test_pred) print('Bagging train/test accuracies %.3f/%.3f' % (bag_train,bag_test)) #Bagging train/test accuracies 1.000/0.917 ''' 我們可以對比兩個準確率,測試準確率較之決策樹得到了顯著的提高 我們來對比下這兩個分類方法上的差異 ''' ## 我們來對比下這兩個分類方法上的差異 x_min = X_train[:, 0].min() - 1 x_max = X_train[:, 0].max() + 1 y_min = X_train[:, 1].min() - 1 y_max = X_train[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(nrows=1, ncols=2,sharex='col',sharey='row',figsize=(12, 6)) for idx, clf, tt in zip([0, 1],[tree, bag],['Decision tree', 'Bagging']): clf.fit(X_train, y_train) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) #ravel()方法將陣列維度拉成一維陣列,np.c_是按行連線兩個矩陣,就是把兩矩陣左右相加,要求行數相等 Z = Z.reshape(xx.shape) axarr[idx].contourf(xx, yy, Z, alpha=0.3) axarr[idx].scatter(X_train[y_train==0, 0],X_train[y_train==0, 1],c='blue', marker='^') axarr[idx].scatter(X_train[y_train==1, 0],X_train[y_train==1, 1],c='green', marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('Alcohol', fontsize=12) plt.tight_layout() plt.text(0, -0.2,s='OD280/OD315 of diluted wines',ha='center',va='center',fontsize=12,transform=axarr[1].transAxes) plt.show() ''' 從結果圖看起來,三個節點深度的決策樹分段線性決策邊界在Bagging整合中看起來更加平滑 '''

class sklearn.ensemble.BaggingClassifier(base_estimator=None, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0)

引數說明:

base_estimator:Object or None。None代表預設是DecisionTree,Object可以指定基估計器(base estimator)
n_estimators:int, optional (default=10)要整合的基估計器的個數
max_samples: int or float, optional (default=1.0)。決定從x_train抽取去訓練基估計器的樣本數量int 代表抽取數量,float代表抽取比例
max_features : int or float, optional (default=1.0)。決定從x_train抽取去訓練基估計器的特徵數量。int 代表抽取數量,float代表抽取比例
bootstrap : boolean, optional (default=True) 決定樣本子集的抽樣方式(有放回和不放回)
bootstrap_features : boolean, optional (default=False)決定特徵子集的抽樣方式(有放回和不放回)
oob_score : bool 決定是否使用包外估計(out of bag estimate)泛化誤差
warm_start : bool, optional (default=False) 設定為True時,請重用上一個呼叫的解決方案以適合併為集合新增更多估計量,否則,僅適合一個全新的集合
n_jobs : int, optional (default=None) fit和 並行執行的作業數predict。None除非joblib.parallel_backend上下文中,否則表示1 。-1表示使用所有處理器
random_state : int, RandomState instance or None, optional (default=None)。如果int,random_state是隨機數生成器使用的種子; 如果RandomState的例項,random_state是隨機數生成器; 如果None,則隨機數生成器是由np.random使用的RandomState例項
verbose : int, optional (default=0)

屬性介紹:
estimators_ : list of estimators。The collection of fitted sub-estimators.
estimators_samples_ : list of arrays
estimators_features_ : list of arrays
oob_score_ : float,使用包外估計這個訓練資料集的得分。
oob_prediction_ : array of shape = [n_samples]。在訓練集上用out-of-bag估計計算的預測。 如果n_estimator很小,則可能在抽樣過程中資料點不會被忽略。 在這種情況下,oob_prediction_可能包含NaN。