首页 > 解决方案 > python 3.x joblib 简单保存功能

问题描述

我正在尝试创建一个简单的 joblib 函数,它将评估表达式并腌制结果,同时检查腌制文件是否存在。但是当我将此函数放在其他文件中并在将文件的路径添加到 sys.path 后导入该函数时。我得到错误。

from pathlib import Path
import joblib as jl    
def saveobj(filename, expression_obj,ignore_file = False):
    fname = Path(filename)
    if fname.exists() and not ignore_file:
        obj = jl.load(filename)
    else:
        obj = eval(expression_obj)
        jl.dump(obj,fname,compress = True)        
    return obj

示例调用:

rf_clf = saveobj(file, "rnd_cv.fit(X_train, np.ravel(y_train))", ignore_file=True)

错误:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-02c2cae43c5d> in <module>
      1 file = Path("rf.pickle")
----> 2 rf_clf = saveobj(file, "rnd_cv.fit(X_train, np.ravel(y_train))", ignore_file=True)

~/Dropbox/myfnlib/util_funs.py in saveobj(filename, expression_obj, ignore_file)
     37         obj = jl.load(filename)
     38     else:
---> 39         obj = eval(expression_obj)
     40         jl.dump(obj,fname,compress = True)
     41     return obj

~/Dropbox/myfnlib/util_funs.py in <module>

NameError: name 'rnd_cv' is not defined

我猜,python 需要在本地评估函数,但由于对象不存在于该范围内,因此会引发此错误。有没有更好的方法来做到这一点。我需要重复执行此操作,这就是函数的原因。非常感谢你的帮助。

标签: pythonpicklejoblib

解决方案


您可以查看以下文档eval

关于内置模块内置函数 eval 的帮助:

评估(来源,全局=无,本地=无,/)

Evaluate the given source in the context of globals and locals.

The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

它具有全局变量和局部变量的参数。因此,在您的情况下,您可以:

from pathlib import Path
import joblib as jl    
def saveobj(filename, expression_obj,global,local,ignore_file = False):
    fname = Path(filename)
    if fname.exists() and not ignore_file:
        obj = jl.load(filename)
    else:
        obj = eval(expression_obj, global, local)
        jl.dump(obj,fname,compress = True)        
    return obj

代码可以改成:

rf_clf = saveobj(file, "rnd_cv.fit(X_train, np.ravel(y_train))", globals(), locals(), ignore_file=True)

推荐阅读