用所有可能的3克矢量化三元组 - Python

时间:2017-08-19 21:36:54

标签: python machine-learning nlp n-gram

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

基本上我正在尝试如下:

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}

我的所有单词都没有空格或特殊字符。 所以当我运行时:

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

我得到了这个回报:

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

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

17576(263) - 代表字母表中的所有3个字母组合(aaa,aab,aac等......)

我试图将我的词汇量设置为一个包含所有3克可能性的数组,如下所示:

#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)

这不起作用......有人可以弄清楚如何做到这一点吗?

感谢!!!

1 个答案:

答案 0 :(得分:1)

我尝试将分析仪更改为“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