microsoft / SynapseML

Simple and Distributed Machine Learning
http://aka.ms/spark
MIT License
5.06k stars 832 forks source link

Cannot proceed post model.fit. No attribute .saveNativeModel and l.oadNativeModelFromFile gives error if used with .save #1297

Closed Nitinsiwach closed 2 years ago

Nitinsiwach commented 2 years ago

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:

  1. There is no saveNativeModel attribute available with model.
model.saveNativeModel("./lgbmclassifier.model") 
output: AttributeError: 'LightGBMClassifier' object has no attribute 'saveNativeModel'
  1. 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)

Expected behavior As mentioned in the official overview.ipynb.

Info (please complete the following information):

Can you please help me understand what to do post training the model. I am looking for save, load and predict capabilities

imatiach-msft commented 2 years ago

@Nitinsiwach those methods are on the LightGBMClassificationModel and not LightGBMClassifier. The notebook is a bit confusing because it does this re-assignment step:

model = model.fit(train_data)

It should be more like:

from synapse.ml.lightgbm import LightGBMClassifier
untrained_model = LightGBMClassifier(objective="binary", featuresCol="features", labelCol="Bankrupt?", isUnbalance=True)
model = untrained_model.fit(train_data)

or something similar. Note in spark the classes are immutable, which is a little different from the scikit-learn style API.

imatiach-msft commented 2 years ago

It looks like you are trying to call the methods on untrained_model and not model, which is why you are seeing the errors.

Nitinsiwach commented 2 years ago

Yup! This solves it all. Thank you very much you good good man! :)