python.nlp随笔(七)贝叶斯,决策树分类

回答下列问题:

(1)怎样才能识别出语言数据中明显用于分类的特征?

(2)怎样才能构建用于自动执行语言处理任务的语言模型?

(3)从这些模型中我们可以学到哪些关于语言的知识?

决策树,朴素贝叶斯分类器和最大熵(shang)分类

一 监督式分类

#性别鉴定

创建分类

[python]  view plain  copy
  1. def gender_features(word):  
  2.     return {'last_letter': word[-1]}  
  3. gender_features('Shrek')  
  4. {'last_letter''k'}  
  5.   
  6. from nltk.corpus import names  
  7. import random  
  8. names = ([(name, 'male'for name in names.words('male.txt')] +   
  9.          [(name, 'female'for name in names.words('female.txt')])  
  10. random.shuffle(names)  
  11.   
  12. import nltk  
  13. featuresets = [ (gender_features(n), g) for (n,g) in names ]  
  14. train_set, test_set = featuresets[500:], featuresets[:500]   #训练集和测试集  
  15. classifier = nltk.NaiveBayesClassifier.train(train_set)  
  16.   
  17. classifier.classify(gender_features('Neo'))  
  18. 'male'  
  19. classifier.classify(gender_features('Trinity'))  
  20. 'female'  
  21. print nltk.classify.accuracy(classifier, test_set)   #评估  
  22. <span style="color:#ff0000;">0.75</span>  
  23. classifier.show_most_informative_features(5)  #哪些特征对于区分名字的性别是最有效的  
  24. Most Informative Features  
  25.              last_letter = u'a'           female : male   =     33.4 : 1.0  
  26.              last_letter = u'k'             male : female =     30.8 : 1.0  
  27.              last_letter = u'f'             male : female =     17.3 : 1.0  
  28.              last_letter = u'p'             male : female =     10.5 : 1.0  
  29.              last_letter = u'd'             male : female =     10.0 : 1.0  

#选择正确的特征

[python]  view plain  copy
  1. def gender_features2(name):  
  2.     features = {}  
  3.     features["firstletter"] = name[0].lower()  
  4.     features["lastletter"] = name[-1].lower()  
  5.     for letter in 'abcdefghijklmnopqrstuvwxyz':  
  6.         features["count(%s)" % letter] = name.lower().count(letter)  
  7.         features["has(%s)" % letter] = (letter in name.lower())  
  8.     return features  
  9. gender_features2('JJohn')  
  10.   
  11. featuresets = [(gender_features2(n), g) for (n,g) in names]  
  12. train_set, test_set = featuresets[500:], featuresets[:500]  
  13. classifier = nltk.NaiveBayesClassifier.train(train_set)  #使用朴素贝叶斯分类器  
  14. print nltk.classify.accuracy(classifier, test_set)  
  15. 0.776  
[python]  view plain  copy
  1. #一种能有效完善特征集的方法称为错误分析。首先,选择开发集,其中包含用于创建模型的语料数据。然后将这种开发集分为训练集和开发测试集  
  2. train_names = names[1500:]  
  3. devtest_names = names[500:1500]  
  4. test_names = names[:500]  
  5. train_set = [(gender_features(n), g) for (n,g) in train_names]  
  6. devtest_set = [(gender_features(n),g) for (n,g) in devtest_names]  
  7. test_set = [(gender_features(n),g) for (n,g) in test_names]  
  8. classifier = nltk.NaiveBayesClassifier.train(train_set)  
  9. print nltk.classify.accuracy(classifier, devtest_set)  
  10. <span style="color:#ff0000;">0.766</span>  
[python]  view plain  copy
  1. errors = []  
  2. for (name, tag) in devtest_names:  
  3.     guess = classifier.classify(gender_features(name))  
  4.     if guess != tag:  
  5.         errors.append( (tag, guess, name) )  
  6. for (tag, guess, name) in sorted(errors):    
  7.     print 'correct=%-8s guess=%-8s name=%-30s' % (tag, guess, name)  
  8. correct=female   guess=male     name=Abagael                         
  9. correct=female   guess=male     name=Adel                            
  10. correct=female   guess=male     name=Alys                            
  11. correct=female   guess=male     name=Amargo                          
  12. correct=female   guess=male     name=Ambur  
[python]  view plain  copy
  1. ...        

[python]  view plain  copy
  1. #调整特征提取器使其包含两个字母后缀的特征  
  2. def gender_features(word):  
  3.     return {'suffix1': word[-1:],  
  4.             'suffix2': word[-2:]}  
  5. train_set = [(gender_features(n), g) for (n,g) in train_names]  
  6. devtest_set = [(gender_features(n),g) for (n,g) in devtest_names]  
  7. classifier = nltk.NaiveBayesClassifier.train(train_set)  
  8. print nltk.classify.accuracy(classifier, devtest_set)  

#文档分类

将电影评论语料库归类为正面或负面

[python]  view plain  copy
  1. from nltk.corpus import movie_reviews  
  2. documents = [(list(movie_reviews.words(fileid)), category)  
  3.               for category in movie_reviews.categories()  
  4.               for fileid in movie_reviews.fileids(category)]  
  5. random.shuffle(documents)  
<text, categories>

[python]  view plain  copy
  1. #文档分类的特征提取器,其特征表示每个词是否在一个给定的文档中  
  2. all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())  
  3. word_features = all_words.keys()[:2000]  
  4. def document_features(document):  
  5.     document_words = set(document)  
  6.     features = {}  
  7.     for word in word_features:  
  8.         features['contains(%s)' % word] = (word in document_words)  
  9.     return features  
  10. print document_features(movie_reviews.words('pos/cv957_8737.txt'))  
  11. {u'contains(corporate)'False, u'contains(barred)'False, u'contains(batmans)'False, u'contains(menacing)'False,   
[python]  view plain  copy
  1. u'contains(rags)'False, u'contains(inquires)'False,   

[python]  view plain  copy
  1. #训练和测试分类器以进行文档分类  
  2. featuresets = [(document_features(d),c) for (d,c) in documents]  
  3. train_set, test_set = featuresets[100:], featuresets[:100]  
  4. classifier = nltk.NaiveBayesClassifier.train(train_set)  
  5. print nltk.classify.accuracy(classifier, test_set)  
  6. 0.73  
[python]  view plain  copy
  1. classifier.show_most_informative_features(5)  #找出哪些特征是分类器发现的并且是最有信息量的  
  2. Most Informative Features  
  3.           contains(sans) = True              neg : pos    =      9.1 : 1.0  
  4.     contains(mediocrity) = True              neg : pos    =      7.8 : 1.0  
  5.      contains(dismissed) = True              pos : neg    =      6.9 : 1.0  
  6.      contains(testament) = True              pos : neg    =      6.5 : 1.0  
  7.    contains(bruckheimer) = True              neg : pos    =      6.4 : 1.0  

#词性标注

[python]  view plain  copy
  1. from nltk.corpus import brown  
  2. suffix_fdist = nltk.FreqDist()  
  3. for word in brown.words():  
  4.     word = word.lower()  
  5.     suffix_fdist[word[-1:]] += 1  
  6.     suffix_fdist[word[-2:]] += 1  
  7.     suffix_fdist[word[-3:]] += 1  
  8. from operator import itemgetter  
  9. common_suffixes = sorted(suffix_fdist.items(), key=itemgetter(1), reverse=True)  
  10. common_suffixes[:100]  
  11. [(u'e'202946),  
  12.  (u','175002),  
  13.  (u'.'152999),  
  14.  (u's'128722),  
  15.  (u'd'105687),  
  16.  (u't'94459),  
[python]  view plain  copy
  1. common_suf = [ suffix[0for suffix in common_suffixes][:100]  
[python]  view plain  copy
  1. common_suf  
[python]  view plain  copy
  1.   
 
   
 
   
 
   

[python]  view plain  copy
  1. def pos_features(word):  
  2.     features = {}  
  3.     for suffix in common_suf:  
  4.         features['endswith(%s)'%suffix] = word.lower().endswith(suffix)  
  5.     return features  
训练新的“决策树”的分类器

[python]  view plain  copy
  1. tagged_words = brown.tagged_words(categories='news')  
  2. tagged_words[0]  
  3. (u'The', u'AT')  
  4. len(tagged_words)  
  5. 100554  
  6. len(pos_features(tagged_words[0][0]))  
  7. 100  
  8. pos_features(tagged_words[0][0])  
  9. {u"endswith('')"False,  
  10.  u"endswith(')"False,  
  11.  u"endswith('s)"False,  
  12.  u'endswith(()'False,  
  13.  u'endswith())'False,  
  14.  u'endswith(,)'False,  
  15. featuresets = [(pos_features(n),g) for (n,g) in tagged_words]  
  16. size = int(len(featuresets) * 0.1)  
  17. size  
  18. Out[52]:  10055  
  19. train_set,test_set = featuresets[size:], featuresets[:size]  
[python]  view plain  copy
  1. classifier = nltk.DecisionTreeClassifier.train(train_set)   #决策树  
  2. nltk.classify.accuracy(classifier, test_set)  
  3. <span style="color:#ff0000;">0.6270512182993535</span>  
  4. classifier.classify(pos_features('cats'))  
  5. Out[54]:  u'NNS'  
  6. #决策树的优点是容易解释,甚至可以它们以伪代码形式输出  
  7. print classifier.pseudocode(depth=4)  
  8. if endswith(the) == False:   
  9.   if endswith(,) == False:   
  10.     if endswith(s) == False:   
  11.       if endswith(.) == Falsereturn u'.'  
  12.       if endswith(.) == Truereturn u'.'  
  13.     if endswith(s) == True:   
  14.       if endswith(is) == Falsereturn u'PP$'  
  15.       if endswith(is) == Truereturn u'BEZ'  
  16.   if endswith(,) == Truereturn u','  
  17. if endswith(the) == Truereturn u'AT'  

#探索上下文语境

不是只传递已标注的词,而是传递整个(未标注的)句子,以及目标词的索引

#特征检测器

[python]  view plain  copy
  1. def pos_features(sentence, i):  
  2.     features = {"suffix(1)": sentence[i][-1:],  
  3.                 "suffix(2)": sentence[i][-2:],  
  4.                 "suffix(3)": sentence[i][-3:]}  
  5.     if i == 0:  
  6.         features["prev-word"] = "<START>"  
  7.     else:  
  8.         features["prev-word"] = sentence[i-1]  
  9.     return features  
  10. brown.sents()[0][7]  
  11. Out[62]:  u'an'  
  12. brown.sents()[0][8]  
  13. Out[63]:  u'investigation'  
  14. pos_features(brown.sents()[0], 8)    ###### 四个特征  
  15. {'prev-word': u'an',  
  16.  'suffix(1)': u'n',  
  17.  'suffix(2)': u'on',  
  18.  'suffix(3)': u'ion'}  
>>>

[python]  view plain  copy
  1. tagged_sents = brown.tagged_sents(categories='news')  
  2. featuresets = []  
  3. for tagged_sent in tagged_sents:  
  4.     untagged_sent = nltk.tag.untag(tagged_sent)  
  5.     for i, (word, tag) in enumerate(tagged_sent):  
  6.         featuresets.append( (pos_features(untagged_sent, i), tag) )  
  7. size = int(len(featuresets) * 0.1)  
  8. 10055  
[python]  view plain  copy
  1. train_set, test_set = featuresets[size:], featuresets[:size]  
  2. classifier = nltk.NaiveBayesClassifier.train(train_set)  
  3. nltk.classify.accuracy(classifier, test_set)  
  4. <span style="color:#ff0000;">0.7891596220785678</span>  

#序列分类

在词性标注的例子中,可以使用各种不同的序列分类器模型为给定的句子中的所有词选择词性标注

一种称为连续分类或贪婪序列分类的序列分类器策略,为第一个输入找到最有可能的类标签,然后在此基础上找到下一个输入的最佳的标签。这个过程可以不断重复直到所有的输入都被贴上标签。

特征提取器

[python]  view plain  copy
  1. def pos_features(sentence, i, history):  
  2.     features = {"suffix(1)": sentence[i][-1:],  
  3.                 "suffix(2)": sentence[i][-2:],  
  4.                 "suffix(3)": sentence[i][-3:] }  
  5.     if i == 0:  
  6.         features["prev-word"] = "<START>"  
  7.         features["prev-tag"] = "<START>"  
  8.     else:  
  9.         features["prev-word"] = sentence[i-1]  
  10.         features["pre-tag"] = history[i-1]  
  11.     return features  
[python]  view plain  copy
  1. class ConsecutivePosTagger(nltk.TaggerI):  
  2.     def __init__(self, train_sents):  
  3.         train_set = []  
  4.         for tagged_sent in train_sents:  
  5.             untagged_sent = nltk.tag.untag(tagged_sent)  
  6.             history = []  
  7.             for i, (word, tag) in enumerate(tagged_sent):  
  8.                 featureset = pos_features(untagged_sent, i, history)  
  9.                 train_set.append((featureset, tag))  
  10.                 history.append(tag)   ######  
  11.             self.classifier = nltk.NaiveBayesClassifier.train(train_set)  
  12.     def tag(self, sentence):  
  13.         history = []  
  14.         for i, word in enumerate(sentence):  
  15.             featureset = pos_features(sentence, i, history)  
  16.             tag = self.classifier.classify(featureset)  
  17.             history.append(tag)  
  18.         return zip(sentence, history)  
[python]  view plain  copy
  1. tagged_sents = brown.tagged_sents(categories='news')  
  2. size = int(len(tagged_sents) * 0.1)  
  3. train_sents, test_sents = tagged_sents[size:], tagged_sents[:size]  
  4. tagger = ConsecutivePosTagger(train_sents)  
  5. print tagger.evaluate(test_sents)  

#其他序列分类方法

这种方法的缺点是一旦做出决定便无法更改。例如:如果决定将一个词标注为名词,但后来发现应该是动词,那也没有办法修复我们的错误了。解决这个问题的方法是采取转型策略。转型联合分类的工作原理是为输入的标签创建一个初始值,然后反复提炼该值,尝试修复相关输入之间的不一致

另一种方案是为词性标记所有可能的序列打分,选择总得分最高的序列。隐马尔科夫模型就采取了这种方法。隐maerkefumox类似于连续分类器,不光考虑输入也考虑已预测标记的历史。然而,不是简单地找出一个给定词的单个最好标签,而是为标记产生一个概率分布。然后这些概率结合起来计算标记序列的概率得分,最后选择最高概率的标记序列。不过,可能的标签序列数量相当大。给定拥有30个标签的标记集,大约有600万亿(30^10)中方式来标记一个10个词的句子。为了避免单独考虑所有这些可能的序列,隐马尔科夫模型要求特征提取器只考虑最近的标记(或最近的n个标记,其中n是相当小的)。由于这种限制,它可以使用动态规划来有效地找出最有可能的标记序列。特别是,对每个连续的词索引i,当前的及以前的每个可能的标记都将计算得分。这种基础的方法被两个更先进的模型所采用,它们被称为最大熵马尔科夫模型和线性链条件随机场模型;但为标记序列打分用的是不同的算法。

二 监督式分类的举例

#句子分割

第一步是获得一些已被分割成句子的数据,将它转换成一种适合提取特征的形式

[python]  view plain  copy
  1. sents = <span style="color:#ff0000;">nltk.corpus.treebank_raw.sents</span>()  
  2. tokens = []  
  3. boundaries = set()  
  4. offset = 0  
  5. for sent in nltk.corpus.treebank_raw.sents():  
  6.     tokens.extend(sent)  
  7.     offset += len(sent)  
  8.     boundaries.add(offset - 1)  
[python]  view plain  copy
  1. def punct_features(tokens, i):  
  2.     return { 'next-word-capitailized': tokens[i+1][0].isupper(),  
  3.              'prevword': tokens[i-1].lower(),  
  4.              'punct': tokens[i],  
  5.              'prev-word-is-one-char': len(tokens[i-1]) == 1}  
[python]  view plain  copy
  1. featuresets = [(punct_features(tokens, i), (i in boundaries)) for i in range(1, len(tokens)-1if tokens[i] in '.?!']  
  2. size = int(len(featuresets) * 0.1)  
  3. train_set, test_set = featuresets[size:], featuresets[:size]  
  4. classifier = nltk.NaiveBayesClassifier.train(train_set)  
  5. nltk.classify.accuracy(classifier, test_set)  
  6. 0.936026936026936  

[python]  view plain  copy
  1. def segment_sentences(words):  #基于分类的断句器  
  2.     start = 0  
  3.     sents = []  
  4.     for i, word in words:  
  5.         if word in '.?!' and classifier.classify(punct_features(words, i)) == True:  
  6.             sents.append(words[start:i+1])  
  7.             start = i+1  
  8.     if start < len(words):  
  9.         sents.append(words[start:])  
  10.         return sents  

#识别对话行为类型

表述行为的陈述句,问候,问题,回答,断言和说明都可以被认为是基于语言的行为类型。识别对话中隐含言语下的对话行为是理解谈话的重要步骤。

利用NPS聊天语料库建立一个分类器,用来识别新的即时消息帖子的对话行为类型

[python]  view plain  copy
  1. posts = nltk.corpus.nps_chat.xml_posts()[:10000]   #每个帖子的XML注释  
[python]  view plain  copy
  1. def dialogue_act_features(post):   #特征提取器  
  2.     features = {}  
  3.     for word in nltk.word_tokenize(post):  
  4.         features['contains(%s)' % word.lower()] = True  
  5.     return features  
  6. featuresets = [(dialogue_act_features(post.text), post.get('class')) for post in posts]  
  7. ({'contains(gay)'True,  
  8.   'contains(im)'True,  
  9.   'contains(left)'True,  
  10.   'contains(name)'True,  
  11.   'contains(now)'True,  
  12.   'contains(this)'True,  
  13.   'contains(with)'True},  
  14.  '<span style="color:#ff0000;">Statement</span>')  #陈述句  
[python]  view plain  copy
  1. size = int(len(featuresets) * 0.1)   #分类器  
  2. train_set, test_set = featuresets[size:], featuresets[:size]  
  3. classifier = nltk.<span style="color:#ff0000;">NaiveBayesClassifier</span>.train(train_set)  
  4. print nltk.classify.accuracy(classifier, test_set)  
  5. 0.668  

#识别文字蕴涵

(Recognizing textual entailment, RTE)是判断文本T内的一个给定片段是否继承另一个叫做“假设”的文本。迄今为止,已经有4个RTE挑战赛,在那里共享的开发和测试数据会提供给参赛队伍。

[python]  view plain  copy
  1. def rte_features(rtepair):  
  2.     extractor = nltk.RTEFeatureExtractor(rtepair)  
  3.     features = {}  
  4.     features['word_overlap'] = len(extractor.overlap('word'))  
  5.     features['word_hyp_extra'] = len(extractor.hyp_extra('word'))  
  6.     features['ne_overlap'] = len(extractor.overlap('ne'))  
  7.     features['ne_hyp_extra'] = len(extractor.hyp_extra('ne'))  
  8.     return features  
[python]  view plain  copy
  1. rtepair = nltk.corpus.rte.pairs(['rte3_dev.xml'])[33]  
  2. extractor = nltk.RTEFeatureExtractor(rtepair)  
  3. print extractor.text_words  
  4. set(['Organisation''Shanghai''Asia''four''at''operation''SCO''Iran''Soviet''Davudi''fight''China''association''fledgling''was''that''republics''former''Co''representing''Russia''Parviz''central''meeting''together''binds''terrorism.'])  
[python]  view plain  copy
  1. print extractor.hyp_words  
  2. set(['member''SCO.''China'])  
  3. print extractor.overlap('word')  
  4. set([])  
  5. print extractor.overlap('ne')  
  6. set(['China'])  
  7. print extractor.hyp_extra('word')  
  8. set(['member'])  

#扩展到大型数据集

纯Python的分类不是很快,建议探索NLTK与外部机器学习包的接口技术,

三 评估

测试集

准确度

精确度和召回率

混淆矩阵

交叉验证

四 决策树

熵和信息增益

五 朴素贝叶斯分类器

潜在概率模型

零计数和平滑

非二元特征

独立的朴素性

双重计数的原因

六 最大熵分类器

最大熵模型

熵的最大化

生成式分类器对比条件分类器

七 为语言模式建模

模型告诉我们什么?

八 深入阅读

使用Weka, Mallet, TADM 和 MegaM




























猜你喜欢

转载自blog.csdn.net/weixin_41285821/article/details/80219091
今日推荐