Spark MLlib:包括分类功能

时间:2016-11-10 19:11:34

标签: apache-spark apache-spark-mllib

将分类变量(字符串和整数)包含到MLlib算法的要素中的正确或最佳方法是什么?

在分类变量上使用OneHotEncoder是否正确,然后将输出列与VectorAssembler中的其他列包含在下面的代码中?

原因是我最终得到一个包含这样的行的数据框,看起来像feature3feature4看起来像是两个分类的重要级别“单独的功能。

+------------------+-----------------------+---------------------------+
|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)

1 个答案:

答案 0 :(得分:1)

  • 一般来说,这是推荐的方法。
  • 在使用树模型时,这是不必要的,应该避免。您只能使用StringIndexer