Working with Pickle Files

In this example, we'll take a pickled file (.pkl) that contains a class, and deploy it.

This example includes 4 files:

  • myclass.py: the class that we want to pickle
  • make-pickle.py: script to read in class myclass and save as zepickle.pkl
  • zepickle.pkl: the pkl file
  • pickle-example.py: script to read in the pkl file and deploy the model that uses myclass

Create our Class (myclass.py)

class MyClass(object):
    def square(self,x):
        return x**2

Create our .pkl file (make-pickle.py)

from myclass import MyClass
import cPickle as pickle

obj = MyClass()

# save the pickle file locally
pkl_file = open('./zepickle.pkl', 'wb')
pickle.dump(obj, pkl_file)
pkl_file.close()
print "pickle of object MyClass saved to zepickle.pkl"

Deploy our model with the class (pickle-example.py)

# MUY IMPORTANTE!
# you must load the class of your pickle object (assuming it's not a built-in type) BEFORE you do pickle.load

from myclass import MyClass
import cPickle as pickle # pickle==cPickle

# load ANY files in relative paths OUTISIDE of YhatModel. This is because when YhatModel is evaluated on Ops Server, it won't have access to these files.

pkl_file = open('./zepickle.pkl', 'rb')
zeNewObject = pickle.load(pkl_file)
zeNewObject.square(2)

from yhat import Yhat, YhatModel

class PickleTest(YhatModel):
    def execute(self, data):
        x = data['x']
        output = zeNewObject.square(x)
        return { "sq": output }

yh = Yhat("USERNAME", "API_KEY", "https://sandbox.yhathq.com/")
yh.deploy("PickleTest", PickleTest, globals(), True)

results matching ""

    No results matching ""