图片来源:随机森林算法原理解析_华山拎壶冲的博客-CSDN博客_随机森林原理
图片来源:随机森林(Random Forest)算法原理_江户川柯壮的博客-CSDN博客_随机森林
Random Forest算法参数解释及调优_nobody~的博客-CSDN博客_随机森林参数调优
1.max_features:允许单个决策树使用特征的最大数量,Python为最大特征数提供了多个可选项:
2.n_estimators:在利用最大投票数或平均值来预测之前,你想要建立子树的数量。
3.min_sample_leaf:最小样本叶片大小。
1.n_jobs:这个参数告诉引擎有多少处理器是它可以使用。
2.random_state:此参数让结果容易复现。
数据集来源:
https://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/
import csv
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier # 决策树
from sklearn.ensemble import RandomForestClassifier # 随机森林
'''加载数据,一行行的存入列表'''
def loadCSV(filename):
dataSet = []
with open(filename, 'r') as file:
csvReader = csv.reader(file)
for line in csvReader:
dataSet.append(line)
return dataSet
dataSet = loadCSV('/Users/Downloads/sonar_all_data.csv')
'''处理数据,除了标签列,其他列都转换为float类型'''
def column_to_float(dataSet):
featLen = len(dataSet[0]) - 1
for data in dataSet:
for column in range(featLen):
data[column] = float(data[column].strip())
column_to_float(dataSet)
'''划分数据集7:3'''
X = []
Y = []
for i in dataSet:
x= i[:-1]
y = i[-1]
Y.append(y)
X.append(x)
X_train, X_test, y_train, y_test = train_test_split(X,Y, test_size=0.3)
'''计算准确率'''
def accuracy(predict_values, actual):
correct = 0
for i in range(len(actual)):
if actual[i] == predict_values[i]:
correct += 1
return correct / float(len(actual))
'''工具包预测结果'''
rf=RandomForestClassifier(random_state=0)# 随机森林
clf = DecisionTreeClassifier(random_state=0)# 单个决策树
rf = rf.fit(X_train,y_train)
clf = clf.fit(X_train,y_train)
score_rf =rf.score(X_test,y_test)
score_clf =clf.score(X_test,y_test)
print("随机森林:",score_rf)
print("决策树:",score_clf)
实验结果:
随机森林: 0.8412698412698413
决策树: 0.6349206349206349
画出随机森林和决策树在十组交叉验证下的效果对比
画出随机森林和决策树在十组交叉验证下的效果对比
rfc_l = []
clf_l = []
for i in range(10):
rfc = RandomForestClassifier(n_estimators=25)
rfc_s = cross_val_score(rfc,X,Y,cv=10).mean()
rfc_l.append(rfc_s)
clf = DecisionTreeClassifier()
clf_s = cross_val_score(clf,X,Y,cv=10).mean()
clf_l.append(clf_s)
plt.plot(range(1,11),rfc_l,label = "Random Forest")
plt.plot(range(1,11),clf_l,label = "Decision Tree")
plt.legend()
plt.show()
import csv
from random import seed
from random import randrange
from math import sqrt
'''决定输出标签'''
def decide_label(data):
output = [row[-1] for row in data]
# 简单投票法
return max(set(output), key=output.count)
'''子分割,不断地构建叶节点的过程'''
def sub_spilt(root, n_features, max_depth, min_size, depth):
left = root['left']
right = root['right']
del (root['left'])
del (root['right'])
if not left or not right:
root['left'] = root['right'] = decide_label(left + right)
return
if depth > max_depth:
root['left'] = decide_label(left)
root['right'] = decide_label(right)
return
if len(left) < min_size:
root['left'] = decide_label(left)
else:
root['left'] = get_best_spilt(left, n_features)
sub_spilt(root['left'], n_features, max_depth, min_size, depth + 1)
if len(right) < min_size:
root['right'] = decide_label(right)
else:
root['right'] = get_best_spilt(right, n_features)
sub_spilt(root['right'], n_features, max_depth, min_size, depth + 1)
'''计算分割代价'''
def spilt_loss(left, right, class_values):
loss = 0.0
for class_value in class_values:
left_size = len(left)
if left_size != 0: # 防止除数为零
# list.count(obj)返回元素在列表中出现的次数。
prop = [row[-1] for row in left].count(class_value) / float(left_size)
loss += (prop * (1.0 - prop))# GINI指数
right_size = len(right)
if right_size != 0:
prop = [row[-1] for row in right].count(class_value) / float(right_size)
loss += (prop * (1.0 - prop))
return loss
'''分割数据集,左右分支'''
def data_spilt(dataSet, index, value):
left = []
right = []
for row in dataSet:
if row[index] < value:
left.append(row)
else:
right.append(row)
return left, right
'''选取任意的n个特征,在这n个特征中,选取分割时的最优特征'''
def get_best_spilt(dataSet, n_features):
features = []
class_values = list(set(row[-1] for row in dataSet))
b_index, b_value, b_loss, b_left, b_right = 999, 999, 999, None, None
# 列采样
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:
left, right = data_spilt(dataSet, index, row[index])#以它为节点的,左右分支
loss = spilt_loss(left, right, class_values)# 计算分割代价
if loss < b_loss:#寻找最小分割代价
b_index, b_value, b_loss, b_left, b_right = index, row[index], loss, left, right
return {'index': b_index, 'value': b_value, 'left': b_left, 'right': b_right}
'''构造决策树'''
def build_tree(dataSet, n_features, max_depth, min_size):
root = get_best_spilt(dataSet, n_features)
sub_spilt(root, n_features, max_depth, min_size, 1)
return root
'''行采样,随机抽样选择N个样本'''
def get_subsample(dataSet, ratio):
subdataSet = []
lenSubdata = round(len(dataSet) * ratio)#四舍五入保留整数
while len(subdataSet) < lenSubdata:
index = randrange(len(dataSet))# 行采样,随机选择
subdataSet.append(dataSet[index])
return subdataSet
'''预测测试集结果'''
def predict(tree, row):
predictions = []
if row[tree['index']] < tree['value']:
if isinstance(tree['left'], dict):
return predict(tree['left'], row)
else:
return tree['left']
else:
if isinstance(tree['right'], dict):
return predict(tree['right'], row)
else:
return tree['right']
def bagging_predict(trees, row):
predictions = [predict(tree, row) for tree in trees]
return max(set(predictions), key=predictions.count)
'''创建随机森林'''
def random_forest(train, test, ratio, n_feature, max_depth, min_size, n_trees):
trees = []
for i in range(n_trees):
train = get_subsample(train, ratio)#从切割的训练集中选取子集
tree = build_tree(train, n_features, max_depth, min_size)#构建 一个决策树
# 随机森林
trees.append(tree)
predict_values = [bagging_predict(trees, row) for row in test]
return predict_values
'''将数据集随机分成n_folds块,方便交叉验证,其中一块是测试集,其他四块是训练集'''
def spiltDataSet(dataSet, n_folds):
fold_size = int(len(dataSet) / n_folds)
dataSet_copy = list(dataSet)
dataSet_spilt = []
for i in range(n_folds):
fold = []
while len(fold) < fold_size: # 这里不能用if,if只是在第一次判断时起作用,while执行循环,直到条件不成立
index = randrange(len(dataSet_copy))
fold.append(dataSet_copy.pop(index)) # pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
dataSet_spilt.append(fold)
return dataSet_spilt
'''加载数据,一行行的存入列表'''
def loadCSV(filename):
dataSet = []
with open(filename, 'r') as file:
csvReader = csv.reader(file)
for line in csvReader:
dataSet.append(line)
return dataSet
dataSet = loadCSV('/Users/Downloads/sonar_all_data.csv')
'''除了标签列,其他列都转换为float类型'''
def column_to_float(dataSet):
featLen = len(dataSet[0]) - 1
for data in dataSet:
for column in range(featLen):
data[column] = float(data[column].strip())
'''计算准确率'''
def accuracy(predict_values, actual):
correct = 0
for i in range(len(actual)):
if actual[i] == predict_values[i]:
correct += 1
return correct / float(len(actual))
n_folds = 5# 划分数据集数,用于后续交叉验证
n_features = 7# 选取特征数
n_trees = 20# 决策树数量
max_depth = 15
min_size = 1
ratio = 1.0
scores = []
folds = spiltDataSet(dataSet, n_folds)
# 该部分选取4个数据集作为训练集,1个数据集作为测试集,实现交叉验证
for fold in folds:
train_set = folds[:]
train_set.remove(fold)
train_set = sum(train_set, [])
test_set = []
for row in fold:
row_copy = list(row)
row_copy[-1] = None
test_set.append(row_copy)
actual = [row[-1] for row in fold]
predict_values = random_forest(train_set, test_set, ratio, n_features, max_depth, min_size, n_trees)
accur = accuracy(predict_values, actual)
scores.append(accur)
print ('Trees is %d' % n_trees)
print ('scores:%s' % scores)
print ('mean score:%s' % (sum(scores) / float(len(scores))))
输出:
Trees is 20
scores:[0.7804878048780488, 0.6341463414634146, 0.4878048780487805, 0.7560975609756098, 0.8048780487804879]
mean score:0.6926829268292682
学习笔记参考以下博客
随机森林原理详解 random forest 代码+参数讲解_统计分析分析的博客-CSDN博客_随机森林代码讲解事实上随机森林的基本单元决策树很早就被提出来了,只不过单个决策树效果不好。这个情况和神经网络差不多。到了2001年Breiman把分类树组合成随机森林(Breiman 2001a),即在变量(列)的使用和数据(行)的使用上进行随机化,生成很多分类树,再汇总分类树的结果。在运算没有增加的情况下,精度提高了不少。进入正题随机森林由两个部分组成随机 和 森林森林简单来说就是很多颗树,而这个树...https://blog.csdn.net/qq_36303521/article/details/88045247?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-2.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-2.pc_relevant_aa&utm_relevant_index=5python实现随机森林_随心1993的博客-CSDN博客_python 随机森林定义:随机森林指的是利用多棵决策树对样本进行训练并预测的一种分类器。可回归可分类。 所以随机森林是基于多颗决策树的一种集成学习算法,常见的决策树算法主要有以下几种: 1. ID3:使用信息增益g(D,A)进行特征选择 2. C4.5:信息增益率 =g(D,A)/H(A) 3. CART:基尼系数 一个特征的信息增益(或信息增益率,或基尼系数)越大,表明特征对样本的熵的减少能力更...https://blog.csdn.net/colourful_sky/article/details/82082854
机器学习:04. 随机森林之RandomForestClassifier - 简书https://www.jianshu.com/p/c1afbe4b9364