2016-02-22 14 views
8

私はあなたが単語 - 単語共起行列を派生させることができるsklearnのモジュールを探しています。私は文書用語行列を得ることができますが、共起の単語語行列を得る方法についてはわかりません。単語 - 単語共出現行列

+0

いくつかのデータを追加して問題を解決しようとしましたか? – Cleb

答えて

1

あなたはCountVectorizerまたはTfidfVectorizer

コード例ではngram_rangeパラメータを使用することができます:あなたが明示的にvocabularyを使用し、あなたがカウントしたい単語の共起言いたい場合

bigram_vectorizer = CountVectorizer(ngram_range=(2, 2)) # by saying 2,2 you are telling you only want pairs of 2 words 

PARAM、すなわち:vocabulary = {'awesome unicorns':0, 'batman forever':1}

http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html

事前に定義された単語と単語の共起を持つ、わかりやすく使いやすいコードです。この場合、我々はawesome unicornsbatman foreverの共起のために追跡されています

from sklearn.feature_extraction.text import CountVectorizer 
import numpy as np 
samples = ['awesome unicorns are awesome','batman forever and ever','I love batman forever'] 
bigram_vectorizer = CountVectorizer(ngram_range=(1, 2), vocabulary = {'awesome unicorns':0, 'batman forever':1}) 
co_occurrences = bigram_vectorizer.fit_transform(samples) 
print 'Printing sparse matrix:', co_occurrences 
print 'Printing dense matrix (cols are vocabulary keys 0-> "awesome unicorns", 1-> "batman forever")', co_occurrences.todense() 
sum_occ = np.sum(co_occurrences.todense(),axis=0) 
print 'Sum of word-word occurrences:', sum_occ 
print 'Pretty printig of co_occurrences count:', zip(bigram_vectorizer.get_feature_names(),np.array(sum_occ)[0].tolist()) 

最終的な出力は、私たちのsamples提供されたデータに正確に対応し、('awesome unicorns', 1), ('batman forever', 2)です。

11

ここでは、scikit-learnでCountVectorizerを使用した私のソリューション例です。このpostを参照すると、単純に行列乗算を使って単語と単語の共起行列を得ることができます。

from sklearn.feature_extraction.text import CountVectorizer 
docs = ['this this this book', 
     'this cat good', 
     'cat good shit'] 
count_model = CountVectorizer(ngram_range=(1,1)) # default unigram model 
X = count_model.fit_transform(docs) 
Xc = (X.T * X) # this is co-occurrence matrix in sparse csr format 
Xc.setdiag(0) # sometimes you want to fill same word cooccurence to 0 
print(Xc.todense()) # print out matrix in dense format 

ます。またcount_modelに単語の辞書を参照することができ、

count_model.vocabulary_ 

それとも、あなたは対角成分で正規化したい場合は、(以前の記事で答えると呼びます)。

import scipy.sparse as sp 
Xc = (X.T * X) 
g = sp.diags(1./Xc.diagonal()) 
Xc_norm = g * XC# normalized co-occurence matrix 
関連する問題