我的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让你秒懂分支逻辑,精准分类不再难
【9月更文挑战第12天】决策树算法作为机器学习领域的一颗明珠,凭借其直观易懂和强大的解释能力,在分类与回归任务中表现出色。相比传统统计方法,决策树通过简单的分支逻辑实现了数据的精准分类。本文将借助Python和scikit-learn库,以鸢尾花数据集为例,展示如何使用决策树进行分类,并探讨其优势与局限。通过构建一系列条件判断,决策树不仅模拟了人类决策过程,还确保了结果的可追溯性和可解释性。无论您是新手还是专家,都能轻松上手,享受机器学习的乐趣。
13 9
|
1天前
|
Python
Python 练习实例48
Python 练习实例48
|
4天前
|
人工智能 Python
Python 练习实例38
Python 练习实例38
|
1天前
|
Python
Python 练习实例47
Python 练习实例47
|
4天前
|
人工智能 Python
Python 练习实例39
Python 练习实例39
|
1天前
|
Python
Python 练习实例46
Python 练习实例46
|
4天前
|
Python
Python 练习实例37
Python 练习实例37
|
3天前
|
Python
Python 练习实例42
Python 练习实例42
|
2天前
|
Python
Python 练习实例45
Python 练习实例45
|
2天前
|
Python
Python 练习实例43
Python 练习实例43