用所有可能的 3-grams 向量化 trigrams - Python

Vectorizing trigrams with all possible 3-grams - Python

我正在尝试创建一个 3-gram 模型来应用机器学习技术。

基本上我正在尝试如下:

import nltk
from sklearn.feature_extraction.text import CountVectorizer
import itertools

my_array = ['worda', 'wordb']
vector = CountVectorizer(analyzer=nltk.trigrams,ngram_range=(3,3))
vector.fit_transform(my_array)

我的词汇量:

{('o', 'r', 'd'): 0,
('r', 'd', 'a'): 1,
('r', 'd', 'b'): 2,
('w', 'o', 'r'): 3}

None 我的话有空格或特殊字符。 所以当我 运行 这个:

tr_test = vector.transform(['word1'])
print(tr_test)
print(tr_test.shape)

我明白了 return:

(0, 0)  1
(0, 1)  1
(0, 3)  1
(1, 4) #this is the shape

我觉得这个是对的。。。至少是有道理的。。。 但我想用一个包含所有 3-gram 可能性的矩阵来表示每个单词。因此,每个作品都将由一个 (1x17576) 矩阵表示。 现在我使用 1x4 矩阵(在这种特殊情况下),因为我的词汇表是根据我的数据构建的。

17576 (26^3)- 表示字母表中的所有 3 个字母组合(aaa、aab、aac 等...)

我尝试将我的词汇表设置为一个包含所有 3-gram 可能性的数组,如下所示:

#This creates an array with all 3 letters combination
#['aaa', 'aab', 'aac', ...]
keywords = [''.join(i) for i in itertools.product(ascii_lowercase, repeat = 3)]
vector = CountVectorizer(analyzer=nltk.trigrams,ngram_range=(3,3), vocabulary=keywords)

这没有用...有人知道怎么做吗?

谢谢!!!

我尝试将分析器更改为 'char',现在似乎可以工作了:

keywords = [''.join(i) for i in itertools.product(ascii_lowercase, repeat = 3)]
vector = CountVectorizer(analyzer='char', ngram_range=(3,3), vocabulary=keywords)
tr_test = vector.transform(['word1'])
print(tr_test)

输出为:

  (0, 9909)  1
  (0, 15253) 1

作为支票:

test = vector.transform(['aaa aab'])
print(test)

输出:

(0, 0)  1
(0, 1)  1