<jupyter_start><jupyter_text>Let's use CoNLL 2002 data to build a NER systemCoNLL2002 corpus is available in NLTK. We use Spanish data.<jupyter_code>nltk.corpus.conll2002.fileids()
%%time
train_sents = list(nltk.corpus.conll2002.iob_sents('esp.train'))
test_sents = list(nltk.corpus.conll2002.iob_sents('esp.testb'))<jupyter_output>CPU times: user 2.42 s, sys: 70.4 ms, total: 2.49 s
Wall time: 2.55 s<jupyter_text>Data format:<jupyter_code>train_sents[0]<jupyter_output><empty_output><jupyter_text>FeaturesNext, define some features. In this example we use word identity, word suffix, word shape and word POS tag; also, some information from nearby words is used. This makes a simple baseline, but you certainly can add and remove some features to get (much?) better results - experiment with it.<jupyter_code>def word2features(sent, i):
    word = sent[i][0]
    postag = sent[i][1]
    features = [
        'bias',
        'word.lower=' + word.lower(),
        'word[-3:]=' + word[-3:],
        'word[-2:]=' + word[-2:],
        'word.isupper=%s' % word.isupper(),
        'word.istitle=%s' % word.istitle(),
        'word.isdigit=%s' % word.isdigit(),
        'postag=' + postag,
        'postag[:2]=' + postag[:2],
    ]
    if i > 0:
        word1 = sent[i-1][0]
        postag1 = sent[i-1][1]
        features.extend([
            '-1:word.lower=' + word1.lower(),
            '-1:word.istitle=%s' % word1.istitle(),
            '-1:word.isupper=%s' % word1.isupper(),
            '-1:postag=' + postag1,
            '-1:postag[:2]=' + postag1[:2],
        ])
    else:
        features.append('BOS')
        
    if i < len(sent)-1:
        word1 = sent[i+1][0]
        postag1 = sent[i+1][1]
        features.extend([
            '+1:word.lower=' + word1.lower(),
            '+1:word.istitle=%s' % word1.istitle(),
            '+1:word.isupper=%s' % word1.isupper(),
            '+1:postag=' + postag1,
            '+1:postag[:2]=' + postag1[:2],
        ])
    else:
        features.append('EOS')
                
    return features


def sent2features(sent):
    return [word2features(sent, i) for i in range(len(sent))]

def sent2labels(sent):
    return [label for token, postag, label in sent]

def sent2tokens(sent):
    return [token for token, postag, label in sent]<jupyter_output><empty_output><jupyter_text>This is what word2features extracts:<jupyter_code>sent2features(train_sents[0])[0]<jupyter_output><empty_output><jupyter_text>Extract the features from the data:<jupyter_code>%%time
X_train = [sent2features(s) for s in train_sents]
y_train = [sent2labels(s) for s in train_sents]

X_test = [sent2features(s) for s in test_sents]
y_test = [sent2labels(s) for s in test_sents]<jupyter_output>CPU times: user 2.24 s, sys: 287 ms, total: 2.53 s
Wall time: 2.53 s<jupyter_text>Train the modelTo train the model, we create pycrfsuite.Trainer, load the training data and call 'train' method. First, create pycrfsuite.Trainer and load the training data to CRFsuite:<jupyter_code>%%time
trainer = pycrfsuite.Trainer(verbose=False)

for xseq, yseq in zip(X_train, y_train):
    trainer.append(xseq, yseq)<jupyter_output>CPU times: user 3.48 s, sys: 90.2 ms, total: 3.57 s
