python - 使用所有可能的 3 元组向量化三元组 - Python

标签 python machine-learning nlp n-gram

我正在尝试创建一个 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}

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

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-gram 可能性的矩阵来表示每个单词。因此,每件作品都由一个 (1x17576) 矩阵表示。 现在我使用 1x4 矩阵(在本例中),因为我的词汇表是基于我的数据构建的。

17576 (26ˆ3)- 表示字母表中的所有 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)

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

谢谢!!!

最佳答案

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

关于python - 使用所有可能的 3 元组向量化三元组 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45776505/

相关文章:

python - 有没有办法检查python中两个完整句子之间的相似性?

python - Sklearn 随机森林回归器出错

python - conv2d 层的输入 0 与层 : expected axis -1 of input shape to have value 1 but received input with shape [None, 64, 64, 3 不兼容]

python - TensorFlow 相当于 PyTorch 的 transforms.Normalize()

python - 将列表元素添加到多行字符串

machine-learning - Spark:单词分类

python - NLTK - nltk.tokenize.RegexpTokenizer - 正则表达式未按预期工作

machine-learning - 如何学习语言模型?

python - 如何从数据帧创建网络图

python - matplotlib 中带有欧元符号的刻度