1. 程式人生 > >RandomForest 隨機森林演算法與模型引數的調優

RandomForest 隨機森林演算法與模型引數的調優

> **公號:碼農充電站pro** > **主頁:** 本篇文章來介紹**隨機森林**(*RandomForest*)演算法。 ### 1,整合演算法之 bagging 演算法 在前邊的文章《[AdaBoost 演算法-分析波士頓房價資料集](https://www.cnblogs.com/codeshell/p/14149923.html)》中,我們介紹過**整合演算法**。整合演算法中有一類演算法叫做 **bagging** 演算法。 **bagging** 演算法是將一個原始資料集隨機抽樣成 **N** 個新的資料集。然後將這 **N** 個新的資料集作用於同一個機器學習演算法,從而得到 **N** 個模型,最終整合一個綜合模型。 在對新的資料進行預測時,需要經過這 **N** 個模型(每個模型互不依賴干擾)的預測(投票),最終綜合 **N** 個投票結果,來形成最後的預測結果。 **bagging** 演算法的流程可用下圖來表示: ![](https://img-blog.csdnimg.cn/20201215133730473.png?) ### 2,隨機森林演算法 隨機森林演算法是 **bagging** 演算法中比較出名的一種。 隨機森林演算法由多個決策樹分類器組成,每一個子分類器都是一棵 **CART** 分類迴歸樹,所以隨機森林既可以做分類,又可以做迴歸。 當隨機森林演算法處理分類問題的時候,分類的最終結果是由所有的子分類器投票而成,投票最多的那個結果就是最終的分類結果。 當隨機森林演算法處理迴歸問題的時候,最終的結果是每棵 **CART** 樹的迴歸結果的平均值。 ### 3,隨機森林演算法的實現 **sklearn** 庫即實現了**隨機森林分類樹**,又實現了**隨機森林迴歸樹**: - [RandomForestClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html):分類樹 - [RandomForestRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html):迴歸樹 **RandomForestClassifier** 類的原型如下: ```python RandomForestClassifier(n_estimators=100, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None) ``` 可以看到分類樹的引數特別多,我們來介紹幾個重要的引數: - **n_estimators**:隨機森林中決策樹的個數,預設為 100。 - **criterion**:隨機森林中決策樹的演算法,可選的有兩種: - **gini**:基尼係數,也就是 **CART 演算法**,為預設值。 - **entropy**:資訊熵,也就是 **ID3 演算法**。 - **max_depth**:決策樹的最大深度。 **RandomForestRegressor** 類的原型如下: ```python RandomForestRegressor(n_estimators=100, criterion='mse', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None) ``` 迴歸樹中的引數與分類樹中的引數基本相同,但 **criterion** 引數的取值不同。 在迴歸樹中,**criterion** 引數有下面兩種取值: - **mse**:表示**均方誤差演算法**,為預設值。 - **mae**:表示**平均誤差演算法**。 ### 4,隨機森林演算法的使用 下面使用隨機森林分類樹來處理[鳶尾花資料集](https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/data/iris.csv),該資料集在《[決策樹演算法-實戰篇](https://www.cnblogs.com/codeshell/p/13984334.html)》中介紹過,這裡不再介紹,我們直接使用它。 首先載入資料集: ```python from sklearn.datasets import load_iris iris = load_iris() # 準備資料集 features = iris.data # 獲取特徵集 labels = iris.target # 獲取目標集 ``` 將資料分成**訓練集**和**測試集**: ```python from sklearn.model_selection import train_test_split train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size=0.33, random_state=0) ``` 接下來構造隨機森林分類樹: ```python from sklearn.ensemble import RandomForestClassifier # 這裡均使用預設引數 rfc = RandomForestClassifier() # 訓練模型 rfc.fit(train_features, train_labels) ``` `estimators_` 屬性中儲存了訓練出來的所有的子分類器,來看下子分類器的個數: ```python >
>> len(rfc.estimators_) 100 ``` 預測資料: ```python test_predict = rfc.predict(test_features) ``` 測試準確率: ```python >>> from sklearn.metrics import accuracy_score >>> accuracy_score(test_labels, test_predict) 0.96 ``` ### 5,模型引數調優 在機器學習演算法模型中,一般都有很多引數,每個引數都有不同的取值。如何才能讓模型達到最好的效果呢?這就需要引數調優。 **sklearn** 庫中有一個 [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) 類,可以幫助我們進行引數調優。 我們只要告訴它想要調優的引數有哪些,以及引數的取值範圍,它就會把所有的情況都跑一遍,然後告訴我們引數的最優取值。 先來看下 **GridSearchCV** 類的原型: ```python GridSearchCV(estimator, param_grid, scoring=None, n_jobs=None, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score=nan, return_train_score=False) ``` 其中有幾個重要的引數: - **estimator**:表示為哪種機器學習演算法進行調優,比如隨機森林,決策樹,SVM 等。 - **param_grid**:要優化的引數及取值,輸入的形式是**字典或列表**。 - **scoring**:準確度的評價標準。 - **cv**:交叉驗證的折數,預設是三折交叉驗證。 下面我們對隨機森林分類樹進行引數調優,還是使用**鳶尾花資料集**。 首先載入資料: ```python from sklearn.datasets import load_iris iris = load_iris() ``` 構造分類樹: ```python from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier() ``` 如果我們要對分類樹的 `n_estimators` 引數進行調優,調優的範圍是 `[1, 10]`,則準備變數: ```python param = {"n_estimators": range(1,11)} ``` 建立 **GridSearchCV** 物件,並調優: ```python from sklearn.model_selection import GridSearchCV gs = GridSearchCV(estimator=rfc, param_grid=param) # 對iris資料集進行分類 gs.fit(iris.data, iris.target) ``` 輸出最優準確率和最優引數: ```python >
>> gs.best_score_ 0.9666666666666668 >>> gs.best_params_ {'n_estimators': 7} ``` 可以看到,最優的結果是 `n_estimators` 取 **7**,也就是隨機森林的子決策樹的個數是 **7** 時,隨機森林的準確度最高,為 **0.9667**。 ### 6,總結 本篇文章主要介紹了隨機森林演算法的原理及應用,並展示瞭如何使用 **GridSearchCV** 進行引數調優。 (本節完。) --- **推薦閱讀:** [AdaBoost 演算法-分析波士頓房價資料集](https://www.cnblogs.com/codeshell/p/14149923.html) [決策樹演算法-實戰篇-鳶尾花及波士頓房價預測](https://www.cnblogs.com/codeshell/p/13984334.html) [EM 演算法-對鳶尾花資料進行聚類](https://www.cnblogs.com/codeshell/p/14132408.html) [Apriori 演算法-如何進行關聯規則挖掘](https://www.cnblogs.com/codeshell/p/14113600.html) [Logistic 迴歸-原理及應用](https://www.cnblogs.com/codeshell/p/14171616.html) --- *歡迎關注作者公眾號,獲取更多技術乾貨。* ![碼農充電站pro](https://img-blog.csdnimg.cn/20200505082843773.png?#pic