Spark机器学习API之特征处理(二)

来源:互联网 发布:推推棒淘宝店在哪里 编辑:程序博客网 时间:2024/06/02 06:46

Spark机器学习库中包含了两种实现方式,一种是spark.mllib,这种是基础的API,基于RDDs之上构建,另一种是spark.ml,这种是higher-level API,基于DataFrames之上构建,spark.ml使用起来比较方便和灵活。

Spark机器学习中关于特征处理的API主要包含三个方面:特征提取、特征转换与特征选择。本文通过例子介绍和学习Spark.ml中提供的关于特征处理API中的特征选择(Feature Selectors)部分。

特征选择(Feature Selectors)

1.  VectorSlicer

VectorSlicer用于从原来的特征向量中切割一部分,形成新的特征向量,比如,原来的特征向量长度为10,我们希望切割其中的5~10作为新的特征向量,使用VectorSlicer可以快速实现。

  1. package com.lxw1234.spark.features.selectors
  2.  
  3. import org.apache.spark.SparkConf
  4. import org.apache.spark.SparkContext
  5.  
  6. import org.apache.spark.ml.attribute.{Attribute, AttributeGroup, NumericAttribute}
  7. import org.apache.spark.ml.feature.VectorSlicer
  8. import org.apache.spark.mllib.linalg.Vectors
  9. import org.apache.spark.sql.Row
  10. import org.apache.spark.sql.types.StructType
  11.  
  12. /**
  13. * By http://lxw1234.com
  14. */
  15. object TestVectorSlicer extends App {
  16. val conf = new SparkConf().setMaster("local").setAppName("lxw1234.com")
  17. val sc = new SparkContext(conf)
  18. val sqlContext = new org.apache.spark.sql.SQLContext(sc)
  19. import sqlContext.implicits._
  20. //构造特征数组
  21. val data = Array(Row(Vectors.dense(-2.0, 2.3, 0.0)))
  22. //为特征数组设置属性名(字段名),分别为f1 f2 f3
  23. val defaultAttr = NumericAttribute.defaultAttr
  24. val attrs = Array("f1", "f2", "f3").map(defaultAttr.withName)
  25. val attrGroup = new AttributeGroup("userFeatures", attrs.asInstanceOf[Array[Attribute]])
  26. //构造DataFrame
  27. val dataRDD = sc.parallelize(data)
  28. val dataset = sqlContext.createDataFrame(dataRDD, StructType(Array(attrGroup.toStructField())))
  29. print("原始特征:")
  30. dataset.take(1).foreach(println)
  31. //构造切割器
  32. var slicer = new VectorSlicer().setInputCol("userFeatures").setOutputCol("features")
  33. //根据索引号,截取原始特征向量的第1列和第3列
  34. slicer.setIndices(Array(0,2))
  35. print("output1: ")
  36. slicer.transform(dataset).select("userFeatures", "features").first()
  37. //根据字段名,截取原始特征向量的f2和f3
  38. slicer = new VectorSlicer().setInputCol("userFeatures").setOutputCol("features")
  39. slicer.setNames(Array("f2","f3"))
  40. print("output2: ")
  41. slicer.transform(dataset).select("userFeatures", "features").first()
  42. //索引号和字段名也可以组合使用,截取原始特征向量的第1列和f2
  43. slicer = new VectorSlicer().setInputCol("userFeatures").setOutputCol("features")
  44. slicer.setIndices(Array(0)).setNames(Array("f2"))
  45. print("output3: ")
  46. slicer.transform(dataset).select("userFeatures", "features").first()
  47. }

程序运行输出为:

  1. 原始特征:
  2. [[-2.0,2.3,0.0]]
  3.  
  4. output1:
  5. org.apache.spark.sql.Row = [[-2.0,2.3,0.0],[-2.0,0.0]]
  6.  
  7. output2:
  8. org.apache.spark.sql.Row = [[-2.0,2.3,0.0],[2.3,0.0]]
  9.  
  10. output3:
  11. org.apache.spark.sql.Row = [[-2.0,2.3,0.0],[-2.0,2.3]]
  12.  

2.  RFormula

RFormula用于将数据中的字段通过R语言的Model Formulae转换成特征值,输出结果为一个特征向量和Double类型的label。关于R语言Model Formulae的介绍可参考:https://stat.ethz.ch/R-manual/R-devel/library/stats/html/formula.html

  1. package com.lxw1234.spark.features.selectors
  2.  
  3. import org.apache.spark.SparkConf
  4. import org.apache.spark.SparkContext
  5.  
  6. import org.apache.spark.ml.feature.RFormula
  7.  
  8. /**
  9. * By http://lxw1234.com
  10. */
  11. object TestRFormula extends App {
  12. val conf = new SparkConf().setMaster("local").setAppName("lxw1234.com")
  13. val sc = new SparkContext(conf)
  14. val sqlContext = new org.apache.spark.sql.SQLContext(sc)
  15. import sqlContext.implicits._
  16. //构造数据集
  17. val dataset = sqlContext.createDataFrame(Seq(
  18. (7, "US", 18, 1.0),
  19. (8, "CA", 12, 0.0),
  20. (9, "NZ", 15, 0.0)
  21. )).toDF("id", "country", "hour", "clicked")
  22. dataset.select("id", "country", "hour", "clicked").show()
  23. //当需要通过country和hour来预测clicked时候,
  24. //构造RFormula,指定Formula表达式为clicked ~ country + hour
  25. val formula = new RFormula().setFormula("clicked ~ country + hour").setFeaturesCol("features").setLabelCol("label")
  26. //生成特征向量及label
  27. val output = formula.fit(dataset).transform(dataset)
  28. output.select("id", "country", "hour", "clicked", "features", "label").show()
  29.  
  30. }

程序输出:



 

3.  ChiSqSelector

ChiSqSelector用于使用卡方检验来选择特征(降维)。

  1. package com.lxw1234.spark.features.selectors
  2.  
  3. import org.apache.spark.SparkConf
  4. import org.apache.spark.SparkContext
  5. import org.apache.spark.ml.feature.ChiSqSelector
  6. import org.apache.spark.mllib.linalg.Vectors
  7.  
  8. /**
  9. * By http://lxw1234.com
  10. */
  11. object TestChiSqSelector extends App {
  12. val conf = new SparkConf().setMaster("local").setAppName("lxw1234.com")
  13. val sc = new SparkContext(conf)
  14. val sqlContext = new org.apache.spark.sql.SQLContext(sc)
  15. import sqlContext.implicits._
  16. //构造数据集
  17. val data = Seq(
  18. (7, Vectors.dense(0.0, 0.0, 18.0, 1.0), 1.0),
  19. (8, Vectors.dense(0.0, 1.0, 12.0, 0.0), 0.0),
  20. (9, Vectors.dense(1.0, 0.0, 15.0, 0.1), 0.0)
  21. )
  22. val df = sc.parallelize(data).toDF("id", "features", "clicked")
  23. df.select("id", "features","clicked").show()
  24. //使用卡方检验,将原始特征向量(特征数为4)降维(特征数为3)
  25. val selector = new ChiSqSelector().setNumTopFeatures(3).setFeaturesCol("features").setLabelCol("clicked").setOutputCol("selectedFeatures")
  26. val result = selector.fit(df).transform(df)
  27. result.show()
  28.  
  29. }

程序输出为:



本文转载自:http://lxw1234.com/archives/2016/03/619.htm

 

2 0
原创粉丝点击