Assignment 2

Due: Tue 18 Dec 2018 Midnight

Natural Language Processing - Fall 2019 Michael Elhadad

This assignment covers the topic of statistical distributions, regression and classification. The objective is:

Submit your solution by email in the form of an iPython ipynb file. Images should be attached as PNG or JPG files. The whole code should also be submitted as a separate folder with all necessary code to run the questions separated in clearly documented functions from a standalone Python shell, with nltk, scipy and numpy pre-installed.

Do not attach the data in your submission. Your notebook should refer to the data folder as "../data".


Q1. Word Classification

This question is adapted from CIS 530 Computational Linguistics with kind authorization from Chris Callison-Burch, Univ of Pennsylvania, Spring 2019.

Here are the materials that you should download for this question:

Identifying Complex Words

Automated text simplification is an NLP task, where the goal is to take as input a complex text, and return a text that is easier to understand. One of the most logical first steps in text simplification, and example of text classification, is identifying which words in a text are hard to understand, and which words are easy to understand.

We have prepared a labeled training set for this assignment. We provide a dataset of words and their corresponding sentences that has been split into training, development, and test sets. The training set is disjoint, so if a word appears in the training set, it will not also appear in the test set or the development set.

This dataset was collected by taking the first 200 tokens in 200 complex texts, and crowdsourcing human judgements. We asked nine human annotators to identify at least 10 complex words in each text. From here, words that were identified as complex by at least 3 annotators were labeled as complex. In addition, words that were identified as complex by zero annotators were labeled as simple. One thing to note is that we kept only nouns, verbs, adjectives, and adverbs, and removed stopwords (i.e. common words like the or and) and proper nouns. After this filtering, we were left with 5,922 unique words. For this homework, we split these words up into 4,000 words for training, 1,000 words for development, and the remaining 922 words are reserved for testing.

Shown below is an example of the training data. Note that the training data and development data files have the same formatting, and the test data does not include the label column:

WORD LABEL ANNOTATORS SENTENCE SENTENCE_INDEX
jumping 0 0 `` Coleman with his jumping frog – bet stranger $ 50 – stranger had no frog & C got him one – in the meantime stranger filled C ‘s frog full of shot & he could n’t jump – the stranger ‘s frog won . ‘’ 4
paths 0 0 The Cannery project will feature drought-tolerant landscaping along its bike paths , and most of the front yards will be landscaped with low-water plants in place of grass . 10
banks 0 0 Extending their protests into the workweek , Hong Kong democracy activists continued occupying major thoroughfares Monday , forcing the closure of some schools , banks and other businesses in the semi-autonomous Chinese territory . 24
fair-weather 1 5 Months ago , many warned him not to invest in a place where fair-weather tourists flee in the fall and the big lake ‘s waters turn cold and storm-tossed , forcing the 100 or so hardy full-time residents of Cornucopia to hibernate for the winter . 13
krill 1 7 But unlike the other whales , the 25-foot-long young adult stuck near the surface – and it did n’t dive down to feast on the blooms of krill that attract humpbacks to the bay . 27
affirmed 1 8 CHARLESTON , S.C. – A grand jury affirmed the state of South Carolina ‘s murder charge on Monday against a white former North Charleston police officer who fatally shot an unarmed black man trying to run from a traffic stop . 7

Here is what the different fields in the file mean:

We have provided the function load_file(data_file), which takes in the file name (data_file) of one of the datasets, and reads in the words and labels from these files. You should make sure your load_file() function makes every word lowercase.

Note: While the context from which each word was found is provided, you do not need it except in Q1.4.

Q1.1. Implement the Evaluation Metrics

Before we start with this text classification task, we need to first determine how we will evaluate our results. The most common metrics for evaluating binary classification (especially in cases of class imbalance) are precision, recall, and f-score. For this assignment, complex words are considered positive examples, and simple words are considered negative examples.

For this problem, you will fill in the following functions:

