【问题标题】:Using DataFrame with MLlib将 DataFrame 与 MLlib 一起使用
【发布时间】:2015-06-05 07:57:30
【问题描述】:

假设我有一个 DataFrame(我从 HDFS 上的 csv 读取),我想通过 MLlib 训练一些算法。如何将行转换为 LabeledPoints 或在此数据集上使用 MLlib?

【问题讨论】:

  • 您没有提到列的数据类型,但如果它们是数字(整数、双精度等),您可以使用VectorAssembler 将特征列转换为Vector 的一列。

标签: apache-spark apache-spark-mllib


【解决方案1】:

假设您使用的是 Scala:

假设您获得DataFrame 如下:

val results : DataFrame = sqlContext.sql(...)

第 1 步:调用 results.printSchema()——这不仅会显示 DataFrame 中的列和(这很重要)它们的顺序,还会显示 Spark SQL 认为它们的类型。一旦你看到这个输出,事情就变得不那么神秘了。

第 2 步:从DataFrame 中获取RDD[Row]:

val rows: RDD[Row] = results.rdd

第 3 步:现在只需将您感兴趣的任何字段从各个行中提取出来。为此,您需要知道每个字段的从 0 开始的位置及其类型,幸运的是,您在上面的步骤 1 中获得了所有这些信息。例如, 假设您执行了SELECT x, y, z, w FROM ... 并打印了生成的架构

root
|-- x double (nullable = ...)
|-- y string (nullable = ...)
|-- z integer (nullable = ...)
|-- w binary (nullable = ...)

假设您想使用x 和z。您可以将它们拉到RDD[(Double, Integer)] 中,如下所示:

rows.map(row => {
    // x has position 0 and type double
    // z has position 2 and type integer
    (row.getDouble(0), row.getInt(2))
})

从这里您只需使用 Core Spark 创建相关的 MLlib 对象。如果您的 SQL 返回数组类型的列,事情可能会变得更复杂一些,在这种情况下,您必须为该列调用 getList(...)。

【讨论】:

    【解决方案2】:

    假设您使用的是 JAVA(Spark 版本 1.6.2):

    这是一个使用 DataFrame 进行机器学习的 JAVA 代码的简单示例。

    • 它加载具有以下结构的 JSON,

      [{"label":1,"att2":5.037089672359123,"att1":2.4100883023159456}, ... ]

    • 将数据拆分为训练和测试,

    • 使用训练数据训练模型,
    • 将模型应用于测试数据并
    • 存储结果。

    此外,根据official documentation,自当前版本 2.0.0 以来,MLlib 的“基于数据帧的 API 是主要 API”。所以你可以找到几个使用 DataFrame 的例子。

    代码:

    SparkConf conf = new SparkConf().setAppName("MyApp").setMaster("local[2]");
    SparkContext sc = new SparkContext(conf);
    String path = "F:\\SparkApp\\test.json";
    String outputPath = "F:\\SparkApp\\justTest";
    
    System.setProperty("hadoop.home.dir", "C:\\winutils\\");
    
    SQLContext sqlContext = new org.apache.spark.sql.SQLContext(sc);
    
    DataFrame df = sqlContext.read().json(path);
    df.registerTempTable("tmp");
    DataFrame newDF = df.sqlContext().sql("SELECT att1, att2, label FROM tmp");
    DataFrame  dataFixed = newDF.withColumn("label", newDF.col("label").cast("Double"));
    
    VectorAssembler assembler = new VectorAssembler().setInputCols(new String[]{"att1", "att2"}).setOutputCol("features");
    StringIndexer indexer = new StringIndexer().setInputCol("label").setOutputCol("labelIndexed");
    
    // Split the data into training and test
    DataFrame[] splits = dataFixed.randomSplit(new double[] {0.7, 0.3});
    DataFrame trainingData = splits[0];
    DataFrame testData = splits[1];
    
    DecisionTreeClassifier dt = new DecisionTreeClassifier().setLabelCol("labelIndexed").setFeaturesCol("features");
    Pipeline pipeline = new Pipeline().setStages(new PipelineStage[] {assembler, indexer, dt});
    // Train model
    PipelineModel model = pipeline.fit(trainingData);
    
    // Make predictions
    DataFrame predictions = model.transform(testData);
    predictions.rdd().coalesce(1,true,null).saveAsTextFile("justPlay.txt"  +System.currentTimeMillis());
    

    【讨论】:

      【解决方案3】:

      基于 RDD 的 Mllib 即将被弃用,因此您应该使用基于 DataFrame 的 Mllib。

      通常,这些 MLlib api 的输入是一个包含 2 列的 DataFrame - 标签和特征。有多种方法可以构建此 DataFrame - 低级 API,例如 org.apache.spark.mllib.linalg.{Vector, Vectors}、org.apache.spark.mllib.regression.LabeledPoint、org.apache.spark.mllib.linalg .{Matrix, Matrices} 等。它们都采用数值作为特征和标签。 可以使用 - org.apache.spark.ml.feature.{Word2Vec, Word2VecModel} 将单词转换为向量。本文档解释更多 - https://spark.apache.org/docs/latest/mllib-data-types.html

      创建带有标签和特征的输入数据框后,实例化 MLlib api 并将 DataFrame 传递给“fit”函数以获取模型,然后在模型上调用“transform”或“predict”函数以获取结果。

      示例 -

      训练文件看起来像 - <numeric label> <a string separated by space>

      //Build word vector
          val trainingData = spark.read.parquet(<path to training file>)
          val sampleDataDf = trainingData
            .map { r =>
              val s = r.getAs[String]("value").split(" ")
              val label = s.head.toDouble
              val feature = s.tail
              (label, feature)
            }.toDF("lable","feature_words")
      
          val word2Vec = new Word2Vec()
            .setInputCol("feature_words")
            .setOutputCol("feature_vectors")
            .setMinCount(0)
            .setMaxIter(10)
      
          //build word2Vector model
          val model = word2Vec.fit(sampleDataDf) 
          //convert training text data to vector and labels
          val wVectors = model.transform(sampleDataDf)
      
          //train LinearSVM model
          val svmAlgorithm = new LinearSVC()
                          .setFeaturesCol("feature_vectors")
                          .setMaxIter(100)
                          .setLabelCol("lable")
                          .setRegParam(0.01)
                          .setThreshold(0.5)
                          .fit(wVectors) //use word vectors created
      
          //Predict new data, same format as training data containing words
           val predictionData = spark.read.parquet(<path to prediction file>)
      
          val pDataDf = predictionData
            .map { r =>
              val s = r.getAs[String]("value").split(" ")
              val label = s.head.toDouble
              val feature = s.tail
              (label, feature)
            }.toDF("lable","feature_words")
      
          val pVectors = model.transform(pDataDf)
          val predictionlResult = pVectors.map{ r =>
              val s = r.getAs[Seq[String]]("feature_words")
              val v = r.getAs[Vector]("feature_vectors")
              val c = svmAlgorithm.predict(v) // predict using trained SVM
      
              s"$c ${s.mkString(" ")}"
            }
      

      【讨论】:

        猜你喜欢
        • 2015-12-18
        • 2016-12-13
        • 1970-01-01
        • 2015-07-15
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多