Scala Spark ML VectorAssembler()处理数据帧中的数千列
我使用spark ML管道在非常宽的表上建立分类模型。这意味着我必须自动生成处理列的所有代码,而不是以文字形式键入每个列。我基本上是scala和spark的初学者。当我尝试执行以下操作时,我被VectorAssembler()部分卡住了:Scala Spark ML VectorAssembler()处理数据帧中的数千列,scala,apache-spark,classification,pipeline,Scala,Apache Spark,Classification,Pipeline,我使用spark ML管道在非常宽的表上建立分类模型。这意味着我必须自动生成处理列的所有代码,而不是以文字形式键入每个列。我基本上是scala和spark的初学者。当我尝试执行以下操作时,我被VectorAssembler()部分卡住了: val featureHeaders = featureHeader.collect.mkString(" ") //convert the header RDD into a string val featureArray = featureHeaders.
val featureHeaders = featureHeader.collect.mkString(" ")
//convert the header RDD into a string
val featureArray = featureHeaders.split(",").toArray
val quote = "\""
val featureSIArray = featureArray.map(x => (s"$quote$x$quote"))
//count the element in headers
val featureHeader_cnt = featureHeaders.split(",").toList.length
// Fit on whole dataset to include all labels in index.
import org.apache.spark.ml.feature.StringIndexer
val labelIndexer = new StringIndexer().
setInputCol("target").
setOutputCol("indexedLabel")
val featureAssembler = new VectorAssembler().
setInputCols(featureSIArray).
setOutputCol("features")
val convpipeline = new Pipeline().
setStages(Array(labelIndexer, featureAssembler))
val myFeatureTransfer = convpipeline.fit(df)
很明显,它不起作用。我不知道该怎么做才能使整个过程更加自动化,或者ML管道此时不占用那么多的列(我对此表示怀疑) 除非列名包含引号,否则不应使用引号(s“$quote$x$quote”
)。试一试
val featureAssembler = new VectorAssembler().
setInputCols(featureArray).
setOutputCol("features")
我终于想出了一个办法,这不是很漂亮。为特征创建vector.dense,然后在此基础上创建数据帧
import org.apache.spark.mllib.regression.LabeledPoint
val myDataRDDLP = inputData.map {line =>
val indexed = line.split('\t').zipWithIndex
val myValues = indexed.filter(x=> {x._2 >1770}).map(x=>x._1).map(_.toDouble)
val mykey = indexed.filter(x=> {x._2 == 3}).map(x=>(x._1.toDouble-1)).mkString.toDouble
LabeledPoint(mykey, Vectors.dense(myValues))
}
val training = sqlContext.createDataFrame(myDataRDDLP).toDF("label", "features")
对于pyspark,您可以首先创建列名列表:
df_colnames = df.columns
然后您可以在vectorAssembler中使用它:
assemble = VectorAssembler(inputCols = df_colnames, outputCol = 'features')
df_vectorized = assemble.transform(df)
谢谢,但是使用featureArray也不起作用。它给出了以下错误:WARN TaskSetManager:在阶段28.0中丢失任务0.2:java.lang.ArrayIndexOutofBounds异常错误TaskSetManager:在阶段28.0中任务0失败4次;中止作业org.apache.spark.SparkException:作业因阶段失败而中止:阶段28.0中的任务0失败了4次,最近的失败:java.lang.ArrayIndexOutofBoundsCeption与此无关。看起来您的数据格式不正确。感谢您的帮助,我将重新访问我的输入数据。=)这对我仍然不起作用。我认为我的输入数据框很好。我可以很容易地创建一个标记点来输入MLlib,但不能用于ML管道。请大家多多指教,谢谢!