我的spark python 决策树实例

简介:
复制代码
from numpy import array
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.tree import DecisionTree, DecisionTreeModel
from pyspark import SparkContext
from pyspark.mllib.evaluation import BinaryClassificationMetrics

sc = SparkContext(appName="PythonDecisionTreeClassificationExample")
data = [
     LabeledPoint(0.0, [0.0]),
     LabeledPoint(1.0, [1.0]),
     LabeledPoint(0.0, [-2.0]),
     LabeledPoint(0.0, [-1.0]),
     LabeledPoint(0.0, [-3.0]),
     LabeledPoint(1.0, [4.0]),
     LabeledPoint(1.0, [4.5]),
     LabeledPoint(1.0, [4.9]),
     LabeledPoint(1.0, [3.0])
 ]
all_data = sc.parallelize(data) 
(trainingData, testData) = all_data.randomSplit([0.8, 0.2])

# model = DecisionTree.trainClassifier(sc.parallelize(data), 2, {})
model = DecisionTree.trainClassifier(trainingData, numClasses=2, categoricalFeaturesInfo={},
                                         impurity='gini', maxDepth=5, maxBins=32)
print(model)
print(model.toDebugString())
model.predict(array([1.0]))
model.predict(array([0.0]))
rdd = sc.parallelize([[1.0], [0.0]])
model.predict(rdd).collect()

predictions = model.predict(testData.map(lambda x: x.features))
labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)

  predictionsAndLabels = predictions.zip(testData.map(lambda lp: lp.label))

metrics = BinaryClassificationMetrics(predictionsAndLabels )
print "AUC=%f PR=%f" % (metrics.areaUnderROC, metrics.areaUnderPR)

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, "./myDecisionTreeClassificationModel")
sameModel = DecisionTreeModel.load(sc, "./myDecisionTreeClassificationModel")
复制代码

 















本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/7151341.html,如需转载请自行联系原作者


相关文章
|
1天前
|
数据可视化 Python
Python绘制基频曲线——实例解析与应用探讨
Python绘制基频曲线——实例解析与应用探讨
19 9
|
1天前
|
Python
Python 练习实例86
Python 练习实例86
|
1天前
|
Python
Python 练习实例87
Python 练习实例87
|
1天前
|
Python
Python 练习实例88
Python 练习实例88
|
2天前
|
Python
Python 练习实例84
Python 练习实例84
|
2天前
|
Python
Python 练习实例83
Python 练习实例83
|
2天前
|
Python
Python 练习实例85
Python 练习实例85
|
分布式计算 算法 测试技术
|
2月前
|
机器学习/深度学习 分布式计算 算法
Spark快速大数据分析PDF下载读书分享推荐
《Spark快速大数据分析》适合初学者,聚焦Spark实用技巧,同时深入核心概念。作者团队来自Databricks,书中详述Spark 3.0新特性,结合机器学习展示大数据分析。Spark是大数据分析的首选工具,本书助你驾驭这一利器。[PDF下载链接][1]。 ![Spark Book Cover][2] [1]: https://zhangfeidezhu.com/?p=345 [2]: https://i-blog.csdnimg.cn/direct/6b851489ad1944548602766ea9d62136.png#pic_center
119 1
Spark快速大数据分析PDF下载读书分享推荐
|
1月前
|
分布式计算 资源调度 大数据
【决战大数据之巅】:Spark Standalone VS YARN —— 揭秘两大部署模式的恩怨情仇与终极对决!
【8月更文挑战第7天】随着大数据需求的增长,Apache Spark 成为关键框架。本文对比了常见的 Spark Standalone 与 YARN 部署模式。Standalone 作为自带的轻量级集群管理服务,易于设置,适用于小规模或独立部署;而 YARN 作为 Hadoop 的资源管理系统,支持资源的统一管理和调度,更适合大规模生产环境及多框架集成。我们将通过示例代码展示如何在这两种模式下运行 Spark 应用程序。
158 3