Skip to main content
 首页 » 编程设计

python之保存和加载 scikit-learn 机器学习模型和函数

2024年09月07日11emanlee

我用 scikit-learn 训练了朴素贝叶斯模型来对我的 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 序列化为文件。

请您参考如下方法:

在第二个程序中还包括:

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 <module '__main__'>它不知道什么是 custom_tokenizer .引用this以便更好地理解。