用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)

 

posted @ 2017-07-05 15:02  大自然的流风  阅读(25955)  评论(2编辑  收藏  举报