Here, y_pred is list of predicted labels from a classifier, and y_true is a list of the true labels.

You may not use sklearn’s built-in functions for this, you must instead write your own code to calculate these metrics.

We recommend that you also write a function test_predictions(y_pred, y_true), which prints out the precision, recall, and f-score.

Q1.2. Baselines

1.2.1 Majority Class Baseline

You should start by implementing simple baselines as classifiers. Your first baseline is a majority class baseline which is the simplest classifier. You should complete the function all_complex(data_file), which takes in the file name of one of the datasets, labels each word in the dataset as complex, and returns out the precision, recall, and f-score.

Report the precision, recall, and f-score on both the training data and the development data individually.

1.2.2 Word Length Baseline

For our next baseline, we will use a slightly complex baseline, the length of each word to predict its complexity.

For the word length baseline, you should try setting various thresholds for word length to classify them as simple or otherwise. For example, you might set a threshold of 9, meaning that any words with less than 9 characters will be labeled simple, and any words with 9 characters or more will be labeled complex. Once you find the best threshold using the training data, use this same threshold for the development data as well.

You will be filling in the function word_length_threshold(training_file, development_file). This function takes in both the training and development data files, and returns out the precision, recall, and f-score for your best threshold’s performance on both the training and development data.

Usually, Precision and Recall are inversely related and while building binary-classification systems we try to find a good balance between them (by maximizing f-score, for example). It is often useful to plot the Precision-Recall curve for various settings of the classifier to gauge its performance and compare it to other classifiers. For example, for this baseline, a Precision-Recall curve can be plotted by plotting the Precision (on the y-axis) and Recall (on the X-axis) for different values of word-length threshold.

Report the precision, recall, and f-score for the training and development data individually, along with the range of thresholds you tried. Also plot the Precision-Recall curve for the various thresholds you tried.

1.2.3 Word Frequency Baseline

Our final baseline is a classifier similar to the last one, but thresholds on word frequency instead of length. We have provided Google NGram frequencies in the text file ngram_counts.txt.gzip, along with the helper function load_ngram_counts(ngram_counts_file) to load them into Python as a dictionary.

You will be filling in the function word_frequency_threshold(training_file, development_file, counts), where counts is the dictionary of word frequencies. This function returns the precision, recall, and fscore for your best threshold’s performance on both the training and development data.

Report the precision, recall, and f-score on the training and development data individually, along with the range of thresholds you tried, and the best threshold to be graded. Similar to the previous baseline, plot the Precision-Recall curve for range of thresholds you tried.

Q1.3. Classifiers

1.3.1 Naive Bayes classification

Now, let’s move on to actual machine learning classifiers. For our first classifier, you will use the built-in Naive Bayes model from sklearn, to train a classifier. You should refer to the online sklearn documentation when you are building your classifier.

The first thing to note is that sklearn classifiers take in numpy arrays, rather than regular lists. To create a numpy list of length 5, you can use the following Python commands:

>>> import numpy as np
>>> X = np.array([1,2,3,4,5])

To train a classifier, you need two numpy arrays: X_train, an m by n array, where m is the number of words in the dataset, and n is the number of features for each word; and Y, an array of length m for the labels of each of the words. Once we have these two arrays, we can fit a Naive Bayes classifier using the following commands:

>>> from sklearn.naive_bayes import GaussianNB
>>> clf = GaussianNB()
>>> clf.fit(X_train, Y)

Finally, to use your model to predict the labels for a set of words, you only need one numpy array: X_test, an m' by n array, where m' is the number of words in the test set, and n is the number of features for each word. Note that the n used here is the same as the n in X_train. Then, we can use our classifier to predict labels using the following command:

>>> Y_pred = clf.predict(X_test)

You should fill in the function naive_bayes(training_file, development_file, counts). This function will train a Naive Bayes classifier on the training data using word length and word frequency as features, and returns your model’s precision, recall, and f-score on the training data and the development data individually.

