Using MLeap with Pyspark getting a strange error
I've been looking at the various places that the MLeap/PySpark integration is documented and I'm finding contradictory information.
Referring to here: http://mleap-docs.combust.ml/getting-started/py-spark.html indicates that I should clone the repo down, setwd to the python folder, and then import mleap.pyspark - however there is no folder named pyspark in the mleap/python folder.
I successfully was able to run
import sys
sys.path.append('/databricks/driver/mleap/python')
import mleap.spark
from mleap.spark.spark_support import SimpleSparkSerializer
where I'm importing mleap.spark .
But when I try to serialize the RandomForestRegressor model I have built I get this error:
rfModel.serializeToBundle("jar:file:/tmp/pyspark.example.zip")
TypeError Traceback (most recent call last)
<ipython-input-94-4a2b69639611> in <module>()
----> 1 pipelineModel.serializeToBundle("jar:file:/tmp/pyspark.example.zip")
/databricks/driver/mleap/python/mleap/spark/spark_support.py in serializeToBundle(self, path)
21
22 def serializeToBundle(self, path):
---> 23 serializer = SimpleSparkSerializer()
24 serializer.serializeToBundle(self, path)
25
/databricks/driver/mleap/python/mleap/spark/spark_support.py in __init__(self)
34 def __init__(self):
35 super(SimpleSparkSerializer, self).__init__()
---> 36 self._java_obj = _jvm().ml.combust.mleap.spark.SimpleSparkSerializer()
37
38 def serializeToBundle(self, transformer, path):
TypeError: 'JavaPackage' object is not callable
Can you correct the documentation on the "getting started with pyspark" page? And do you have thoughts on this error?
Hi @jmi5 , which version of PySpark are you running?
@seme0021 I am using a Databricks notebook and running sc.version gives me 2.1.0
@jmi5 In my case, after adding jars mleap-spark-base_2.11-0.6.0.jar and mleap-spark_2.11-0.6.0.jar, it works
Thanks for responding @LTzycLT - I added those jars and am now getting this java.lang.NoSuchMethodError: scala.Predef$.ArrowAssoc(Ljava/lang/Object;)Ljava/lang/Object; error:
Code:
git clone -b "feature/scikit-v2" https://github.com/combust/mleap.git
import sys
sys.path.append('/databricks/driver/mleap/python')
import mleap.pyspark
from mleap.pyspark.spark_support import SimpleSparkSerializer
diamonds = sqlContext.read.format("csv")\
.option("header", "true")\
.option("inferSchema", "true")\
.load("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv")
featurecols = ['carat', 'cut', 'color', 'depth']
outputcol = ['price']
diamonds2 = diamonds.select(outputcol + featurecols)
# what are the categorical columns
catcols = []
numcols = []
for dt in diamonds2.dtypes:
if dt[0] in featurecols:
if dt[1] == 'string':
catcols += [dt[0]]
elif dt[1] == 'double' or dt[1] == 'int':
numcols += [dt[0]]
from pyspark.ml import Pipeline as mlPipeline
from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler
stages = []
stages = [] # stages in our Pipeline
for categoricalCol in catcols:
stringIndexer = StringIndexer(inputCol=categoricalCol, outputCol=categoricalCol+"Index")
encoder = OneHotEncoder(inputCol=categoricalCol+"Index", outputCol=categoricalCol+"classVec")
stages += [stringIndexer, encoder]
assemblerInputs = map(lambda c: c + "classVec", catcols) + numcols
assembler = VectorAssembler(inputCols=assemblerInputs, outputCol="features")
stages += [assembler]
# print assemblerInputs
pipeline = mlPipeline(stages=stages)
pipelineModel = pipeline.fit(diamonds2)
dataset = pipelineModel.transform(diamonds2)
dset2 = dataset.select(['price', 'features'])
(trainingData, testData) = dset2.randomSplit([0.7, 0.3], seed = 8)
from pyspark.ml.regression import RandomForestRegressor
# Create an initial RandomForest model.
rf = RandomForestRegressor(labelCol="price", featuresCol="features")
# Train model with Training Data
rfModel = rf.fit(trainingData)
import mleap.pyspark
from mleap.pyspark.spark_support import SimpleSparkSerializer
ss = SimpleSparkSerializer()
ss.serializeToBundle(rfModel, 'jar:file:/tmp/example.zip',dataset=trainingData) #error
Error:
---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
<ipython-input-23-ec5f35e328a3> in <module>()
3
4 ss = SimpleSparkSerializer()
----> 5 ss.serializeToBundle(rfModel, 'jar:file:/tmp/example.zip',dataset=trainingData) # mleap built under scala 2.11, this is running scala 2.10.6
/databricks/driver/mleap/python/mleap/pyspark/spark_support.py in serializeToBundle(self, transformer, path, dataset)
40
41 def serializeToBundle(self, transformer, path, dataset):
---> 42 self._java_obj.serializeToBundle(transformer._to_java(), path, dataset._jdf)
43
44 def deserializeFromBundle(self, path):
/databricks/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py in __call__(self, *args)
1131 answer = self.gateway_client.send_command(command)
1132 return_value = get_return_value(
-> 1133 answer, self.gateway_client, self.target_id, self.name)
1134
1135 for temp_arg in temp_args:
/databricks/spark/python/pyspark/sql/utils.pyc in deco(*a, **kw)
61 def deco(*a, **kw):
62 try:
---> 63 return f(*a, **kw)
64 except py4j.protocol.Py4JJavaError as e:
65 s = e.java_exception.toString()
/databricks/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
317 raise Py4JJavaError(
318 "An error occurred while calling {0}{1}{2}.\n".
--> 319 format(target_id, ".", name), value)
320 else:
321 raise Py4JError(
Py4JJavaError: An error occurred while calling o742.serializeToBundle.
: java.lang.NoSuchMethodError: scala.Predef$.ArrowAssoc(Ljava/lang/Object;)Ljava/lang/Object;
at ml.combust.bundle.BundleRegistry$$anonfun$5.apply(BundleRegistry.scala:45)
at ml.combust.bundle.BundleRegistry$$anonfun$5.apply(BundleRegistry.scala:43)
at scala.collection.IndexedSeqOptimized$class.foldl(IndexedSeqOptimized.scala:51)
at scala.collection.IndexedSeqOptimized$class.foldLeft(IndexedSeqOptimized.scala:60)
at scala.collection.mutable.ArrayBuffer.foldLeft(ArrayBuffer.scala:47)
at ml.combust.bundle.BundleRegistry$.apply(BundleRegistry.scala:42)
at ml.combust.bundle.BundleRegistry$.apply(BundleRegistry.scala:27)
at org.apache.spark.ml.bundle.SparkBundleContext$.apply(SparkBundleContext.scala:17)
at org.apache.spark.ml.bundle.SparkBundleContext$.defaultContext$lzycompute(SparkBundleContext.scala:11)
at org.apache.spark.ml.bundle.SparkBundleContext$.defaultContext(SparkBundleContext.scala:11)
at ml.combust.mleap.spark.SimpleSparkSerializer$$anonfun$1.apply(SimpleSparkSerializer.scala:17)
at ml.combust.mleap.spark.SimpleSparkSerializer$$anonfun$1.apply(SimpleSparkSerializer.scala:17)
at scala.Option.map(Option.scala:145)
at ml.combust.mleap.spark.SimpleSparkSerializer.serializeToBundle(SimpleSparkSerializer.scala:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:280)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Thread.java:745)
@jmi5 Sorry, the 'it works' just mean the callable problem can be solved. I'm working on applying this project as well and it seems like you go father than me now.
Currently, I don't know how to pass dataset to java because the origin python API for me is just like def serializeToBundle(self, transformer, path): and you modified it by yourself like this, right? ss.serializeToBundle(rfModel, 'jar:file:/tmp/example.zip',dataset=trainingData)
@LTzycLT I'm actually pulling down the feature/scikit-v2 branch which seems to have the most fully built out python support, not sure why it hasn't been merged into master.
Ex: https://github.com/combust/mleap/tree/feature/scikit-v2/python/mleap
@jmi5 @LTzycLT We're planning to merge in feature/scikit-v2 into master for the next official release of mleap by the end of this month. We'll update the mleap-docs to point to the feature branch for the time being.
@jmi5 @LTzycLT Is this issue still happening with 0.7.0 and the mleap pip package or can we close it out?
@hollinwilkins - will provide an update soon, thanks for checking back in
Hi I just tried using pyspark support for mleap. I did the following.
created a session with
{ "conf": {"spark.jars.packages": "ml.combust.mleap:mleap-spark-base_2.11:0.7.0,ml.combust.mleap:mleap-spark_2.11:0.7.0" }}```
following is my simple pipeline
```tokenizer = Tokenizer(inputCol="violations", outputCol="words")
hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
lr = LogisticRegression(maxIter=10, regParam=0.01)
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])
model = pipeline.fit(labeledData)
model```
```model.serializeToBundle("file:/home/vibhatia/simple-json-dir")```
when i try to do the above i get the following error
```'NoneType' object has no attribute '_jdf'
Traceback (most recent call last):
File "/usr/bin/anaconda/lib/python2.7/site-packages/mleap/pyspark/spark_support.py", line 25, in serializeToBundle
serializer.serializeToBundle(self, path, dataset=dataset)
File "/usr/bin/anaconda/lib/python2.7/site-packages/mleap/pyspark/spark_support.py", line 42, in serializeToBundle
self._java_obj.serializeToBundle(transformer._to_java(), path, dataset._jdf)
AttributeError: 'NoneType' object has no attribute '_jdf'```
So seems like the problem is not yet resolved.
@vidit-bhatia can you try:
model.serializeToBundle("file:/home/vibhatia/simple-json-dir", model.transform(labeledData))
Hi @seme0021 this seem to work is there any way I can export the model to HDFS or Azure blob store marked with WASB://URI
I have the following setup
- Python 3.5.2 Anaconda custom (64-bit)
- Spark 2.2.0
- added the following jar files inside $SPARK_HOME/jars
- mleap-spark-base_2.11-0.7.0.jar
- mleap-core_2.11-0.7.0.jar
- mleap-runtime_2.11-0.7.0.jar
- mleap-spark_2.11-0.7.0.jar
- bundle-ml_2.11-0.7.0.jar
- config-0.3.0.jar
- scalapb-runtime_2.11-0.6.1.jar
- mleap-tensor_2.11-0.7.0.jar
- installed using pip mleap (0.7.0) - MLeap Python API
And I have 2 problems Problem 1:
- cannot import
SimpleSparkSerializer
TypeError Traceback (most recent call last)
<ipython-input-2-f8a44b40601b> in <module>()
----> 1 from mleap.pyspark.spark_support import SimpleSparkSerializer
/Apps/anaconda3/lib/python3.5/site-packages/mleap/pyspark/spark_support.py in <module>()
31
32 setattr(Transformer, 'serializeToBundle', serializeToBundle)
---> 33 setattr(Transformer.__class__, 'deserializeFromBundle', deserializeFromBundle)
34 #setattr(Transformer, 'deserializeFromBundle', deserializeFromBundle)
35
TypeError: can't set attributes of built-in/extension type 'type'
- after checking
spark_support.pyfile @ line 33 and modifyingTransformer.__class__into simpleTransformer(eg:
setattr(Transformer, 'deserializeFromBundle', deserializeFromBundle)
import works fine
Problem 2:
- cannot serialize model.
Py4JJavaError: An error occurred while calling o126.serializeToBundle.
: java.lang.NoClassDefFoundError: resource/package$
at ml.combust.mleap.spark.SimpleSparkSerializer.serializeToBundle(SimpleSparkSerializer.scala:20)
- full stack trace and jupyter notebook @ github link
Am I missing something?
any thoughts on the above issue?
@rgeos I have a similar issue. AttributeError: 'Pipeline' object has no attribute 'serializeToBundle' python 3.5.4, spark 2.1.xx (hdp 2.6)
import sys sys.path.append('/opt/mleap/python') import mleap.pyspark from mleap.pyspark.spark_support import SimpleSparkSerializer
from pyspark.ml.feature import VectorAssembler, StandardScaler, OneHotEncoder, StringIndexer from pyspark.ml import Pipeline, PipelineModel from pyspark.sql import Row
--usual ML pipeline preparation--
featurePipeline = Pipeline(stages=feature_pipeline)
featurePipeline.fit(df2) featurePipeline.serializeToBundle("jar:file:/tmp/pyspark.example.zip")
Traceback (most recent call last):
File "
I think pyspark.ml.Pipeline should be overridden with mleap's Pipeline somehow...
Replacing sys.modules in init.py is not working properly.. maybe?
@rgeos I was also seeing the resource/package$ error, with a setup similar to yours except 0.8.1 everything.
You can bypass it by building a jar-with-dependencies off a scala example that does model serialization (like the MNIST example), then passing that jar with your pyspark job. jar tf confirms resource/package$ etc. are in there, but I haven't figured out what the ultimate dependency is.
Failing to prefix the model path with jar:file: also results in an obscure error.
Hello! any updates on this issue? I have a dockerfile with pyspark installed on it and I have the same problem Dockerfile
FROM java:8
RUN apt-get update \
&& apt-get install -y wget
RUN apt-get update && apt-get install git
RUN apt-get update && apt-get install -y python-pip python-dev build-essential
RUN pip install --upgrade pip
RUN pip install --upgrade virtualenv
RUN pip2 install pandas
RUN pip2 install boto3
#Spark installation
####################
ENV SPARK_VERSION 2.1.0
ENV SPARK_HOME /home/spark-$SPARK_VERSION-bin-hadoop2.6
WORKDIR /home
RUN wget http://d3kbcqa49mib13.cloudfront.net/spark-$SPARK_VERSION-bin-hadoop2.6.tgz
RUN tar -xvzf /home/spark-$SPARK_VERSION-bin-hadoop2.6.tgz \
&& rm /home/spark-$SPARK_VERSION-bin-hadoop2.6.tgz
# Install sbt
ENV SBT_VERSION 1.0.4
RUN \
curl -L -o sbt-$SBT_VERSION.deb https://dl.bintray.com/sbt/debian/sbt-$SBT_VERSION.deb && \
dpkg -i sbt-$SBT_VERSION.deb && \
rm sbt-$SBT_VERSION.deb && \
apt-get update && \
apt-get install sbt && \
sbt sbtVersion
WORKDIR /home
RUN git clone https://github.com/combust/mleap.git
WORKDIR /home/mleap
RUN git submodule init
RUN git submodule update
RUN sbt compile
RUN pip2 install sklearn
RUN pip2 install scipy
RUN apt-get update && apt-get install nano
WORKDIR $SPARK_HOME
ADD script.py ./
CMD ["./bin/spark-submit","--packages", "ml.combust.mleap:mleap-spark_2.11:0.9.0", "script.py"]
script.py
import sys
sys.path.append('/home/mleap/python')
# Imports MLeap serialization functionality for PySpark
import mleap.pyspark
from mleap.pyspark.spark_support import SimpleSparkSerializer
from pyspark import SparkContext
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local").appName("Mleap").getOrCreate()
sc = spark.sparkContext
# Import standard PySpark Transformers and packages
from pyspark.ml.feature import VectorAssembler, StandardScaler, OneHotEncoder, StringIndexer
from pyspark.ml import Pipeline, PipelineModel
from pyspark.sql import Row
# Create a test data frame
l = [('Alice', 1), ('Bob', 2)]
rdd = sc.parallelize(l)
Person = Row('name', 'age')
person = rdd.map(lambda r: Person(*r))
df2 = spark.createDataFrame(person)
df2.collect()
# Build a very simple pipeline using two transformers
string_indexer = StringIndexer(inputCol='name', outputCol='name_string_index')
feature_assembler = VectorAssembler(inputCols=[string_indexer.getOutputCol()], outputCol="features")
feature_pipeline = [string_indexer, feature_assembler]
featurePipeline = Pipeline(stages=feature_pipeline)
featurePipeline.fit(df2)
featurePipeline.serializeToBundle("jar:file:/tmp/pyspark.example.zip")
Am I doing something wrong? Thanks
There have been a lot of changes to the python code since this issue. Closing for now, please reopen if this is still an issue.
I just got started with mleap and I ran into this issue
I'm starting my spark context with the suggested mleap-spark-base and mleap-spark packages
spark = SparkSession \
.builder \
.master(SPARK_MASTER) \
.config('spark.executor.memory', TOTAL_MEMORY) \
.config('spark.cores.max', TOTAL_CORES) \
.config('spark.jars.packages',
'ml.combust.mleap:mleap-spark-base_2.11:0.9.3,ml.combust.mleap:mleap-spark_2.11:0.9.3') \
.appName("ClassifierTraining") \
.getOrCreate()
However when it comes to serializing the pipeline with the suggested systanx
model.serializeToBundle("jar:file:/tmp/{}-s.zip".format(model_filename))
I get the error
Traceback (most recent call last):
File "/Users/dvaldivia/classifier/ml_classifier/train_v4.py", line 138, in train
model.serializeToBundle("jar:file:/tmp/{}-s.zip".format(model_filename))
File "/Users/dvaldivia/classifier/pyenv/lib/python2.7/site-packages/mleap/pyspark/spark_support.py", line 25, in serializeToBundle
serializer.serializeToBundle(self, path, dataset=dataset)
File "/Users/dvaldivia/classifier/pyenv/lib/python2.7/site-packages/mleap/pyspark/spark_support.py", line 42, in serializeToBundle
self._java_obj.serializeToBundle(transformer._to_java(), path, dataset._jdf)
AttributeError: 'NoneType' object has no attribute '_jdf'
@hollinwilkins I'm confused on wether using the pip install method is sufficience to get the python going or if we still need to add the sourcecode as suggested in docs