2017-08-08 5 views
0

私はLDAを単純なドキュメントの集合に使用しています。トピックを抽出し、抽出したトピックをフィーチャーとして使用して自分のモデルを評価することが私の目標です。見つかったアレイが暗い3.見積もりが期待値= 2

私は、評価者として多項式SVMを使用することに決めました。その良いかどうかわからない?

import itertools 
from gensim.models import ldamodel 
from nltk.tokenize import RegexpTokenizer 
from nltk.stem.porter import PorterStemmer 
from gensim import corpora, models 
from sklearn.naive_bayes import MultinomialNB 

tokenizer = RegexpTokenizer(r'\w+') 

# create English stop words list 
en_stop = {'a'} 

# Create p_stemmer of class PorterStemmer 
p_stemmer = PorterStemmer() 

# create sample documents 
doc_a = "Brocolli is good to eat. My brother likes to eat good brocolli, but not my mother." 
doc_b = "My mother spends a lot of time driving my brother around to baseball practice." 
doc_c = "Some health experts suggest that driving may cause increased tension and blood pressure." 
doc_d = "I often feel pressure to perform well at school, but my mother never seems to drive my brother to do better." 
doc_e = "Health professionals say that brocolli is good for your health." 

# compile sample documents into a list 
doc_set = [doc_a, doc_b, doc_c, doc_d, doc_e] 

# list for tokenized documents in loop 
texts = [] 

# loop through document list 
for i in doc_set: 
    # clean and tokenize document string 
    raw = i.lower() 
    tokens = tokenizer.tokenize(raw) 

    # remove stop words from tokens 
    stopped_tokens = [i for i in tokens if not i in en_stop] 

    # stem tokens 
    stemmed_tokens = [p_stemmer.stem(i) for i in stopped_tokens] 

    # add tokens to list 
    texts.append(stemmed_tokens) 

# turn our tokenized documents into a id <-> term dictionary 
dictionary = corpora.Dictionary(texts) 

# convert tokenized documents into a document-term matrix 
corpus = [dictionary.doc2bow(text) for text in texts] 


# generate LDA model 
#ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=2, id2word=dictionary, passes=20) 

id2word = corpora.Dictionary(texts) 
# Creates the Bag of Word corpus. 
mm = [id2word.doc2bow(text) for text in texts] 

# Trains the LDA models. 
lda = ldamodel.LdaModel(corpus=mm, id2word=id2word, num_topics=4, 
           update_every=1, chunksize=10000, passes=1) 


# Assigns the topics to the documents in corpus 
a=[] 
lda_corpus = lda[mm] 
for i in range(len(doc_set)): 
    a.append(lda_corpus[i]) 
    print(lda_corpus[i]) 
merged_list = list(itertools.chain(*lda_corpus)) 
print(a) 
    #my_list.append(my_list[i]) 


sv=MultinomialNB() 

yvalues = [0,1,2,3] 

sv.fit(a,yvalues) 
predictclass = sv.predict(a) 

testLables=[0,1,2,3] 
from sklearn import metrics, tree 
#yacc=metrics.accuracy_score(testLables,predictclass) 
#print (yacc) 

このコードを実行すると、このエラーメッセージが表示されます。

もこれは私がSVMにフィードLDAモデル(トピックドキュメント分布)の出力である:ここ

[[(0, 0.95533888404477663), (1, 0.014775921798986477), (2, 0.015161897773308793), (3, 0.014723296382928375)], [(0, 0.019079556242721694), (1, 0.017932434792585779), (2, 0.94498655991579728), (3, 0.018001449048895311)], [(0, 0.017957955483631164), (1, 0.017900184473362918), (2, 0.018133572636989413), (3, 0.9460082874060165)], [(0, 0.96554611572184923), (1, 0.011407838337200715), (2, 0.011537900721487016), (3, 0.011508145219463113)], [(0, 0.023306931039431281), (1, 0.022823706054846005), (2, 0.93072240824085961), (3, 0.023146954664863096)]] 

