我正在使用服装标记器传递给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并用pickle加载它时,我都会收到一个错误:
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如何工作?
答案 0 :(得分:1)
只需弄清楚,我需要在加载腌制的TfidVectorizer的同一代码中添加方法tokenize_terms(),导入TermExtractor,然后创建提取器:
extractor = TermExtractor()