我现在正在使用 nltk 学习 naivebayes 分类器。
在文档(http://www.nltk.org/book/ch06.html)1.3文档分类中,有一个featureset示例。
featuresets = [(document_features(d), c) for (d,c) in documents]
train_set, test_set = featuresets[100:], featuresets[:100]
classifier = nltk.NaiveBayesClassifier.train(train_set)
all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())
word_features = list(all_words)[:2000] [1]
def document_features(document): [2]
document_words = set(document) [3]
features = {}
for word in word_features:
features['contains({})'.format(word)] = (word in document_words)
return features
所以特征集形式的例子是 {('contains(waste)': False, 'contains(lot)': False, ...},'neg')...}
但我想将字典形式从'contains(waste)': False更改为'contains(waste)': 2。我认为那种形式('contains(waste)':2)很好地解释了文件,因为它可以计算世界的频率。所以特征集是{('contains(waste)': 2, 'contains(lot)': 5, ...},'neg')...}
但我担心'contains(waste)': 2和'contains(waste)': 1是否与 naivebayesclassifier 完全不同。然后它无法解释'contains(waste)': 2和'contains(waste)': 1的相似性。
{'contains(lot)': 1 和 'contains(waste)': 1}和{'contains(waste)': 2 和 'contains(waste)': 1}可以与程序相同。
nltk.naivebayesclassifier 能理解单词的频率吗?
这是我使用的代码
def split_and_count_word(data):
#belongs_to : Main
#Role : make featuresets from korean words using konlpy.
#Parameter : dictionary data(dict of contents ex.{'politic':{'parliament': [content,content]}..})
#Return : list featuresets([{'word':True',...},'politic'] == featureset + category)
featuresets = []
twitter = konlpy.tag.Twitter()#Korean word splitter
for big_cat in data:
for small_cat in data[big_cat]:
#save category name needed in featuresets
category = str(big_cat[0:3])+'/'+str(small_cat)
count = 0; print(small_cat)
for one_news in data[big_cat][small_cat]:
count+=1; if count%100==0: print(count,end=' ')
#one_news is list in list so open it!
doc = one_news
#split word as using konlpy
list_of_splited_word = twitter.morphs(doc[:-63])#delete useless sentences.
#get word length is higher than two and get list of splited words
list_of_up_two_word = [word for word in list_of_splited_word if len(word)>1]
dict_of_featuresets = make_featuresets(list_of_up_two_word)
#save
featuresets.append((dict_of_featuresets,category))
return featuresets
def make_featuresets(data):
#belongs_to : split_and_count_word
#Role : make featuresets
#Parameter : list list_of_up_two_word(ex.['비누','떨어','지다']
#Return : dictionary {word : True for word in data}
#PROBLEM :(
#cannot consider the freqency of word
return {word : True for word in data}
def naive_train(featuresets):
#belongs_to : Main
#Role : Learning by naive bayes rule
#Parameter : list featuresets([{'word':True',...},'pol/pal'])
#Return : object classifier(nltk naivebayesclassifier object),
# list test_set(the featuresets that are randomly selected)
random.shuffle(featuresets)
train_set, test_set = featuresets[1000:], featuresets[:1000]
classifier = naivebayes.NaiveBayesClassifier.train(train_set)
return classifier,test_set
featuresets = split_and_count_word(data)
classifier,test_set = naive_train(featuresets)