[英]Cache dynamically generated functions
I have the probability density functions func1
and func2
(including the support
of each) of two random variables. 我有两个随机变量的概率密度函数func1
和func2
(包括每个函数的support
)。 Now I need the probability density function of the sum of these both random variables, which I create via: 现在,我需要这两个随机变量之和的概率密度函数,该函数是通过以下方式创建的:
import numpy as np
import scipy.integrate
[...]
def density_add(func1, func2, support):
return np.vectorize(lambda xi: scipy.integrate.simps(func1(support) * func2(xi-support), support))
The problem with that is the huge redundancy. 这样做的问题是巨大的冗余。 Many values have to be calculated more than once. 必须多次计算许多值。 So I tried to cache but problems appeared due to the dynamically generated functions without unique names. 所以我尝试缓存,但是由于动态生成的函数没有唯一名称而出现了问题。
from joblib import Memory
mem = Memory(cachedir="/tmp/joblib", verbose=0)
[...]
def density_add(func1, func2, support):
return np.vectorize(mem.cache(lambda xi: scipy.integrate.simps(func1(support) * func2(xi-support), support))
/usr/lib/python3/dist-packages/numpy/lib/function_base.py:2232: JobLibCollisionWarning: Cannot detect name collisions for function '<lambda> [...]
/usr/lib/python3/dist-packages/numpy/lib/function_base.py:2232: JobLibCollisionWarning: Possible name collisions between functions '<lambda>' [...]
What is a better approach to cache such dynamically generated functions? 有什么更好的方法来缓存此类动态生成的函数?
Could you use functools.lru_cache
? 您可以使用functools.lru_cache
吗? https://docs.python.org/3/library/functools.html#functools.lru_cache . https://docs.python.org/3/library/functools.html#functools.lru_cache 。 It would be all in memory, so you would lose values between restarts of your program, but the cache would warm up. 它全部都在内存中,因此您将在程序重新启动之间丢失值,但是缓存会预热。
from functools import lru_cache 从functools导入lru_cache
>>> @lru_cache()
>>> def myfunc(x):
>>> print('sleeping')
>>> return x + 1
>>> myfunc(1)
sleeping
2
>>> myfunc(1)
2
>>> myfunc2 = lru_cache()(lambda x: myfunc(x) *2)
>>> myfunc2(2)
sleeping
6
>>> myfunc2(2)
6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.