如何获得tf-idf分类器的最佳功能?

问题描述 投票:3回答:1

我有一个注释列表(文本),我必须使用一些分类器(输入)进行分类。我正在使用pipeline来执行此操作,并且我也会执行KFold,因为数据集非常小。我想用SelectKBest知道分类器的最佳功能的名称,但是由于它在pipeline中,所以我不知道如何获得最佳功能的名称。

comments是字符串列表。

def classify(classifiers, folder="tfidf-classifiers"):
    comments = get_comments()
    labels = get_labels()

    tfidf_vector = TfidfVectorizer(tokenizer=tokenizer, lowercase=False)
    stats = {}
    for i in classifiers:
        classifier = i()
        pipe = Pipeline(
            [('vectorizer', tfidf_vector), ('feature_selection', SelectKBest(chi2)), ('classifier', classifier)])

        result = cross_val_predict(pipe, comments, labels, cv=KFold(n_splits=10, shuffle=True))

        cm = confusion_matrix(result, labels, [information, non_information])
        saveHeatmap(cm, i.__name__, folder)

        report = classification_report(labels, result, digits=3, target_names=['no', 'yes'], output_dict=True)

        stats[i.__name__] = report
    return stats

我在互联网上搜索并找到了:

 pipe.named_steps['feature_selection'].get_support()

但是我不能这样做,因为我没有在管道上调用fit。我在这里使用管道:

 result = cross_val_predict(pipe, comments, labels, cv=KFold(n_splits=10, shuffle=True))

如何获得最佳的K个功能名称?

[我想要的是一个简单的单词列表,这些单词“最有效地”帮助分类员完成工作...

python scikit-learn tf-idf feature-selection tfidfvectorizer
1个回答
0
投票

来自NLP in Python: Obtain word names from SelectKBest after vectorizing

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(lowercase=True,stop_words='english')
X = vectorizer.fit_transform(df["Notes"])

from sklearn.feature_selection import chi2
chi2score = chi2(X,df['AboveAverage'])[0]

wscores = zip(vectorizer.get_feature_names(),chi2score)
wchi2 = sorted(wscores,key=lambda x:x[1]) 
topchi2 = zip(*wchi2[-20:])
show=list(topchi2)

您可以使用f_classif或其他轻松更改得分。

© www.soinside.com 2019 - 2024. All rights reserved.