Report the precision, recall, and f-score on the training and development data for your Naive Bayes classifier that uses word length and word frequency.

NOTE: Before training and testing a classifier, it is generally important to normalize your features. This means that you need to find the mean and standard deviation (sd) of a feature. Then, for each row, perform the following transformation:

X_scaled = (X_original - mean)/sd

Be sure to always use the means and standard deviations from the training data.

Q1.4. Ambiguity

In the training dataset, can you find evidence that the word classification task (complex vs. simple) is ambiguous? In other words, is the classification of a word sensitive to its context in a sentence?

Provide code to list context-sensitive words in the dataset.


Q2. Document Classification

Q2.1. Reuters Dataset

Execute the notebook tutorial of Scikit-Learn on text classification: out of core classification.

Your task:

Q2.2 Spam Dataset

Execute the notebook on Spam detection prepared in spam-classification (download the notebook).

Your task:


Q3. Named Entity Recognition

Named Entity Recognition

The task of Named Entity Recognition (NER) involves the recognition of names of persons, locations, organizations, dates in free text. For example, the following sentence is tagged with sub-sequences indicating PER (for persons), LOC (for location) and ORG (for organization):
Wolff, currently a journalist in Argentina, played with Del Bosque in the final years of the seventies in Real Madrid.

[PER Wolff ] , currently a journalist in [LOC Argentina ] , played with [PER Del Bosque ] in the final years of the seventies in 
[ORG Real Madrid ] .
NER involves 2 sub-tasks: identifying the boundaries of such expressions (the open and close brackets) and labelling the expressions (with tags such as PER, LOC or ORG). This sequence labelling task is reduced into a classification task, using the BIO encoding of the data:
        Wolff B-PER
            , O
    currently O
            a O
   journalist O
           in O
    Argentina B-LOC
            , O
       played O
         with O
          Del B-PER
       Bosque I-PER
           in O
          the O
        final O
        years O
           of O
          the O
    seventies O
           in O
         Real B-ORG
       Madrid I-ORG
            . O

Dataset

The dataset we will use for this question is derived from the CoNLL 2002 shared task - which is about NER in Spanish and Dutch. The dataset is included in the NLTK distribution. Explanations on the dataset are provided in the CoNLL 2002 page.

To access the data in Python, do:

from nltk.corpus import conll2002

etr = conll2002.chunked_sents('esp.train') # In Spanish
eta = conll2002.chunked_sents('esp.testa') # In Spanish
etb = conll2002.chunked_sents('esp.testb') # In Spanish

dtr = conll2002.chunked_sents('ned.train') # In Dutch
dta = conll2002.chunked_sents('ned.testa') # In Dutch
dtb = conll2002.chunked_sents('ned.testb') # In Dutch
The data consists of three files per language (Spanish and Dutch): one training file and two test files testa and testb. The first test file is to be used in the development phase for finding good parameters for the learning system. The second test file will be used for the final evaluation.

Q3.1 Features

Your task consists of:
  1. Choosing good features for encoding the problem.
  2. Encode your training dataset.
  3. Run a classifier over the training dataset.
  4. Train and test the model.
  5. Perform error analysis and fine tune model parameters on the testa part of the datasets.
  6. Perform evaluation over the testb part of the dataset, reporting on accuracy, per label precision, per label recall and per label F-measure, and confusion matrix.

Here is a list of features that have been found appropriate for NER in previous work:

  1. The word form (the string as it appears in the sentence)
  2. The POS of the word (which is provided in the dataset)
  3. ORT - a feature that captures the orthographic (letter) structure of the word. It can have any of the following values: number, contains-digit, contains-hyphen, capitalized, all-capitals, URL, punctuation, regular.
  4. prefix1: first letter of the word
  5. prefix2: first two letters of the word
  6. prefix3: first three letters of the word
  7. suffix1: last letter of the word
  8. suffix2: last two letters of the word
  9. suffix3: last three letters of the word

