Spark-MLlib 学习入门到掌握-DecisionTreeClassifier决策树分类器[19]

  • 决策树是一个预测模型;他代表的是对象属性与对象值之间的一种映射关系。树中每个节点表示某个对象,而每个分叉路径则代表的某个可能的属性值,而每个叶结点则对应从根节点到该叶节点所经历的路径所表示的对象的值。决策树仅有单一输出,若欲有复数输出,可以建立独立的决策树以处理不同输出。
def DecisionTreeClassifier(): Unit ={
  import org.apache.spark.ml.Pipeline
  import org.apache.spark.ml.classification.DecisionTreeClassificationModel
  import org.apache.spark.ml.classification.DecisionTreeClassifier
  import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
  import org.apache.spark.ml.feature.{IndexToString, StringIndexer, VectorIndexer}
  val spark: SparkSession = SparkSession.builder().appName("implicits").master("local[2]").getOrCreate()

  // 加载和解析数据文件,将其转换为DataFrame。
  val data = spark.read.format("libsvm").load("F:/工具包/spark-2.3.1-bin-hadoop2/spark-2.3.1-bin-hadoop2.7/data/mllib/sample_libsvm_data.txt")

  //索引标签,向标签列添加元数据。
  //适合整个数据集,以包括索引中的所有标签。
  val labelIndexer = new StringIndexer()
    .setInputCol("label")
    .setOutputCol("indexedLabel")
    .fit(data)
  //自动识别分类特征,并对其进行索引。
  //设置maxCategories,使具有>4个不同值的特征被视为连续的。
  val featureIndexer = new VectorIndexer()
    .setInputCol("features")
    .setOutputCol("indexedFeatures")
    .setMaxCategories(4) // features with > 4 distinct values are treated as continuous.
    .fit(data)

  // 将数据分成训练集和测试集(30%用于测试)。
  val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))

  // 创建一个随机决策树模型类。
  val dt = new DecisionTreeClassifier()
    .setLabelCol("indexedLabel")
    .setFeaturesCol("indexedFeatures")

  // 将索引标签转换回原始标签。
  val labelConverter = new IndexToString()
    .setInputCol("prediction")
    .setOutputCol("predictedLabel")
    .setLabels(labelIndexer.labels)

  // 将上诉三个操作放入管道依次执行
  val pipeline = new Pipeline()
    .setStages(Array(labelIndexer, featureIndexer, dt, labelConverter))

  // 训练一个决策树模型。
  val model = pipeline.fit(trainingData)

  // 用模型作出预测。
  val predictions = model.transform(testData)

  // 选择要显示的示例行。
  predictions.select("predictedLabel", "label", "features").show(5)

  // 选择 (prediction, true label) 并计算测试误差.
  val evaluator = new MulticlassClassificationEvaluator()
    .setLabelCol("indexedLabel")
    .setPredictionCol("prediction")
    .setMetricName("accuracy")
  val accuracy = evaluator.evaluate(predictions)
  println(s"Test Error = ${(1.0 - accuracy)}")

  val treeModel = model.stages(2).asInstanceOf[DecisionTreeClassificationModel]
  println(s"Learned classification tree model:\n ${treeModel.toDebugString}")
}

运行结果
在这里插入图片描述
训练的决策树
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值