Spark MLlib特征处理:OneHotEncoder OneHot编码 ---原理及实战
2016-11-12 14:06
351 查看
原理
1)String字符串转换成索引IndexDouble2)索引转换成SparseVector
总结:OneHotEncoder = String > IndexDouble > SparseVector
代码实战
import org.apache.spark.ml.feature.{OneHotEncoder, StringIndexer} import org.apache.spark.sql.{DataFrame, SQLContext} import org.apache.spark.{SparkContext, SparkConf} object OneHotEncoderExample { def main(args: Array[String]) { val conf = new SparkConf().setAppName("OneHotEncoderExample").setMaster("local[8]") val sc = new SparkContext(conf) val sqlContext = new SQLContext(sc) // 将Seq集合转换成DataFrame // Seq是一个有先后次序的序列(也可以叫集合),Vector Range List Array都属于Seq类型 val df: DataFrame = sqlContext.createDataFrame(Seq( (0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c") )).toDF("id", "category") // String => IndexDouble val indexer = new StringIndexer().setInputCol("category").setOutputCol("categoryIndex") val indexed = indexer.fit(df).transform(df) // IndexDouble => SparseVector // OneHotEncode:实际上是转换成了稀疏向量 // Spark源码: The last category is not included by default 最后一个种类默认不包含 // 和python scikit-learn's OneHotEncoder不同,scikit-learn's OneHotEncoder包含所有 val encoder = new OneHotEncoder().setInputCol("categoryIndex").setOutputCol("categoryVec") // 设置最后一个是否包含 .setDropLast(false) //transform 转换成稀疏向量 val encoded = encoder.transform(indexed) encoded.select("category","categoryIndex", "categoryVec").show() sc.stop() } } // 输出 // +--------+-------------+-------------+ // |category|categoryIndex| categoryVec| // +--------+-------------+-------------+ // | a| 0.0|(3,[0],[1.0])| // | b| 2.0|(3,[2],[1.0])| // | c| 1.0|(3,[1],[1.0])| // | a| 0.0|(3,[0],[1.0])| // | a| 0.0|(3,[0],[1.0])| // | c| 1.0|(3,[1],[1.0])| // +--------+-------------+-------------+
相关文章推荐
- Spark MLlib特征处理:OneHotEncoder OneHot编码 ---原理及实战
- Spark MLlib特征处理:SVD 奇异值分解 ---原理及实战
- Spark MLlib特征处理:MinMax最大最小值区间缩放---原理及实战
- Spark MLlib特征处理:PCA 主成分分析 ---原理及实战
- Spark MLlib特征处理:StringToIndex 字符串索引---原理及实战
- Spark MLlib特征处理:Binarizer 二值化---原理及实战
- Spark MLlib特征处理:TF-IDF 词频-逆文频---原理及实战
- Spark MLlib特征处理:均值、方差、协方差 ---原理及实战
- Spark MLlib特征处理:Normalizer 正则化---原理及实战
- 处理离散型特征和连续型特征共存的情况 归一化 论述了对离散特征进行one-hot编码的意义
- One-hot 编码/TF-IDF 值来提取特征,LAD/梯度下降法(Gradient Descent),Sigmoid
- 独热编码 OneHotEncoder()
- 机器学习之离散型特征处理--独热码(one_hot_encoding)
- 基于sklearn的序列处理 : LabelEncoder 与 OneHotEncoder
- scikit-learn使用OneHotEncoder处理Nominal属性的机器学习流程(Random Forest算法为例)
- scikit-learn使用OneHotEncoder处理Nominal属性的机器学习流程(Random Forest算法为例)
- 机器学习之离散型特征的处理-one hot encoder
- pandas 下的 one hot encoder 及 pd.get_dummies() 与 sklearn.preprocessing 下的 OneHotEncoder 的区别
- Android的framework层音量控制原理分析--hot(key)处理
- One-hot编码:Python sklearn CTR实验