如何在 CountVectorizer 中自定义分词?

数据挖掘 Python scikit-学习 正则表达式 ngram 标记化
2022-02-20 18:49:57
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> import numpy
>>> import pandas

>>> vectorizer = CountVectorizer()
>>> corpus1 = ['abc-@@-123','cde-@@-true','jhg-@@-hud']
>>> xtrain = vectorizer.fit_transform(corpus1)
>>> xtrain
<3x6 sparse matrix of type '<class 'numpy.int64'>'
    with 6 stored elements in Compressed Sparse Row format>

>>> xtraindf = pd.DataFrame(xtrain.toarray())
>>> xtraindf.columns = vectorizer.get_feature_names()
>>> xtraindf.columns
Index(['123', 'abc', 'cde', 'hud', 'jhg', 'true'], dtype='object')

我看到特殊字符(-@@-)被省略了,“abc”和“123”被分开考虑。但是,我希望将“abc-@@-123”视为一个单词。有没有可能实现?如果是,如何?

任何帮助将非常感激。

1个回答

如果您定义 CountVectorizer 的token_pattern参数,这是可能的。

如果您不熟悉正则表达式,Python 的文档会介绍它如何使用该模块处理正则表达式re(scikit-learn 在后台使用它),我建议您使用像这样的在线正则表达式测试器,它可以为您提供即时反馈关于你的模式是否准确地捕捉到了你想要的东西。

token_pattern期望一个正则表达式来定义您希望矢量化器考虑一个词的内容。您尝试匹配的字符串的一个示例是此模式,从使用的默认正则表达式修改token_pattern

(?u)\b\w\w+\-\@\@\-\w+\b

应用于您的示例,您会这样做

vectorizer = CountVectorizer(token_pattern=r'(?u)\b\w\w+\-\@\@\-\w+\b')
corpus1 = ['abc-@@-123','cde-@@-true','jhg-@@-hud']
xtrain = vectorizer.fit_transform(corpus1)
xtraindf = pd.DataFrame(xtrain.toarray())
xtraindf.columns = vectorizer.get_feature_names()

哪个返回

Index(['abc-@@-123', 'cde-@@-true', 'jhg-@@-hud'], dtype='object')

这里有一个重要的注意事项是,它总是希望你的话有 -@@- 嵌套在你的标记中。例如:

corpus2 = ['abc-@@-123','cde-@@-true','jhg-@@-hud', 'unexpected']
xtrain = vectorizer.fit_transform(corpus2)
xtraindf = pd.DataFrame(xtrain.toarray())
xtraindf.columns = vectorizer.get_feature_names()
print(xtraindf.columns)

会给你

Index(['abc-@@-123', 'cde-@@-true', 'jhg-@@-hud'], dtype='object')

如果您需要匹配不具有确切特殊字符结构的单词,您可以将特殊字符字符串包装在一个组中并使用非匹配组修饰符?:

more_robust_vec = CountVectorizer(token_pattern=r'(?u)\b\w\w+(?:\-\@\@\-)?\w+\b')
xtrain = more_robust_vec.fit_transform(corpus2)
xtraindf = pd.DataFrame(xtrain.toarray())
xtraindf.columns = more_robust_vec.get_feature_names()
print(xtraindf.columns)

哪个打印

Index(['abc-@@-123', 'cde-@@-true', 'jhg-@@-hud', 'unexpected'], dtype='object')

我希望这有帮助!