python - 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
最好的方法是什么?
解决方案
根据文档,您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}
推荐阅读
- debugging - Dialogflow Flutter Chatbot - NoSuchMethodError:在 null 上调用了方法“[]”
- c# - Linq查询更新符合我条件的组中的所有项目
- html - 我无法填写“输入”和“文本区域”
- c# - 从 asp.net core 中的 Bootstrap 双列表中检索选定的值
- android - 如何使用 Volley 将 Recyclerview 列表发送到服务器
- tensorflow - 沿张量流中张量的行或列的范围
- nestjs - NestJS - 无法解析 ConfigService
- python - 在 Python 中实现重试时创建通用异常类
- javascript - 如何计算坐标
- mongodb - 在monogdb slave中存在显示零文档的文档计数