给 scikit-learn 分类器自定义训练数据?
Give scikit-learn classifier custom training data?
我整天都在为此工作(相当挣扎)。阅读了文档和许多其他教程后,由于我的经验不足,我无法弄清楚如何将自己的数据与 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 呢?而下面训练数据中的每一项都归为其中的一个类别,这是如何实现的?
我知道这不是一个很好的问题,但在这个需要的时候,我只想了解它是如何工作的。谢谢
几乎所有 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
方法将保持不变,因为它还会获取您要测试的样本列表,并将 return 包含每个测试样本的预测标签的列表。
我整天都在为此工作(相当挣扎)。阅读了文档和许多其他教程后,由于我的经验不足,我无法弄清楚如何将自己的数据与 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 呢?而下面训练数据中的每一项都归为其中的一个类别,这是如何实现的?
我知道这不是一个很好的问题,但在这个需要的时候,我只想了解它是如何工作的。谢谢
几乎所有 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
方法将保持不变,因为它还会获取您要测试的样本列表,并将 return 包含每个测试样本的预测标签的列表。