一、集成學習方法之隨機森林
集成學習通過建立幾個模型組合來解決單一模型預測的問題。它的工作原理是生成多個分類器/模型,各自獨立地學習和作出預測。這些預測最后結合成單預測,因此優於任何一個單分類的做出預測。
1、什么是隨機森林
隨機森林是一個包含多個決策樹的分類器,並且其輸出的類別是由個別樹輸出的類別的眾數而定。假設你訓練了n棵樹,其中有n-2棵樹的結果類別是1,2棵樹的結果的類別是2,那么最后的類別結果就是1。
2、隨機森林創建流程
在創建隨機森林之前,我們需要先知道隨機森林中單棵決策樹的創建流程:
- 隨機在N個樣本中以有放回抽樣的方式,取樣N次(樣本有可能重復)
- 隨機在M個特征中選出m個特征(m<M)
可以以這種方式創建多棵樹,顯然每棵樹的樣本和特征大多不一樣。
值得注意的是上面的抽樣是:有放回的抽樣,如果不是有放回的抽樣,這樣每棵樹的訓練樣本都是不同,之間也沒有交集,也就是說每棵樹訓練出來都是有很大的差異的;而隨機森林最后分類取決於多棵樹的投票表決。
二、集成學習API
1、class sklearn.ensemble.RandomForestClassifier(n_estimators=10, criterion=’gini’, max_depth=None, bootstrap=True, random_state=None)
上述就是隨機森林的分類器,其中:
- n_estimators:integer,optional(default = 10) 森林里的樹木數量
- criteria:string,可選(default =“gini”)分割特征的測量方法
- max_depth:integer或None,可選(默認=無)樹的最大深度
- bootstrap:boolean,optional(default = True)是否在構建樹時使用放回抽樣
2、實例
import pandas as pd from sklearn.model_selection import train_test_split,GridSearchCV from sklearn.feature_extraction import DictVectorizer from sklearn.ensemble import RandomForestClassifier def decision(): """ 決策樹對泰坦尼克號乘客進行生死預測 :return: None """ # 讀取數據 data = pd.read_csv("./data/決策樹數據/data.csv") # 選取特征值、目標值 x = data[['pclass', 'age', 'sex']] y = data['survived'] # 處理缺失值 x['age'].fillna(x['age'].mean(), inplace=True) print(x) """ pclass age sex 1st 29.000000 female 1st 2.000000 female ... """ # 分割數據集為訓練集和測試集 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25) # 特征工程,pclass與sex都是非數字的值,所以需要將其值得類別進行one-hot編碼,使用字典抽取,age值不變 dict = DictVectorizer(sparse=False) x_train = dict.fit_transform(x_train.to_dict(orient='records')) x_test = dict.transform(x_test.to_dict(orient='records')) print(dict.get_feature_names()) # ['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male'] print(x_train) """ [[32. 0. 0. 1. 0. 1. ] ... [58. 1. 0. 0. 1. 0. ] [35. 0. 1. 0. 0. 1. ] [31.19418104 0. 0. 1. 0. 1. ]] """ # 用隨機森林進行預測(超參數調優) rf = RandomForestClassifier() param = {"n_estimators":[120, 200, 300, 500],"max_depth":[5, 8, 15]} # 網格搜索與交叉驗證 gc = GridSearchCV(rf,param_grid=param,cv=2) gc.fit(x_train,y_train) # 准確率 print(gc.score(x_test,y_test)) #參數模型 print(gc.best_params_) """ {'max_depth': 5, 'n_estimators': 300} """ if __name__ == '__main__': decision()
隨機森林幾乎沒有什么缺點,它有以下的優點:
- 在當前所有算法中,具有極好的准確率
- 能夠有效地運行在大數據集上
- 能夠處理具有高維特征的輸入樣本,而且不需要降維
- 能夠評估各個特征在分類問題上的重要性
- 對於缺省值問題也能夠獲得很好得結果