gpt4 book ai didi

python - Scikit-learn 多标签分类

转载 作者:太空宇宙 更新时间:2023-11-03 16:27:48 25 4
gpt4 key购买 nike

我正在尝试使用 Scikit-learn 了解文本的多标签分类,我正在尝试改编 scikit 附带的初始示例教程之一,以使用维基百科文章作为训练数据进行语言分类。我正在尝试在下面实现这一点,但代码仍然为每个我希望最后一个预测返回 fr, en 的位置返回一个标签

有人可以建议启用多标签分类的正确方法吗?

import sys

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.datasets import make_multilabel_classification
from sklearn.preprocessing import LabelBinarizer

from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_files
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.multiclass import OneVsRestClassifier
#change model_selection to cross_validation

# The training data folder must be passed as first argument - This uses the example wiki language data files
languages_data_folder = sys.argv[1]
dataset = load_files(languages_data_folder)

# Split the dataset in training and test set:
docs_train, docs_test, y_train, y_test = train_test_split(
dataset.data, dataset.target, test_size=0.5)


#pipeline
clf = Pipeline([
('vectorizer', CountVectorizer(ngram_range=(1,2))),
('tfidf', TfidfTransformer()),
('clf', OneVsRestClassifier(LinearSVC())),
])
target_names=dataset.target_names



# TASK: Fit the pipeline on the training set
clf.fit(docs_train, y_train)

# TASK: Predict the outcome on the testing set in a variable named y_predicted
y_predicted = clf.predict(docs_test)

print target_names


# Predict the result on some short new sentences:
sentences = [
u'This is a language detection test.',
u'Ceci est un test de d\xe9tection de la langue.',
u'Dies ist ein Test, um die Sprache zu erkennen.',
u'Bonjour Mon ami. This is a language detection test.',

]
predicted = clf.predict(sentences)

for s, p in zip(sentences, predicted):
print(u'The language of "%s" is "%s"' % (s, target_names[p]))

返回 -

“这是语言检测测试”的语言。是“en”

“Ceci est un test de détection de la langue”的语言。是“fr”

“Dies ist ein Test, um die Sprache zu erkennen”的语言。是“德”

“Bonjour Mon ami。这是语言检测测试”的语言。是“en”

最佳答案

您可以使用scikit-multilearn对于多标签分类,它是一个构建在 scikit-learn 之上的库。对于语言来说,标签之间的相关性并不那么重要,因此二元分类器应该非常适合。您可以在documentation中找到如何进行分类的示例。但就你而言,你需要的是替换:

('clf', OneVsRestClassifier(LinearSVC())),

('clf', BinaryRelevance(LinearSVC())),

并在顶部添加导入:

from skmultilearn.problem_transform import BinaryRelevance

记住先安装 scikit-multilearn!

关于python - Scikit-learn 多标签分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37858697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com