将分类变量(字符串和整数)包含到MLlib算法的要素中的正确或最佳方法是什么?
在分类变量上使用OneHotEncoder
是否正确,然后将输出列与VectorAssembler
中的其他列包含在下面的代码中?
原因是我最终得到一个包含这样的行的数据框,看起来像feature3
和feature4
看起来像是两个分类的重要级别“单独的功能。
+------------------+-----------------------+---------------------------+
|prediction |actualVal |features |
+------------------+-----------------------+---------------------------+
|355416.44924898935|990000.0 |(17,[0,1,2,3,4,5,10,15],[1.0,206.0]) |
|358917.32988024893|210000.0 |(17,[0,1,2,3,4,5,10,15,16],[1.0,172.0]) |
|291313.84175674635|4600000.0 |(17,[0,1,2,3,4,5,12,15,16],[1.0,239.0]) |
这是我的代码:
val indexer = new StringIndexer()
.setInputCol("stringFeatureCode")
.setOutputCol("stringFeatureCodeIndex")
.fit(data)
val indexed = indexer.transform(data)
val encoder = new OneHotEncoder()
.setInputCol("stringFeatureCodeIndex")
.setOutputCol("stringFeatureCodeVec")
var encoded = encoder.transform(indexed)
encoded = encoded.withColumn("intFeatureCodeTmp", encoded.col("intFeatureCode")
.cast(DoubleType))
.drop("intFeatureCode")
.withColumnRenamed("intFeatureCodeTmp", "intFeatureCode")
val intFeatureCodeEncoder = new OneHotEncoder()
.setInputCol("intFeatureCode")
.setOutputCol("intFeatureCodeVec")
encoded = intFeatureCodeEncoder.transform(encoded)
val assemblerDeparture =
new VectorAssembler()
.setInputCols(
Array("stringFeatureCodeVec", "intFeatureCodeVec", "feature3", "feature4"))
.setOutputCol("features")
var data2 = assemblerDeparture.transform(encoded)
val Array(trainingData, testData) = data2.randomSplit(Array(0.7, 0.3))
val rf = new RandomForestRegressor()
.setLabelCol("actualVal")
.setFeaturesCol("features")
.setNumTrees(100)
答案 0 :(得分:1)
StringIndexer
。