TfIdfVectorizer 没有正确标记化

TfIdfVectorizer not tokenizing properly

在我看来,没有这样的问题。我正在 Kaggle 中从事 NLP 和情绪分析项目,首先我正在准备我的数据。 数据框是一个文本列,后面跟着一个从 0 到 9 的数字,它对行(文档)属于哪个集群进行分类。 我在 sklearn 中使用 TF-IDF Vectorizer。我想摆脱任何不是英语单词的东西,所以我使用以下内容:

class LemmaTokenizer(object):
    def __init__(self):
        self.wnl = WordNetLemmatizer()
    def __call__(self, doc):
        return [self.wnl.lemmatize(t) for t in word_tokenize(doc)]

s_words = list(nltk.corpus.stopwords.words("english"))

c = TfidfVectorizer(sublinear_tf=False,
                    stop_words=s_words,
                    token_pattern =r"(?ui)\b\w*[a-z]+\w*\b",
                    tokenizer = LemmaTokenizer(),
                    analyzer = "word",
                    strip_accents = "unicode")

#a_df is the original dataframe
X = a_df['Text']
X_text = c.fit_transform(X)

据我所知,在调用 c.get_feature_names() 时,应该 return 只有正确单词的标记,没有数字或标点符号。 我在 Whosebug 的 post 中找到了正则表达式,但使用更简单的 [a-zA-Z]+ 会做完全相同的事情(这没什么)。 当我调用功能名称时,我得到类似

的东西
["''abalone",
"#",
"?",
"$",
"'",
"'0",
"'01",
"'accidentally",
...]

这些只是示例,但它代表了我得到的输出,而不仅仅是文字。 几天来我一直坚持这个尝试不同的正则表达式或方法来调用。甚至硬编码了停用词特征的一些输出。 我问这个是因为后来我使用 LDA 来获取每个集群的主题并获取标点符号作为 "topics"。 我希望我没有复制另一个 post。我很乐意提供任何我需要提供的信息。提前致谢!

如果您传递自定义分词器,正则表达式模式将被忽略。文档中没有提到这一点,但您可以在此处的源代码中清楚地看到它:

https://github.com/scikit-learn/scikit-learn/blob/9e5819aa413ce907134ee5704abba43ad8a61827/sklearn/feature_extraction/text.py#L333

def build_tokenizer(self):
    """Return a function that splits a string into a sequence of tokens.
    Returns
    -------
    tokenizer: callable
          A function to split a string into a sequence of tokens.
    """
    if self.tokenizer is not None:
        return self.tokenizer
    token_pattern = re.compile(self.token_pattern)
    return token_pattern.findall

如果 self.tokenizer 不是 None,您将不会对标记模式执行任何操作。

解决这个问题很简单,只需将正则表达式标记模式放入您的自定义标记器中,然后将其用于 select 个标记。