NLP | Chunking Based on Classifier | Set 1

3-tuples (word, pos, iob) are converted to 2-tuples ((word, pos), iob) using chunk_trees2train_chunks () from tree2conlltags () ClassiferBasedTagger class .

Code # 1: Let`s figure it out

# Loading libraries

from nltk.chunk import ChunkParserI

from nltk.chunk.util import tree2conlltags, conlltags2tree

from nltk.tag import ClassifierBasedTag ger

 

def chunk_trees2train_chunks (chunk_sents):

  

  # Using tree2conlltags

tag_sents = [tree2conlltags (sent) for  

sent in chunk_sents]

 

3 - tuple is to 2 - tuple

  return [ [((w, t), c) for  

(w, t, c) in sent] for sent in tag_sents]

The function detector function is now needed to go to ClassifierBasedTagger. Any object detector function used with the ClassifierChunker class (defined below) must recognize that tokens are a list of tuples (word, pos) and have the same function signature as prev_next_pos_iob (). To give the classifier as much information as possible, this feature set contains the current, previous, and next word and part of speech tag as well as the previous IOB tag.

Code # 2: Detector Function

def prev_next_pos_iob (tokens, index, history):

 

word, pos = tokens [index]

if index = = 0 :

prevword, prevpos, previob = ( `& lt; START & gt;` ,) * 3

else :

prevword, prevpos = tokens [index - 1 ]

previob = history [index - 1 ]

 

if index = = len (tokens) - 1 :

nextword, nextpos = ( `& lt; END & gt;` ,) * 2

else :

nextword, nextpos = tokens [index + 1 ]

  feats = { `word` : word,

  ` pos` : pos,

` nextword` : nextword,

` nextpos` : nextpos,

` prevword` : prevword,

` prevpos` : prevpos,

` previob` : previob

}

  return feats

Now need a ClassifierChunker class which uses internally A new ClassifierBasedTagger with tutorial sentences from chunk_trees2train_chunks () and functions extracted using prev_next_pos_iob () . As a subclass of ChunkerParserI ClassifierChunker implements the parse () method to convert ((w, t), c) tuples generated by the inner tag into trees using conlltags2tree()

Code # 3:

class ClassifierChunker (ChunkParserI):

def __ init __ ( self , train_sents, 

feature_detector = prev_next_pos_iob , * * kwargs):

 

  if not feature_detector:

feature_detector = self . feature_detector

  train_chunks = chunk_trees2train_chunks (train_sents)

self . tagger = ClassifierBasedTagger (train = train_chunks,

  feature_detector = feature_detector, * * kwargs)

  

def parse ( self , tagged_sent):

 

  if not tagged_sent: return None

chunks = self . tagger.tag (tagged_sent)

 

return conlltags2tree (

[(w , t, c) < code class = "keyword"> for ((w, t), c) in chunks])