隨機森林
1、什麼是集成學習方法
集成學習通過建立幾個板型組合的來解決單一預測問題,它的工作原理是生成多個分類器/模型,各獨立地學習和作出預測。這些預測最後結合成組合預測,因此優於任何一個單分類的做出預測。決策樹過度擬合可以用剪枝或者集成學習方法的隨機森林實現。
2、什麼是隨機森林
在機器學習中,隨機森林是一個包含多個決策樹的分類器,並且其輸出的類別是由多個決策樹輸出的類別的衆數而定。例如,如果你訓練了5個樹,其中有4個樹的結果是True,1個樹的結果是False,那麼最終投票結果就是True。
隨機:
森林:包含多個決策樹的分類器
3、隨機森林的原理過程
隨機:特值隨機,訓練集隨機
隨機森林算法根據下列算法而建造每棵樹:
·用N來表示訓練用例(樣本)的個數,M表示特徵數目。
。1、一次隨機選出一個樣本,重紅N次。《隨機有放回的抽取,有可能出現重複的樣本)
。2、隨機去選出m個特徵,m << M,建立決策制,每棵樹有m個特徵。
·採取bootstrap抽樣 《隨機有放回的抽樣》
4、爲什麼採取bootstrap抽樣
爲什麼要隨機推樣訓練?
- 如果不進行隨機抽樣,每棵樹的訓練集都一樣,那麼最終訓練出的樹分類結果也一樣
爲什麼要有放回地抽樣?
- 如果不是有放回的抽樣,那麼每棵樹的訓練樣本都是不同的,都是沒有交集的,也就是說每棵樹訓練出來都是有很大的差異的;而隨機森林最後分類取決於多棵樹(弱分類器》的投票表決。
5、python實現隨機森林的接口
· class sklearn.ensemble.RandomForestClassifier(n_estimators=10,criterion='gini',max_depth=None,bootstrap=True,random_state=None,min_samples_split=2)
隨機森林分類器參數解釋:
。n_estimators:integer,optional(default=10)森林裏的樹木數量100,150,300,...
。criteria:string,可選(default="gini")分割特徵的測量方法"entropy"、"gini"
。max_depth:integer或None,可選(默認=無)樹的最大深度5,8,15,25,30
。max_features="auto”,每個決策樹的量大特徵數量
·If"auto",then max_features=sqrt(n_features).
·If"sqrt",then max_features=sqrt(n features)(same as"auto").
·If"log2",then max_features=log2(n_features).
·If None,then max_features = n_features.
。bootstrap:boolean,optional(default=True)是否在構建樹時使用放回抽樣\
。min_samples_split:節點劃分最少樣本數
。min_samples_leaf:葉子節點的最小樣本數
·其中超參數有:n_estimator,max_depth,min_samples_split,min_samples_leaf
6、應用總結
在當前所有分類算法中,具有極好的準確率
能夠有效地運行在大數據集上,處理具有高維特徵的輸入樣本,而且不需要降維
能夠評估各個特徵在分類問題上的重要性
7、案例:隨機森林對泰坦尼克號乘客的生存進行預測
import pandas as pd
'''1 獲取數據'''
path = "http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt"
titanic = pd.read_csv(path)
row.names | pclass | survived | name | age | embarked | home.dest | room | ticket | boat | sex | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 1st | 1 | Allen, Miss Elisabeth Walton | 29.0000 | Southampton | St Louis, MO | B-5 | 24160 L221 | 2 | female |
1 | 2 | 1st | 0 | Allison, Miss Helen Loraine | 2.0000 | Southampton | Montreal, PQ / Chesterville, ON | C26 | NaN | NaN | female |
2 | 3 | 1st | 0 | Allison, Mr Hudson Joshua Creighton | 30.0000 | Southampton | Montreal, PQ / Chesterville, ON | C26 | NaN | (135) | male |
3 | 4 | 1st | 0 | Allison, Mrs Hudson J.C. (Bessie Waldo Daniels) | 25.0000 | Southampton | Montreal, PQ / Chesterville, ON | C26 | NaN | NaN | female |
4 | 5 | 1st | 1 | Allison, Master Hudson Trevor | 0.9167 | Southampton | Montreal, PQ / Chesterville, ON | C22 | NaN | 11 | male |
display(titanic.head(3))
# 解釋數據
#字段: row.names pclass survived name age embarked home.dest room ticket boat sex
#解釋:人員編號 人員等級劃分 是否倖存 名字 年齡 上傳地點 家庭地址 所在船艙 船票 boat(我也不知道怎麼解釋) 性別
# 篩選特徵值和目標值
x = titanic[["pclass", "age", "sex","embarked","home.dest","room"]]
y = titanic["survived"]
row.names | pclass | survived | name | age | embarked | home.dest | room | ticket | boat | sex | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 1st | 1 | Allen, Miss Elisabeth Walton | 29.0 | Southampton | St Louis, MO | B-5 | 24160 L221 | 2 | female |
1 | 2 | 1st | 0 | Allison, Miss Helen Loraine | 2.0 | Southampton | Montreal, PQ / Chesterville, ON | C26 | NaN | NaN | female |
2 | 3 | 1st | 0 | Allison, Mr Hudson Joshua Creighton | 30.0 | Southampton | Montreal, PQ / Chesterville, ON | C26 | NaN | (135) | male |
'''2 數據預處理'''
x.info() #發現缺失值,
#root變量缺失值太多,不具備解釋性,刪除。
x = x.drop("room", inplace=False, axis=1) #刪除room列
#age變量缺失值,用均值代替
x["age"] = x["age"].fillna(x["age"].mean(), inplace=False)
#embarked 、home.dest 缺失,使用上一個人的向下填充
x = x.fillna(method="ffill",inplace=False)
#home.dest 缺失值用向上填充
display(x.head(3))
<class ‘pandas.core.frame.DataFrame’>
RangeIndex: 1313 entries, 0 to 1312
Data columns (total 6 columns):
pclass 1313 non-null object
age 633 non-null float64
sex 1313 non-null object
embarked 821 non-null object
home.dest 754 non-null object
room 77 non-null object
dtypes: float64(1), object(5)
memory usage: 61.6+ KB
pclass | age | sex | embarked | home.dest | |
---|---|---|---|---|---|
0 | 1st | 29.0 | female | Southampton | St Louis, MO |
1 | 1st | 2.0 | female | Southampton | Montreal, PQ / Chesterville, ON |
2 | 1st | 30.0 | male | Southampton | Montreal, PQ / Chesterville, ON |
x.info() #發現缺失值
<class ‘pandas.core.frame.DataFrame’>
RangeIndex: 1313 entries, 0 to 1312
Data columns (total 5 columns):
pclass 1313 non-null object
age 1313 non-null float64
sex 1313 non-null object
embarked 1313 non-null object
home.dest 1313 non-null object
dtypes: float64(1), object(4)
memory usage: 51.4+ KB
'''3 特徵工程'''
# 1) 轉換成字典
x = x.to_dict(orient="records")
# print(x)
# 2、數據集劃分
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=11)
# display(x_train)
# 3、字典特徵抽取
from sklearn.feature_extraction import DictVectorizer
from sklearn.tree import DecisionTreeClassifier, export_graphviz
transfer = DictVectorizer(sparse=False)
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# print(transfer.get_feature_names()) #返回類別名稱
# print(x_train)
'''4 模型預估器'''
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
estimator = RandomForestClassifier()
# 加入網格搜索與交叉驗證
# 參數準備
param_dict = {"n_estimators": [100,120,200,300,500,800], "max_depth": [3,5,8,10,15], "max_features":["auto","log2"]}
estimator = GridSearchCV(estimator, param_grid=param_dict, cv=3)
estimator.fit(x_train, y_train)
GridSearchCV(cv=3, error_score=‘raise’,
estimator=RandomForestClassifier(bootstrap=True, class_weight=None, criterion=‘gini’,
max_depth=None, max_features=‘auto’, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False),
fit_params=None, iid=True, n_jobs=1,
param_grid={‘n_estimators’: [100, 120, 200, 300, 500, 800], ‘max_depth’: [3, 5, 8, 10, 15], ‘max_features’: [‘auto’, ‘log2’]},
pre_dispatch=‘2*n_jobs’, refit=True, return_train_score=‘warn’,
scoring=None, verbose=0)
'''5 模型評估'''
# 方法1:直接比對真實值和預測值
y_predict = estimator.predict(x_test)
print("y_predict:\n", y_predict)
#print("直接比對真實值和預測值:\n", y_test == y_predict)
# 方法2:計算準確率
score = estimator.score(x_test, y_test)
print("準確率爲:\n", score)
# 最佳參數:best_params_
print("最佳參數:\n", estimator.best_params_)
# 最佳結果:best_score_
print("最佳結果:\n", estimator.best_score_)
# 最佳估計器:best_estimator_
print("最佳估計器:\n", estimator.best_estimator_)
# 交叉驗證結果:cv_results_
#print("交叉驗證結果:\n", estimator.cv_results_) transfer.get_feature_names()
y_predict:
[0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0
1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 0 0 1 1 1 0 0
0 1 0 0 0 1 1 0 1 1 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 1 1 0 0 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0 0 1 1 1 0 0 0 1 0 1 1 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1
1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0]
準確率爲:
0.8206686930091185
最佳參數:
{‘max_depth’: 15, ‘max_features’: ‘auto’, ‘n_estimators’: 200}
最佳結果:
0.8262195121951219
最佳估計器:
RandomForestClassifier(bootstrap=True, class_weight=None, criterion=‘gini’,
max_depth=15, max_features=‘auto’, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=200, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False)