自然语言处理 |基于分类器的分块 |设置 2
使用来自 treebank_chunk 语料库的数据让我们评估分块器(在上一篇文章中准备)。
代码#1:
# loading libraries
from chunkers import ClassifierChunker
from nltk.corpus import treebank_chunk
train_data = treebank_chunk.chunked_sents()[:3000]
test_data = treebank_chunk.chunked_sents()[3000:]
# initializing
chunker = ClassifierChunker(train_data)
# evaluation
score = chunker.evaluate(test_data)
a = score.accuracy()
p = score.precision()
r = recall
print ("Accuracy of ClassifierChunker : ", a)
print ("\nPrecision of ClassifierChunker : ", p)
print ("\nRecall of ClassifierChunker : ", r)
输出 :
Accuracy of ClassifierChunker : 0.9721733155838022
Precision of ClassifierChunker : 0.9258838793383068
Recall of ClassifierChunker : 0.9359016393442623
代码#2:让我们比较一下 conll_train 的性能
chunker = ClassifierChunker(conll_train)
score = chunker.evaluate(conll_test)
a = score.accuracy()
p = score.precision()
r = score.recall()
print ("Accuracy of ClassifierChunker : ", a)
print ("\nPrecision of ClassifierChunker : ", p)
print ("\nRecall of ClassifierChunker : ", r)
输出 :
Accuracy of ClassifierChunker : 0.9264622074002153
Precision of ClassifierChunker : 0.8737924310910219
Recall of ClassifierChunker : 0.9007354620620346
通过创建 ((word, pos), iob) 形式的嵌套 2 元组,单词可以通过标注器传递到我们的特征检测器函数中,chunk_trees2train_chunks() 方法生成这些嵌套的 2 元组。
提取了以下特征:
- 当前单词和词性标签
- 上一个词和 IOB 标签,词性标签
- 下一个词和词性标签
ClassifierChunker 类使用内部 ClassifierBasedTagger 和 prev_next_pos_iob() 作为其默认特征检测器。来自标记器的结果,它们是相同的嵌套 2 元组形式,然后使用 conlltags2tree() 将其重新格式化为 3 元组以返回最终树。
代码#3:不同的分类器构建器
# loading libraries
from chunkers import ClassifierChunker
from nltk.corpus import treebank_chunk
from nltk.classify import MaxentClassifier
train_data = treebank_chunk.chunked_sents()[:3000]
test_data = treebank_chunk.chunked_sents()[3000:]
builder = lambda toks: MaxentClassifier.train(
toks, trace = 0, max_iter = 10, min_lldelta = 0.01)
chunker = ClassifierChunker(
train_data, classifier_builder = builder)
score = chunker.evaluate(test_data)
a = score.accuracy()
p = score.precision()
r = score.recall()
print ("Accuracy of ClassifierChunker : ", a)
print ("\nPrecision of ClassifierChunker : ", p)
print ("\nRecall of ClassifierChunker : ", r)
输出 :
Accuracy of ClassifierChunker : 0.9743204362949285
Precision of ClassifierChunker : 0.9334423548650859
Recall of ClassifierChunker : 0.9357377049180328
ClassifierBasedTagger 类默认使用 NaiveBayesClassifier.train 作为它的 classifier_builder。但是任何分类器都可以通过覆盖 classifier_builder 关键字参数来使用。