2017-11-30 16 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

다른 것들을 시도했지만 효과가있는 것을 찾을 수 없었습니다. 나는 단지 두 가지 이유로 그것을 포함 시켰습니다. 우선, 나는 누군가가 "이 질문이 묻 혔고 여기는 대답이다"라고 신속하게 말할 것이라고 생각했다. 그래서 나는 그 질문이 질문되었다는 것을 알고있다. 둘째로, 다른 사람들은 그 대답에 운이 좋았습니다. 그래서 나는 그것이 해결책에 가깝다고 가정하고 제공되는 어떤 도움은 그것으로 땜질하는 것으로 이루어질 것입니다; 결과적으로, 그것이 가능할 때 내 대답을 맹목적으로 정리하는 것은 (a) 능률도 아니고 (b) 합리적인 것도 아닙니다. – thewhitetie

+0

다른 사람에게는 효과적이지만 다른 사람에게는 효과가 없다면 다른 일을해야합니다. 그것이 우리가 알아 내야 할 것입니다. – Rob

답변

0

당신은 vectorizer.get_feature_names()를 호출하기 전에 CountVectorizer에 맞게해야합니다. 귀하의 코드에서, 당신은 오직 CountVectorizer 클래스를 가진 다른 함수를 호출 할뿐입니다.

당신이 더 문제에 스스로를 적응해야하지만, 이미 제공하는 기능을 CountVectorizer와 벡터화를 만든 다음 텍스트에 fit 전화, 결국 사용하는 파이프 라인에서 independtly 시도해야

.

사용하는 기능에 클래스가 아닌 인스턴스화 된 객체가 필요하다는 것을 쉽게 이해해야합니다. 네가하지 않으면 말해봐.

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

그건 의미가 있습니다. 고맙습니다!(\t'VECT = CountVectorizer (STOP_WORDS의 = '영어') \t vect_to_use = vect.fit (헤드 라인) \t show_most_informative_features을 vect_to_use을 : 나는 (이상없는 줄 바꿈 형식에 대해 사과) 내'scikit_naivebayes' 기능에 다음을 추가했다 , cf1)' 그런데'show_most_informative_features'는'AttributeError : 'Pipeline'객체에 'coef_'' 속성이 없습니다. – thewhitetie

+0

올바르게 벡터화를 초기화하지 않았습니까? 어느 쪽이든, 내가 간과 한 것을 제출해 주셔서 감사합니다. – thewhitetie

+1

답변을 업데이트했습니다! – Elliot