私のラベルは0,1,2,3です。

私は応答here

が見つかりましたが、私が書き留めたとき:

nsamples, nx, ny = a.shape 
d2_train_dataset = a.reshape((nsamples,nx*ny)) 

を私の場合によると、それは動作しません。実際には形状メソッドがありません。

全体トレースバックエラー

Traceback (most recent call last): 
    File "/home/saria/PycharmProjects/TfidfLDA/test3.py", line 87, in <module> 
    sv.fit(a,yvalues) 
    File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/sklearn/naive_bayes.py", line 562, in fit 
    X, y = check_X_y(X, y, 'csr') 
    File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/sklearn/utils/validation.py", line 521, in check_X_y 
    ensure_min_features, warn_on_dtype, estimator) 
    File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/sklearn/utils/validation.py", line 405, in check_array 
    % (array.ndim, estimator_name)) 
ValueError: Found array with dim 3. Estimator expected <= 2. 
+0

エラーの原因は何ですか? – vealkind

+0

@vealkindコメントありがとうございました:)トレースバックで質問を更新しました。多くのお時間ありがとうございました。 – saria

+0

@ saria-の中には、各ドキュメントのタプルのリストとしてデータが保存されています。各文書の0,1,2,3の番号は意味がありますか? 'MultinomialNB'は行列のようなオブジェクトを入力と想定しており、各ドキュメントの入力としてタプルのリストを使用しているので、あなたは問題に遭遇していると思います。 – vealkind

答えて

1

aに含まれるデータが2より大きい次元であるため、MultinomialNBfitを呼び出そうとエラーが発生しています。今構築されているように、aは各文書のタプルのリストを供給していますが、これはモデルでは許可されていません。

タプルの最初の部分はトピックラベルだけなので、タプルからその値を削除し、データを2次元の行列に再構成することができます。以下のコードは

new_a = [] 
new_y = [] 
for x in a: 
    temp_a = [] 
    sorted_labels = sorted(x, key=lambda x: x[1], reverse=True) 
    new_y.append(sorted_labels[0][0]) 
    for z in x: 
     temp_a.append(z[1]) 
    new_a.append(temp_a) 

new_aは、各文書が話題0、1、2のスコアが含まれています文書のリストになる、ということでしょう、そして3.次に、あなたのモデルに合うようにsv.fit(new_a, yvalues)を呼び出すことができます。

+0

私はあなたにどのように感謝するか分からない、本当に本当に本当にあなたの助けに感謝して、私は一種の失望していた。また、明日まで私の質問に答えるように頼んでもらえますか?このコードを変更して、コード内のいくつかの例をファイルのコレクションから読み取るようにしています。私は厳しいエラーに直面するかもしれません。問題なくうまくいくことを願っています。再び多くの人生の節約に感謝:) – saria

+0

まったく問題はありません!問題がある場合は教えてください。上記のコードには、大きなデータセットを保持したいと思うサンプルデータに基づいて2つの前提があります。最初に、私はすべての文書が各トピック(0,1,2,3など)の価値を持っていると仮定しました。第二に、私は各文書内でトピックが既にソートされており、順番に並べられていると仮定しました。大規模なデータセットに対してこれらのいずれかが当てはまらない場合は、若干の調整が行われます。 – vealkind

+0

多くの私の問題についてくれてありがとう。実際に、1つの問題を説明することは、ラベルを付けることです。 LDAを使用すると、それぞれに用語の分布でトピックが生成されます。最後に、トピックとしてラベルを付けた文書があります。だからアウトマトリックスでは行はDOCですが、カラムはfeatures.soでなければなりません。問題はSVMが各行のラベルを必要とすることです。私は4つのラベルが必要なときに30行を持っています。実行するラベルを30にする必要があります。私が行列を作成しているときに、ラベルを1列にする方法でそれを変更しなければならないようです。私の言うことは明らかですか? – saria

関連する問題