用Python實現(xiàn)隨機森林算法的示例
擁有高方差使得決策樹(secision tress)在處理特定訓(xùn)練數(shù)據(jù)集時其結(jié)果顯得相對脆弱。bagging(bootstrap aggregating 的縮寫)算法從訓(xùn)練數(shù)據(jù)的樣本中建立復(fù)合模型,可以有效降低決策樹的方差,但樹與樹之間有高度關(guān)聯(lián)(并不是理想的樹的狀態(tài))。
隨機森林算法(Random forest algorithm)是對 bagging 算法的擴展。除了仍然根據(jù)從訓(xùn)練數(shù)據(jù)樣本建立復(fù)合模型之外,隨機森林對用做構(gòu)建樹(tree)的數(shù)據(jù)特征做了一定限制,使得生成的決策樹之間沒有關(guān)聯(lián),從而提升算法效果。
本教程將實現(xiàn)如何用 Python 實現(xiàn)隨機森林算法。
- bagged decision trees 與隨機森林算法的差異;
- 如何構(gòu)建含更多方差的裝袋決策樹;
- 如何將隨機森林算法運用于預(yù)測模型相關(guān)的問題。
算法描述
這個章節(jié)將對隨機森林算法本身以及本教程的算法試驗所用的聲納數(shù)據(jù)集(Sonar dataset)做一個簡要介紹。
隨機森林算法
決策樹運行的每一步都涉及到對數(shù)據(jù)集中的最優(yōu)分裂點(best split point)進行貪婪選擇(greedy selection)。
這個機制使得決策樹在沒有被剪枝的情況下易產(chǎn)生較高的方差。整合通過提取訓(xùn)練數(shù)據(jù)庫中不同樣本(某一問題的不同表現(xiàn)形式)構(gòu)建的復(fù)合樹及其生成的預(yù)測值能夠穩(wěn)定并降低這樣的高方差。這種方法被稱作引導(dǎo)聚集算法(bootstrap aggregating),其簡稱 bagging 正好是裝進口袋,袋子的意思,所以被稱為「裝袋算法」。該算法的局限在于,由于生成每一棵樹的貪婪算法是相同的,那么有可能造成每棵樹選取的分裂點(split point)相同或者極其相似,最終導(dǎo)致不同樹之間的趨同(樹與樹相關(guān)聯(lián))。相應(yīng)地,反過來說,這也使得其會產(chǎn)生相似的預(yù)測值,降低原本要求的方差。
我們可以采用限制特征的方法來創(chuàng)建不一樣的決策樹,使貪婪算法能夠在建樹的同時評估每一個分裂點。這就是隨機森林算法(Random Forest algorithm)。
與裝袋算法一樣,隨機森林算法從訓(xùn)練集里擷取復(fù)合樣本并訓(xùn)練。其不同之處在于,數(shù)據(jù)在每個分裂點處完全分裂并添加到相應(yīng)的那棵決策樹當(dāng)中,且可以只考慮用于存儲屬性的某一固定子集。
對于分類問題,也就是本教程中我們將要探討的問題,其被考慮用于分裂的屬性數(shù)量被限定為小于輸入特征的數(shù)量之平方根。代碼如下:
num_features_for_split = sqrt(total_input_features)
這個小更改會讓生成的決策樹各不相同(沒有關(guān)聯(lián)),從而使得到的預(yù)測值更加多樣化。而多樣的預(yù)測值組合往往會比一棵單一的決策樹或者單一的裝袋算法有更優(yōu)的表現(xiàn)。
聲納數(shù)據(jù)集(Sonar dataset)
我們將在本教程里使用聲納數(shù)據(jù)集作為輸入數(shù)據(jù)。這是一個描述聲納反射到不同物體表面后返回的不同數(shù)值的數(shù)據(jù)集。60 個輸入變量表示聲納從不同角度返回的強度。這是一個二元分類問題(binary classification problem),要求模型能夠區(qū)分出巖石和金屬柱體的不同材質(zhì)和形狀,總共有 208 個觀測樣本。
該數(shù)據(jù)集非常易于理解——每個變量都互有連續(xù)性且都在 0 到 1 的標(biāo)準(zhǔn)范圍之間,便于數(shù)據(jù)處理。作為輸出變量,字符串'M'表示金屬礦物質(zhì),'R'表示巖石。二者需分別轉(zhuǎn)換成整數(shù) 1 和 0。
通過預(yù)測數(shù)據(jù)集(M 或者金屬礦物質(zhì))中擁有最多觀測值的類,零規(guī)則算法(Zero Rule Algorithm)可實現(xiàn) 53% 的精確度。
更多有關(guān)該數(shù)據(jù)集的內(nèi)容可參見 UCI Machine Learning repository:https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+(Sonar,+Mines+vs.+Rocks)
免費下載該數(shù)據(jù)集,將其命名為 sonar.all-data.csv,并存儲到需要被操作的工作目錄當(dāng)中。
教程
此次教程分為兩個步驟。
1. 分裂次數(shù)的計算。
2. 聲納數(shù)據(jù)集案例研究
這些步驟能讓你了解為你自己的預(yù)測建模問題實現(xiàn)和應(yīng)用隨機森林算法的基礎(chǔ)
1. 分裂次數(shù)的計算
在決策樹中,我們通過找到一些特定屬性和屬性的值來確定分裂點,這類特定屬性需表現(xiàn)為其所需的成本是最低的。
分類問題的成本函數(shù)(cost function)通常是基尼指數(shù)(Gini index),即計算由分裂點產(chǎn)生的數(shù)據(jù)組的純度(purity)。對于這樣二元分類的分類問題來說,指數(shù)為 0 表示絕對純度,說明類值被完美地分為兩組。
從一棵決策樹中找到最佳分裂點需要在訓(xùn)練數(shù)據(jù)集中對每個輸入變量的值做成本評估。
在裝袋算法和隨機森林中,這個過程是在訓(xùn)練集的樣本上執(zhí)行并替換(放回)的。因為隨機森林對輸入的數(shù)據(jù)要進行行和列的采樣。對于行采樣,采用有放回的方式,也就是說同一行也許會在樣本中被選取和放入不止一次。
我們可以考慮創(chuàng)建一個可以自行輸入屬性的樣本,而不是枚舉所有輸入屬性的值以期找到獲取成本最低的分裂點,從而對這個過程進行優(yōu)化。
該輸入屬性樣本可隨機選取且沒有替換過程,這就意味著在尋找最低成本分裂點的時候每個輸入屬性只需被選取一次。
如下的代碼所示,函數(shù) get_split() 實現(xiàn)了上述過程。它將一定數(shù)量的來自待評估數(shù)據(jù)的輸入特征和一個數(shù)據(jù)集作為參數(shù),該數(shù)據(jù)集可以是實際訓(xùn)練集里的樣本。輔助函數(shù) test_split() 用于通過候選的分裂點來分割數(shù)據(jù)集,函數(shù) gini_index() 用于評估通過創(chuàng)建的行組(groups of rows)來確定的某一分裂點的成本。
以上我們可以看出,特征列表是通過隨機選擇特征索引生成的。通過枚舉該特征列表,我們可將訓(xù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}
至此,我們知道該如何改造一棵用于隨機森林算法的決策樹。我們可將之與裝袋算法結(jié)合運用到真實的數(shù)據(jù)集當(dāng)中。
2. 關(guān)于聲納數(shù)據(jù)集的案例研究
在這個部分,我們將把隨機森林算法用于聲納數(shù)據(jù)集。本示例假定聲納數(shù)據(jù)集的 csv 格式副本已存在于當(dāng)前工作目錄中,文件名為 sonar.all-data.csv。
首先加載該數(shù)據(jù)集,將字符串轉(zhuǎn)換成數(shù)字,并將輸出列從字符串轉(zhuǎn)換成數(shù)值 0 和 1. 這個過程是通過輔助函數(shù) load_csv()、str_column_to_float() 和 str_column_to_int() 來分別實現(xiàn)的。
我們將通過 K 折交叉驗證(k-fold cross validatio)來預(yù)估得到的學(xué)習(xí)模型在未知數(shù)據(jù)上的表現(xiàn)。這就意味著我們將創(chuàng)建并評估 K 個模型并預(yù)估這 K 個模型的平均誤差。評估每一個模型是由分類準(zhǔn)確度來體現(xiàn)的。輔助函數(shù) cross_validation_split()、accuracy_metric() 和 evaluate_algorithm() 分別實現(xiàn)了上述功能。
裝袋算法將通過分類和回歸樹算法來滿足。輔助函數(shù) test_split() 將數(shù)據(jù)集分割成不同的組;gini_index() 評估每個分裂點;前文提及的改進過的 get_split() 函數(shù)用來獲取分裂點;函數(shù) to_terminal()、split() 和 build_tree() 用以創(chuàng)建單個決策樹;predict() 用于預(yù)測;subsample() 為訓(xùn)練集建立子樣本集; bagging_predict() 對決策樹列表進行預(yù)測。
新命名的函數(shù) random_forest() 首先從訓(xùn)練集的子樣本中創(chuàng)建決策樹列表,然后對其進行預(yù)測。
正如我們開篇所說,隨機森林與決策樹關(guān)鍵的區(qū)別在于前者在建樹的方法上的小小的改變,這一點在運行函數(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))))
這里對第 197 行之后對各項參數(shù)的賦值做一個說明。
將 K 賦值為 5 用于交叉驗證,得到每個子樣本為 208/5 = 41.6,即超過 40 條聲納返回記錄會用于每次迭代時的評估。
每棵樹的最大深度設(shè)置為 10,每個節(jié)點的最小訓(xùn)練行數(shù)為 1. 創(chuàng)建訓(xùn)練集樣本的大小與原始數(shù)據(jù)集相同,這也是隨機森林算法的默認(rèn)預(yù)期值。
我們把在每個分裂點需要考慮的特征數(shù)設(shè)置為總的特征數(shù)目的平方根,即 sqrt(60)=7.74,取整為 7。
將含有三組不同數(shù)量的樹同時進行評估,以表明添加更多的樹可以使該算法實現(xiàn)的功能更多。
最后,運行這個示例代碼將會 print 出每組樹的相應(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%
擴展
本節(jié)會列出一些與本次教程相關(guān)的擴展內(nèi)容。大家或許有興趣一探究竟。
- 算法調(diào)校(Algorithm Tuning)。本文所用的配置參數(shù)或有未被修正的錯誤以及有待商榷之處。用更大規(guī)模的樹,不同的特征數(shù)量甚至不同的樹的結(jié)構(gòu)都可以改進試驗結(jié)果。
- 更多問題。該方法同樣適用于其他的分類問題,甚至是用新的成本計算函數(shù)以及新的組合樹的預(yù)期值的方法使其適用于回歸算法。
回顧總結(jié)
通過本次教程的探討,你知道了隨機森林算法是如何實現(xiàn)的,特別是:
隨機森林與裝袋決策樹的區(qū)別。
如何用決策樹生成隨機森林算法。
如何將隨機森林算法應(yīng)用于解決實際操作中的預(yù)測模型問題。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python?for循環(huán)詳細(xì)講解(附代碼實例)
這篇文章主要給大家介紹了關(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的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Python采集天天基金數(shù)據(jù)掌握最新基金動向
這篇文章主要介紹了Python采集天天基金數(shù)據(jù)掌握最新基金動向,本次案例實現(xiàn)流程為發(fā)送請求、獲取數(shù)據(jù)、解析數(shù)據(jù)、多頁爬取、保存數(shù)據(jù),接下來來看看具體的操作過程吧2022-01-01

