我正在使用服装标记器传递给TfidfVectorizer。该分词器依赖于外部类 TermExtractor,该类位于另一个文件中。
我基本上想基于某些术语构建一个 TfidVectorizer,而不是所有单个单词/标记。
这是对它进行编码:
from sklearn.feature_extraction.text import TfidfVectorizer
from TermExtractor import TermExtractor
extractor = TermExtractor()
def tokenize_terms(text):
terms = extractor.extract(text)
tokens = []
for t in terms:
tokens.append('_'.join(t))
return tokens
def main():
vectorizer = TfidfVectorizer(lowercase=True, min_df=2, norm='l2', smooth_idf=True, stop_words=stop_words, tokenizer=tokenize_terms)
vectorizer.fit(corpus)
pickle.dump(vectorizer, open("models/terms_vectorizer", "wb"))
这运行良好,但是每当我想重用这个 TfidfVectorizer 并用泡菜加载它时,我都会收到一个错误:
vectorizer = pickle.load(open("models/terms_vectorizer", "rb"))
Traceback (most recent call last):
File "./train-nps-comments-classifier.py", line 427, in <module>
main()
File "./train-nps-comments-classifier.py", line 325, in main
vectorizer = pickle.load(open("models/terms_vectorizer", "rb"))
File "/usr/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "/usr/lib/python2.7/pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'tokenize_terms'
当存在依赖类时,Python pickle 如何工作?
弄清楚了,我需要在加载酸洗的 TfidVectorizer 的同一代码中添加方法 tokenize_terms(),导入 TermExtractor,并创建一个提取器:
extractor = TermExtractor()
此外,您可以尝试使用名为 dill
的新插入式替换库它是pickel库的扩展,确实支持更多的序列化对象类型