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'
다른 사람의 답변을 자신의 것으로 사용하지 마십시오. 그것은 당신이 아무것도 작동시키지 않았 음을 의미합니다. 이 일에 어떤 노력을 기울 였는지, 그리고 무엇을 발견했는지를 보여줄 필요가 있습니다. 우리를 당신을 위해 일하게하지 마십시오. [mcve] – Rob
다른 것들을 시도했지만 효과가있는 것을 찾을 수 없었습니다. 나는 단지 두 가지 이유로 그것을 포함 시켰습니다. 우선, 나는 누군가가 "이 질문이 묻 혔고 여기는 대답이다"라고 신속하게 말할 것이라고 생각했다. 그래서 나는 그 질문이 질문되었다는 것을 알고있다. 둘째로, 다른 사람들은 그 대답에 운이 좋았습니다. 그래서 나는 그것이 해결책에 가깝다고 가정하고 제공되는 어떤 도움은 그것으로 땜질하는 것으로 이루어질 것입니다; 결과적으로, 그것이 가능할 때 내 대답을 맹목적으로 정리하는 것은 (a) 능률도 아니고 (b) 합리적인 것도 아닙니다. – thewhitetie
다른 사람에게는 효과적이지만 다른 사람에게는 효과가 없다면 다른 일을해야합니다. 그것이 우리가 알아 내야 할 것입니다. – Rob