AttributeError:模块“ __main__”没有属性“ AverageWordLengthExtractor”

时间:2019-04-25 01:50:11

标签: python python-3.x flask scikit-learn pipeline

我在管道代码中创建了一个自定义转换器类AverageWordLengthExtractor,并在成功运行模型后保存了该模型。现在,当我尝试使用Flask应用加载模型时,它会显示AttributeError: module '__main__' has no attribute 'AverageWordLengthExtractor'

成功运行并保存模型的管道代码

自定义类

class AverageWordLengthExtractor(BaseEstimator, TransformerMixin):

    def __init__(self):
        pass
    def average_word_length(self, text):
        return np.mean([len(word) for word in text.split( ) if word not in stopWords])
    def fit(self, x, y=None):
        return self
    def transform(self, x , y=None):
        return pd.DataFrame(pd.Series(x).apply(self.average_word_length)).fillna(0)

保存模型

def save_model(model, model_filepath):
    # Save best grid search pipeline to file
    dump_file = model_filepath
    joblib.dump(model, dump_file, compress=1)

以上代码成功运行。

现在,我正在尝试使用flask加载模型。

app = Flask(__name__)
....
....
# load model
model = joblib.load("../models/classifier2.pkl")

我正在尝试使用此模型进行预测,但是它给出了错误,

$ python run.py
Traceback (most recent call last):
  File "run.py", line 33, in <module>
    model = joblib.load("../models/classifier2.pkl")
  File "C:\Users\609775743\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\externals\joblib\numpy_pickle.py", line 578, in load
    obj = _unpickle(fobj, filename, mmap_mode)
  File "C:\Users\609775743\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\externals\joblib\numpy_pickle.py", line 508, in _unpickle
    obj = unpickler.load()
  File "C:\Users\609775743\AppData\Local\Continuum\anaconda3\lib\pickle.py", line 1050, in load
    dispatch[key[0]](self)
  File "C:\Users\609775743\AppData\Local\Continuum\anaconda3\lib\pickle.py", line 1338, in load_global
    klass = self.find_class(module, name)
  File "C:\Users\609775743\AppData\Local\Continuum\anaconda3\lib\pickle.py", line 1392, in find_class
    return getattr(sys.modules[module], name)
AttributeError: module '__main__' has no attribute 'AverageWordLengthExtractor'

注释:如果没有自定义类,代码可以正常工作。

1 个答案:

答案 0 :(得分:0)

您是否在您的 Flask 应用程序中导入了 AverageWordLengthExtractor 类? 例如

import joblib
from average_word_length_extractor import AverageWordLengthExtractor
app = Flask(__name__)
# ...
# ...
# load model
model = joblib.load("../models/classifier2.pkl")

average_word_length_extractor 是您的 AverageWordLengthExtractor 类所在的 Python 文件。在这种情况下:average_word_length_extractor.py