【发布时间】:2016-01-15 23:54:39
【问题描述】:
我用来训练决策树的代码如下:
import org.apache.spark.SparkContext
import org.apache.spark.mllib.tree.DecisionTree
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.tree.configuration.Algo._
import org.apache.spark.mllib.tree.impurity.Gini
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.mllib.evaluation.MulticlassMetrics
//加载并解析数据文件
val data = sc.textFile("data/mllib/spt.csv")
val parsedData = data.map { line =>
val parts = line.split(',').map(_.toDouble)
LabeledPoint(parts(0), Vectors.dense(parts.tail))
}
//拆分数据
val splits = parsedData.randomSplit(Array(0.7, 0.3))
val (trainingData, testData) = (splits(0), splits(1))
// 训练一个决策树模型。
// 空的 categoricalFeaturesInfo 表示所有特征都是连续的。
val numClasses = 2
val categoricalFeaturesInfo = Map[Int, Int]()
val impurity = "gini"
val maxDepth = 5
val maxBins = 32
val model = DecisionTree.trainClassifier(trainingData, numClasses, categoricalFeaturesInfo,
impurity, maxDepth, maxBins)
val labelAndPreds = trainingData.map { point =>
val prediction = model.predict(point.features)
(point.label, prediction)
}
//Training error
val trainErr = labelAndPreds.filter(r => r._1 != r._2).count.toDouble / trainingData.count
println("Training Error = " + trainErr)
//Model Output
println("Learned classification tree model:\n" + model)
println("Learned classification tree model:\n" + model.toDebugString)
我希望“model.toDebugString”以文本文件的形式写入或输出。我找到了很多类似这个问题的答案,但并不具体。如果可以提供具体的帮助或提示,那将是非常有帮助的。由于我是 SCALA 的新手,因此我面临要包含的正确库的问题。
我尝试了以下代码:
modelFile = ~/decisionTreeModel.txt"
f = open(modelFile,"w")
f.write(model.toDebugString())
f.close()
但它给了我这个错误:
<console>:1: error: ';' expected but '.' found.
modelFile = ~/decisionTreeModel.txt"
^
<console>:1: error: unclosed string literal
modelFile = ~/decisionTreeModel.txt"
^
另外,尝试保存模型:
// Save and load model
model.save(sc, "myModelPath")
val sameModel = DecisionTreeModel.load(sc, "myModelPath")
上面的代码也抛出错误。感谢任何帮助或建议。
【问题讨论】:
-
Partha,你有没有看到分配给modelFile时缺少一个前导引号?
-
是的,我试过放它,但仍然抛出错误
标签: scala apache-spark decision-tree