Wall time: 3.56 s<jupyter_text>Set training parameters. We will use L-BFGS training algorithm (it is default) with Elastic Net (L1 + L2) regularization.<jupyter_code>trainer.set_params({
    'c1': 1.0,   # coefficient for L1 penalty
    'c2': 1e-3,  # coefficient for L2 penalty
    'max_iterations': 50,  # stop earlier

    # include transitions that are possible, but not observed
    'feature.possible_transitions': True
})<jupyter_output><empty_output><jupyter_text>Possible parameters for the default training algorithm:<jupyter_code>trainer.params()<jupyter_output><empty_output><jupyter_text>Train the model:<jupyter_code>%%time
trainer.train('conll2002-esp.crfsuite')<jupyter_output>CPU times: user 18.8 s, sys: 102 ms, total: 18.9 s
Wall time: 19.2 s<jupyter_text>trainer.train saves model to a file:<jupyter_code>!ls -lh ./conll2002-esp.crfsuite<jupyter_output>-rw-r--r--  1 gsh25  staff   600K Jun 22 14:56 ./conll2002-esp.crfsuite<jupyter_text>We can also get information about the final state of the model by looking at the trainer's logparser. If we had tagged our input data using the optional group argument in add, and had used the optional holdout argument during train, there would be information about the trainer's performance on the holdout set as well.<jupyter_code>trainer.logparser.last_iteration<jupyter_output><empty_output><jupyter_text>We can also get this information for every step using trainer.logparser.iterations<jupyter_code>print len(trainer.logparser.iterations), trainer.logparser.iterations[-1]<jupyter_output>50 {'loss': 14807.577946, 'error_norm': 1262.912078, 'linesearch_trials': 1, 'active_features': 11346, 'num': 50, 'time': 0.342, 'scores': {}, 'linesearch_step': 1.0, 'feature_norm': 79.110017}<jupyter_text>Make predictionsTo use the trained model, create pycrfsuite.Tagger, open the model and use "tag" method:<jupyter_code>tagger = pycrfsuite.Tagger()
tagger.open('conll2002-esp.crfsuite')<jupyter_output><empty_output><jupyter_text>Let's tag a sentence to see how it works:<jupyter_code>example_sent = test_sents[0]
print(' '.join(sent2tokens(example_sent)), end='\n\n')

print("Predicted:", ' '.join(tagger.tag(sent2features(example_sent))))
print("Correct:  ", ' '.join(sent2labels(example_sent)))<jupyter_output>La Coruña , 23 may ( EFECOM ) .

Predicted: B-LOC I-LOC O O O O B-ORG O O
Correct:   B-LOC I-LOC O O O O B-ORG O O<jupyter_text>Evaluate the model<jupyter_code>def bio_classification_report(y_true, y_pred):
    """
    Classification report for a list of BIO-encoded sequences.
    It computes token-level metrics and discards "O" labels.
    
    Note that it requires scikit-learn 0.15+ (or a version from github master)
    to calculate averages properly!
    """
    lb = LabelBinarizer()
    y_true_combined = lb.fit_transform(list(chain.from_iterable(y_true)))
    y_pred_combined = lb.transform(list(chain.from_iterable(y_pred)))
        
    tagset = set(lb.classes_) - {'O'}
    tagset = sorted(tagset, key=lambda tag: tag.split('-', 1)[::-1])
    class_indices = {cls: idx for idx, cls in enumerate(lb.classes_)}
    
    return classification_report(
        y_true_combined,
        y_pred_combined,
        labels = [class_indices[cls] for cls in tagset],
        target_names = tagset,
    )<jupyter_output><empty_output><jupyter_text>Predict entity labels for all sentences in our testing set ('testb' Spanish data):<jupyter_code>%%time
y_pred = [tagger.tag(xseq) for xseq in X_test]<jupyter_output>CPU times: user 598 ms, sys: 17.4 ms, total: 616 ms
Wall time: 615 ms<jupyter_text>..and check the result. Note this report is not comparable to results in CONLL2002 papers because here we check per-token results (not per-entity). Per-entity numbers will be worse.<jupyter_code>print(bio_classification_report(y_test, y_pred))<jupyter_output>precision    recall  f1-score   support

      B-LOC       0.78      0.75      0.76      1084
      I-LOC       0.87      0.93      0.90       634
     B-MISC       0.69      0.47      0.56       339
     I-MISC       0.87      0.93      0.90       634
      B-ORG       0.82      0.87      0.84       735
      I-ORG       0.87      0.93      0.90       634
      B-PER       0.61      0.49      0.54       557
      I-PER       0.87      0.93      0.90       634

avg / total       0.81      0.81      0.80      5251<jupyter_text>Let's check what classifier learned<jupyter_code>from collections import Counter
info = tagger.info()

def print_transitions(trans_features):
    for (label_from, label_to), weight in trans_features:
        print("%-6s -> %-7s %0.6f" % (label_from, label_to, weight))

