'Issue with save, load and predict with lightgbm from synapseml
Things don't work out as per the official overview.ipynb
I am trying to build a model in local mode on pyspark.
import pyspark
from pyspark.ml.feature import VectorAssembler
from synapse.ml.lightgbm import LightGBMClassificationModel, LightGBMClassifier
spark = pyspark.sql.SparkSession.builder.appName("MyApp") \
.config("spark.jars.packages", "com.microsoft.azure:synapseml_2.12:0.9.4") \
.config("spark.jars.repositories", "https://mmlspark.azureedge.net/maven") \
.getOrCreate()
##build modeling data
non_feats = [i for i in df.columns if '__val_col' in i.lower()]
non_feats.extend(['index','label','fold'])
feature_cols = [i for i in df.columns if i not in non_feats]
featurizer = VectorAssembler(
inputCols = feature_cols,
outputCol = 'features',handleInvalid='keep')
spark_df = df.to_spark() #will not run on koalas or pandas on pysaprk dataframes. This step is necessary
modeling_data = featurizer.transform(spark_df)
##build the model
model=LightGBMClassifier(objective='binary',isUnbalance=True,metric='auc',
earlyStoppingRound=10,featuresShapCol='shap',validationIndicatorCol='__val_col0',labelCol='label',
)
Post this I am able to train the model successfully (I think!)
model.fit(dataset=modeling_data)
output: LightGBMClassifier_867a1dd2276d
Issues:
- There is no
saveNativeModelattribute available with model.
model.saveNativeModel("./lgbmclassifier.model")
output: AttributeError: 'LightGBMClassifier' object has no attribute 'saveNativeModel'
- Model does not load post saving it with
.save(this is the only save attribute available)
model.save("./lgbmclassifier_test.model")
LightGBMClassificationModel.loadNativeModelFromFile("./lgbmclassifier_test.model")
output:
[LightGBM] [Fatal] Model file doesn't specify the number of classes
---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
/tmp/ipykernel_268437/1849142297.py in <module>
----> 1 LightGBMClassificationModel.loadNativeModelFromFile("./lgbmclassifier_test.model")
/tmp/spark-5794a877-8405-42db-b23c-33bfa7d0eacd/userFiles-9a0cfba3-8761-4c76-9d83-ae455b04cb37/com.microsoft.azure_synapseml-lightgbm_2.12-0.9.4.jar/synapse/ml/lightgbm/LightGBMClassificationModel.py in loadNativeModelFromFile(filename)
19 ctx = SparkContext._active_spark_context
20 loader = ctx._jvm.com.microsoft.azure.synapse.ml.lightgbm.LightGBMClassificationModel
---> 21 java_model = loader.loadNativeModelFromFile(filename)
22 return JavaParams._from_java(java_model)
23
~/miniconda3/envs/pyspark/lib/python3.9/site-packages/py4j/java_gateway.py in __call__(self, *args)
1307
1308 answer = self.gateway_client.send_command(command)
-> 1309 return_value = get_return_value(
1310 answer, self.gateway_client, self.target_id, self.name)
1311
~/miniconda3/envs/pyspark/lib/python3.9/site-packages/pyspark/sql/utils.py in deco(*a, **kw)
109 def deco(*a, **kw):
110 try:
--> 111 return f(*a, **kw)
112 except py4j.protocol.Py4JJavaError as e:
113 converted = convert_exception(e.java_exception)
~/miniconda3/envs/pyspark/lib/python3.9/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
324 value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
325 if answer[1] == REFERENCE_TYPE:
--> 326 raise Py4JJavaError(
327 "An error occurred while calling {0}{1}{2}.\n".
328 format(target_id, ".", name), value)
Py4JJavaError: An error occurred while calling z:com.microsoft.azure.synapse.ml.lightgbm.LightGBMClassificationModel.loadNativeModelFromFile.
: java.lang.Exception: Booster LoadFromString call failed in LightGBM with error: Model file doesn't specify the number of classes
at com.microsoft.azure.synapse.ml.lightgbm.LightGBMUtils$.validate(LightGBMUtils.scala:24)
at com.microsoft.azure.synapse.ml.lightgbm.booster.BoosterHandler$.com$microsoft$azure$synapse$ml$lightgbm$booster$BoosterHandler$$createBoosterPtrFromModelString(LightGBMBooster.scala:46)
at com.microsoft.azure.synapse.ml.lightgbm.booster.BoosterHandler.<init>(LightGBMBooster.scala:63)
at com.microsoft.azure.synapse.ml.lightgbm.booster.LightGBMBooster.boosterHandler$lzycompute(LightGBMBooster.scala:236)
at com.microsoft.azure.synapse.ml.lightgbm.booster.LightGBMBooster.boosterHandler(LightGBMBooster.scala:230)
at com.microsoft.azure.synapse.ml.lightgbm.booster.LightGBMBooster.numClasses$lzycompute(LightGBMBooster.scala:500)
at com.microsoft.azure.synapse.ml.lightgbm.booster.LightGBMBooster.numClasses(LightGBMBooster.scala:500)
at com.microsoft.azure.synapse.ml.lightgbm.LightGBMClassificationModel$.loadNativeModelFromFile(LightGBMClassifier.scala:199)
at com.microsoft.azure.synapse.ml.lightgbm.LightGBMClassificationModel.loadNativeModelFromFile(LightGBMClassifier.scala)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:282)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
at java.base/java.lang.Thread.run(Thread.java:829)
Env information:
- SynapseML Version: How to check the version? There is no .version on synapse when I import it. But, I guess it is 0.9.4 since that is the jar that I provide("com.microsoft.azure:synapseml_2.12:0.9.4") while creating the context.
- Spark Version: 3.2.0
- Spark Platform: local[*]
Can you please help me understand what to do post training the model. I am looking for save, load and predict capabilities
Solution 1:[1]
You have to save on filesytem and then move to sandbox:
gbm.save_model('/tmp/%s'%(gbm_name))
storage_account_name = "name"
storage_account_key = "key"
container_name = "container_name"
directory_name = "ml_path"
service_client = DataLakeServiceClient(account_url="{}://{}.dfs.core.windows.net".format(
"https", storage_account_name), credential=storage_account_key)
file_system_client = service_client.get_file_system_client(file_system=container_name)
dir_client = file_system_client.get_directory_client(directory_name)
dir_client.create_directory()
local_path = '/tmp/%s'%(gbm_name)
file_client = dir_client.create_file(gbm_name)
f = open(local_path,'rb')
file_contents = f.read()
file_client.upload_data(file_contents, overwrite=True)
f.close()
Then you can load and score with sparkmml.
from mmlspark.lightgbm import LightGBMClassificationModel
gbm_spark = LightGBMClassificationModel().loadNativeModelFromFile('directory_name/gbm_name')
featurizer = VectorAssembler(
handleInvalid = "keep",
inputCols=feature_cols,
outputCol='features'
)
score_data= featurizer.transform(var_score)
scored_data = gbm_spark.transform(score_data)
I hope it helps you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maria |
