I have train a small model and use joblib to save it.
But i get an error while trying to load it.
This is my structure of directory:

loader.py
package
    model_folder
        __init__.py
        model.py
        model.pkl
    predict_folder
        __init__.py
        predict.py

package.predict_folder.predict.py中,我写了一个函数来加载model.pkl.

from ..model import model
import joblib
import sys

def predict(model_path):
    # sys.path.append(model_path)
    model = joblib.load(model_path)

然后在loader.py中,我调用这个函数.

from package.predict_folder.predict import predict
predict('package/model_folder/model.pkl')

但我得到了这个错误: ModuleNotFoundError: No module named 'model_folder'

我试着用sys来添加path:sys.path.append('package/model_folder/model.pkl'),就像我上面 comments 的那样.但一切都没有改变. 有人能帮我吗?

推荐答案

I got this error ModuleNotFoundError: No module named 'model_folder' when i reconstruct my folder structure.
The previous structure is:

train.py
model_folder
    model.pkl

After training, i directly save the model by joblib.dumb(model, 'model_folder/model.pkl').
Then i reconstruct:

predict.py
package
    model
        model.pkl
    train
        train.py

The diffrence between us is that you load your model inside package.predict_folder.predict.py, mean inside the package folder, but i load from outside package, in predict.py, like above.
But the same error occurs for me.

Solution就是if you reconstruct like meyou must retrain your model and resave it to 100, but with new path,比如package/model_folder/model.pkl.

The reason of error may because when you save model before reconstructing, joblib has remembered full path to model.pkl.
So when you load it, joblib just use the old path, model_folder/model.pkl, instead the new one, package/model_folder/model.pkl.

Python相关问答推荐

仅从风格中获取 colored颜色 循环

仿制药的类型铸造

SQLGory-file包FilField不允许提供自定义文件名,自动将文件保存为未命名

未删除映射表的行

如何在虚拟Python环境中运行Python程序?

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

如何在给定的条件下使numpy数组的计算速度最快?

使用密钥字典重新配置嵌套字典密钥名

部分视图的DataFrame

有没有一种ONE—LINER的方法给一个框架的每一行一个由整数和字符串组成的唯一id?

python中的解释会在后台调用函数吗?

在Python中调用变量(特别是Tkinter)

Flask Jinja2如果语句总是计算为false&

如何使用使用来自其他列的值的公式更新一个rabrame列?

基于另一列的GROUP-BY聚合将列添加到Polars LazyFrame

pandas fill和bfill基于另一列中的条件

有没有办法让Re.Sub报告它所做的每一次替换?

EST格式的Azure数据库笔记本中的当前时间戳

Match-Case构造中的对象可调用性测试

将鼠标悬停在海运`pairplot`的批注/高亮显示上