赞
踩
OneHotEncoder has been deprecated in 2.3.0 and will be removed in 3.0.0. Please use OneHotEncoderEstimator instead.
import org.apache.spark.ml.feature.{OneHotEncoder, StringIndexer} val df = spark.createDataFrame(Seq( (0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c") )).toDF("id", "category") val indexer = new StringIndexer() .setInputCol("category") .setOutputCol("categoryIndex") .fit(df) val indexed = indexer.transform(df) val encoder = new OneHotEncoder() .setInputCol("categoryIndex") .setOutputCol("categoryVec") .setDropLast(false) val encoded = encoder.transform(indexed) encoded.show()
【说明】
1、OneHotEncoder缺省状态下将删除最后一个分类或把最后一个分类作为0.
// 示例
import org.apache.spark.ml.feature.{OneHotEncoder, StringIndexer}
val fd = spark.createDataFrame( Seq((1.0, "a"), (1.5, "a"), (10.0, "b"), (3.2, "c"),(3.8,"c"))).toDF("x","c")
val ss =new StringIndexer().setInputCol("c").setOutputCol("c_idx")
val ff = ss.fit(fd).transform(fd)
ff.show()
最后一个分类为b,通过OneHotEncoder变为向量后,已被删除。
import org.apache.spark.ml.feature.{OneHotEncoder, StringIndexer}
val fd = spark.createDataFrame( Seq((1.0, "a"), (1.5, "a"), (10.0, "b"), (3.2, "c"),(3.8,"c"))).toDF("x","c")
val ss =new StringIndexer().setInputCol("c").setOutputCol("c_idx")
val ff = ss.fit(fd).transform(fd)
ff.show()
与其他特征组合为特征向量后,将置为0,请看下例
val assembler = new VectorAssembler().setInputCols(Array("x", "c_idx", "c_idx_vec")).setOutputCol("features")
val vecDF: DataFrame = assembler.transform(fe)
vecDF.show(false)
如果想不删除最后一个分类,可添加setDropLast(False)。
oe.setDropLast(false)
val fl = oe.transform(ff)
fl.show()
与其他特征向量结合后,情况如下:
val vecDFl: DataFrame = assembler.transform(fl)
vecDFl.show(false)
2、如果分类中出现空字符,需要进行处理,如设置为"None",否则会报错。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。