用Python實現隨機森林算法,深度學習


用Python實現隨機森林算法,深度學習

擁有高方差使得決策樹(secision tress)在處理特定訓練數據集時其結果顯得相對脆弱。bagging(bootstrap aggregating 的縮寫)算法從訓練數據的樣本中建立復合模型,可以有效降低決策樹的方差,但樹與樹之間有高度關聯(並不是理想的樹的狀態)。

隨機森林算法(Random forest algorithm)是對 bagging 算法的擴展。除了仍然根據從訓練數據樣本建立復合模型之外,隨機森林對用做構建樹(tree)的數據特征做了一定限制,使得生成的決策樹之間沒有關聯,從而提升算法效果。

本教程將實現如何用 Python 實現隨機森林算法。

  • bagged decision trees 與隨機森林算法的差異;

  • 如何構建含更多方差的裝袋決策樹;

  • 如何將隨機森林算法運用於預測模型相關的問題。

 

算法描述

這個章節將對隨機森林算法本身以及本教程的算法試驗所用的聲納數據集(Sonar dataset)做一個簡要介紹。

 

隨機森林算法

決策樹運行的每一步都涉及到對數據集中的最優分裂點(best split point)進行貪婪選擇(greedy selection)。

這個機制使得決策樹在沒有被剪枝的情況下易產生較高的方差。整合通過提取訓練數據庫中不同樣本(某一問題的不同表現形式)構建的復合樹及其生成的預測值能夠穩定並降低這樣的高方差。這種方法被稱作引導聚集算法(bootstrap aggregating),其簡稱 bagging 正好是裝進口袋,袋子的意思,所以被稱為「裝袋算法」。該算法的局限在於,由於生成每一棵樹的貪婪算法是相同的,那么有可能造成每棵樹選取的分裂點(split point)相同或者極其相似,最終導致不同樹之間的趨同(樹與樹相關聯)。相應地,反過來說,這也使得其會產生相似的預測值,降低原本要求的方差。

我們可以采用限制特征的方法來創建不一樣的決策樹,使貪婪算法能夠在建樹的同時評估每一個分裂點。這就是隨機森林算法(Random Forest algorithm)。

與裝袋算法一樣,隨機森林算法從訓練集里擷取復合樣本並訓練。其不同之處在於,數據在每個分裂點處完全分裂並添加到相應的那棵決策樹當中,且可以只考慮用於存儲屬性的某一固定子集。

對於分類問題,也就是本教程中我們將要探討的問題,其被考慮用於分裂的屬性數量被限定為小於輸入特征的數量之平方根。代碼如下:

num_features_for_split = sqrt(total_input_features)

這個小更改會讓生成的決策樹各不相同(沒有關聯),從而使得到的預測值更加多樣化。而多樣的預測值組合往往會比一棵單一的決策樹或者單一的裝袋算法有更優的表現。

 

聲納數據集(Sonar dataset)

我們將在本教程里使用聲納數據集作為輸入數據。這是一個描述聲納反射到不同物體表面后返回的不同數值的數據集。60 個輸入變量表示聲納從不同角度返回的強度。這是一個二元分類問題(binary classification problem),要求模型能夠區分出岩石和金屬柱體的不同材質和形狀,總共有 208 個觀測樣本。

該數據集非常易於理解——每個變量都互有連續性且都在 0 到 1 的標准范圍之間,便於數據處理。作為輸出變量,字符串'M'表示金屬礦物質,'R'表示岩石。二者需分別轉換成整數 1 和 0。

通過預測數據集(M 或者金屬礦物質)中擁有最多觀測值的類,零規則算法(Zero Rule Algorithm)可實現 53% 的精確度。

更多有關該數據集的內容可參見 UCI Machine Learning repository:https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+(Sonar,+Mines+vs.+Rocks)

免費下載該數據集,將其命名為 sonar.all-data.csv,並存儲到需要被操作的工作目錄當中。

 

教程

此次教程分為兩個步驟。

1. 分裂次數的計算。

2. 聲納數據集案例研究

這些步驟能讓你了解為你自己的預測建模問題實現和應用隨機森林算法的基礎

 

1. 分裂次數的計算

在決策樹中,我們通過找到一些特定屬性和屬性的值來確定分裂點,這類特定屬性需表現為其所需的成本是最低的。

分類問題的成本函數(cost function)通常是基尼指數(Gini index),即計算由分裂點產生的數據組的純度(purity)。對於這樣二元分類的分類問題來說,指數為 0 表示絕對純度,說明類值被完美地分為兩組。

