【问题标题】:Save and load scikit-learn machine learning model and function保存和加载 scikit-learn 机器学习模型和函数
【发布时间】:2018-07-07 07:49:15
【问题描述】:

我使用 scikit-learn 训练了 Naive Bayes 模型,以对我的 Web 应用程序中的文章进行分类。为了避免重复学习模型,我想保存模型并稍后将其部署到应用程序中。当我搜索这个问题时,很多人推荐pickle库。

我有这个模型:

import pickle
import os
def custom_tokenizer (doc) :
    tokens = vect_tokenizer(doc)
    return [lemmatizer.lemmatize(token) for token in tokens]

tfidf = TfidfVectorizer(tokenizer = custom_tokenizer,stop_words = "english")
clf = MultinomialNB()

我已经执行了tfidf.fit_transform() 并训练了clf。最后,我得到了一个模型并使用此代码保存了clf 分类器:

dest = os.path.join('classifier','pkl_object')
f = open(os.path.join(dest,'classifier.pkl'),'wb')
pickle.dump(best_classifier,f,protocol = 4)
f.close()

我也尝试以这种方式将我的 Vectorizer 保存为文件。

f =  open(os.path.join(dest,'vect.pkl'),'wb')
pickle.dump(custom_tokenizer,f,protocol = 4)
pickle.dump(best_vector,f,protocol = 4)
f.close()

没有错误。但是当我尝试加载文件时,弹出此错误消息。

import pickle
import os

with open(os.path.join('pkl_object','classifier.pkl'),'rb') as file :
    clf = pickle.load(file)

with open(os.path.join('pkl_vect','vect.pkl'),'rb') as file:
    vect = pickle.load(file)

错误信息:

AttributeError                            Traceback (most recent call last)
<ipython-input-55-d4b562870a02> in <module>()
     11 
     12 with open(os.path.join('pkl_vect','vect.pkl'),'rb') as file:
---> 13     vect = pickle.load(file)
     14 
     15 '''

AttributeError: Can't get attribute 'custom_tokenizer' on <module '__main__'>

我认为pickle 库不具备正确存储函数的能力。如何将我的自定义 TfidfVectorizer 序列化为文件。

【问题讨论】:

  • 这是在同一台电脑上吗?如果不是,请验证两台机器上的 sklearn 版本是否相同。
  • @pault 这些在同一台计算机上。
  • 在您从中加载泡菜的文件中,您是否定义了 custom_tokenizer?需要为泡菜正确加载定义函数,在您的情况下,它也需要在全局范围内。

标签: python serialization scikit-learn pickle text-mining


【解决方案1】:

在第二个程序中还包括:

def custom_tokenizer (doc) :
    tokens = vect_tokenizer(doc)
    return [lemmatizer.lemmatize(token) for token in tokens]

因为 pickle 实际上并不存储有关如何构造类/对象的信息,因为错误日志中的这一行显示 AttributeError: Can't get attribute 'custom_tokenizer' on &lt;module '__main__'&gt; 它不知道 custom_tokenizer 是什么。请参阅 this 以获得更好的理解。

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 2020-12-10
    • 2019-03-09
    • 1970-01-01
    • 2018-04-23
    相关资源
    最近更新 更多