我尝试在https://spark.apache.org/docs/latest/mllib-decision-tree.html
的spark中为决策树做示例我从http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html#a1a
下载了a1a数据集数据集采用LIBSVM格式,其中两个类的标签为+1.0和-1.0 当我尝试
import org.apache.spark.mllib.tree.DecisionTree
import org.apache.spark.mllib.tree.model.DecisionTreeModel
import org.apache.spark.mllib.util.MLUtils
// Load and parse the data file.
val data = MLUtils.loadLibSVMFile(sc, "/user/cloudera/testDT/a1a.t")
// Split the data into training and test sets (30% held out for testing)
val splits = data.randomSplit(Array(0.7, 0.3))
val (trainingData, testData) = (splits(0), splits(1))
// Train a DecisionTree model.
// Empty categoricalFeaturesInfo indicates all features are continuous.
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)
我明白了:
java.lang.IllegalArgumentException:给定标签为-1.0的GiniAggregator但要求标签是非负的。
所以我尝试将标签-1.0更改为0.0。我试过像
这样的东西def changeLabel(a: org.apache.spark.mllib.regression.LabeledPoint) =
{ if (a.label == -1.0) {a.label = 0.0} }
我收到错误的地方:
重新分配给val
所以我的问题是:如何更改数据的标签?或者有一个解决方法,所以DecisionTree.trainClassifier()使用负标签的数据?
答案 0 :(得分:1)
TL; DR 您无法重置Product
类的值参数,即使可能(声明为var
),您也不应该< / strong>在Spark中修改数据。
怎么样:
def changeLabel(a: org.apache.spark.mllib.regression.LabeledPoint) =
if (a.label == -1.0) a.copy(label = 0.0) else a
scala> changeLabel(LabeledPoint(-1.0, Vectors.dense(1.0, 2.0, 3.0)))
res1: org.apache.spark.mllib.regression.LabeledPoint = (0.0,[1.0,2.0,3.0])
scala> changeLabel(LabeledPoint(1.0, Vectors.dense(1.0, 2.0, 3.0)))
res2: org.apache.spark.mllib.regression.LabeledPoint = (1.0,[1.0,2.0,3.0])