spark 决策树分类算法demo
分类(Classification)
下面的例子说明了怎样导入LIBSVM 数据文件,解析成RDD[LabeledPoint],然后使用决策树进行分类。GINI不纯度作为不纯度衡量标准并且树的最大深度设置为5。最后计算了测试错误率从而评估算法的准确性。
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.tree import DecisionTree, DecisionTreeModel
from pyspark.mllib.util import MLUtils
# Load and parse the data file into an RDD of LabeledPoint.
data = MLUtils.loadLibSVMFile(sc, 'data/mllib/sample_libsvm_data.txt')
# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.randomSplit([0.7, 0.3])
# Train a DecisionTree model.
# Empty categoricalFeaturesInfo indicates all features are continuous.
model = DecisionTree.trainClassifier(trainingData, numClasses=2, categoricalFeaturesInfo={},
impurity='gini', maxDepth=5, maxBins=32)
# Evaluate model on test instances and compute test error
predictions = model.predict(testData.map(lambda x: x.features))
labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)
testErr = labelsAndPredictions.filter(lambda (v, p): v != p).count() / float(testData.count())
print('Test Error = ' + str(testErr))
print('Learned classification tree model:')
print(model.toDebugString())
# Save and load model
model.save(sc, "myModelPath")
sameModel = DecisionTreeModel.load(sc, "myModelPath")
以下代码展示了如何载入一个LIBSVM数据文件,解析成一个LabeledPointRDD,然后使用决策树,使用Gini不纯度作为不纯度衡量指标,最大树深度是5.测试误差用来计算算法准确率。
# -*- coding:utf-8 -*-"""测试决策树"""import osimport sysimport loggingfrom pyspark.mllib.tree import DecisionTree,DecisionTreeModelfrom pyspark.mllib.util import MLUtils# Path for spark source folderos.environ['SPARK_HOME']="D:\javaPackages\spark-1.6.0-bin-hadoop2.6"# Append pyspark to Python Pathsys.path.append("D:\javaPackages\spark-1.6.0-bin-hadoop2.6\python")sys.path.append("D:\javaPackages\spark-1.6.0-bin-hadoop2.6\python\lib\py4j-0.9-src.zip")from pyspark import SparkContextfrom pyspark import SparkConfconf = SparkConf()conf.set("YARN_CONF_DIR ", "D:\javaPackages\hadoop_conf_dir\yarn-conf")conf.set("spark.driver.memory", "2g")#conf.set("spark.executor.memory", "1g")#conf.set("spark.python.worker.memory", "1g")conf.setMaster("yarn-client")conf.setAppName("TestDecisionTree")logger = logging.getLogger('pyspark')sc = SparkContext(conf=conf)mylog = []#载入和解析数据文件为 LabeledPoint RDDdata = MLUtils.loadLibSVMFile(sc,"/home/xiatao/machine_learing/")#将数据拆分成训练集合测试集(trainingData,testData) = data.randomSplit([0.7,0.3])##训练决策树模型#空的 categoricalFeauresInfo 代表了所有的特征都是连续的model = DecisionTree.trainClassifier(trainingData, numClasses=2,categoricalFeaturesInfo={},impurity='gini',maxDepth=5,maxBins=32)# 在测试实例上评估模型并计算测试误差predictions = model.predict(testData.map(lambda x:x.features))labelsAndPoint = testData.map(lambda lp:lp.label).zip(predictions)testMSE = labelsAndPoint.map(lambda (v,p):(v-p)**2).sum()/float(testData.count())mylog.append("测试误差是")mylog.append(testMSE)#存储模型model.save(sc,"/home/xiatao/machine_learing/")sc.parallelize(mylog).saveAsTextFile("/home/xiatao/machine_learing/log")sameModel = DecisionTreeModel.load(sc,"/home/xiatao/machine_learing/")
spark 决策树分类算法demo的更多相关文章
- 决策树分类算法及python代码实现案例
决策树分类算法 1.概述 决策树(decision tree)——是一种被广泛使用的分类算法. 相比贝叶斯算法,决策树的优势在于构造过程不需要任何领域知识或参数设置 在实际应用中,对于探测式的知识发现 ...
- 用Python开始机器学习(2:决策树分类算法)
http://blog.csdn.net/lsldd/article/details/41223147 从这一章开始进入正式的算法学习. 首先我们学习经典而有效的分类算法:决策树分类算法. 1.决策树 ...
- python 之 决策树分类算法
发现帮助新手入门机器学习的一篇好文,首先感谢博主!:用Python开始机器学习(2:决策树分类算法) J. Ross Quinlan在1975提出将信息熵的概念引入决策树的构建,这就是鼎鼎大名的ID3 ...
- Spark 决策树--分类模型
package Spark_MLlib import org.apache.spark.ml.Pipeline import org.apache.spark.ml.classification.{D ...
- DNS通道检测 国内学术界研究情况——研究方法:基于特征或者流量,使用机器学习决策树分类算法居多
http://xuewen.cnki.net/DownloadArticle.aspx?filename=BMKJ201104017&dbtype=CJFD<浅析基于DNS协议的隐蔽通道 ...
- 决策树ID3算法--python实现
参考: 统计学习方法>第五章决策树] http://pan.baidu.com/s/1hrTscza 决策树的python实现 有完整程序 决策树(ID3.C4.5.CART ...
- R语言学习笔记—决策树分类
一.简介 决策树分类算法(decision tree)通过树状结构对具有某特征属性的样本进行分类.其典型算法包括ID3算法.C4.5算法.C5.0算法.CART算法等.每一个决策树包括根节点(root ...
- AI学习---分类算法[K-近邻 + 朴素贝叶斯 + 决策树 + 随机森林 ]
分类算法:对目标值进行分类的算法 1.sklearn转换器(特征工程)和预估器(机器学习) 2.KNN算法(根据邻居确定类别 + 欧氏距离 + k的确定),时间复杂度高,适合小数据 ...
- SparkMLlib分类算法之决策树学习
SparkMLlib分类算法之决策树学习 (一) 决策树的基本概念 决策树(Decision Tree)是在已知各种情况发生概率的基础上,通过构成决策树来求取净现值的期望值大于等于零的概率,评价项目风 ...
随机推荐
- 【转载】【翻译】JavaScript Scoping and Hoisting--JS作用域和变量提升的探讨
原文链接:http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting 你知道下面的JavaScript代码执行后会aler ...
- C#调用Java的WebService出现500 服务器错误
最近在用C#调用Java写的WebService时,发现老是返回500 服务器错误,到底什么原因一直找不出来, 后来google了以后,找到国外的http://stackoverflow.com站点已 ...
- 复习java基础第七天(反射)
一:目标 Ø理解 Class 类 Ø理解 Java 的类加载机制 Ø学会使用 ClassLoader 进行类加载 Ø理解反射的机制 Ø掌握 Constructor.Method.Field 类的用法 ...
- [读书笔记]-技术学习-Redis
1:Redis概览 Remote Dictionary Server 远程字典服务 Redis是基于内存的存储 在一台普通的笔记本上,Redis每秒的读取速度可以达到10万 内存读取数据,断电的时候数 ...
- MVC返回400 /404/...
return new HttpStatusCodeResult(HttpStatusCode.BadRequest); //HttpStatusCode statusCode 枚举 // HttpSt ...
- <转>c++引用与指针的区别(着重理解)
★ 相同点: 1. 都是地址的概念: 指针指向一块内存,它的内容是所指内存的地址:引用是某块内存的别名. ★ 区别: 1. 指针是一个实体,而引用仅是个别名: 2. 引用使用时无需解引用(*),指 ...
- react-draft-wysiwyg富文本
import { EditorState, convertToRaw } from 'draft-js'; import { Editor } from 'react-draft-wysiwyg' ...
- /proc目录介绍
1. /proc目录 Linux 内核提供了一种通过 /proc 文件系统,在运行时访问内核内部数据结构.改变内核设置的机制.proc文件系统是一个伪文件系统,它只存在内存当中,而不占用外存空间.它以 ...
- Linux启用ftp服务及连接
虚拟机的系统是centos6.3 第一步.启动ftp service vsftpd restart 提示 vsftpd: 未被识别的服务 解决方法是升级vsftpd服务 yum install vsf ...
- 50.常用的query查询方式
主要知识点 match all match multi match range query term query terms query exist query 1.match all ...