给scikit学习分类器自定义训练数据



我已经为此工作了一整天(相当吃力(。在阅读了文档和许多其他教程后,由于我缺乏经验,我不知道如何使用MultinomialNB分类器使用我自己的数据?

以下是主教程中的代码:

from sklearn.datasets import fetch_20newsgroups
from sklearn.naive_bayes import MultinomialNB
categories = ['alt.atheism', 'soc.religion.christian',
'comp.graphics', 'sci.med']
text_clf = Pipeline([('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', MultinomialNB()),
])
twenty_train = fetch_20newsgroups(subset='train',
categories=categories, shuffle=True, random_state=42)
text_clf.fit(twenty_train.data, twenty_train.target)  
docs_test = ['Graphics is love', 'the brain is part of the body']
predicted = text_clf.predict(docs_test)
for doc, category in zip(docs_test, predicted):
print('%r => %s' % (doc, twenty_train.target_names[category]))

显然,它是有效的。但是,我如何用自己的数据(存储在python字典或类似的东西中(替换fetch_20新闻组呢?下面的训练数据中的每个项目都被归类为其中一个类别,这是如何实现的?

我很感激这不是一个好问题,但在这个需要的时候,我只想了解一下这是如何运作的。感谢

几乎所有sklearnfit方法都采用训练数据列表和标签列表作为输入。在您的情况下,训练数据列表将是字符串列表(您必须在其上训练模型的文本(。如['this is my first training sample', 'this is second string', 'and this is third', ...]和另一个标签列表如['label1', 'label2', 'label1', ...]

您将把这些列表传递给拟合方法:

text_clf.fit(list_of_training_datas, list_of_labels)

predict方法将保持不变,因为它还将获取要测试的样本列表,并将返回一个包含每个测试样本的预测标签的列表。

最新更新