【问题标题】:Give scikit-learn classifier custom training data?给 scikit-learn 分类器自定义训练数据?
【发布时间】:2023-04-09 02:13:01
【问题描述】:

我整天都在为此工作(相当挣扎)。阅读了文档、许多其他教程后,由于我缺乏经验,我无法弄清楚如何将自己的数据与 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_20newsgroups?而下面训练数据中的每一项都归为一类,这是如何实现的?

我明白这不是一个好问题,但在这个需要的时候,我只是想了解它是如何工作的。谢谢

【问题讨论】:

    标签: python scikit-learn training-data


    【解决方案1】:

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

    然后你会将这些列表传递给 fit 方法:

    text_clf.fit(list_of_training_datas, list_of_labels)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-21
      • 2016-11-26
      • 2022-01-05
      • 2021-04-19
      • 2013-07-04
      • 2013-07-04
      • 2020-01-04
      • 2017-06-21
      相关资源
      最近更新 更多