print("Top likely transitions:")
print_transitions(Counter(info.transitions).most_common(15))

print("\nTop unlikely transitions:")
print_transitions(Counter(info.transitions).most_common()[-15:])<jupyter_output>Top likely transitions:
B-ORG  -> I-ORG   8.631963
I-ORG  -> I-ORG   7.833706
B-PER  -> I-PER   6.998706
B-LOC  -> I-LOC   6.913675
I-MISC -> I-MISC  6.129735
B-MISC -> I-MISC  5.538291
I-LOC  -> I-LOC   4.983567
I-PER  -> I-PER   3.748358
B-ORG  -> B-LOC   1.727090
B-PER  -> B-LOC   1.388267
B-LOC  -> B-LOC   1.240278
O      -> O       1.197929
O      -> B-ORG   1.097062
I-PER  -> B-LOC   1.083332
O      -> B-MISC  1.046113

Top unlikely transitions:
I-PER  -> B-ORG   -2.056130
I-LOC  -> I-ORG   -2.143940
B-ORG  -> I-MISC  -2.167501
I-PER  -> I-ORG   -2.369380
B-ORG  -> I-PER   -2.378110
I-MISC -> I-PER   -2.458788
B-LOC  -> I-PER   -2.516414
I-ORG  -> I-MISC  -2.571973
I-LOC  -> B-PER   -2.697791
I-LOC  -> I-PER   -3.065950
I-ORG  -> I-PER   -3.364434
O      -> I-PER   -7.322841
O      -> I-MISC  -7.648246
O      -> I-ORG   -8.024126
O      -> I-LOC   -8.333815<jupyter_text>We can see that, for example, it is very likely that the beginning of an organization name (B-ORG) will be followed by a token inside organization name (I-ORG), but transitions to I-ORG from tokens with other labels are penalized. Also note I-PER -> B-LOC transition: a positive weight means that model thinks that a person name is often followed by a location.Check the state features:<jupyter_code>def print_state_features(state_features):
    for (attr, label), weight in state_features:
        print("%0.6f %-6s %s" % (weight, label, attr))    

print("Top positive:")
print_state_features(Counter(info.state_features).most_common(20))

print("\nTop negative:")
print_state_features(Counter(info.state_features).most_common()[-20:])<jupyter_output>Top positive:
8.886516 B-ORG  word.lower=efe-cantabria
8.743642 B-ORG  word.lower=psoe-progresistas
5.769032 B-LOC  -1:word.lower=cantabria
5.195429 I-LOC  -1:word.lower=calle
5.116821 O      word.lower=mayo
4.990871 O      -1:word.lower=día
4.910915 I-ORG  -1:word.lower=l
4.721572 B-MISC word.lower=diversia
4.676259 B-ORG  word.lower=telefónica
4.334354 B-ORG  word[-2:]=-e
4.149862 B-ORG  word.lower=amena
4.141370 B-ORG  word.lower=terra
3.942852 O      word.istitle=False
3.926397 B-ORG  word.lower=continente
3.924672 B-ORG  word.lower=acesa
3.888706 O      word.lower=euro
3.856445 B-PER  -1:word.lower=según
3.812373 B-MISC word.lower=exteriores
3.807582 I-MISC -1:word.lower=1.9
3.807098 B-MISC word.lower=sanidad

Top negative:
-1.965379 O      word.lower=fundación
-1.981541 O      -1:word.lower=británica
-2.118347 O      word.lower=061
-2.190653 B-PER  word[-3:]=nes
-2.226373 B-ORG  postag=SP
-2.226373 B-ORG  postag[:2]=SP
-2.260972 O      word[-3:]=uia
-2.384920 O      -1:word.lower[...]
{'fraction_non_alphanumeric': 0.1286757819816445, 'fraction_numerical': 0.0739838921146282, 'mean_word_length': 3.307785397337636, 'pattern_counts': {'":': 0, '<': 67, '<?xml version=': 0, '>': 99, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '257267', 'license': 'MIT', 'n_tokens_mistral': 4403, 'n_tokens_neox': 3964, 'n_words': 976, 'path': 'examples/CoNLL 2002.ipynb', 'repo_name': 'ahegel/python-crfsuite', 'size': '10678'}