從一棵決策樹中找到最佳分裂點需要在訓練數據集中對每個輸入變量的值做成本評估。

在裝袋算法和隨機森林中,這個過程是在訓練集的樣本上執行並替換(放回)的。因為隨機森林對輸入的數據要進行行和列的采樣。對於行采樣,采用有放回的方式,也就是說同一行也許會在樣本中被選取和放入不止一次。

我們可以考慮創建一個可以自行輸入屬性的樣本,而不是枚舉所有輸入屬性的值以期找到獲取成本最低的分裂點,從而對這個過程進行優化。

該輸入屬性樣本可隨機選取且沒有替換過程,這就意味着在尋找最低成本分裂點的時候每個輸入屬性只需被選取一次。

如下的代碼所示,函數 get_split() 實現了上述過程。它將一定數量的來自待評估數據的輸入特征和一個數據集作為參數,該數據集可以是實際訓練集里的樣本。輔助函數 test_split() 用於通過候選的分裂點來分割數據集,函數 gini_index() 用於評估通過創建的行組(groups of rows)來確定的某一分裂點的成本。

以上我們可以看出,特征列表是通過隨機選擇特征索引生成的。通過枚舉該特征列表,我們可將訓練集中的特定值評估為符合條件的分裂點。

 1 # Select the best split point for a dataset
 2 def get_split(dataset, n_features):
 3     class_values = list(set(row[-1] for row in dataset))
 4     b_index, b_value, b_score, b_groups = 999, 999, 999, None
 5     features = list()
 6     while len(features) < n_features:
 7         index = randrange(len(dataset[0])-1)
 8         if index not in features:
 9             features.append(index)
10     for index in features:
11         for row in dataset:
12             groups = test_split(index, row[index], dataset)
13             gini = gini_index(groups, class_values)
14             if gini < b_score:
15                 b_index, b_value, b_score, b_groups = index, row[index], gini, groups
16     return {'index':b_index, 'value':b_value, 'groups':b_groups}

至此,我們知道該如何改造一棵用於隨機森林算法的決策樹。我們可將之與裝袋算法結合運用到真實的數據集當中。

 

2. 關於聲納數據集的案例研究

在這個部分,我們將把隨機森林算法用於聲納數據集。本示例假定聲納數據集的 csv 格式副本已存在於當前工作目錄中,文件名為 sonar.all-data.csv。

首先加載該數據集,將字符串轉換成數字,並將輸出列從字符串轉換成數值 0 和 1. 這個過程是通過輔助函數 load_csv()、str_column_to_float() 和 str_column_to_int() 來分別實現的。

我們將通過 K 折交叉驗證(k-fold cross validatio)來預估得到的學習模型在未知數據上的表現。這就意味着我們將創建並評估 K 個模型並預估這 K 個模型的平均誤差。評估每一個模型是由分類准確度來體現的。輔助函數 cross_validation_split()、accuracy_metric() 和 evaluate_algorithm() 分別實現了上述功能。

裝袋算法將通過分類和回歸樹算法來滿足。輔助函數 test_split() 將數據集分割成不同的組;gini_index() 評估每個分裂點;前文提及的改進過的 get_split() 函數用來獲取分裂點;函數 to_terminal()、split() 和 build_tree() 用以創建單個決策樹;predict() 用於預測;subsample() 為訓練集建立子樣本集; bagging_predict() 對決策樹列表進行預測。

新命名的函數 random_forest() 首先從訓練集的子樣本中創建決策樹列表,然后對其進行預測。

正如我們開篇所說,隨機森林與決策樹關鍵的區別在於前者在建樹的方法上的小小的改變,這一點在運行函數 get_split() 得到了體現。

