Using my own corpus for category classification in Python NLTK

梦想的初衷 提交于 2019-12-20 14:09:12

问题


I'm a NTLK/Python beginner and managed to load my own corpus using CategorizedPlaintextCorpusReader but how do I actually train and use the data for classification of text?

>>> from nltk.corpus.reader import CategorizedPlaintextCorpusReader
>>> reader = CategorizedPlaintextCorpusReader('/ebs/category', r'.*\.txt', cat_pattern=r'(.*)\.txt')
>>> len(reader.categories())
234

回答1:


Assuming you want a naive Bayes classifier with bag of words features:

from nltk import FreqDist
from nltk.classify.naivebayes import NaiveBayesClassifier

def make_training_data(rdr):
    for c in rdr.categories():
        for f in rdr.fileids(c):
            yield FreqDist(rdr.words(fileids=[f])), c

clf = NaiveBayesClassifier.train(list(make_training_data(reader)))

The resulting clf's classify method can be used on any FreqDist of words.

(But note: from your cap_pattern, it seems you have sample and a single category per file in your corpus. Please check whether that's really what you want.)



来源:https://stackoverflow.com/questions/8818265/using-my-own-corpus-for-category-classification-in-python-nltk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!