Search code examples
apache-sparkpysparkpipelineapache-spark-ml

Load Pyspark.ml model from S3 using Pipeline


I am trying to save a trained model to S3 storage and then trying to load and predict using this model via Pipeline package from pyspark.ml. Here's an example of how I am saving my model.

#stage_1 to stage_4 are some basic trasnformation on data one-hot encoding e.t.c
# define stage 5: logistic regression model                          
 stage_5 = LogisticRegression(featuresCol='features',labelCol='label')

 # SETUP THE PIPELINE
 regression_pipeline = Pipeline(stages= [stage_1, stage_2, stage_3, stage_4, stage_5])

 # fit the pipeline for the trainind data
 model = regression_pipeline.fit(dataFrame1)

 model_path ="s3://s3-dummy_path-orch/dummy models/pipeline_testing_1.model"
 model.save(model_path)

I am able to save the model successfully & at the above mentioned model path two folders get created

  1. stages
  2. metadata.

However when I am trying to load the model it is giving me the below error.

Traceback (most recent call last):
  File "/tmp/pythonScript_85ff2462_e087_4805_9f50_0c75fc4302e2958379757178872310.py", line 75, in <module>
    pipelineModel = Pipeline.load(model_path)
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/ml/util.py", line 362, in load
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/ml/pipeline.py", line 207, in load
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/ml/util.py", line 300, in load
  File "/usr/lib/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py", line 1257, in __call__
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 79, in deco
pyspark.sql.utils.IllegalArgumentException: 'requirement failed: Error loading metadata: Expected class name org.apache.spark.ml.Pipeline but found class name org.apache.spark.ml.PipelineModel'

I am trying to load the model as below:

from pyspark.ml import Pipeline

## same path used while #model.save in the above code snippet
model_path ="s3://s3-dummy_path-orch/dummy models/pipeline_testing_1.model" 

pipelineModel = Pipeline.load(model_path)

How could I go about rectifying this?


Solution

  • If you saved a pipeline model, you should load it as a pipeline model, not as a pipeline. The difference is that a pipeline model is fitted to a dataframe, but a pipeline is not.

    from pyspark.ml import PipelineModel
    
    pipelineModel = PipelineModel.load(model_path)