2017-11-30 6 views
0

は私が学んSciKitでバイナリNBのための最も有益な機能機能を実装したいです。私はPython3を使用しています。有益な特長

まず第一に、私はSciKitの多項NBのための「情報提供機能」関数のいくつかの並べ替えを実装するための質問が尋ねてきたことを理解しています。しかし、私はレスポンスを試してみたが運がなかったので、SciKitを更新したか、何か非常に間違っていると思う。私は tobigueのanswer here機能のために使用しています。

from nltk.corpus import stopwords 
import numpy as np 
from sklearn.naive_bayes import MultinomialNB 
from sklearn.pipeline import Pipeline 
from sklearn.feature_extraction.text import TfidfVectorizer 
from sklearn.feature_extraction.text import TfidfTransformer 
from sklearn.feature_extraction.text import CountVectorizer 
from sklearn.model_selection import GridSearchCV 
from sklearn.model_selection import train_test_split 



#Array contains a list of (headline, source) tupples where there are two sources. 
#I want to classify each headline as belonging to a given source. 
array = [('toyota showcases humanoid that mirrors user', 'drudge'), ('virginia again delays vote certification after error in ballot distribution', 'npr'), ("do doctors need to use computers? one physician's case highlights the quandary", 'npr'), ('office sex summons', 'drudge'), ('launch calibrated to avoid military response?', 'drudge'), ('snl skewers alum al franken, trump sons', 'npr'), ('mulvaney shows up for work at consumer watchdog group, as leadership feud deepens', 'npr'), ('indonesia tries to evacuate 100,000 people away from erupting volcano on bali', 'npr'), ('downing street blasts', 'drudge'), ('stocks soar more; records smashed', 'drudge'), ('aid begins to filter back into yemen, as saudi-led blockade eases', 'npr'), ('just look at these fancy port-a-potties', 'npr'), ('nyt turns to twitter activism to thwart', 'drudge'), ('uncertainty reigns in battle for virginia house of delegates', 'npr'), ('u.s. reverses its decision to close palestinian office in d.c.', 'npr'), ("'i don't believe in science,' says flat-earther set to launch himself in own rocket", 'npr'), ("bosnian war chief 'dies' after being filmed 'drinking poison' at the hague", 'drudge'), ('federal judge blocks new texas anti-abortion law', 'npr'), ('gm unveils driverless cars, aiming to lead pack', 'drudge'), ('in japan, a growing scandal over companies faking product-quality data', 'npr')] 


#I want to classify each headline as belonging to a given source. 
def scikit_naivebayes(data_array): 
    headlines = [element[0] for element in data_array] 
    sources = [element[1] for element in data_array] 
    text_clf = Pipeline([('vect', CountVectorizer(stop_words='english')), ('tfidf', TfidfTransformer()),('clf', MultinomialNB())]) 
    cf1 = text_clf.fit(headlines, sources) 
    train(cf1,headlines,sources) 

    #Call most_informative_features function on CountVectorizer and classifier 
    show_most_informative_features(CountVectorizer, cf1) 


def train(classifier, X, y): 
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=33) 
    classifier.fit(X_train, y_train) 
    print ("Accuracy: {}".format(classifier.score(X_test, y_test))) 


#tobigue's code: 
def show_most_informative_features(vectorizer, clf, n=20): 
    feature_names = vectorizer.get_feature_names() 
    coefs_with_fns = sorted(zip(clf.coef_[0], feature_names)) 
    top = zip(coefs_with_fns[:n], coefs_with_fns[:-(n + 1):-1]) 
    for (coef_1, fn_1), (coef_2, fn_2) in top: 
    print ("\t%.4f\t%-15s\t\t%.4f\t%-15s" % (coef_1, fn_1, coef_2, fn_2)) 


def main(): 
    scikit_naivebayes(array) 


main() 

#ERROR: 
# File "file_path_here", line 34, in program_name 
# feature_names = vectorizer.get_feature_names() 
# TypeError: get_feature_names() missing 1 required positional argument: 'self' 
+0

のために外を見る必要があります。それはあなたがそれを働かせるために何かを試していないことを意味します。あなたはこれにどのような努力を払い、あなたが何を発見したのかを示す必要があります。私たちがあなたのために仕事をしないようにしてください。 [mcve] – Rob

+0

私は別のものを試しましたが、うまくいかないものは見つかりませんでした。私は単にそれを2つの理由から含めました。まず、誰かがすぐに「この質問は尋ねられました、ここは答えです」と言いました。質問がされたことを認識しています。第二に、他の人はその答えで運が良かったので、私はそれが解決策に近いと仮定しています。したがって、それが利用可能であったときに自分の答えを盲目的にコード化することは、(a)効率的でも(b)合理的でもない。 – thewhitetie

+0

それ以外の人にはうまくいくが、それ以外の人には当てはまらない場合は、何か異なることがあるはずです。それが私たちが知る必要があるものです。 – Rob

答えて

0

あなたはvectorizer.get_feature_names()を呼び出す前にCountVectorizerに合うようにする必要があります。あなたのコードでは、あなたはクラスCountVectorizerで他の関数を呼び出すだけで何もできません。

CountVectorizerでベクターライザーを作成してから、テキストにfitを呼び出し、最終的には既に提供されている機能を使用することをお勧めします。

あなたは、あなたが使う関数がクラスインスタンス化オブジェクトを必要としないことを簡単に理解する必要があります。あなたがしなければ教えてください。

coef_

編集は推定でのみアクセス属性、すなわち分類器(およびすべてではない)です。 Pipelineは、分類器にフィードするために異なるステップを組み合わせるために使用されるsklearnオブジェクトです。一般的に、袋の-言葉パイプラインが特徴抽出と分類器(ここではロジスティック回帰)によってconstituedさ:

pipeline = Pipeline([ 
('vectorizer', CountVectorizer(args)), 
('classifier', LogisticRegression() 
]) 

だから、あなたのケースでは、あなたは、パイプラインを使用しないでくださいどちらか(私はあなたが開始することをお勧めしますどのような)、またはパイプラインからget_params()メソッドを使用して分類器にアクセスします。それはあなたが動作するかどう

vectorizer = CountVectorizer(stop_words='english') 
X = vectorizer.fit_transform(headlines, sources) 
naive_bayes = MultinomialNB() 
naive_bayes.fit(X, sources) 
show_most_informative_features(vectorizer, naive_bayes) 

ファーストはそれをしてみてください、と私はあなたがテキストをfit_transformすることをお勧め

は、その後、ロジスティック回帰やナイーブベイズ分類器に変換結果を供給した後、あなたが持っている機能を呼び出しますパイプラインの使い方を理解しています。フィジカル・エクストラクタと組み合わせてパイプラインを動作させるべきではないことに注意してください。最後のステップはエスカレータです。あなたは機能抽出にスタックする場合は、あなた自身のように誰かの他の人の答えを使用しないでくださいFeatureUnion

+0

それは理にかなっています。ありがとうございました!私は(奇妙な無改行の書式をお詫び申し上げます)私の 'scikit_naivebayes'機能に以下を追加しました:\t' VECT = CountVectorizer(stop_words = '英語')を \t vect_to_use = vect.fit(見出し) \t show_most_informative_features(vect_to_use 、cf1) ' しかし、' show_most_informative_features'は 'AttributeError: 'Pipeline'オブジェクトに 'coef_''属性がありません。 – thewhitetie

+0

正しくベクトル化されていませんか?いずれにせよ、私が見落としたものを出してくれてありがとう。 – thewhitetie

+1

私は答えを更新しました! – Elliot

関連する問題