sklearn - 从文本文档中预测多标签分类中的前3-4个标签

时间:2016-08-04 15:25:27

标签: python scikit-learn classification text-classification multilabel-classification

我目前使用MultinomialNB()设置了一个分类器CountVectorizer,用于从文本文档中提取特征,虽然效果很好,但我希望使用相同的方法来预测前3-4个标签,而不仅仅是最重要的一个。

主要原因是有c.90标签和数据输入不是很好,导致最高估计的准确率为35%。如果我可以向用户提供最可能的3-4个标签作为建议,那么我可以显着提高准确度。

有什么建议吗?任何指针都将不胜感激!

目前的代码如下:

import numpy
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.cross_validation import KFold
from sklearn.metrics import confusion_matrix, accuracy_score

df = pd.read_csv("data/corpus.csv", sep=",", encoding="latin-1")

df = df.set_index('id')
df.columns = ['class', 'text']

data = df.reindex(numpy.random.permutation(df.index))

pipeline = Pipeline([
    ('count_vectorizer',   CountVectorizer(ngram_range=(1, 2))),
    ('classifier',         MultinomialNB())
])

k_fold = KFold(n=len(data), n_folds=6, shuffle=True)

for train_indices, test_indices in k_fold:
    train_text = data.iloc[train_indices]['text'].values
    train_y = data.iloc[train_indices]['class'].values.astype(str)

    test_text = data.iloc[test_indices]['text'].values
    test_y = data.iloc[test_indices]['class'].values.astype(str)

    pipeline.fit(train_text, train_y)
    predictions = pipeline.predict(test_text)
    confusion = confusion_matrix(test_y, predictions)

    accuracy = accuracy_score(test_y, predictions)
    print accuracy

2 个答案:

答案 0 :(得分:2)

完成预测后,您可以获得每个标签的概率:

labels_probability = pipeline.predict_proba(test_text)

您将获得每个标签的概率。见http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline.predict_proba

答案 1 :(得分:0)

要获得前N个标签,请执行以下操作:

import numpy as np

n = 3
top_n_predictions = np.argsort(probas, axis=1)[:, -n:]