How to access parameters of the underlying model in ML Pipeline?
Asked Answered
Z

1

2

I have a DataFrame that is processed with LinearRegression. If I do it directly, like below, I can display the details of the model:

val lr = new LinearRegression()
val lrModel = lr.fit(df)

lrModel: org.apache.spark.ml.regression.LinearRegressionModel = linReg_b22a7bb88404

println(s"Coefficients: ${lrModel.coefficients} Intercept: ${lrModel.intercept}")
Coefficients: [0.9705748115939526] Intercept: 0.31041486689532866

However, if I use it inside a pipeline (like in the simplified example below),

val pipeline = new Pipeline().setStages(Array(lr))
val lrModel = pipeline.fit(df)

then I get the following error.

scala> lrModel
res9: org.apache.spark.ml.PipelineModel = pipeline_99ca9cba48f8

scala> println(s"Coefficients: ${lrModel.coefficients} Intercept: ${lrModel.intercept}")
<console>:68: error: value coefficients is not a member of org.apache.spark.ml.PipelineModel
       println(s"Coefficients: ${lrModel.coefficients} Intercept: ${lrModel.intercept}")
                                         ^
<console>:68: error: value intercept is not a member of org.apache.spark.ml.PipelineModel
       println(s"Coefficients: ${lrModel.coefficients} Intercept: ${lrModel.intercept}")

I understand what it means (it's obvious I got a different class, because of the pipeline), but don't know how to get to the real underlying model.

Zachery answered 20/7, 2017 at 21:10 Comment(0)
R
9

LinearRegressionModel should be inside stages at the exact same index as its corresponding LinearRegression.

import org.apache.spark.ml.regressio‌​n.LinearRegressionMo‌​del
lrModel.stages(0).asInstanceOf[LinearRegressionMo‌​del]
Rhythmist answered 20/7, 2017 at 21:16 Comment(2)
This works for me to get the parameters from the best model from a CrossValidatorModelPostaxial
If your ML model is the last stage in a pipeline you can use model.stages.lastHew

© 2022 - 2024 — McMap. All rights reserved.