完整的代碼如下:

  1 # Random Forest Algorithm on Sonar Dataset
  2 from random import seed
  3 from random import randrange
  4 from csv import reader
  5 from math import sqrt
  6 
  7 # Load a CSV file
  8 def load_csv(filename):
  9    dataset = list()
 10    with open(filename, 'r') as file:
 11        csv_reader = reader(file)
 12        for row in csv_reader:
 13            if not row:
 14                continue
 15            dataset.append(row)
 16    return dataset
 17 
 18 # Convert string column to float
 19 def str_column_to_float(dataset, column):
 20    for row in dataset:
 21        row[column] = float(row[column].strip())
 22 
 23 # Convert string column to integer
 24 def str_column_to_int(dataset, column):
 25    class_values = [row[column] for row in dataset]
 26    unique = set(class_values)
 27    lookup = dict()
 28    for i, value in enumerate(unique):
 29        lookup[value] = i
 30    for row in dataset:
 31        row[column] = lookup[row[column]]
 32    return lookup
 33 
 34 # Split a dataset into k folds
 35 def cross_validation_split(dataset, n_folds):
 36    dataset_split = list()
 37    dataset_copy = list(dataset)
 38    fold_size = len(dataset) / n_folds
 39    for i in range(n_folds):
 40        fold = list()
 41        while len(fold) < fold_size:
 42            index = randrange(len(dataset_copy))
 43            fold.append(dataset_copy.pop(index))
 44        dataset_split.append(fold)
 45    return dataset_split
 46 
 47 # Calculate accuracy percentage
 48 def accuracy_metric(actual, predicted):
 49    correct = 0
 50    for i in range(len(actual)):
 51        if actual[i] == predicted[i]:
 52            correct += 1
 53    return correct / float(len(actual)) * 100.0
 54 
 55 # Evaluate an algorithm using a cross validation split
 56 def evaluate_algorithm(dataset, algorithm, n_folds, *args):
 57    folds = cross_validation_split(dataset, n_folds)
 58    scores = list()
 59    for fold in folds:
 60        train_set = list(folds)
 61        train_set.remove(fold)
 62        train_set = sum(train_set, [])
 63        test_set = list()
 64        for row in fold:
 65            row_copy = list(row)
 66            test_set.append(row_copy)
 67            row_copy[-1] = None
 68        predicted = algorithm(train_set, test_set, *args)
 69        actual = [row[-1] for row in fold]
 70        accuracy = accuracy_metric(actual, predicted)
 71        scores.append(accuracy)
 72    return scores
 73 
 74 # Split a dataset based on an attribute and an attribute value
 75 def test_split(index, value, dataset):
 76    left, right = list(), list()
 77    for row in dataset:
 78        if row[index] < value:
 79            left.append(row)
 80        else:
 81            right.append(row)
 82    return left, right
 83 
 84 # Calculate the Gini index for a split dataset
 85 def gini_index(groups, class_values):
 86    gini = 0.0
 87    for class_value in class_values:
 88        for group in groups:
 89            size = len(group)
 90            if size == 0:
 91                continue
 92            proportion = [row[-1] for row in group].count(class_value) / float(size)
 93            gini += (proportion * (1.0 - proportion))
 94    return gini
 95 
 96 # Select the best split point for a dataset
 97 def get_split(dataset, n_features):
 98    class_values = list(set(row[-1] for row in dataset))
 99    b_index, b_value, b_score, b_groups = 999, 999, 999, None
