最近学了一下随机森林,本来想自己总结一下,但是觉得有一篇已经很好的博客,就给大家分享,我主要讲讲scikit-learn中如何使用随机森林算法。

  scikit-learn中和随机森林算法相关的类为RangeForestClassifier,相关官方文档讲解点击这里,这个类的主要参数和方法如下:

类的构造函数为:

RandomForestClassifier(n_estimators=10,criterion=’gini’, max_depth=None,min_samples_split=2,min_samples_leaf=1,
min_weight_fraction_leaf=0.0, max_features=’auto’, max_leaf_nodes=None, min_impurity_decrease=0.0,
min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None,
verbose=0, warm_start=False, class_weight=None)

其中构造函数的参数说明为:

参数(params):n_estimators:数值型取值森林中决策树的个数,默认是10criterion:字符型取值采用何种方法度量分裂质量,信息熵或者基尼指数,默认是基尼指数max_features:取值为int型, float型, string类型, or None(),默认"auto"寻求最佳分割时的考虑的特征数量,即特征数达到多大时进行分割。int:max_features等于这个int值float:max_features是一个百分比,每(max_features * n_features)特征在每个分割出被考虑。"auto":max_features等于sqrt(n_features)"sqrt":同等于"auto"时"log2":max_features=log2(n_features)None:max_features = n_featuresmax_depth:int型取值或者None,默认为None树的最大深度min_samples_split:int型取值,float型取值,默认为2分割内部节点所需的最少样本数量int:如果是int值,则就是这个int值float:如果是float值,则为min_samples_split * n_samplesmin_samples_leaf:int取值,float取值,默认为1叶子节点上包含的样本最小值int:就是这个int值float:min_samples_leaf * n_samplesmin_weight_fraction_leaf : float,default=0.能成为叶子节点的条件是:该节点对应的实例数和总样本数的比值,至少大于这个min_weight_fraction_leaf值max_leaf_nodes:int类型,或者None(默认None)最大叶子节点数,以最好的优先方式生成树,最好的节点被定义为杂质相对较少,即纯度较高的叶子节点min_impurity_split:float取值 树增长停止的阀值。一个节点将会分裂,如果他的杂质度比这个阀值;如果比这个值低,就会成为一个叶子节点。min_impurity_decrease:float取值,默认0.一个节点将会被分裂,如果分裂之后,杂质度的减少效果高于这个值。bootstrap:boolean类型取值,默认True是否采用有放回式的抽样方式oob_score:boolean类型取值,默认False是否使用袋外样本来估计该模型大概的准确率n_jobs:int类型取值,默认1拟合和预测过程中并行运用的作业数量。如果为-1,则作业数设置为处理器的core数。class_weight:dict, list or dicts, "balanced"如果没有给定这个值,那么所有类别都应该是权重1对于多分类问题,可以按照分类结果y的可能取值的顺序给出一个list或者dict值,用来指明各类的权重."balanced"模式,使用y值自动调整权重,该模式类别权重与输入数据中的类别频率成反比,
即n_samples / (n_classes * np.bincount(y)),分布为第n个类别对应的实例数。"balanced_subsample"模式和"balanced"模式类似,只是它计算使用的是有放回式的取样中取得样本数,而不是总样本数

该类主要的属性为:

属性:estimators_:决策树列表拟合好的字分类器列表,也就是单个决策树classes_:array of shape = [n_features]类别标签列表n_classes_:int or list类别数量n_features:int拟合过程中使用的特征的数量n_outputs:int 拟合过程中输出的数量featrue_importances:特征重要程度列表值越大,说明越重要oob_score:array of shape = [n_features]使用oob数据集测试得到的得分数oob_decision_funtion_:array of shape = [n_features, n_classes]oob样本预测结果,每一个样本及相应结果对列表

该类主要的方法为:

方法:apply(X):用构造好的森林中的树对数据集X进行预测,返回每棵树预测的叶子节点。所以结果应该是二维矩阵,
行为样本第几个样本,列为每棵树预测的叶子节点。 decision_path(X):返回森林中的决策路径fit(X, y[, sample_weight]):用训练数据集(x, y)来构造森林get_params([deep]):获得分类器的参数predict(X):预测X的类别predict_log_proba(X):预测X的类的对数概率,和predict_proba类似,只是取了对数predict_proba(X):预测X的类别的概率。输入样本的预测类别概率被计算为森林中树木的平均预测类别概率。
单个树的类概率是叶中同一类的样本的比率。因为叶子节点并不是完全纯净的,它也有杂质,
不同种类所占恶比率是不一样的,但肯定有一类纯度很高。返回值是array of shape = [n_samples, n_classes]score(X, y[,sample_weight]):返回给定的数据集(数据集指定了类别)的预测准确度set_params(**params):设置决策树的参数

   分享一段本人用随机森林算法写的关于kaggle上旧金山犯罪预测的题目,使用的是Python,正确率还未知,代码如下(刚学着用scikit-learn等工具,可能代码比较粗糙,敬请谅解!):

