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.
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:
get_precision(y_pred, y_true)get_recall(y_pred, y_true)get_fscore(y_pred, y_true)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.
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.
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.
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.
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.
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
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.
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:1When 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.
# conda install gensimYou 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: