用Python實(shí)現(xiàn)隨機(jī)森林算法的示例
擁有高方差使得決策樹(shù)(secision tress)在處理特定訓(xùn)練數(shù)據(jù)集時(shí)其結(jié)果顯得相對(duì)脆弱。bagging(bootstrap aggregating 的縮寫(xiě))算法從訓(xùn)練數(shù)據(jù)的樣本中建立復(fù)合模型,可以有效降低決策樹(shù)的方差,但樹(shù)與樹(shù)之間有高度關(guān)聯(lián)(并不是理想的樹(shù)的狀態(tài))。
隨機(jī)森林算法(Random forest algorithm)是對(duì) bagging 算法的擴(kuò)展。除了仍然根據(jù)從訓(xùn)練數(shù)據(jù)樣本建立復(fù)合模型之外,隨機(jī)森林對(duì)用做構(gòu)建樹(shù)(tree)的數(shù)據(jù)特征做了一定限制,使得生成的決策樹(shù)之間沒(méi)有關(guān)聯(lián),從而提升算法效果。
本教程將實(shí)現(xiàn)如何用 Python 實(shí)現(xiàn)隨機(jī)森林算法。
- bagged decision trees 與隨機(jī)森林算法的差異;
- 如何構(gòu)建含更多方差的裝袋決策樹(shù);
- 如何將隨機(jī)森林算法運(yùn)用于預(yù)測(cè)模型相關(guān)的問(wèn)題。
算法描述
這個(gè)章節(jié)將對(duì)隨機(jī)森林算法本身以及本教程的算法試驗(yàn)所用的聲納數(shù)據(jù)集(Sonar dataset)做一個(gè)簡(jiǎn)要介紹。
隨機(jī)森林算法
決策樹(shù)運(yùn)行的每一步都涉及到對(duì)數(shù)據(jù)集中的最優(yōu)分裂點(diǎn)(best split point)進(jìn)行貪婪選擇(greedy selection)。
這個(gè)機(jī)制使得決策樹(shù)在沒(méi)有被剪枝的情況下易產(chǎn)生較高的方差。整合通過(guò)提取訓(xùn)練數(shù)據(jù)庫(kù)中不同樣本(某一問(wèn)題的不同表現(xiàn)形式)構(gòu)建的復(fù)合樹(shù)及其生成的預(yù)測(cè)值能夠穩(wěn)定并降低這樣的高方差。這種方法被稱作引導(dǎo)聚集算法(bootstrap aggregating),其簡(jiǎn)稱 bagging 正好是裝進(jìn)口袋,袋子的意思,所以被稱為「裝袋算法」。該算法的局限在于,由于生成每一棵樹(shù)的貪婪算法是相同的,那么有可能造成每棵樹(shù)選取的分裂點(diǎn)(split point)相同或者極其相似,最終導(dǎo)致不同樹(shù)之間的趨同(樹(shù)與樹(shù)相關(guān)聯(lián))。相應(yīng)地,反過(guò)來(lái)說(shuō),這也使得其會(huì)產(chǎn)生相似的預(yù)測(cè)值,降低原本要求的方差。
我們可以采用限制特征的方法來(lái)創(chuàng)建不一樣的決策樹(shù),使貪婪算法能夠在建樹(shù)的同時(shí)評(píng)估每一個(gè)分裂點(diǎn)。這就是隨機(jī)森林算法(Random Forest algorithm)。
與裝袋算法一樣,隨機(jī)森林算法從訓(xùn)練集里擷取復(fù)合樣本并訓(xùn)練。其不同之處在于,數(shù)據(jù)在每個(gè)分裂點(diǎn)處完全分裂并添加到相應(yīng)的那棵決策樹(shù)當(dāng)中,且可以只考慮用于存儲(chǔ)屬性的某一固定子集。
對(duì)于分類問(wèn)題,也就是本教程中我們將要探討的問(wèn)題,其被考慮用于分裂的屬性數(shù)量被限定為小于輸入特征的數(shù)量之平方根。代碼如下:
num_features_for_split = sqrt(total_input_features)
這個(gè)小更改會(huì)讓生成的決策樹(shù)各不相同(沒(méi)有關(guān)聯(lián)),從而使得到的預(yù)測(cè)值更加多樣化。而多樣的預(yù)測(cè)值組合往往會(huì)比一棵單一的決策樹(shù)或者單一的裝袋算法有更優(yōu)的表現(xiàn)。
聲納數(shù)據(jù)集(Sonar dataset)
我們將在本教程里使用聲納數(shù)據(jù)集作為輸入數(shù)據(jù)。這是一個(gè)描述聲納反射到不同物體表面后返回的不同數(shù)值的數(shù)據(jù)集。60 個(gè)輸入變量表示聲納從不同角度返回的強(qiáng)度。這是一個(gè)二元分類問(wèn)題(binary classification problem),要求模型能夠區(qū)分出巖石和金屬柱體的不同材質(zhì)和形狀,總共有 208 個(gè)觀測(cè)樣本。
該數(shù)據(jù)集非常易于理解——每個(gè)變量都互有連續(xù)性且都在 0 到 1 的標(biāo)準(zhǔn)范圍之間,便于數(shù)據(jù)處理。作為輸出變量,字符串'M'表示金屬礦物質(zhì),'R'表示巖石。二者需分別轉(zhuǎn)換成整數(shù) 1 和 0。
通過(guò)預(yù)測(cè)數(shù)據(jù)集(M 或者金屬礦物質(zhì))中擁有最多觀測(cè)值的類,零規(guī)則算法(Zero Rule Algorithm)可實(shí)現(xiàn) 53% 的精確度。
更多有關(guān)該數(shù)據(jù)集的內(nèi)容可參見(jiàn) UCI Machine Learning repository:https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+(Sonar,+Mines+vs.+Rocks)
免費(fèi)下載該數(shù)據(jù)集,將其命名為 sonar.all-data.csv,并存儲(chǔ)到需要被操作的工作目錄當(dāng)中。
教程
此次教程分為兩個(gè)步驟。
1. 分裂次數(shù)的計(jì)算。
2. 聲納數(shù)據(jù)集案例研究
這些步驟能讓你了解為你自己的預(yù)測(cè)建模問(wèn)題實(shí)現(xiàn)和應(yīng)用隨機(jī)森林算法的基礎(chǔ)
1. 分裂次數(shù)的計(jì)算
在決策樹(shù)中,我們通過(guò)找到一些特定屬性和屬性的值來(lái)確定分裂點(diǎn),這類特定屬性需表現(xiàn)為其所需的成本是最低的。
分類問(wèn)題的成本函數(shù)(cost function)通常是基尼指數(shù)(Gini index),即計(jì)算由分裂點(diǎn)產(chǎn)生的數(shù)據(jù)組的純度(purity)。對(duì)于這樣二元分類的分類問(wèn)題來(lái)說(shuō),指數(shù)為 0 表示絕對(duì)純度,說(shuō)明類值被完美地分為兩組。
從一棵決策樹(shù)中找到最佳分裂點(diǎn)需要在訓(xùn)練數(shù)據(jù)集中對(duì)每個(gè)輸入變量的值做成本評(píng)估。
在裝袋算法和隨機(jī)森林中,這個(gè)過(guò)程是在訓(xùn)練集的樣本上執(zhí)行并替換(放回)的。因?yàn)殡S機(jī)森林對(duì)輸入的數(shù)據(jù)要進(jìn)行行和列的采樣。對(duì)于行采樣,采用有放回的方式,也就是說(shuō)同一行也許會(huì)在樣本中被選取和放入不止一次。
我們可以考慮創(chuàng)建一個(gè)可以自行輸入屬性的樣本,而不是枚舉所有輸入屬性的值以期找到獲取成本最低的分裂點(diǎn),從而對(duì)這個(gè)過(guò)程進(jìn)行優(yōu)化。
該輸入屬性樣本可隨機(jī)選取且沒(méi)有替換過(guò)程,這就意味著在尋找最低成本分裂點(diǎn)的時(shí)候每個(gè)輸入屬性只需被選取一次。
如下的代碼所示,函數(shù) get_split() 實(shí)現(xiàn)了上述過(guò)程。它將一定數(shù)量的來(lái)自待評(píng)估數(shù)據(jù)的輸入特征和一個(gè)數(shù)據(jù)集作為參數(shù),該數(shù)據(jù)集可以是實(shí)際訓(xùn)練集里的樣本。輔助函數(shù) test_split() 用于通過(guò)候選的分裂點(diǎn)來(lái)分割數(shù)據(jù)集,函數(shù) gini_index() 用于評(píng)估通過(guò)創(chuàng)建的行組(groups of rows)來(lái)確定的某一分裂點(diǎn)的成本。
以上我們可以看出,特征列表是通過(guò)隨機(jī)選擇特征索引生成的。通過(guò)枚舉該特征列表,我們可將訓(xùn)練集中的特定值評(píng)估為符合條件的分裂點(diǎn)。
# Select the best split point for a dataset
def get_split(dataset, n_features):
class_values = list(set(row[-1] for row in dataset))
b_index, b_value, b_score, b_groups = 999, 999, 999, None
features = list()
while len(features) < n_features:
index = randrange(len(dataset[0])-1)
if index not in features:
features.append(index)
for index in features:
for row in dataset:
groups = test_split(index, row[index], dataset)
gini = gini_index(groups, class_values)
if gini < b_score:
b_index, b_value, b_score, b_groups = index, row[index], gini, groups
return {'index':b_index, 'value':b_value, 'groups':b_groups}
至此,我們知道該如何改造一棵用于隨機(jī)森林算法的決策樹(shù)。我們可將之與裝袋算法結(jié)合運(yùn)用到真實(shí)的數(shù)據(jù)集當(dāng)中。
2. 關(guān)于聲納數(shù)據(jù)集的案例研究
在這個(gè)部分,我們將把隨機(jī)森林算法用于聲納數(shù)據(jù)集。本示例假定聲納數(shù)據(jù)集的 csv 格式副本已存在于當(dāng)前工作目錄中,文件名為 sonar.all-data.csv。
首先加載該數(shù)據(jù)集,將字符串轉(zhuǎn)換成數(shù)字,并將輸出列從字符串轉(zhuǎn)換成數(shù)值 0 和 1. 這個(gè)過(guò)程是通過(guò)輔助函數(shù) load_csv()、str_column_to_float() 和 str_column_to_int() 來(lái)分別實(shí)現(xiàn)的。
我們將通過(guò) K 折交叉驗(yàn)證(k-fold cross validatio)來(lái)預(yù)估得到的學(xué)習(xí)模型在未知數(shù)據(jù)上的表現(xiàn)。這就意味著我們將創(chuàng)建并評(píng)估 K 個(gè)模型并預(yù)估這 K 個(gè)模型的平均誤差。評(píng)估每一個(gè)模型是由分類準(zhǔn)確度來(lái)體現(xiàn)的。輔助函數(shù) cross_validation_split()、accuracy_metric() 和 evaluate_algorithm() 分別實(shí)現(xiàn)了上述功能。
裝袋算法將通過(guò)分類和回歸樹(shù)算法來(lái)滿足。輔助函數(shù) test_split() 將數(shù)據(jù)集分割成不同的組;gini_index() 評(píng)估每個(gè)分裂點(diǎn);前文提及的改進(jìn)過(guò)的 get_split() 函數(shù)用來(lái)獲取分裂點(diǎn);函數(shù) to_terminal()、split() 和 build_tree() 用以創(chuàng)建單個(gè)決策樹(shù);predict() 用于預(yù)測(cè);subsample() 為訓(xùn)練集建立子樣本集; bagging_predict() 對(duì)決策樹(shù)列表進(jìn)行預(yù)測(cè)。
新命名的函數(shù) random_forest() 首先從訓(xùn)練集的子樣本中創(chuàng)建決策樹(shù)列表,然后對(duì)其進(jìn)行預(yù)測(cè)。
正如我們開(kāi)篇所說(shuō),隨機(jī)森林與決策樹(shù)關(guān)鍵的區(qū)別在于前者在建樹(shù)的方法上的小小的改變,這一點(diǎn)在運(yùn)行函數(shù) get_split() 得到了體現(xiàn)。
完整的代碼如下:
# Random Forest Algorithm on Sonar Dataset
from random import seed
from random import randrange
from csv import reader
from math import sqrt
# Load a CSV file
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
dataset.append(row)
return dataset
# Convert string column to float
def str_column_to_float(dataset, column):
for row in dataset:
row[column] = float(row[column].strip())
# Convert string column to integer
def str_column_to_int(dataset, column):
class_values = [row[column] for row in dataset]
unique = set(class_values)
lookup = dict()
for i, value in enumerate(unique):
lookup[value] = i
for row in dataset:
row[column] = lookup[row[column]]
return lookup
# Split a dataset into k folds
def cross_validation_split(dataset, n_folds):
dataset_split = list()
dataset_copy = list(dataset)
fold_size = len(dataset) / n_folds
for i in range(n_folds):
fold = list()
while len(fold) < fold_size:
index = randrange(len(dataset_copy))
fold.append(dataset_copy.pop(index))
dataset_split.append(fold)
return dataset_split
# Calculate accuracy percentage
def accuracy_metric(actual, predicted):
correct = 0
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / float(len(actual)) * 100.0
# Evaluate an algorithm using a cross validation split
def evaluate_algorithm(dataset, algorithm, n_folds, *args):
folds = cross_validation_split(dataset, n_folds)
scores = list()
for fold in folds:
train_set =a list(folds)
train_set.remove(fold)
train_set = sum(train_set, [])
test_set = list()
for row in fold:
row_copy = list(row)
test_set.append(row_copy)
row_copy[-1] = None
predicted = algorithm(train_set, test_set, *args)
actual = [row[-1] for row in fold]
accuracy = accuracy_metric(actual, predicted)
scores.append(accuracy)
return scores
# Split a dataset based on an attribute and an attribute value
def test_split(index, value, dataset):
left, right = list(), list()
for row in dataset:
if row[index] < value:
left.append(row)
else:
right.append(row)
return left, right
# Calculate the Gini index for a split dataset
def gini_index(groups, class_values):
gini = 0.0
for class_value in class_values:
for group in groups:
size = len(group)
if size == 0:
continue
proportion = [row[-1] for row in group].count(class_value) / float(size)
gini += (proportion * (1.0 - proportion))
return gini
# Select the best split point for a dataset
def get_split(dataset, n_features):
class_values = list(set(row[-1] for row in dataset))
b_index, b_value, b_score, b_groups = 999, 999, 999, None
features = list()
while len(features) < n_features:
index = randrange(len(dataset[0])-1)
if index not in features:
features.append(index)
for index in features:
for row in dataset:
groups = test_split(index, row[index], dataset)
gini = gini_index(groups, class_values)
if gini < b_score:
b_index, b_value, b_score, b_groups = index, row[index], gini, groups
return {'index':b_index, 'value':b_value, 'groups':b_groups}
# Create a terminal node value
def to_terminal(group):
outcomes = [row[-1] for row in group]
return max(set(outcomes), key=outcomes.count)
# Create child splits for a node or make terminal
def split(node, max_depth, min_size, n_features, depth):
left, right = node['groups']
del(node['groups'])
# check for a no split
if not left or not right:
node['left'] = node['right'] = to_terminal(left + right)
return
# check for max depth
if depth >= max_depth:
node['left'], node['right'] = to_terminal(left), to_terminal(right)
return
# process left child
if len(left) <= min_size:
node['left'] = to_terminal(left)
else:
node['left'] = get_split(left, n_features)
split(node['left'], max_depth, min_size, n_features, depth+1)
# process right child
if len(right) <= min_size:
node['right'] = to_terminal(right)
else:
node['right'] = get_split(right, n_features)
split(node['right'], max_depth, min_size, n_features, depth+1)
# Build a decision tree
def build_tree(train, max_depth, min_size, n_features):
root = get_split(dataset, n_features)
split(root, max_depth, min_size, n_features, 1)
return root
# Make a prediction with a decision tree
def predict(node, row):
if row[node['index']] < node['value']:
if isinstance(node['left'], dict):
return predict(node['left'], row)
else:
return node['left']
else:
if isinstance(node['right'], dict):
return predict(node['right'], row)
else:
return node['right']
# Create a random subsample from the dataset with replacement
def subsample(dataset, ratio):
sample = list()
n_sample = round(len(dataset) * ratio)
while len(sample) < n_sample:
index = randrange(len(dataset))
sample.append(dataset[index])
return sample
# Make a prediction with a list of bagged trees
def bagging_predict(trees, row):
predictions = [predict(tree, row) for tree in trees]
return max(set(predictions), key=predictions.count)
# Random Forest Algorithm
def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
trees = list()
for i in range(n_trees):
sample = subsample(train, sample_size)
tree = build_tree(sample, max_depth, min_size, n_features)
trees.append(tree)
predictions = [bagging_predict(trees, row) for row in test]
return(predictions)
# Test the random forest algorithm
seed(1)
# load and prepare data
filename = 'sonar.all-data.csv'
dataset = load_csv(filename)
# convert string attributes to integers
for i in range(0, len(dataset[0])-1):
str_column_to_float(dataset, i)
# convert class column to integers
str_column_to_int(dataset, len(dataset[0])-1)
# evaluate algorithm
n_folds = 5
max_depth = 10
min_size = 1
sample_size = 1.0
n_features = int(sqrt(len(dataset[0])-1))
for n_trees in [1, 5, 10]:
scores = evaluate_algorithm(dataset, random_forest, n_folds, max_depth, min_size, sample_size, n_trees, n_features)
print('Trees: %d' % n_trees)
print('Scores: %s' % scores)
print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))
這里對(duì)第 197 行之后對(duì)各項(xiàng)參數(shù)的賦值做一個(gè)說(shuō)明。
將 K 賦值為 5 用于交叉驗(yàn)證,得到每個(gè)子樣本為 208/5 = 41.6,即超過(guò) 40 條聲納返回記錄會(huì)用于每次迭代時(shí)的評(píng)估。
每棵樹(shù)的最大深度設(shè)置為 10,每個(gè)節(jié)點(diǎn)的最小訓(xùn)練行數(shù)為 1. 創(chuàng)建訓(xùn)練集樣本的大小與原始數(shù)據(jù)集相同,這也是隨機(jī)森林算法的默認(rèn)預(yù)期值。
我們把在每個(gè)分裂點(diǎn)需要考慮的特征數(shù)設(shè)置為總的特征數(shù)目的平方根,即 sqrt(60)=7.74,取整為 7。
將含有三組不同數(shù)量的樹(shù)同時(shí)進(jìn)行評(píng)估,以表明添加更多的樹(shù)可以使該算法實(shí)現(xiàn)的功能更多。
最后,運(yùn)行這個(gè)示例代碼將會(huì) print 出每組樹(shù)的相應(yīng)分值以及每種結(jié)構(gòu)的平均分值。如下所示:
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%
擴(kuò)展
本節(jié)會(huì)列出一些與本次教程相關(guān)的擴(kuò)展內(nèi)容。大家或許有興趣一探究竟。
- 算法調(diào)校(Algorithm Tuning)。本文所用的配置參數(shù)或有未被修正的錯(cuò)誤以及有待商榷之處。用更大規(guī)模的樹(shù),不同的特征數(shù)量甚至不同的樹(shù)的結(jié)構(gòu)都可以改進(jìn)試驗(yàn)結(jié)果。
- 更多問(wèn)題。該方法同樣適用于其他的分類問(wèn)題,甚至是用新的成本計(jì)算函數(shù)以及新的組合樹(shù)的預(yù)期值的方法使其適用于回歸算法。
回顧總結(jié)
通過(guò)本次教程的探討,你知道了隨機(jī)森林算法是如何實(shí)現(xiàn)的,特別是:
隨機(jī)森林與裝袋決策樹(shù)的區(qū)別。
如何用決策樹(shù)生成隨機(jī)森林算法。
如何將隨機(jī)森林算法應(yīng)用于解決實(shí)際操作中的預(yù)測(cè)模型問(wèn)題。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python實(shí)現(xiàn)漢諾塔算法
- Python遞歸實(shí)現(xiàn)漢諾塔算法示例
- python實(shí)現(xiàn)漢諾塔遞歸算法經(jīng)典案例
- python實(shí)現(xiàn)漢諾塔方法匯總
- 使用python實(shí)現(xiàn)遞歸版漢諾塔示例(漢諾塔遞歸算法)
- python益智游戲計(jì)算漢諾塔問(wèn)題示例
- Python基于遞歸算法實(shí)現(xiàn)的漢諾塔與Fibonacci數(shù)列示例
- Python 連連看連接算法
- Python決策樹(shù)和隨機(jī)森林算法實(shí)例詳解
- python實(shí)現(xiàn)的漢諾塔算法示例
相關(guān)文章
Python?for循環(huán)詳細(xì)講解(附代碼實(shí)例)
這篇文章主要給大家介紹了關(guān)于Python?for循環(huán)詳細(xì)講解的相關(guān)資料,在Python中,for循環(huán)是一種常用的控制結(jié)構(gòu),用于遍歷序列(如列表、元組、字符串等)中的元素,需要的朋友可以參考下2024-03-03
Pandas查詢數(shù)據(jù)df.query的使用
本文主要介紹了Pandas查詢數(shù)據(jù)df.query的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Python采集天天基金數(shù)據(jù)掌握最新基金動(dòng)向
這篇文章主要介紹了Python采集天天基金數(shù)據(jù)掌握最新基金動(dòng)向,本次案例實(shí)現(xiàn)流程為發(fā)送請(qǐng)求、獲取數(shù)據(jù)、解析數(shù)據(jù)、多頁(yè)爬取、保存數(shù)據(jù),接下來(lái)來(lái)看看具體的操作過(guò)程吧2022-01-01
Python隨機(jī)生成數(shù)模塊random使用實(shí)例
這篇文章主要介紹了Python隨機(jī)生成數(shù)模塊random使用實(shí)例,本文直接給出示例代碼,需要的朋友可以參考下2015-04-04

