如何获取PySpark封装的XGBoost4J参数实际设置值
问题描述
我正在使用搭配PySpark封装器的Spark XGBoost4j组件,需要获取模型的特征贡献列名称。执行如下代码:
xgboost = XGBoostClassifier( featuresCol="features", labelCol="labelCol", predictionCol="prediction", contribPredictionCol="contribs", seed=42, ) xgboost.getParam("contribPredictionCol")
代码执行后输出结果为:
Param(parent='XGBoostClassifier_998c81888fa3', name='contribPredictionCol', doc='name of the predictContrib results')
预期上述操作返回该参数设置的实际值contribs,需要找到对应的实现方法。
解决方法
getParam()方法的作用是返回参数的元数据对象(包含参数所属实例、参数名、参数说明文档),不会返回参数的实际配置值。要获取设置的参数值,可以使用以下三种方式:
- 调用参数对应的专属getter方法:Spark ML组件的每个可配置参数都有对应的
get[驼峰格式参数名]()方法,针对contribPredictionCol参数,直接调用xgboost.getContribPredictionCol()即可返回设置的实际值。 - 调用
getOrDefault()方法:将getParam()返回的Param对象传入该方法,写法为xgboost.getOrDefault(xgboost.getParam("contribPredictionCol")),如果参数被手动赋值则返回自定义值,未赋值则返回组件内置的默认值。 - 使用参数快捷取值语法:PySpark支持直接用
实例[Param对象]的形式取值,写法为xgboost[xgboost.getParam("contribPredictionCol")],效果和getOrDefault()完全一致。
验证代码如下:
xgboost = XGBoostClassifier( featuresCol="features", labelCol="labelCol", predictionCol="prediction", contribPredictionCol="contribs", seed=42, ) # 方法1 print(xgboost.getContribPredictionCol()) # 输出:contribs # 方法2 print(xgboost.getOrDefault(xgboost.getParam("contribPredictionCol"))) # 输出:contribs # 方法3 print(xgboost[xgboost.getParam("contribPredictionCol")]) # 输出:contribs
内容的提问来源于stack exchange,提问作者itscarlayall
相关产品推荐
相关产品推荐

