如何解决Scala (NOT pyspark) 将线性回归系数映射到特征名称分类和连续
我在 Scala 中有一个像这样的数据框
df.show
+---+-----+-------------------+--------+------------------+--------+------+------------+-------------+
| id|group| normalized_amount|query_id| y| y1|group1|groupIndexed| groupEncoded|
+---+-----+-------------------+--------+------------------+--------+------+------------+-------------+
| 1| B| 0.22874172014806| 1| 0.317739988492575| 0| B| 1.0|(2,[1],[1.0])|
| 2| A| -1.42432215217563| 2| -1.32008967486074| 0| C| 0.0|(2,[0],[1.0])|
| 3| B| -2.03644548423379| 3| -1.65740392834359| 0| B| 1.0|(2,[1.0])|
| 4| B| 0.425753803902096| 4|-0.127591370989296| 0| C| 0.0|(2,[1.0])|
| 5| A| 0.521050829955076| 5| 0.824285664580579| 1| A| 2.0| (2,[],[])|
| 6| A|-0.0416682439998418| 6| 0.321350404322885| 1| C| 0.0|(2,[1.0])|
| 7| A| -1.2787327462978| 7| -0.88099379032367| 0| A| 2.0| (2,[])|
| 8| A| 0.431780409975322| 8| 0.575249966796747| 1| C| 0.0|(2,[1.0])|
我正在对 y
(3 个类别的分类变量)和 group1
(连续变量)进行线性回归,如下所示
normalized_amount
我可以按如下方式访问系数和标准误差
var assembler = new VectorAssembler().setInputCols(Array("groupEncoded","normalized_amount")).setoutputCol("features")
val dfFeatures = assembler.transform(df)
var lr = new LinearRegression()
var lrModel = lr.fit(dfFeatures)
var lrPrediction = lrModel.transform(dfFeatures)
我的问题是
我看过一些类似问题的答案,但它们都在 pyspark 中而不是在 scala 中,而且我只使用了 scala
解决方法
将数据帧作为转换后的 df,包括预测和 LogisticRegressionModel,您可以访问 VectorAssembler 字段的属性。这段来自 databricks 的代码,我稍微修改了它用于 LogisticRegressionModel 而不是 Pipeline。请注意,您可以选择是否要拦截估计:
val lrToFit : LinearRegression = ???
lrToFit.setFitIntercept(false)
// With this dataframe as your transformed df that includes the prediction
val df: DataFrame = ???
val lr : LogisticRegressionModel = ???
val schema = df.schema
// Using the schema,the attributes of the Vector Assembler(features) can be extracted
val features = AttributeGroup.fromStructField(schema(lr.getFeaturesCol)).attributes.get.map(_.name.get)
val featureNames: Array[String] = if (lr.getFitIntercept) {
Array("(Intercept)") ++ features
} else {
features
}
val coefficients = lr.coefficients.toArray
val coeffs = if (lr.getFitIntercept) {
coefficients ++ Array(lr.intercept)
} else {
coefficients
}
featureNames.zip(coeffs).foreach { case (feature,coeff) =>
println(s"$feature\t$coeff")
}
这是一种可以在加载预训练模型时使用的方法,因为在这种情况下,您可能不知道 VectorAssembler 转换中特征的顺序。我认为您需要手动选择参考类别。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。