Spark ML包广告检测 - Jeffrey511/Jeffrey-Yu GitHub Wiki
使用Spark ML包的API以及用它来实现一个文本分类用例。
广告检测Scala代码片段:
第一步:创建一个定制的类,用来存储广告内容的细节。 case class SpamDocument(file: String, text: String, label: Double)
第二步:初始化SQLContext,并通过隐式转换方法来把Scala对象转换成DataFrame。然后从存放着输入文件的指定目录导入数据集,结果会返回RDD对象。然后由这两个数据集的RDD对象创建DataFrame对象。 val sqlContext = new SQLContext(sc) import sqlContext.implicits._
// Load the data files with spam val rddSData = sc.wholeTextFiles("SPAM_DATA_FILE_DIR", 1) val dfSData = rddSData.map(d => SpamDocument(d._1, d._2,1)).toDF() dfSData.show()
// Load the data files with no spam val rddNSData = sc.wholeTextFiles("NO_SPAM_DATA_FILE_DIR",1) val dfNSData = rddNSData.map(d => SpamDocument(d._1,d._2, 0)).toDF() dfNSData.show()
第三步:现在,把数据集汇聚起来,然后根据70%和30%的比例来把整份数据拆分成训练数据和测试数据。 // Aggregate both data frames val dfAllData = dfSData.unionAll(dfNSData) dfAllData.show()
// Split the data into 70% training data and 30% test data val Array(trainingData, testData) = dfAllData.randomSplit(Array(0.7, 0.3))
第四步:现在可以配置机器学习数据流水线了,要创建我们在文章前面部分讨论到的几个部分:Tokenizer、HashingTF和IDF。然后再用训练数据创建回归模型,在这个例子中是逻辑回归。 // Configure the ML data pipeline // Create the Tokenizer step val tokenizer = new Tokenizer()
.setInputCol("text")
.setOutputCol("words")
// Create the TF and IDF steps val hashingTF = new HashingTF()
.setInputCol(tokenizer.getOutputCol)
.setOutputCol("rawFeatures")
val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")
// Create the Logistic Regression step val lr = new LogisticRegression()
.setMaxIter(5)
lr.setLabelCol("label") lr.setFeaturesCol("features")
// Create the pipeline val pipeline = new Pipeline()
.setStages(Array(tokenizer, hashingTF, idf, lr))
val lrModel = pipeline.fit(trainingData) println(lrModel.toString())
第五步:最后,我们调用逻辑回归模型中的转换方法来用测试数据做预测。 // Make predictions. val predictions = lrModel.transform(testData)
// Display prediction results predictions.select("file", "text", "label", "features", "prediction").show(300)