For example, given the following toy training data, the encoding of the features would be:

        Wolff NP  B-PER
            , ,   O
    currently RB  O
            a AT  O
   journalist NN  O
           in IN  O
    Argentina NP  B-LOC
            , ,   O
       played VBD O
         with IN  O
          Del NP  B-PER
       Bosque NP  I-PER
           in IN  O
          the AT  O
        final JJ  O
        years NNS O
           of IN  O
          the AT  O
    seventies NNS O
           in IN  O
         Real NP  B-ORG
       Madrid NP  I-ORG
            . .   O

Classes
1 B-PER
2 I-PER
3 B-LOC
4 I-LOC
5 B-ORG
6 I-ORG
7 O

Feature WORD-FORM:
1 Wolff
2 ,
3 currently
4 a
5 journalist
6 in
7 Argentina
8 played
9 with
10 Del
11 Bosque
12 the
13 final
14 years
15 of
16 seventies
17 Real
18 Madrid
19 .

Feature POS
20 NP
21 ,
22 RB
23 AT
24 NN
25 VBD
26 JJ
27 NNS
28 .

Feature ORT
29 number
30 contains-digit
31 contains-hyphen
32 capitalized
33 all-capitals
34 URL
35 punctuation
36 regular

Feature Prefix1
37 W
38 ,
39 c
40 a
41 j
42 i
43 A
44 p
45 w
46 D
47 B
48 t
49 f
50 y
51 o
52 s
53 .
Given this encoding, we can compute the vector representing the first word "Wolff NP B-PER" as:
# Class: B-PER=1
# Word-form: Wolff=1
# POS: NP=20
# ORT: Capitalized=32
# prefix1: W=37
1 1:1 20:1 32:1 37:1
When you encode the test dataset, some of the word-forms will be unknown (not seen in the training dataset). You should, therefore, plan for a special value for each feature of type "unknown" when this is expected.

Instead of writing the code as explained above, use the Scikit-learn vectorizer and pipeline library. General information on feature extraction for text data in Scikit-Learn is in the Scikit-Learn documentation. Refer to the DictVectorizer for this specific task. Hashing vs. DictVectorizer also provides useful background.

3.1.1 Feature Extraction: Start from the following example notebook CoNLL 2002 Classification with CRF. You do not need to install Python-CRFSuite - just take this notebook as a starting point to explore the dataset and ways to encode features. (This notebook also gives you an indication of the level of result you can expect to obtain.)

3.1.2 Train the model using a logistic regression classifier and experiment with better features - looking at the tags of the previous word, the previous word and the following word (add padding words in the vectorizer).

3.1.3 We implemented above a version of NER which is based on greedy tagging: that is, without optimizing the sequence of tags as we would obtain by training an HMM or CRF model. In particular, we did not check that the BIO tags produced by the tagger is a legal sequence. Write code to identify sequences of BIO tags which are illegal and report on the frequency of this problem for each type of illegal tags transition (O-IX, IX-IY, BX-IY). Comment on your observations.

Q3.2 Using Word Embeddings

One way to improve a greedy tagger for NER is to use Word Embeddings as features. A convenient package to manipulate Word2Vec word embeddings is provided in the gensim package by Radim Rehurek. To install it, use:
# conda install gensim
You must also download a pre-trained Word2Vec or fastText word embedding model. The models must naturally be in Spanish or Dutch. (Only test word embeddings for one language.) You can find pre-trained word embedding models in different formats:
  1. fastText pretrained models (includes models for 294 languages)
  2. Spanish Word2vec models
Specific information on manipulating word vectors with Gensim are provided in Gensim with the KeyedVector. Practical examples are available for Spanish in this notebook. (Pay attention that word embeddings large are pretty big files - about 3GB when uncompressed.) Your task:
  1. Add word embeddings as dense vectors to the features of your NER classifier for each word feature (current word, previous word, next word) - either in Spanish or in Dutch.
  2. Retrain the model and report on performance. Comment.



Last modified 29 Nov, 2018