我试图了解 Spark.ml 如何处理字符串分类自变量。我知道在 Spark 中我必须使用 StringIndexer 将字符串转换为 double .
例如,“a”/“b”/“c”=> 0.0/1.0/2.0。
但我真正想避免的是必须使用 OneHotEncoder在那一列 double 上。这似乎使管道变得不必要的困惑。特别是因为 Spark 知道数据是分类的。希望下面的示例代码能让我的问题更清楚。
import org.apache.spark.ml.feature.StringIndexer
import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.classification.LogisticRegression
val df = sqlContext.createDataFrame(Seq(
Tuple2(0.0,"a"), Tuple2(1.0, "b"), Tuple2(1.0, "c"), Tuple2(0.0, "c")
)).toDF("y", "x")
// index the string column "x"
val indexer = new StringIndexer().setInputCol("x").setOutputCol("xIdx").fit(df)
val indexed = indexer.transform(df)
// build a data frame of label, vectors
val assembler = (new VectorAssembler()).setInputCols(List("xIdx").toArray).setOutputCol("features")
val assembled = assembler.transform(indexed)
// build a logistic regression model and fit it
val logreg = (new LogisticRegression()).setFeaturesCol("features").setLabelCol("y")
val model = logreg.fit(assembled)
逻辑回归将其视为只有一个自变量的模型。
model.coefficients
res1: org.apache.spark.mllib.linalg.Vector = [0.7667490491775728]
但是自变量是分类的,具有三个类别= [“a”,“b”,“c”]。我知道我从未做过 k 编码之一,但数据帧的元数据知道特征向量是名义上的。
import org.apache.spark.ml.attribute.AttributeGroup
AttributeGroup.fromStructField(assembled.schema("features"))
res2: org.apache.spark.ml.attribute.AttributeGroup = {"ml_attr":{"attrs":
{"nominal":[{"vals":["c","a","b"],"idx":0,"name":"xIdx"}]},
"num_attrs":1}}
如何将此信息传递给 LogisticRegression ?这不是保留数据帧元数据的全部意义吗?好像没有CategoricalFeaturesInfo在 SparkML 中。我真的需要对每个分类特征进行 1 of k 编码吗?
最佳答案
也许我错过了一些东西,但这看起来确实像是 RFormula ( https://spark.apache.org/docs/latest/ml-features.html#rformula ) 的工作。
顾名思义,它采用“R 式”公式来描述如何从输入数据列组成特征向量。
对于每个分类输入列(即 StringType 作为类型),它都会将 StringIndexer + OneHotEncoder 添加到在底层实现公式的最终管道中。
输出是一个特征向量( double ),可以与 org.apache.spark.ml 包中的任何算法一起使用,就像您所定位的算法一样。
关于apache-spark - Spark 和分类字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35070309/