2017-03-06 15 views
1

我想有例如無序二元語法:「貓坐在墊子上」是否有可能有無序的雙字母組在countvectorizer

[("cat","the"),("cat","sat"),("on","sat"),("on","the"),("mat","the")]

每個兩字是按字母順序排列 - 這意味着,例如,「爲了安置」將給予[("house", "to"),("house","to")],這將爲這些bigrams提供更高的頻率,同時最小化搜索空間。

我能夠獲得使用上述:
unordered_bigrams = [tuple(sorted(n)) for n in list(nltk.bigrams(words))]
但我現在想對這些一「袋的字」型載體。使用

我已下令兩字特徵向量
o_bigram_vectorizer = CountVectorizer(ngram_range=(2, 2))

所以想爲我的無序二元語法一樣......我掙扎找到CountVectorizer一個選項,可以給我這個處理選項(我看的詞彙和預處理沒有多少運氣)

回答

0

你並不真的需要一個兩字發生器如果你需要的是對可能的話給出的單詞的無序列表:

>>> from itertools import permutations 
>>> words = set("the cat sat on the mat".split()) 
>>> list(permutations(words, 2)) 
[('on', 'the'), ('on', 'sat'), ('on', 'mat'), ('on', 'cat'), ('the', 'on'), ('the', 'sat'), ('the', 'mat'), ('the', 'cat'), ('sat', 'on'), ('sat', 'the'), ('sat', 'mat'), ('sat', 'cat'), ('mat', 'on'), ('mat', 'the'), ('mat', 'sat'), ('mat', 'cat'), ('cat', 'on'), ('cat', 'the'), ('cat', 'sat'), ('cat', 'mat')] 

或者,如果你不想重複元組同樣的話,但順序不同:

>>> from itertools import combinations 
>>> list(combinations(words, 2)) 
[('on', 'the'), ('on', 'sat'), ('on', 'mat'), ('on', 'cat'), ('the', 'sat'), ('the', 'mat'), ('the', 'cat'), ('sat', 'mat'), ('sat', 'cat'), ('mat', 'cat')] 

有上productcombinationpermutation一個很好的答案上https://stackoverflow.com/a/942551/610569

+0

您好,我有這個已經 - 我更關心將這些bigrams轉換爲特徵向量,例如[[0,1,1,2,1,...],[]]可用於分類模型 – charlotte75