如何用含结果列依赖的已保存Pipeline预测无结果列数据集?
问题解决:加载已训练PipelineModel预测无outcome列的数据集
问题根源
你保存的PipelineModel中包含StringIndexerModel阶段(训练时用于将outcome列转换为模型所需的label列),该阶段在预测时仍会尝试读取outcome列,但你的预测数据集未包含该列,因此触发报错。
解决方案一:移除PipelineModel中的多余Stage
加载模型后,手动剔除依赖outcome列的StringIndexerModel阶段,保留特征处理、模型预测和标签反转的核心逻辑:
from pyspark.ml import PipelineModel # 加载已保存的模型 model = PipelineModel.load("/FileStore/project") # 过滤掉需要outcome列的Stage(即StringIndexerModel) new_stages = [stage for stage in model.stages if stage.getInputCol() != "outcome"] # 构建新的PipelineModel new_model = PipelineModel(stages=new_stages) # 执行预测 score_output_df = new_model.transform(score_this)
注:可先遍历
model.stages打印每个阶段的类名和输入列,确认要移除的Stage是否正确。
解决方案二:为预测数据集添加虚拟outcome列
临时添加一个任意值的outcome列,满足StringIndexerModel的输入要求(该列不会影响最终预测结果):
from pyspark.sql.functions import lit # 添加虚拟outcome列,值可任意设置 score_this_with_dummy = score_this.withColumn("outcome", lit("dummy")) # 加载模型并执行预测 model = PipelineModel.load("/FileStore/project") score_output_df = model.transform(score_this_with_dummy) # 可选:移除临时添加的outcome列 score_output_df = score_output_df.drop("outcome")
推荐方案
优先选择方案一,直接移除不必要的Stage更高效,避免额外的数据处理开销。
内容的提问来源于stack exchange,提问作者user3245747
相关产品推荐
相关产品推荐

