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:

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

Create our Class (

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

Create our .pkl file (

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)
print "pickle of object MyClass saved to zepickle.pkl"

Deploy our model with the class (

# 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)

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", "")
yh.deploy("PickleTest", PickleTest, globals(), True)

results matching ""

    No results matching ""