【问题标题】:Vectorizing trigrams with all possible 3-grams - Python用所有可能的 3-gram 向量化三元组 - Python
【发布时间】:2018-01-28 07:29:43
【问题描述】:

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

这不起作用...有人能弄清楚怎么做吗?

谢谢!!!

【问题讨论】:

    标签: python machine-learning nlp n-gram


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2017-04-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多