Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

python - How to serialize sympy lambdified function?

The title says it all. Is there any way to serialize a function generated by sympy.lambdify?:

import sympy as sym
import pickle
import dill
a, b = sym.symbols("a, b")
expr = sym.sin(a) + sym.cos(b)
lambdified_expr = sym.lambdify((a, b), expr, modules="numpy")
pickle.dumps(lambdified_expr) # won't work
dill.dumps(lambdified_expr) # won't work either

... The reason I want to do this is because my code generates so many lambdified functions but I found it takes too long every time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You actually can use dill to pickle it. The most recent versions of dill (e.g. on github) has "settings" that allow variants of how the pickle is constructed on dump. Yes, the default settings for dill fail on this object, but not if you use the setting that recursively traces global references (i.e. recurse = True). This setting is similar to what cloudpickle gives you by default.

>>> import sympy as sym
>>> import pickle
>>> import dill
>>> a, b = symbols("a, b")
>>> a, b = sym.symbols("a, b")
>>> expr = sym.sin(a) + sym.cos(b)
>>> lambdified_expr = sym.lambdify((a, b), expr, modules="numpy")
>>> 
>>> dill.settings
{'recurse': False, 'byref': False, 'protocol': 2, 'fmode': 0}
>>> dill.settings['recurse'] = True
>>> dill.dumps(lambdified_expr)
'x80x02cdill.dill
_create_function
qx00(cdill.dill
_unmarshal
qx01Ux83cx02x00x00x00x02x00x00x00x03x00x00x00C x00x00sx14x00x00x00tx00x00|x00x00x83x01x00tx01x00|x01x00x83x01x00x17S(x01x00x00x00N(x02x00x00x00tx03x00x00x00sintx03x00x00x00cos(x02x00x00x00tx01x00x00x00atx01x00x00x00b(x00x00x00x00(x00x00x00x00sx08x00x00x00<string>tx08x00x00x00<lambda>x01x00x00x00sx00x00x00x00qx02x85qx03Rqx04}qx05(Ux03cosqx06cnumpy.core.umath
cos
qx07Ux03sinqx08cnumpy.core.umath
sin
quUx08<lambda>q
NN}qx0btqx0cRq
.'

P.S. I'm the dill author, so I'd know.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...