0

I know savez_compressed can save the functions generated from scipy. Is there any way to save lambda functions?

Attempt:

import numpy as np
from scipy.interpolate import interp1d
xAxis = np.array([1,2,3,4])
data = np.array([1,3,5,6])

yAxisInterp = interp1d(xAxis, data, kind='linear')

np.savez_compressed('myDataLambda.npz', yAxisInterp=yAxisInterp)
print('yAxisInterp is saved')

# Following command does not work
# ------------------------------
yAxisLambda = lambda x : x

np.savez_compressed('myData.npz', yAxisLambda=yAxisLambda)
print('yAxisLambda is saved')
Taygun Bulmuş
  • 113
  • 1
  • 8
  • 4
    Does this answer your question? [Is there an easy way to pickle a python function (or otherwise serialize its code)?](https://stackoverflow.com/questions/1253528/is-there-an-easy-way-to-pickle-a-python-function-or-otherwise-serialize-its-cod) – user2653663 Feb 14 '20 at 11:02
  • Actually, I searched some packages that can save the function, but I want to ask is there any options for np.save? – Taygun Bulmuş Feb 14 '20 at 13:16
  • `yAxisInterp` is not a function. It an object of class `interp1d` with a `__call__`. `pickle.dumps(yAxisInterp)` works as does the `loads`. Presumably it's saving the attributes which you can see with `vars(yAxisInterp)`. – hpaulj Feb 14 '20 at 17:36
  • I can `pickle` a function, but not a `lambda`. That means I can also `np.save` it. But the `load` has to `allow_pickle`, and the retrieved function will be embedded in an 0d object dtype array. – hpaulj Feb 14 '20 at 17:38
  • I think `lambda` function has a different behavior for python. Thank you for your support @hpaulj – Taygun Bulmuş Feb 15 '20 at 19:40

1 Answers1

1

No, numpy.savez does not save the functions in scipy, it saves numpy.ndarray objects, which are returned from those scipy functions.

That is, when you do:

yAxisInterp = interp1d(xAxis, data, kind='linear')

You've created an array, and that is what you are saving when you do:

np.savez_compressed('myDataLambda.npz', yAxisInterp=yAxisInterp)

You are not saving the function.

So no, you cannot save functions, any functions, with numpy.savez (and related methods).

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • `yAxisInterp` is not an array. It's an instance of a scipy class. I can `save` a function, or anything that can be `pickled`. A `lambda` cannot be pickled. – hpaulj Feb 14 '20 at 17:40