100    features = list()
101    while len(features) < n_features:
102        index = randrange(len(dataset[0])-1)
103        if index not in features:
104            features.append(index)
105    for index in features:
106        for row in dataset:
107            groups = test_split(index, row[index], dataset)
108            gini = gini_index(groups, class_values)
109            if gini < b_score:
110                b_index, b_value, b_score, b_groups = index, row[index], gini, groups
111    return {'index':b_index, 'value':b_value, 'groups':b_groups}
112 
113 # Create a terminal node value
114 def to_terminal(group):
115    outcomes = [row[-1] for row in group]
116    return max(set(outcomes), key=outcomes.count)
117 
118 # Create child splits for a node or make terminal
119 def split(node, max_depth, min_size, n_features, depth):
120    left, right = node['groups']
121    del(node['groups'])
122    # check for a no split
123    if not left or not right:
124        node['left'] = node['right'] = to_terminal(left + right)
125        return
126    # check for max depth
127    if depth >= max_depth:
128        node['left'], node['right'] = to_terminal(left), to_terminal(right)
129        return
130    # process left child
131    if len(left) <= min_size:
132        node['left'] = to_terminal(left)
133    else:
134        node['left'] = get_split(left, n_features)
135        split(node['left'], max_depth, min_size, n_features, depth+1)
136    # process right child
137    if len(right) <= min_size:
138        node['right'] = to_terminal(right)
139    else:
140        node['right'] = get_split(right, n_features)
141        split(node['right'], max_depth, min_size, n_features, depth+1)
142 
143 # Build a decision tree
144 def build_tree(train, max_depth, min_size, n_features):
145    root = get_split(dataset, n_features)
146    split(root, max_depth, min_size, n_features, 1)
147    return root
148 
149 # Make a prediction with a decision tree
150 def predict(node, row):
151    if row[node['index']] < node['value']:
152        if isinstance(node['left'], dict):
153            return predict(node['left'], row)
154        else:
155            return node['left']
156    else:
157        if isinstance(node['right'], dict):
158            return predict(node['right'], row)
159        else:
160            return node['right']
161 
162 # Create a random subsample from the dataset with replacement
163 def subsample(dataset, ratio):
164    sample = list()
165    n_sample = round(len(dataset) * ratio)
166    while len(sample) < n_sample:
167        index = randrange(len(dataset))
168        sample.append(dataset[index])
169    return sample
170 
171 # Make a prediction with a list of bagged trees
172 def bagging_predict(trees, row):
173    predictions = [predict(tree, row) for tree in trees]
174    return max(set(predictions), key=predictions.count)
175 
176 # Random Forest Algorithm
177 def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
178    trees = list()
179    for i in range(n_trees):
180        sample = subsample(train, sample_size)
181        tree = build_tree(sample, max_depth, min_size, n_features)
182        trees.append(tree)
183    predictions = [bagging_predict(trees, row) for row in test]
184    return(predictions)
185 
186 # Test the random forest algorithm
187 seed(1)
188 # load and prepare data
189 filename = 'sonar.all-data.csv'
190 dataset = load_csv(filename)
191 # convert string attributes to integers
192 for i in range(0, len(dataset[0])-1):
193    str_column_to_float(dataset, i)
194 # convert class column to integers
195 str_column_to_int(dataset, len(dataset[0])-1)
196 # evaluate algorithm
197 n_folds = 5
198 max_depth = 10
199 min_size = 1
200 sample_size = 1.0
201 n_features = int(sqrt(len(dataset[0])-1))
202 for n_trees in [1, 5, 10]:
203    scores = evaluate_algorithm(dataset, random_forest, n_folds, max_depth, min_size, sample_size, n_trees, n_features)
204    print('Trees: %d' % n_trees)
205    print('Scores: %s' % scores)
206        print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))

這里對第 197 行之后對各項參數的賦值做一個說明。

將 K 賦值為 5 用於交叉驗證,得到每個子樣本為 208/5 = 41.6,即超過 40 條聲納返回記錄會用於每次迭代時的評估。

每棵樹的最大深度設置為 10,每個節點的最小訓練行數為 1. 創建訓練集樣本的大小與原始數據集相同,這也是隨機森林算法的默認預期值。

我們把在每個分裂點需要考慮的特征數設置為總的特征數目的平方根,即 sqrt(60)=7.74,取整為 7。

將含有三組不同數量的樹同時進行評估,以表明添加更多的樹可以使該算法實現的功能更多。

 

最后,運行這個示例代碼將會 print 出每組樹的相應分值以及每種結構的平均分值。如下所示:

Trees: 1
Scores: [68.29268292682927, 75.60975609756098, 70.73170731707317, 63.41463414634146, 65.85365853658537]
Mean Accuracy: 68.780%
 
Trees: 5
Scores: [68.29268292682927, 68.29268292682927, 78.04878048780488, 65.85365853658537, 68.29268292682927]
Mean Accuracy: 69.756%
 
Trees: 10
Scores: [68.29268292682927, 78.04878048780488, 75.60975609756098, 70.73170731707317, 70.73170731707317]
Mean Accuracy: 72.683%

 

擴展

本節會列出一些與本次教程相關的擴展內容。大家或許有興趣一探究竟。

  • 算法調校(Algorithm Tuning)。本文所用的配置參數或有未被修正的錯誤以及有待商榷之處。用更大規模的樹,不同的特征數量甚至不同的樹的結構都可以改進試驗結果。

  • 更多問題。該方法同樣適用於其他的分類問題,甚至是用新的成本計算函數以及新的組合樹的預期值的方法使其適用於回歸算法。

回顧總結

通過本次教程的探討,你知道了隨機森林算法是如何實現的,特別是:
隨機森林與裝袋決策樹的區別。
如何用決策樹生成隨機森林算法。
如何將隨機森林算法應用於解決實際操作中的預測模型問題。

--------------------------

機器學習算法之隨機森林(Random Forest)
http://backnode.github.io/pages/2015/04/23/random-forest.html

--------------------

ps:本人和朋友正在研究隨機森林算法 在彩票預測中的應用 ,大家有興趣可以關注對應公眾號討論下

------------------------------

 本人微信公眾帳號: 心禪道(xinchandao)

 

本人微信公眾帳號:雙色球預測合買(ssqyuce)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM