打赏

Spark MLlib编程API入门系列之特征选择之卡方特征选择(ChiSqSelector)

 

不多说,直接上干货!

 

  特征选择里,常见的有:VectorSlicer(向量选择) RFormula(R模型公式) ChiSqSelector(卡方特征选择)。

   

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

 

 

 

   我这里,采取手动创建。(但是,这仅仅是为了初学者。我不建议,最好用maven)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

完整代码

ChiSqSelector .scala
package zhouls.bigdata.DataFeatureSelection


import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.ml.feature.ChiSqSelector//导入mi里的特征选择里的ChiSqSelector算法
import org.apache.spark.mllib.linalg.Vectors//特征向量
 
/**
 * By  zhouls
 */ 
object ChiSqSelector extends App {
  
    val conf = new SparkConf().setMaster("local").setAppName("ChiSqSelector")
    val sc = new SparkContext(conf)
    
    val sqlContext = new org.apache.spark.sql.SQLContext(sc)
    import sqlContext.implicits._
    
    //构造数据集
    val data = Seq(
      (7, Vectors.dense(0.0, 0.0, 18.0, 1.0), 1.0),
      (8, Vectors.dense(0.0, 1.0, 12.0, 0.0), 0.0),
      (9, Vectors.dense(1.0, 0.0, 15.0, 0.1), 0.0)
    )
    val df = sc.parallelize(data).toDF("id", "features", "clicked")//将构造的数据集,转成DF,即DataFrame
    df.select("id", "features","clicked").show()
    
    //使用卡方检验,将原始特征向量(特征数为4)降维(特征数为3)
    val selector = new ChiSqSelector().setNumTopFeatures(3).setFeaturesCol("features").setLabelCol("clicked").setOutputCol("selectedFeatures")
    
    val result = selector.fit(df).transform(df)
    result.show()
 
}

 

 

 

 

  由

 

 

  变成

 

posted @ 2017-08-19 12:42  大数据和AI躺过的坑  阅读(1334)  评论(0编辑  收藏  举报