分类(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.测试误差用来计算算法准确率。

  1. # -*- coding:utf-8 -*-
  2. """
  3. 测试决策树
  4. """
  5. import os
  6. import sys
  7. import logging
  8. from pyspark.mllib.tree import DecisionTree,DecisionTreeModel
  9. from pyspark.mllib.util import MLUtils
  10. # Path for spark source folder
  11. os.environ['SPARK_HOME']="D:\javaPackages\spark-1.6.0-bin-hadoop2.6"
  12. # Append pyspark to Python Path
  13. sys.path.append("D:\javaPackages\spark-1.6.0-bin-hadoop2.6\python")
  14. sys.path.append("D:\javaPackages\spark-1.6.0-bin-hadoop2.6\python\lib\py4j-0.9-src.zip")
  15. from pyspark import SparkContext
  16. from pyspark import SparkConf
  17. conf = SparkConf()
  18. conf.set("YARN_CONF_DIR ", "D:\javaPackages\hadoop_conf_dir\yarn-conf")
  19. conf.set("spark.driver.memory", "2g")
  20. #conf.set("spark.executor.memory", "1g")
  21. #conf.set("spark.python.worker.memory", "1g")
  22. conf.setMaster("yarn-client")
  23. conf.setAppName("TestDecisionTree")
  24. logger = logging.getLogger('pyspark')
  25. sc = SparkContext(conf=conf)
  26. mylog = []
  27. #载入和解析数据文件为 LabeledPoint RDDdata = MLUtils.loadLibSVMFile(sc,"/home/xiatao/machine_learing/")
  28. #将数据拆分成训练集合测试集
  29. (trainingData,testData) = data.randomSplit([0.7,0.3])
  30. ##训练决策树模型
  31. #空的 categoricalFeauresInfo 代表了所有的特征都是连续的
  32. model = DecisionTree.trainClassifier(trainingData, numClasses=2,categoricalFeaturesInfo={},impurity='gini',maxDepth=5,maxBins=32)
  33. # 在测试实例上评估模型并计算测试误差
  34. predictions = model.predict(testData.map(lambda x:x.features))
  35. labelsAndPoint = testData.map(lambda lp:lp.label).zip(predictions)
  36. testMSE = labelsAndPoint.map(lambda (v,p):(v-p)**2).sum()/float(testData.count())
  37. mylog.append("测试误差是")
  38. mylog.append(testMSE)
  39. #存储模型
  40. model.save(sc,"/home/xiatao/machine_learing/")
  41. sc.parallelize(mylog).saveAsTextFile("/home/xiatao/machine_learing/log")
  42. sameModel = DecisionTreeModel.load(sc,"/home/xiatao/machine_learing/")
 

spark 决策树分类算法demo的更多相关文章

  1. 决策树分类算法及python代码实现案例

    决策树分类算法 1.概述 决策树(decision tree)——是一种被广泛使用的分类算法. 相比贝叶斯算法,决策树的优势在于构造过程不需要任何领域知识或参数设置 在实际应用中,对于探测式的知识发现 ...

  2. 用Python开始机器学习(2:决策树分类算法)

    http://blog.csdn.net/lsldd/article/details/41223147 从这一章开始进入正式的算法学习. 首先我们学习经典而有效的分类算法:决策树分类算法. 1.决策树 ...

  3. python 之 决策树分类算法

    发现帮助新手入门机器学习的一篇好文,首先感谢博主!:用Python开始机器学习(2:决策树分类算法) J. Ross Quinlan在1975提出将信息熵的概念引入决策树的构建,这就是鼎鼎大名的ID3 ...

  4. Spark 决策树--分类模型

    package Spark_MLlib import org.apache.spark.ml.Pipeline import org.apache.spark.ml.classification.{D ...

  5. DNS通道检测 国内学术界研究情况——研究方法:基于特征或者流量,使用机器学习决策树分类算法居多

    http://xuewen.cnki.net/DownloadArticle.aspx?filename=BMKJ201104017&dbtype=CJFD<浅析基于DNS协议的隐蔽通道 ...

  6. 决策树ID3算法--python实现

    参考: 统计学习方法>第五章决策树]   http://pan.baidu.com/s/1hrTscza 决策树的python实现     有完整程序     决策树(ID3.C4.5.CART ...

  7. R语言学习笔记—决策树分类

    一.简介 决策树分类算法(decision tree)通过树状结构对具有某特征属性的样本进行分类.其典型算法包括ID3算法.C4.5算法.C5.0算法.CART算法等.每一个决策树包括根节点(root ...

  8. AI学习---分类算法[K-近邻 + 朴素贝叶斯 + 决策树 + 随机森林 ]

    分类算法:对目标值进行分类的算法    1.sklearn转换器(特征工程)和预估器(机器学习)    2.KNN算法(根据邻居确定类别 + 欧氏距离 + k的确定),时间复杂度高,适合小数据    ...

  9. SparkMLlib分类算法之决策树学习

    SparkMLlib分类算法之决策树学习 (一) 决策树的基本概念 决策树(Decision Tree)是在已知各种情况发生概率的基础上,通过构成决策树来求取净现值的期望值大于等于零的概率,评价项目风 ...

随机推荐

  1. 前端-git思维导图笔记

    命令汇总 git config配置本地仓库 常用git config --global user.name.git config --global user.email git config --li ...

  2. SharedPreferences用法

    SharedPreferences是Android四种数据存储技术中的一种,它是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信 息,其对 ...

  3. Eclipse安装配置——For Java

    1.下载安装JRE 2.下载Eclipse,解压到相应文件夹 3.配置Eclipse 3.1 配置字体大小  -12号 3.2配置workspace默认编码,utf-8,默认系统windows 3.3 ...

  4. Assembly之instruction之JUMP

    JMP  Jump unconditionally Syntax   JMP  label Operation PC + 2 × offset −> PC Description The 10- ...

  5. Haar、pico、npd、dlib等多种人脸检测特征及算法结果比较

    原文:opencv.pico.npd.dlib.face++等多种人脸检测算法结果比较 NDP检测结果: 结果分析: Pico(Pixel Intensity Comparison-based Obj ...

  6. Type inference

    Type inference refers to the automatic detection of the data type of an expression in a programming ...

  7. 备份xx

    https://www.tuicool.com/articles/V3EBzev https://www.tuicool.com/topics/11080087?st=0&lang=1& ...

  8. JQ 获取下一个元素和获取下一个元素的[指定]子元素

    <script type="text/javascript"> $(function () { $("#div1").next().addClass ...

  9. javaee IO流打印一行的方式

    package Dayin; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.F ...

  10. DATEPART()

    定义和用法 DATEPART() 函数用于返回日期/时间的单独部分,比如年.月.日.小时.分钟等等. 语法 DATEPART(datepart,date) date 参数是合法的日期表达式.datep ...