首页 > 解决方案 > 如何分两步使用 TfidfVectorizer,增加分析文本的数量?

问题描述

我正在使用 sklearn 在 Python3 中处理文本分类问题。

我正在执行以下步骤:

  1. 清理所有文本以训练分类器
  2. 提取训练文本的特征并使用 TfidfVectorizer 向量化
  3. 生成分类器(RandomForestClassifier)

这很好用,现在当我得到一个我想分类的新文本时,处理它的最佳方法是什么?我知道 Tfidf 方法还会查看其他数据集中特征的出现,这就是我现在将 TfidfVectorizer 应用于旧数据集+新文本的原因。但是有没有一种方法可以让我以一种渐进的方式做到这一点?这样一旦训练集就不会再被触及了。这有意义吗?

预先感谢您的帮助!卢卡

标签: pythonscikit-learnnlp

解决方案


矢量化器根据您传递的文档语料库进行拟合。通常,如果您正在处理大型文档语料库,您将首先将矢量化器适合整个语料库。这允许矢量化器正确地断言文档中术语的频率并适当地应用min_dfmax_dfmax_features参数。一旦向量化器已经适合,您就可以简单地转换文档以提取 tfidf 向量。(此文档不必在训练语料库中)

例如:

from nltk import word_tokenize
from nltk.stem import PorterStemmer
from sklearn.feature_extraction import TfidfVectorizer

class Tokenizer(object):
    def __init__(self):
        self.stemmer = PorterStemmer()
    def __call__(self, doc):
        return [self.stemmer.stem(w) for w in word_tokenize(doc)]
tfidf = TfidfVectorizer(stop_words='english', max_features=500, lowercase=True, tokenizer=Tokenizer)
# raw_docs can be collection of documents i.e. list, generator, etc...
raw_docs = ['The quick red fox jumped over the lazy brown dog', 'Carlos made a quick jumping catch in the game last night', 'How much wood would a woodchuck chuck if a woodchuck could chuck wood']
tfidf.fit(raw_docs[:1])
tfidf.vocabulary_
{'quick': 5, 'red': 6, 'fox': 2, 'jump': 3, 'lazi': 4, 'brown': 0, 'dog': 1}
# Notice only the first sentence in vocab
tfidf.transform(raw_docs[1:2]).todense()
matrix([[0.        , 0.        , 0.        , 0.70710678, 0.        ,
         0.70710678, 0.        ]])
#Vectorizing the second sentence only gives scores for 'jump' and 'quick'
tfidf.fit(raw_docs)
tfidf.vocabulary_
{'quick': 10,
 'red': 11,
 'fox': 5,
 'jump': 7,
 'lazi': 8,
 'brown': 0,
 'dog': 4,
 'carlo': 1,
 'catch': 2,
 'game': 6,
 'night': 9,
 'wood': 12,
 'woodchuck': 13,
 'chuck': 3}
# Notice terms from each sentence now
matrix([[0.        , 0.44036207, 0.44036207, 0.        , 0.        ,
         0.        , 0.44036207, 0.3349067 , 0.        , 0.44036207,
         0.3349067 , 0.        , 0.        , 0.        ]])
# We now have twice the features 14 v 7 and the vector catches each of the terms in the sentence.

推荐阅读