其實隨機森林就是由許多的決策樹組成。每一顆決策樹可能誤差較大,但是綜合在一起最後通過選舉的方式產生的結果將非常準確。
隨機森林不需要像決策樹一樣剪枝,理由很簡單。剪枝是爲了防止我們的算法over-fitting。在有n的樣本,m個屬性(特徵)的數據中,我們有放回隨機選擇n個樣本(可能重複),隨機選擇k個屬性(k小於m,一般情況下我們取k =sqrt(m-1)),我們也通過限制最大樹深度,分類結果中最小的樣本數量來做限制,從而防止了over-fitting(因爲加入了隨機性)。
在這裏我們用的是cart分類樹(其實是網上找找的代碼,,自己慢慢理解 哈哈)來實現決策樹。
步驟:
1.導入數據,並將除最後一列判斷結果外所有數據變爲float形式。
在這裏有個小技巧就是使用了map內置函數。在python2.7版本中使用map返回的是一個list
而在3.x版本中返回的是一個map對象,若想得到list,必須使用list(map()),下面代碼有寫。
2.得到交叉驗證數據集
3.計算正確率
4.根據特徵和特徵值來分數據集。
5.計算gini值
6.找出分類的最優特徵,和最優特徵的值。
也就是說通過計算gini指數,你可以得到最優特徵和用最優特徵的哪個值來進行分類。當我們測試時來了一個數據你若進行判斷肯定是先對比特徵,然後再對比測試數據的該特徵的值和最優特徵的值後再進行判斷。
7.選擇出現次數最多
8.子劃分。 在4中我們得到了group(group中包含了左子樹和右子樹),我們要對其再細分。
9.建樹。用6找出最優特徵index 和 row【index】,再用8來進行細劃分得到最終的樹。
10.用單科樹來預測
11.用整個森林來預測
12.構造樣本子集。就是又放回隨機抽取n個樣本
最後綜合 和評價。
好了,直接貼代碼吧。看完其實應該想到這個實現有個問題。我能想到的寫到最下面。
#-*- coding: utf-8 -*-
# Random Forest Algorithm on Sonar Dataset
from random import seed
from random import randrange
from csv import reader
from math import sqrt
from math import log
# Load a CSV file
def load_csv(filename): #導入csv文件
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): #將數據集的第column列轉換成float形式
for row in dataset:
row[column] = float(row[column].strip()) #strip()返回移除字符串頭尾指定的字符生成的新字符串。
# Convert string column to integer
def str_column_to_int(dataset, column): #將最後一列表示標籤的值轉換爲Int類型0,1,...
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分成n_flods份,每份包含len(dataset) / n_folds個值,每個值由dataset數據集的內容隨機產生,每個值被使用一次
dataset_split = list()
dataset_copy = list(dataset) #複製一份dataset,防止dataset的內容改變
fold_size = len(dataset) / n_folds
for i in range(n_folds):
fold = list() #每次循環fold清零,防止重複導入dataset_split
while len(fold) < fold_size: #這裏不能用if,if只是在第一次判斷時起作用,while執行循環,直到條件不成立
index = randrange(len(dataset_copy))
fold.append(dataset_copy.pop(index)) #將對應索引index的內容從dataset_copy中導出,並將該內容從dataset_copy中刪除。pop() 函數用於移除列表中的一個元素(默認最後一個元素),並且返回該元素的值。
dataset_split.append(fold)
return dataset_split #由dataset分割出的n_folds個數據構成的列表,爲了用於交叉驗證
# 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
# 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越小
gini = 0.0
for class_value in class_values: #class_values =[0,1]
for group in groups: #groups=(left,right)
size = len(group)
if size == 0:
continue
proportion = [row[-1] for row in group].count(class_value) / float(size)
gini += (proportion * (1.0 - proportion)) #個人理解:計算代價,分類越準確,則gini越小
return gini
# Select the best split point for a dataset #找出分割數據集的最優特徵,得到最優的特徵index,特徵值row[index],以及分割完的數據groups(left,right)
def get_split(dataset, n_features):
class_values = list(set(row[-1] for row in dataset)) #class_values =[0,1]
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) #往features添加n_features個特徵(n_feature等於特徵數的根號),特徵索引從dataset中隨機取
if index not in features:
features.append(index)
for index in features: #在n_features個特徵中選出最優的特徵索引,並沒有遍歷所有特徵,從而保證了每課決策樹的差異性
for row in dataset:
groups = test_split(index, row[index], dataset) #groups=(left,right);row[index]遍歷每一行index索引下的特徵值作爲分類值value,找出最優的分類特徵和特徵值
gini = gini_index(groups, class_values)
if gini < b_score:
b_index, b_value, b_score, b_groups = index, row[index], gini, groups #最後得到最優的分類特徵b_index,分類特徵值b_value,分類結果b_groups。b_value爲分錯的代價成本。
#print b_score
return {'index':b_index, 'value':b_value, 'groups':b_groups}
# Create a terminal node value #輸出group中出現次數較多的標籤
def to_terminal(group):
outcomes = [row[-1] for row in group] #max()函數中,當key參數不爲空時,就以key的函數對象爲判斷的標準;
return max(set(outcomes), key=outcomes.count) # 輸出group中出現次數較多的標籤
# Create child splits for a node or make terminal #創建子分割器,遞歸分類,直到分類結束
def split(node, max_depth, min_size, n_features, depth): #max_depth = 10,min_size = 1,n_features = int(sqrt(len(dataset[0])-1))
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: #max_depth=10表示遞歸十次,若分類還未結束,則選取數據中分類標籤較多的作爲結果,使分類提前結束,防止過擬合
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) #node['left']是一個字典,形式爲{'index':b_index, 'value':b_value, 'groups':b_groups},所以node是一個多層字典
split(node['left'], max_depth, min_size, n_features, depth+1) #遞歸,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)
root = get_split(train, 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): #isinstance是Python中的一個內建函數。是用來判斷一個對象是否是一個已知的類型。
return predict(node['left'], row)
else:
return node['left']
else:
if isinstance(node['right'], dict):
return predict(node['right'], row)
else:
return node['right']
# Make a prediction with a list of bagged trees
def bagging_predict(trees, row):
predictions = [predict(tree, row) for tree in trees] #使用多個決策樹trees對測試集test的第row行進行預測,再使用簡單投票法判斷出該行所屬分類
return max(set(predictions), key=predictions.count)
# Create a random subsample from the dataset with replacement
def subsample(dataset, ratio): #創建數據集的隨機子樣本
sample = list()
n_sample = round(len(dataset) * ratio) #round() 方法返回浮點數x的四捨五入值。
while len(sample) < n_sample:
index = randrange(len(dataset)) #有放回的隨機採樣,有一些樣本被重複採樣,從而在訓練集中多次出現,有的則從未在訓練集中出現,此則自助採樣法。從而保證每棵決策樹訓練集的差異性
sample.append(dataset[index])
return sample
# 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): #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)
# 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: #每次循環從folds從取出一個fold作爲測試集,其餘作爲訓練集,遍歷整個folds,實現交叉驗證
train_set = list(folds)
train_set.remove(fold)
train_set = sum(train_set, []) #將多個fold列表組合成一個train_set列表
test_set = list()
for row in fold: #fold表示從原始數據集dataset提取出來的測試集
row_copy = list(row)
row_copy[-1] = None
test_set.append(row_copy)
predicted = algorithm(train_set, test_set, *args)
actual = [row[-1] for row in fold]
accuracy = accuracy_metric(actual, predicted)
scores.append(accuracy)
return scores
# 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) ##將最後一列表示標籤的值轉換爲Int類型0,1(可以不用轉換,標籤可以爲str型)
# evaluate algorithm
n_folds = 5 #分成5份數據,進行交叉驗證
#max_depth = 10 #遞歸十次
max_depth = 20 #調參(自己修改) #決策樹深度不能太深,不然容易導致過擬合
min_size = 1
sample_size = 1.0
#n_features = int(sqrt(len(dataset[0])-1))
n_features =15 #調參(自己修改) #準確性與多樣性之間的權衡
for n_trees in [1,10,20]: #樹的數量的選擇並非越多越好,得自己調
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))))
雖然在隨機森林中我們需要隨機的選取特徵,但是隻選一次,之後每次從第一次選擇的特徵中再選。但是這個代碼卻沒有這麼做,他總是隨機重複選擇。這就牽扯到一個問題,已經被選過的特徵又被選擇一次,運行後發現這個代碼正確率並不高。
其次是在該算法中,總是完整的數據集,運行速度十分慢。當我們選完特徵後,如果只把我們選的特徵那些數據取出來是不是會更快呢,答案肯定的。
詳情請看下一篇。