#author = liuweiimport pandas as pd
import numpy as np
import joblib
from sklearn.ensemble import RandomForestClassifierdef split_single_date(date_time_):'''split dateTime to year, month, day, hour, minute, and nomalize'''#split, use spacetmp_ = date_time_.split(' ')        date_, time_ = tmp_[0], tmp_[1]    #split date with '-'date_tmp_ = date_.split('-')  year_, month_, day_ = int(date_tmp_[0]), int(date_tmp_[1]), int(date_tmp_[2])#split time with ':'hour_tmp_ = time_.split(':')hour_ = int(hour_tmp_[0])return year_, month_, day_, hour_  def str_to_int(values):'''transform str to int, only simple enumerate, use the position value in values to replace value'''#get all possible valuecategorys_ =pd.Categorical(values).codesreturn categorys_#read data
train_data_ = pd.read_csv('datas/train.csv')test_data_ = pd.read_csv('datas/test.csv')#print('train_data:' + str(train_data_[:10]))#######################train_datas#################################get weekdays datas,and transform string to int
train_weekday_values_ = train_data_.DayOfWeek.values
train_weekday_ = str_to_int(train_weekday_values_)
train_weekdays_ = pd.Series(train_weekday_, name = 'weekday')#get district datas,and transform string to int
train_district_values_ = train_data_.PdDistrict.values
train_district_ = str_to_int(train_district_values_)
train_districts_ = pd.Series(train_district_, name = 'district')train_dates_ = train_data_.Dates.values#map(function, list):use function  on every element in the list
train_parse_date_ = list(map(split_single_date, train_dates_))#lambda is a way of simple function
train_years_ = pd.Series(data = map(lambda x : x[0], train_parse_date_), name = 'year')
train_months_ = pd.Series(data = map(lambda x : x[1], train_parse_date_), name = 'month')
train_days_ = pd.Series(data = map(lambda x : x[2], train_parse_date_), name = 'day')
train_hours_ = pd.Series(data = map(lambda x : x[3], train_parse_date_), name = 'hour')#the crime type
train_categorys_ = train_data_.Category.values#build the new train_datas, the method pd.concat's param asix is tell how to contract, when 1 is contract by column, 0 is row
train_datas_ = pd.concat([train_years_, train_months_, train_days_, train_hours_, train_weekdays_, train_districts_], axis = 1)######################test_datas#############################
test_weekday_values_ = test_data_.DayOfWeek.values
test_weekday_ = str_to_int(test_weekday_values_)
test_weekdays_ = pd.Series(test_weekday_, name = 'weekday')test_district_values_ = test_data_.PdDistrict.values
test_district_ = str_to_int(test_district_values_)
test_districts_ = pd.Series(test_district_, name = 'district')test_dates_ = test_data_.Dates.valuestest_parse_date_ = list(map(split_single_date, test_dates_))test_years_ = pd.Series(data = map(lambda x : x[0], test_parse_date_), name = 'year')test_months_ = pd.Series(data = map(lambda x : x[1], test_parse_date_), name = 'month') test_days_ = pd.Series(data = map(lambda x : x[2], test_parse_date_), name = 'day')test_hours_ = pd.Series(data = map(lambda x : x[3], test_parse_date_), name = 'hour')test_datas_ = pd.concat([test_years_, test_months_, test_days_, test_hours_, test_weekdays_, test_districts_], axis = 1)#######################RandomForestClassifier################use RandomForestClassifier to be the Classifier
#clf = RandomForestClassifier(n_estimators = 20, min_samples_leaf = 2000, bootstrap = True, oob_score = True, criterion = 'gini')
clf = RandomForestClassifier(bootstrap = True, oob_score = True, criterion = 'gini')#train the data
print('-------------train start---------------')
clf.fit(train_datas_, train_categorys_)#save the model,if need load the model, joblib.load(filename)
joblib.dump(clf, 'model/clf.pkl')#predict test_datas, every class will has a probabilities,the order of the class same to the attribute classes_
print('-------------train end---------------')print('-------------predict start---------------')
result_ = clf.predict_proba(test_datas_)print('-------------predict end---------------')#get all classes
classes_ = clf.classes_#save the predict result to file
res_data_frame_ = pd.DataFrame(data = result_, columns = classes_)
res_data_frame_.to_csv('result.csv', index_label = 'Id')

  因为ubuntu中的sublime text3无法写中文,所以注释写的是英文,但是很简单的英文,稍微看一下应该就能懂了!!!有问题可以一起交流!!!

