首页 > 解决方案 > sklearn TfidfVectorizer 自定义 ngrams 没有来自正则表达式模式的字符

问题描述

我想使用sklearn TfidfVectorizer执行自定义 ngram 矢量化。生成的 ngram 不应包含来自给定正则表达式模式的任何字符。analyzer='char'不幸的是,自定义标记器功能在(ngram 模式)时被完全忽略。请参见以下示例:

import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

pattern = re.compile(r'[\.-]'). # split on '.' and on '-'

def tokenize(text):
    return pattern.split(text)

corpus = np.array(['abc.xyz', 'zzz-m.j'])

# word vectorization
tfidf_vectorizer = TfidfVectorizer(tokenizer=tokenize, analyzer='word', stop_words='english')
tfidf_vectorizer.fit_transform(corpus)
print(tfidf_vectorizer.vocabulary_)
# Output -> {'abc': 0, 'xyz': 3, 'zzz': 4, 'm': 2, 'j': 1}
# This is ok!

# ngram vectorization
tfidf_vectorizer = TfidfVectorizer(tokenizer=tokenize, analyzer='char', ngram_range=(2, 2))
tfidf_vectorizer.fit_transform(corpus)
print(tfidf_vectorizer.vocabulary_)
# Output -> {'ab': 3, 'bc': 4, 'c.': 5, '.x': 2, 'xy': 7, 'yz': 8, 'zz': 10, 'z-': 9, '-m': 0, 'm.': 6, '.j': 1}
# This is not ok! I don't want ngrams to include the '.' and '-' chars used for tokenization

最好的方法是什么?

标签: pythonscikit-learnnlptf-idf

解决方案


根据文档,您tokenizer只能在analyzer=word. 这是他们的原话:

tokenizer (default=None) 覆盖字符串标记化步骤,同时保留预处理和 n-gram 生成步骤。仅在分析器 == 'word' 时适用。

您可以采取一种解决方法,即从词汇表中删除其中包含.或包含其中的所有标记。-下面的代码就是这样做的:

from copy import copy


for token in copy(tfidf_vectorizer.vocabulary_):
    if re.search(pattern, token):
        del tfidf_vectorizer.vocabulary_[token]

print(tfidf_vectorizer.vocabulary_)
#{'ab': 3, 'bc': 4, 'xy': 7, 'yz': 8, 'zz': 10}

推荐阅读