joblib:无法从另一个目录加载转储的 joblib 文件

joblib: cannot load dumped joblib file from another directory

我正在尝试从另一个目录加载转储的 joblib 文件,它给出了以下错误

Traceback (most recent call last):
  File "D:\dir\loader.py", line 5, in <module>
    foob = joblib.load(r'D:\foob.joblib')
  File "C:\programming\programmeFiles\anaconda\envs\tensor_gpu\lib\site-packages\joblib\numpy_pickle.py", line 585, in load
    obj = _unpickle(fobj, filename, mmap_mode)
  File "C:\programming\programmeFiles\anaconda\envs\tensor_gpu\lib\site-packages\joblib\numpy_pickle.py", line 504, in _unpickle
    obj = unpickler.load()
  File "C:\programming\programmeFiles\anaconda\envs\tensor_gpu\lib\pickle.py", line 1088, in load
    dispatch[key[0]](self)
  File "C:\programming\programmeFiles\anaconda\envs\tensor_gpu\lib\pickle.py", line 1376, in load_global
    klass = self.find_class(module, name)
  File "C:\programming\programmeFiles\anaconda\envs\tensor_gpu\lib\pickle.py", line 1426, in find_class
    __import__(module, level=0)
ModuleNotFoundError: No module named 'foo'  

重现错误的最少代码
目录如下所示

D-
   \
    foo.py
    dumper.py
    foob.joblib
    dir-
        \
         loader.py 

foo.py

class Foo:
    def __init__(self):
        self.s = "here at Foo"
    def __repr__(self):
        return "fooObject"

dumper.py

import joblib
import foo

foob = foo.Foo()
joblib.dump(foob,'foob.joblib')

loader.py

import joblib
foob = joblib.load(r'D:\foob.joblib')
print(foob)  

如果我尝试从同一目录 (D) 加载 foob.joblib 它工作正常,当 运行 loader.py 来自不同目录

时会发生错误

joblib.load() 要求 unpickling 所需的任何模块都在路径中。所以你需要在加载时以某种方式添加 foo.py 系统路径的位置。

例如添加:

import sys
import os
this_dir = os.path.dirname(__file__) # Path to loader.py
sys.path.append(os.path.join(this_dir, <rel_path_to_foo.py>))

loader.py

的顶部