scikit-learn中随机森林使用详解相关推荐

  1. 随机森林原理详解及python代码实现

    随机森林(RF)算法 1.算法原理 2.对数据的要求(无需规范化) 3.算法的优缺点 4.算法需要注意的点 5.python代码实现(待更......) 导入相关包 读取数据并预处理(必须处理缺失值) ...

  2. 随机森林的特征 是放回抽样么_机器学习超详细实践攻略(10):随机森林算法详解及小白都能看懂的调参指南...

    一.什么是随机森林 前面我们已经介绍了决策树的基本原理和使用.但是决策树有一个很大的缺陷:因为决策树会非常细致地划分样本,如果决策树分得太多细致,会导致其在训练集上出现过拟合,而如果决策树粗略地划分样 ...

  3. 【机器学习】红酒数据集和加利福尼亚的房价数据的随机森林算法详解

    一.随机森林 1.1随机森林的构建 bootstrap参数代表的是bootstrap sample,也就是"有放回抽样"的意思,指每次从样本空间中可以重复抽取同一个样本(因为样本在 ...

  4. python随机森林 交叉验证_随机森林算法详解及Python实现

    一 简介 随机森林是一种比较有名的集成学习方法,属于集成学习算法中弱学习器之间不存在依赖的一部分,其因为这个优点可以并行化运行,因此随机森林在一些大赛中往往是首要选择的模型. 随机森立中随机是核心,通 ...

  5. 机器学习-随机森林(RandomForest)详解

    1.什么是随机森林 随机森林就是通过集成学习的思想将多棵树集成的一种算法,它的基本单元是决策树,而它的本质属于机器学习的一大分支--集成学习(Ensemble Learning)方法. 解读下上面的话 ...

  6. matlab中随机森林实现,随机森林实现 MATLAB

    matlab 中随机森林工具箱的下载地址: http://code.google.com/p/randomforest-matlab/downloads/detail?name=Windows-Pre ...

  7. Lesson13【加餐】 损失函数的随机创建现象详解

    [Lesson 13 加餐]损失函数的随机创建现象详解   接下来,我们通过手动创建一个实例,来观察在小批梯度下降过程中,损失函数是如何根据数据数据变化而变化的,这里既是作为本节内容的一个补充,同时也 ...

  8. python 消息队列 get是从队首还是队尾取东西_python分布式爬虫中消息队列知识点详解...

    当排队等待人数过多的时候,我们需要设置一个等待区防止秩序混乱,同时再有新来的想要排队也可以呆在这个地方.那么在python分布式爬虫中,消息队列就相当于这样的一个区域,爬虫要进入这个区域找寻自己想要的 ...

  9. JSP中meta标签之详解

    JSP中meta标签之详解 2013年01月26日 16:09:27 阅读数:5589 JSP标签 <meta.....>作用总结 <metahttp-equiv="pra ...

最新文章

  1. 生成xml_Java操作XML
  2. 改变2020年及未来的8大人工智能趋势
  3. 把二叉搜索树转换为累加树
  4. STM32F4启动流程分析
  5. 2022年中国CRM行业研究报告
  6. pythonfor循环加2_python中for循环如何实现每次控制变量翻倍
  7. data后缀文件解码_小白学PyTorch | 17 TFrec文件的创建与读取
  8. 1057 字符转数字,判断
  9. 数据--第47课 - 查找的概念
  10. 好看的流程审批html,审批流程(加班)驳回(流程被删除).html
  11. 求数的绝对值一定是正数_有理数的绝对值难,那是因为你这些知识点和题型没掌握...
  12. mysql 备份还原策略_Mysql备份恢复
  13. TRNSYS 内区之间通风原理试验
  14. 自己动手搭建家庭局域网(一),服务器搭建和文件共享
  15. 计算机文件夹添加密码,电脑如何给文件夹设置密码
  16. pytorch深度学习_用于数据科学家的深度学习的最小pytorch子集
  17. 输入adb devices 显示设备序列号
  18. 【微信小程序原生】 上传图片和视频
  19. Java高级编程学习
  20. html5表格在线生成,专业的Web报表工具——表格在线生成制作工具

热门文章

  1. Shell入门:掌握Linux,OS X,Unix的Shell环境
  2. 汇编语言---函数调用栈
  3. Linux中文件查找技术大全
  4. Taro多端开发实现原理与项目实战(一)
  5. 图片服务 - thumbor启用AutoJPG
  6. MinIO Docker 快速入门
  7. CentOS切换运行级别 图形模式/命令行模式
  8. docker之阿里云centos 7.x 启动容器报错处理办法
  9. 了解git的命令行使用
  10. 【Java】从键盘中输入一个值,在数组中查找该值的索引并输出