text stringlengths 1 7.76k | source stringlengths 17 81 |
|---|---|
4.3. DESIGN DECISIONS FOR TEXT CLASSIFICATION 79 0 10000 20000 30000 40000 Vocabulary size 0.5 1.0 Token coverage Pang and Lee Movie Reviews (English) (a) Movie review data in English 0 10000 20000 30000 40000 50000 60000 70000 Vocabulary size 0.5 1.0 Token coverage MAC-Morpho Corpus (Brazilian Portuguese) (b) News articles in Brazilian Portuguese Figure 4.3: Tradeoff between token coverage (y-axis) and vocabulary size, on the NLTK movie review dataset, after sorting the vocabulary by decreasing frequency. The red dashed lines indicate 80%, 90%, and 95% coverage. sisters (by analogy to fix/fixers), and both stemmers incorrectly identify -s as a suffix of this and Williams. Fortunately, even inaccurate stemming can improve bag-of-words classifi- cation models, by merging related strings and thereby reducing the vocabulary size. Accurately handling irregular orthography requires word-specific rules. Lemmatizers are systems that identify the underlying lemma of a given wordform. They must avoid the over-generalization errors of the stemmers in Figure 4.2, and also handle more complex transformations, such as geese→goose. The output of the WordNet lemmatizer is shown in the final line of Figure 4.2. Both stemming and lemmatization are language-specific: an English stemmer or lemmatizer is of little use on a text written in another language. The discipline of morphology relates to the study of word-internal structure, and is described in more detail in § 9.1.2. The value of normalization depends on the data and the task. Normalization re- duces the size of the feature space, which can help in generalization. However, there is always the risk of merging away linguistically meaningful distinctions. In supervised machine learning, regularization and smoothing can play a similar role to normalization — preventing the learner from overfitting to rare features — while avoiding the language- specific engineering required for accurate normalization. In unsupervised scenarios, such as content-based information retrieval (Manning et al., 2008) and topic modeling (Blei et al., 2003), normalization is more critical. 4.3.2 How many words? Limiting the size of the feature vector reduces the memory footprint of the resulting mod- els, and increases the speed of prediction. Normalization can help to play this role, but a more direct approach is simply to limit the vocabulary to the N most frequent words in the dataset. For example, in the MOVIE-REVIEWS dataset provided with NLTK (origi- nally from Pang et al., 2002), there are 39,768 word types, and 1.58M tokens. As shown Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_97_Chunk101 |
80 CHAPTER 4. LINGUISTIC APPLICATIONS OF CLASSIFICATION in Figure 4.3a, the most frequent 4000 word types cover 90% of all tokens, offering an order-of-magnitude reduction in the model size. Such ratios are language-specific: in for example, in the Brazilian Portuguese Mac-Morpho corpus (Alu´ısio et al., 2003), attain- ing 90% coverage requires more than 10000 word types (Figure 4.3b). This reflects the morphological complexity of Portuguese, which includes many more inflectional suffixes than English. Eliminating rare words is not always advantageous for classification performance: for example, names, which are typically rare, play a large role in distinguishing topics of news articles. Another way to reduce the size of the feature space is to eliminate stopwords such as the, to, and and, which may seem to play little role in expressing the topic, sentiment, or stance. This is typically done by creating a stoplist (e.g., NLTK.CORPUS.STOPWORDS), and then ignoring all terms that match the list. However, corpus linguists and social psy- chologists have shown that seemingly inconsequential words can offer surprising insights about the author or nature of the text (Biber, 1991; Chung and Pennebaker, 2007). Further- more, high-frequency words are unlikely to cause overfitting in discriminative classifiers. As with normalization, stopword filtering is more important for unsupervised problems, such as term-based document retrieval. Another alternative for controlling model size is feature hashing (Weinberger et al., 2009). Each feature is assigned an index using a hash function. If a hash function that permits collisions is chosen (typically by taking the hash output modulo some integer), then the model can be made arbitrarily small, as multiple features share a single weight. Because most features are rare, accuracy is surprisingly robust to such collisions (Ganchev and Dredze, 2008). 4.3.3 Count or binary? Finally, we may consider whether we want our feature vector to include the count of each word, or its presence. This gets at a subtle limitation of linear classification: it’s worse to have two failures than one, but is it really twice as bad? Motivated by this intuition, Pang et al. (2002) use binary indicators of presence or absence in the feature vector: fj(x, y) ∈ {0, 1}. They find that classifiers trained on these binary vectors tend to outperform feature vectors based on word counts. One explanation is that words tend to appear in clumps: if a word has appeared once in a document, it is likely to appear again (Church, 2000). These subsequent appearances can be attributed to this tendency towards repetition, and thus provide little additional information about the class label of the document. 4.4 Evaluating classifiers In any supervised machine learning application, it is critical to reserve a held-out test set. This data should be used for only one purpose: to evaluate the overall accuracy of a single Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_98_Chunk102 |
4.4. EVALUATING CLASSIFIERS 81 classifier. Using this data more than once would cause the estimated accuracy to be overly optimistic, because the classifier would be customized to this data, and would not perform as well as on unseen data in the future. It is usually necessary to set hyperparameters or perform feature selection, so you may need to construct a tuning or development set for this purpose, as discussed in § 2.2.5. There are a number of ways to evaluate classifier performance. The simplest is accu- racy: the number of correct predictions, divided by the total number of instances, acc(y, ˆy) = 1 N N X i δ(y(i) = ˆy). [4.4] Exams are usually graded by accuracy. Why are other metrics necessary? The main reason is class imbalance. Suppose you are building a classifier to detect whether an electronic health record (EHR) describes symptoms of a rare disease, which appears in only 1% of all documents in the dataset. A classifier that reports ˆy = NEGATIVE for all documents would achieve 99% accuracy, but would be practically useless. We need metrics that are capable of detecting the classifier’s ability to discriminate between classes, even when the distribution is skewed. One solution is to build a balanced test set, in which each possible label is equally rep- resented. But in the EHR example, this would mean throwing away 98% of the original dataset! Furthermore, the detection threshold itself might be a design consideration: in health-related applications, we might prefer a very sensitive classifier, which returned a positive prediction if there is even a small chance that y(i) = POSITIVE. In other applica- tions, a positive result might trigger a costly action, so we would prefer a classifier that only makes positive predictions when absolutely certain. We need additional metrics to capture these characteristics. 4.4.1 Precision, recall, and F -MEASURE For any label (e.g., positive for presence of symptoms of a disease), there are two possible errors: • False positive: the system incorrectly predicts the label. • False negative: the system incorrectly fails to predict the label. Similarly, for any label, there are two ways to be correct: • True positive: the system correctly predicts the label. • True negative: the system correctly predicts that the label does not apply to this instance. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_99_Chunk103 |
82 CHAPTER 4. LINGUISTIC APPLICATIONS OF CLASSIFICATION Classifiers that make a lot of false positives have low precision: they predict the label even when it isn’t there. Classifiers that make a lot of false negatives have low recall: they fail to predict the label, even when it is there. These metrics distinguish these two sources of error, and are defined formally as: RECALL(y, ˆy, k) = TP TP + FN [4.5] PRECISION(y, ˆy, k) = TP TP + FP. [4.6] Recall and precision are both conditional likelihoods of a correct prediction, which is why their numerators are the same. Recall is conditioned on k being the correct label, y(i) = k, so the denominator sums over true positive and false negatives. Precision is conditioned on k being the prediction, so the denominator sums over true positives and false positives. Note that true negatives are not considered in either statistic. The classifier that labels every document as “negative” would achieve zero recall; precision would be 0 0. Recall and precision are complementary. A high-recall classifier is preferred when false positives are cheaper than false negatives: for example, in a preliminary screening for symptoms of a disease, the cost of a false positive might be an additional test, while a false negative would result in the disease going untreated. Conversely, a high-precision classifier is preferred when false positives are more expensive: for example, in spam de- tection, a false negative is a relatively minor inconvenience, while a false positive might mean that an important message goes unread. The F -MEASURE combines recall and precision into a single metric, using the har- monic mean: F -MEASURE(y, ˆy, k) = 2rp r + p, [4.7] where r is recall and p is precision.6 Evaluating multi-class classification Recall, precision, and F -MEASURE are defined with respect to a specific label k. When there are multiple labels of interest (e.g., in word sense disambiguation or emotion classification), it is necessary to combine the F -MEASURE across each class. Macro F -MEASURE is the average F -MEASURE across several classes, Macro-F(y, ˆy) = 1 |K| X k∈K F -MEASURE(y, ˆy, k) [4.8] 6F -MEASURE is sometimes called F1, and generalizes to Fβ = (1+β2)rp β2p+r . The β parameter can be tuned to emphasize recall or precision. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_100_Chunk104 |
4.4. EVALUATING CLASSIFIERS 83 0.0 0.2 0.4 0.6 0.8 1.0 False positive rate 0.0 0.2 0.4 0.6 0.8 1.0 True positive rate AUC=0.89 AUC=0.73 AUC=0.5 Figure 4.4: ROC curves for three classifiers of varying discriminative power, measured by AUC (area under the curve) In multi-class problems with unbalanced class distributions, the macro F -MEASURE is a balanced measure of how well the classifier recognizes each class. In micro F -MEASURE, we compute true positives, false positives, and false negatives for each class, and then add them up to compute a single recall, precision, and F -MEASURE. This metric is balanced across instances rather than classes, so it weights each class in proportion to its frequency — unlike macro F -MEASURE, which weights each class equally. 4.4.2 Threshold-free metrics In binary classification problems, it is possible to trade off between recall and precision by adding a constant “threshold” to the output of the scoring function. This makes it possible to trace out a curve, where each point indicates the performance at a single threshold. In the receiver operating characteristic (ROC) curve,7 the x-axis indicates the false positive rate, FP FP+TN, and the y-axis indicates the recall, or true positive rate. A perfect classifier attains perfect recall without any false positives, tracing a “curve” from the origin (0,0) to the upper left corner (0,1), and then to (1,1). In expectation, a non-discriminative classifier traces a diagonal line from the origin (0,0) to the upper right corner (1,1). Real classifiers tend to fall between these two extremes. Examples are shown in Figure 4.4. The ROC curve can be summarized in a single number by taking its integral, the area under the curve (AUC). The AUC can be interpreted as the probability that a randomly- selected positive example will be assigned a higher score by the classifier than a randomly- 7The name “receiver operator characteristic” comes from the metric’s origin in signal processing applica- tions (Peterson et al., 1954). Other threshold-free metrics include precision-recall curves, precision-at-k, and balanced F -MEASURE; see Manning et al. (2008) for more details. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_101_Chunk105 |
84 CHAPTER 4. LINGUISTIC APPLICATIONS OF CLASSIFICATION selected negative example. A perfect classifier has AUC = 1 (all positive examples score higher than all negative examples); a non-discriminative classifier has AUC = 0.5 (given a randomly selected positive and negative example, either could score higher with equal probability); a perfectly wrong classifier would have AUC = 0 (all negative examples score higher than all positive examples). One advantage of AUC in comparison to F -MEASURE is that the baseline rate of 0.5 does not depend on the label distribution. 4.4.3 Classifier comparison and statistical significance Natural language processing research and engineering often involves comparing different classification techniques. In some cases, the comparison is between algorithms, such as logistic regression versus averaged perceptron, or L2 regularization versus L1. In other cases, the comparison is between feature sets, such as the bag-of-words versus positional bag-of-words (see § 4.2.2). Ablation testing involves systematically removing (ablating) various aspects of the classifier, such as feature groups, and testing the null hypothesis that the ablated classifier is as good as the full model. A full treatment of hypothesis testing is beyond the scope of this text, but this section contains a brief summary of the techniques necessary to compare classifiers. The main aim of hypothesis testing is to determine whether the difference between two statistics — for example, the accuracies of two classifiers — is likely to arise by chance. We will be concerned with chance fluctuations that arise due to the finite size of the test set.8 An improvement of 10% on a test set with ten instances may reflect a random fluctuation that makes the test set more favorable to classifier c1 than c2; on another test set with a different ten instances, we might find that c2 does better than c1. But if we observe the same 10% improvement on a test set with 1000 instances, this is highly unlikely to be explained by chance. Such a finding is said to be statistically significant at a level p, which is the probability of observing an effect of equal or greater magnitude when the null hypothesis is true. The notation p < .05 indicates that the likelihood of an equal or greater effect is less than 5%, assuming the null hypothesis is true.9 The binomial test The statistical significance of a difference in accuracy can be evaluated using classical tests, such as the binomial test.10 Suppose that classifiers c1 and c2 disagree on N instances in a 8Other sources of variance include the initialization of non-convex classifiers such as neural networks, and the ordering of instances in online learning such as stochastic gradient descent and perceptron. 9Statistical hypothesis testing is useful only to the extent that the existing test set is representative of the instances that will be encountered in the future. If, for example, the test set is constructed from news documents, no hypothesis test can predict which classifier will perform best on documents from another domain, such as electronic health records. 10A well-known alternative to the binomial test is McNemar’s test, which computes a test statistic based on the number of examples that are correctly classified by one system and incorrectly classified by the other. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_102_Chunk106 |
4.4. EVALUATING CLASSIFIERS 85 0 5 10 15 20 25 30 Instances where c1 is right and c2 is wrong 0.00 0.05 0.10 0.15 p(k N = 30, = 0.5) Figure 4.5: Probability mass function for the binomial distribution. The pink highlighted areas represent the cumulative probability for a significance test on an observation of k = 10 and N = 30. test set with binary labels, and that c1 is correct on k of those instances. Under the null hy- pothesis that the classifiers are equally accurate, we would expect k/N to be roughly equal to 1/2, and as N increases, k/N should be increasingly close to this expected value. These properties are captured by the binomial distribution, which is a probability over counts of binary random variables. We write k ∼Binom(θ, N) to indicate that k is drawn from a binomial distribution, with parameter N indicating the number of random “draws”, and θ indicating the probability of “success” on each draw. Each draw is an example on which the two classifiers disagree, and a “success” is a case in which c1 is right and c2 is wrong. (The label space is assumed to be binary, so if the classifiers disagree, exactly one of them is correct. The test can be generalized to multi-class classification by focusing on the examples in which exactly one classifier is correct.) The probability mass function (PMF) of the binomial distribution is, pBinom(k; N, θ) = N k θk(1 −θ)N−k, [4.9] with θk representing the probability of the k successes, (1 −θ)N−k representing the prob- ability of the N −k unsuccessful draws. The expression | nlp_Page_103_Chunk107 |
86 CHAPTER 4. LINGUISTIC APPLICATIONS OF CLASSIFICATION because it is computed from the area under the binomial probability mass function from 0 to k, as shown in the left tail of Figure 4.5. This cumulative probability is computed as a sum over all values i ≤k, Pr Binom count(ˆy(i) 2 = y(i) ̸= ˆy(i) 1 ) ≤k; N, θ = 1 2 = k X i=0 pBinom i; N, θ = 1 2 . [4.10] The one-tailed p-value applies only to the asymmetric null hypothesis that c1 is at least as accurate as c2. To test the two-tailed null hypothesis that c1 and c2 are equally accu- rate, we would take the sum of one-tailed p-values, where the second term is computed from the right tail of Figure 4.5. The binomial distribution is symmetric, so this can be computed by simply doubling the one-tailed p-value. Two-tailed tests are more stringent, but they are necessary in cases in which there is no prior intuition about whether c1 or c2 is better. For example, in comparing logistic regression versus averaged perceptron, a two-tailed test is appropriate. In an ablation test, c2 may contain a superset of the features available to c1. If the additional features are thought to be likely to improve performance, then a one-tailed test would be appropriate, if chosen in advance. However, such a test can only prove that c2 is more accurate than c1, and not the reverse. *Randomized testing The binomial test is appropriate for accuracy, but not for more complex metrics such as F -MEASURE. To compute statistical significance for arbitrary metrics, we can apply ran- domization. Specifically, draw a set of M bootstrap samples (Efron and Tibshirani, 1993), by resampling instances from the original test set with replacement. Each bootstrap sam- ple is itself a test set of size N. Some instances from the original test set will not appear in any given bootstrap sample, while others will appear multiple times; but overall, the sample will be drawn from the same distribution as the original test set. We can then com- pute any desired evaluation on each bootstrap sample, which gives a distribution over the value of the metric. Algorithm 7 shows how to perform this computation. To compare the F -MEASURE of two classifiers c1 and c2, we set the function δ(·) to compute the difference in F -MEASURE on the bootstrap sample. If the difference is less than or equal to zero in at least 5% of the samples, then we cannot reject the one-tailed null hypothesis that c2 is at least as good as c1 (Berg-Kirkpatrick et al., 2012). We may also be interested in the 95% confidence interval around a metric of interest, such as the F -MEASURE of a single classifier. This can be computed by sorting the output of Algorithm 7, and then setting the top and bottom of the 95% confidence interval to the values at the 2.5% and 97.5% percentiles of the sorted outputs. Alternatively, you can fit a normal distribution to the set of differences across bootstrap samples, and compute a Gaussian confidence interval from the mean and variance. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_104_Chunk108 |
4.4. EVALUATING CLASSIFIERS 87 Algorithm 7 Bootstrap sampling for classifier evaluation. The original test set is {x(1:N), y(1:N)}, the metric is δ(·), and the number of samples is M. procedure BOOTSTRAP-SAMPLE(x(1:N), y(1:N), δ(·), M) for t ∈{1, 2, . . . , M} do for i ∈{1, 2, . . . , N} do j ∼UniformInteger(1, N) ˜x(i) ←x(j) ˜y(i) ←y(j) d(t) ←δ(˜x(1:N), ˜y(1:N)) return {d(t)}M t=1 As the number of bootstrap samples goes to infinity, M →∞, the bootstrap estimate is increasingly accurate. A typical choice for M is 104 or 105; larger numbers of samples are necessary for smaller p-values. One way to validate your choice of M is to run the test multiple times, and ensure that the p-values are similar; if not, increase M by an order of magnitude. This is a heuristic measure of the variance of the test, which can decreases with the square root √ M (Robert and Casella, 2013). 4.4.4 *Multiple comparisons Sometimes it is necessary to perform multiple hypothesis tests, such as when compar- ing the performance of several classifiers on multiple datasets. Suppose you have five datasets, and you compare four versions of your classifier against a baseline system, for a total of 20 comparisons. Even if none of your classifiers is better than the baseline, there will be some chance variation in the results, and in expectation you will get one statis- tically significant improvement at p = 0.05 = 1 20. It is therefore necessary to adjust the p-values when reporting the results of multiple comparisons. One approach is to require a threshold of α m to report a p value of p < α when per- forming m tests. This is known as the Bonferroni correction, and it limits the overall probability of incorrectly rejecting the null hypothesis at α. Another approach is to bound the false discovery rate (FDR), which is the fraction of null hypothesis rejections that are incorrect. Benjamini and Hochberg (1995) propose a p-value correction that bounds the fraction of false discoveries at α: sort the p-values of each individual test in ascending order, and set the significance threshold equal to largest k such that pk ≤k mα. If k > 1, the FDR adjustment is more permissive than the Bonferroni correction. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_105_Chunk109 |
88 CHAPTER 4. LINGUISTIC APPLICATIONS OF CLASSIFICATION 4.5 Building datasets Sometimes, if you want to build a classifier, you must first build a dataset of your own. This includes selecting a set of documents or instances to annotate, and then performing the annotations. The scope of the dataset may be determined by the application: if you want to build a system to classify electronic health records, then you must work with a corpus of records of the type that your classifier will encounter when deployed. In other cases, the goal is to build a system that will work across a broad range of documents. In this case, it is best to have a balanced corpus, with contributions from many styles and genres. For example, the Brown corpus draws from texts ranging from government doc- uments to romance novels (Francis, 1964), and the Google Web Treebank includes an- notations for five “domains” of web documents: question answers, emails, newsgroups, reviews, and blogs (Petrov and McDonald, 2012). 4.5.1 Metadata as labels Annotation is difficult and time-consuming, and most people would rather avoid it. It is sometimes possible to exploit existing metadata to obtain labels for training a classi- fier. For example, reviews are often accompanied by a numerical rating, which can be converted into a classification label (see § 4.1). Similarly, the nationalities of social media users can be estimated from their profiles (Dredze et al., 2013) or even the time zones of their posts (Gouws et al., 2011). More ambitiously, we may try to classify the political af- filiations of social media profiles based on their social network connections to politicians and major political parties (Rao et al., 2010). The convenience of quickly constructing large labeled datasets without manual an- notation is appealing. However this approach relies on the assumption that unlabeled instances — for which metadata is unavailable — will be similar to labeled instances. Consider the example of labeling the political affiliation of social media users based on their network ties to politicians. If a classifier attains high accuracy on such a test set, is it safe to assume that it accurately predicts the political affiliation of all social media users? Probably not. Social media users who establish social network ties to politicians may be more likely to mention politics in the text of their messages, as compared to the average user, for whom no political metadata is available. If so, the accuracy on a test set constructed from social network metadata would give an overly optimistic picture of the method’s true performance on unlabeled data. 4.5.2 Labeling data In many cases, there is no way to get ground truth labels other than manual annotation. An annotation protocol should satisfy several criteria: the annotations should be expressive enough to capture the phenomenon of interest; they should be replicable, meaning that Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_106_Chunk110 |
4.5. BUILDING DATASETS 89 another annotator or team of annotators would produce very similar annotations if given the same data; and they should be scalable, so that they can be produced relatively quickly. Hovy and Lavid (2010) propose a structured procedure for obtaining annotations that meet these criteria, which is summarized below. 1. Determine what to annotate. This is usually based on some theory of the under- lying phenomenon: for example, if the goal is to produce annotations about the emotional state of a document’s author, one should start with a theoretical account of the types or dimensions of emotion (e.g., Mohammad and Turney, 2013). At this stage, the tradeoff between expressiveness and scalability should be considered: a full instantiation of the underlying theory might be too costly to annotate at scale, so reasonable approximations should be considered. 2. Optionally, one may design or select a software tool to support the annotation effort. Existing general-purpose annotation tools include BRAT (Stenetorp et al., 2012) and MMAX2 (M¨uller and Strube, 2006). 3. Formalize the instructions for the annotation task. To the extent that the instruc- tions are not explicit, the resulting annotations will depend on the intuitions of the annotators. These intuitions may not be shared by other annotators, or by the users of the annotated data. Therefore explicit instructions are critical to ensuring the an- notations are replicable and usable by other researchers. 4. Perform a pilot annotation of a small subset of data, with multiple annotators for each instance. This will give a preliminary assessment of both the replicability and scalability of the current annotation instructions. Metrics for computing the rate of agreement are described below. Manual analysis of specific disagreements should help to clarify the instructions, and may lead to modifications of the annotation task itself. For example, if two labels are commonly conflated by annotators, it may be best to merge them. 5. Annotate the data. After finalizing the annotation protocol and instructions, the main annotation effort can begin. Some, if not all, of the instances should receive multiple annotations, so that inter-annotator agreement can be computed. In some annotation projects, instances receive many annotations, which are then aggregated into a “consensus” label (e.g., Danescu-Niculescu-Mizil et al., 2013). However, if the annotations are time-consuming or require significant expertise, it may be preferable to maximize scalability by obtaining multiple annotations for only a small subset of examples. 6. Compute and report inter-annotator agreement, and release the data. In some cases, the raw text data cannot be released, due to concerns related to copyright or Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_107_Chunk111 |
90 CHAPTER 4. LINGUISTIC APPLICATIONS OF CLASSIFICATION privacy. In these cases, one solution is to publicly release stand-off annotations, which contain links to document identifiers. The documents themselves can be re- leased under the terms of a licensing agreement, which can impose conditions on how the data is used. It is important to think through the potential consequences of releasing data: people may make personal data publicly available without realizing that it could be redistributed in a dataset and publicized far beyond their expecta- tions (boyd and Crawford, 2012). Measuring inter-annotator agreement To measure the replicability of annotations, a standard practice is to compute the extent to which annotators agree with each other. If the annotators frequently disagree, this casts doubt on either their reliability or on the annotation system itself. For classification, one can compute the frequency with which the annotators agree; for rating scales, one can compute the average distance between ratings. These raw agreement statistics must then be compared with the rate of agreement by chance — the expected level of agreement that would be obtained between two annotators who ignored the data. Cohen’s Kappa is widely used for quantifying the agreement on discrete labeling tasks (Cohen, 1960; Carletta, 1996),11 κ = agreement −E[agreement] 1 −E[agreement] . [4.11] The numerator is the difference between the observed agreement and the chance agree- ment, and the denominator is the difference between perfect agreement and chance agree- ment. Thus, κ = 1 when the annotators agree in every case, and κ = 0 when the annota- tors agree only as often as would happen by chance. Various heuristic scales have been proposed for determining when κ indicates “moderate”, “good”, or “substantial” agree- ment; for reference, Lee and Narayanan (2005) report κ ≈0.45 −0.47 for annotations of emotions in spoken dialogues, which they describe as “moderate agreement”; Stolcke et al. (2000) report κ = 0.8 for annotations of dialogue acts, which are labels for the pur- pose of each turn in a conversation. When there are two annotators, the expected chance agreement is computed as, E[agreement] = X k ˆPr(Y = k)2, [4.12] where k is a sum over labels, and ˆPr(Y = k) is the empirical probability of label k across all annotations. The formula is derived from the expected number of agreements if the annotations were randomly shuffled. Thus, in a binary labeling task, if one label is applied to 90% of instances, chance agreement is .92 + .12 = .82. 11 For other types of annotations, Krippendorf’s alpha is a popular choice (Hayes and Krippendorff, 2007; Artstein and Poesio, 2008). Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_108_Chunk112 |
4.5. BUILDING DATASETS 91 Crowdsourcing Crowdsourcing is often used to rapidly obtain annotations for classification problems. For example, Amazon Mechanical Turk makes it possible to define “human intelligence tasks (hits)”, such as labeling data. The researcher sets a price for each set of annotations and a list of minimal qualifications for annotators, such as their native language and their satisfaction rate on previous tasks. The use of relatively untrained “crowdworkers” con- trasts with earlier annotation efforts, which relied on professional linguists (Marcus et al., 1993). However, crowdsourcing has been found to produce reliable annotations for many language-related tasks (Snow et al., 2008). Crowdsourcing is part of the broader field of human computation (Law and Ahn, 2011).For a critical examination of ethical issues related to crowdsourcing, see Fort et al. (2011). Additional resources Many of the preprocessing issues discussed in this chapter also arise in information re- trieval. See Manning et al. (2008) for discussion of tokenization and related algorithms. For more on hypothesis testing in particular and replicability in general, see (Dror et al., 2017, 2018). Exercises 1. As noted in § 4.3.3, words tend to appear in clumps, with subsequent occurrences of a word being more probable. More concretely, if word j has probability φy,j of appearing in a document with label y, then the probability of two appearances (x(i) j = 2) is greater than φ2 y,j. Suppose you are applying Na¨ıve Bayes to a binary classification. Focus on a word j which is more probable under label y = 1, so that, Pr(w = j | y = 1) > Pr(w = j | y = 0). [4.13] Now suppose that x(i) j > 1. All else equal, will the classifier overestimate or under- estimate the posterior Pr(y = 1 | x)? 2. Prove that F-measure is never greater than the arithmetic mean of recall and preci- sion, r+p 2 . Your solution should also show that F-measure is equal to r+p 2 iff r = p. 3. Given a binary classification problem in which the probability of the “positive” label is equal to α, what is the expected F -MEASURE of a random classifier which ignores the data, and selects ˆy = +1 with probability 1 2? (Assume that p(ˆy)⊥p(y).) What is the expected F -MEASURE of a classifier that selects ˆy = +1 with probability α (also independent of y(i))? Depending on α, which random classifier will score better? Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_109_Chunk113 |
92 CHAPTER 4. LINGUISTIC APPLICATIONS OF CLASSIFICATION 4. Suppose that binary classifiers c1 and c2 disagree on N = 30 cases, and that c1 is correct in k = 10 of those cases. • Write a program that uses primitive functions such as exp and factorial to com- pute the two-tailed p-value — you may use an implementation of the “choose” function if one is avaiable. Verify your code against the output of a library for computing the binomial test or the binomial CDF, such as SCIPY.STATS.BINOM in Python. • Then use a randomized test to try to obtain the same p-value. In each sample, draw from a binomial distribution with N = 30 and θ = 1 2. Count the fraction of samples in which k ≤10. This is the one-tailed p-value; double this to compute the two-tailed p-value. • Try this with varying numbers of bootstrap samples: M ∈{100, 1000, 5000, 10000}. For M = 100 and M = 1000, run the test 10 times, and plot the resulting p- values. • Finally, perform the same tests for N = 70 and k = 25. 5. SemCor 3.0 is a labeled dataset for word sense disambiguation. You can download it,12 or access it in NLTK.CORPORA.SEMCOR. Choose a word that appears at least ten times in SemCor (find), and annotate its WordNet senses across ten randomly-selected examples, without looking at the ground truth. Use online WordNet to understand the definition of each of the senses.13 Have a partner do the same annotations, and compute the raw rate of agreement, expected chance rate of agreement, and Cohen’s kappa. 6. Download the Pang and Lee movie review data, currently available from http: //www.cs.cornell.edu/people/pabo/movie-review-data/. Hold out a randomly-selected 400 reviews as a test set. Download a sentiment lexicon, such as the one currently available from Bing Liu, https://www.cs.uic.edu/˜liub/FBS/sentiment-analysis.html. Tokenize the data, and classify each document as positive iff it has more positive sentiment words than negative sentiment words. Compute the accuracy and F -MEASURE on detecting positive reviews on the test set, using this lexicon-based classifier. Then train a discriminative classifier (averaged perceptron or logistic regression) on the training set, and compute its accuracy and F -MEASURE on the test set. Determine whether the differences are statistically significant, using two-tailed hy- pothesis tests: Binomial for the difference in accuracy, and bootstrap for the differ- ence in macro-F -MEASURE. 12e.g., https://github.com/google-research-datasets/word_sense_disambigation_ corpora or http://globalwordnet.org/wordnet-annotated-corpora/ 13http://wordnetweb.princeton.edu/perl/webwn Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_110_Chunk114 |
4.5. BUILDING DATASETS 93 The remaining problems will require you to build a classifier and test its properties. Pick a multi-class text classification dataset that is not already tokenized. One example is a dataset of New York Times headlines and topics (Boydstun, 2013).14 Divide your data into training (60%), development (20%), and test sets (20%), if no such division already exists. If your dataset is very large, you may want to focus on a few thousand instances at first. 7. Compare various vocabulary sizes of 102, 103, 104, 105, using the most frequent words in each case (you may use any reasonable tokenizer). Train logistic regression clas- sifiers for each vocabulary size, and apply them to the development set. Plot the accuracy and Macro-F -MEASURE with the increasing vocabulary size. For each vo- cabulary size, tune the regularizer to maximize accuracy on a subset of data that is held out from the training set. 8. Compare the following tokenization algorithms: • Whitespace, using a regular expression; • The Penn Treebank tokenizer from NLTK; • Splitting the input into non-overlapping five-character units, regardless of whites- pace or punctuation. Compute the token/type ratio for each tokenizer on the training data, and explain what you find. Train your classifier on each tokenized dataset, tuning the regularizer on a subset of data that is held out from the training data. Tokenize the development set, and report accuracy and Macro-F -MEASURE. 9. Apply the Porter and Lancaster stemmers to the training set, using any reasonable tokenizer, and compute the token/type ratios. Train your classifier on the stemmed data, and compute the accuracy and Macro-F -MEASURE on stemmed development data, again using a held-out portion of the training data to tune the regularizer. 10. Identify the best combination of vocabulary filtering, tokenization, and stemming from the previous three problems. Apply this preprocessing to the test set, and compute the test set accuracy and Macro-F -MEASURE. Compare against a baseline system that applies no vocabulary filtering, whitespace tokenization, and no stem- ming. Use the binomial test to determine whether your best-performing system is signifi- cantly more accurate than the baseline. 14Available as a CSV file at http://www.amber-boydstun.com/ supplementary-information-for-making-the-news.html. Use the field TOPIC 2DIGIT for this problem. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_111_Chunk115 |
94 CHAPTER 4. LINGUISTIC APPLICATIONS OF CLASSIFICATION Use the bootstrap test with M = 104 to determine whether your best-performing system achieves significantly higher macro-F -MEASURE. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_112_Chunk116 |
Chapter 5 Learning without supervision So far, we have assumed the following setup: • a training set where you get observations x and labels y; • a test set where you only get observations x. Without labeled data, is it possible to learn anything? This scenario is known as unsu- pervised learning, and we will see that indeed it is possible to learn about the underlying structure of unlabeled observations. This chapter will also explore some related scenarios: semi-supervised learning, in which only some instances are labeled, and domain adap- tation, in which the training data differs from the data on which the trained system will be deployed. 5.1 Unsupervised learning To motivate unsupervised learning, consider the problem of word sense disambiguation (§ 4.2). The goal is to classify each instance of a word, such as bank into a sense, • bank#1: a financial institution • bank#2: the land bordering a river It is difficult to obtain sufficient training data for word sense disambiguation, because even a large corpus will contain only a few instances of all but the most common words. Is it possible to learn anything about these different senses without labeled data? Word sense disambiguation is usually performed using feature vectors constructed from the local context of the word to be disambiguated. For example, for the word 95 | nlp_Page_113_Chunk117 |
96 CHAPTER 5. LEARNING WITHOUT SUPERVISION 0 10 20 30 40 density of word group 1 0 20 40 density of word group 2 Figure 5.1: Counts of words from two different context groups bank, the immediate context might typically include words from one of the following two groups: 1. financial, deposits, credit, lending, capital, markets, regulated, reserve, liquid, assets 2. land, water, geography, stream, river, flow, deposits, discharge, channel, ecology Now consider a scatterplot, in which each point is a document containing the word bank. The location of the document on the x-axis is the count of words in group 1, and the location on the y-axis is the count for group 2. In such a plot, shown in Figure 5.1, two “blobs” might emerge, and these blobs correspond to the different senses of bank. Here’s a related scenario, from a different problem. Suppose you download thousands of news articles, and make a scatterplot, where each point corresponds to a document: the x-axis is the frequency of the group of words (hurricane, winds, storm); the y-axis is the frequency of the group (election, voters, vote). This time, three blobs might emerge: one for documents that are largely about a hurricane, another for documents largely about a election, and a third for documents about neither topic. These clumps represent the underlying structure of the data. But the two-dimensional scatter plots are based on groupings of context words, and in real scenarios these word lists are unknown. Unsupervised learning applies the same basic idea, but in a high- dimensional space with one dimension for every context word. This space can’t be di- rectly visualized, but the goal is the same: try to identify the underlying structure of the observed data, such that there are a few clusters of points, each of which is internally coherent. Clustering algorithms are capable of finding such structure automatically. 5.1.1 K-means clustering Clustering algorithms assign each data point to a discrete cluster, zi ∈1, 2, . . . K. One of the best known clustering algorithms is K-means, an iterative algorithm that maintains Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_114_Chunk118 |
5.1. UNSUPERVISED LEARNING 97 Algorithm 8 K-means clustering algorithm 1: procedure K-MEANS(x1:N, K) 2: for i ∈1 . . . N do ▷initialize cluster memberships 3: z(i) ←RANDOMINT(1, K) 4: repeat 5: for k ∈1 . . . K do ▷recompute cluster centers 6: νk ← 1 δ(z(i)=k) PN i=1 δ(z(i) = k)x(i) 7: for i ∈1 . . . N do ▷reassign instances to nearest clusters 8: z(i) ←argmink ||x(i) −νk||2 9: until converged 10: return {z(i)} ▷return cluster assignments a cluster assignment for each instance, and a central (“mean”) location for each cluster. K-means iterates between updates to the assignments and the centers: 1. each instance is placed in the cluster with the closest center; 2. each center is recomputed as the average over points in the cluster. This procedure is formalized in Algorithm 8. The term ||x(i) −ν||2 refers to the squared Euclidean norm, PV j=1(x(i) j −νj)2. An important property of K-means is that the con- verged solution depends on the initialization, and a better clustering can sometimes be found simply by re-running the algorithm from a different random starting point. Soft K-means is a particularly relevant variant. Instead of directly assigning each point to a specific cluster, soft K-means assigns to each point a distribution over clusters q(i), so that PK k=1 q(i)(k) = 1, and ∀k, q(i)(k) ≥0. The soft weight q(i)(k) is computed from the distance of x(i) to the cluster center νk. In turn, the center of each cluster is computed from a weighted average of the points in the cluster, νk = 1 PN i=1 q(i)(k) N X i=1 q(i)(k)x(i). [5.1] We will now explore a probablistic version of soft K-means clustering, based on expectation- maximization (EM). Because EM clustering can be derived as an approximation to maximum- likelihood estimation, it can be extended in a number of useful ways. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_115_Chunk119 |
98 CHAPTER 5. LEARNING WITHOUT SUPERVISION 5.1.2 Expectation-Maximization (EM) Expectation-maximization combines the idea of soft K-means with Na¨ıve Bayes classifi- cation. To review, Na¨ıve Bayes defines a probability distribution over the data, log p(x, y; φ, µ) = N X i=1 log p(x(i) | y(i); φ) × p(y(i); µ) [5.2] Now suppose that you never observe the labels. To indicate this, we’ll refer to the label of each instance as z(i), rather than y(i), which is usually reserved for observed variables. By marginalizing over the latent variables z, we obtain the marginal probability of the observed instances x: log p(x; φ, µ) = N X i=1 log p(x(i); φ, µ) [5.3] = N X i=1 log K X z=1 p(x(i), z; φ, µ) [5.4] = N X i=1 log K X z=1 p(x(i) | z; φ) × p(z; µ). [5.5] The parameters φ and µ can be obtained by maximizing the marginal likelihood in Equation 5.5. Why is this the right thing to maximize? Without labels, discriminative learning is impossible — there’s nothing to discriminate. So maximum likelihood is all we have. When the labels are observed, we can estimate the parameters of the Na¨ıve Bayes probability model separately for each label. But marginalizing over the labels couples these parameters, making direct optimization of log p(x) intractable. We will approxi- mate the log-likelihood by introducing an auxiliary variable q(i), which is a distribution over the label set Z = {1, 2, . . . , K}. The optimization procedure will alternate between updates to q and updates to the parameters (φ, µ). Thus, q(i) plays here as in soft K- means. To derive the updates for this optimization, multiply the right side of Equation 5.5 by Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_116_Chunk120 |
5.1. UNSUPERVISED LEARNING 99 the ratio q(i)(z) q(i)(z) = 1, log p(x; φ, µ) = N X i=1 log K X z=1 p(x(i) | z; φ) × p(z; µ) × q(i)(z) q(i)(z) [5.6] = N X i=1 log K X z=1 q(i)(z) × p(x(i) | z; φ) × p(z; µ) × 1 q(i)(z) [5.7] = N X i=1 log Eq(i) " p(x(i) | z; φ)p(z; µ) q(i)(z) # , [5.8] where Eq(i) [f(z)] = PK z=1 q(i)(z) × f(z) refers to the expectation of the function f under the distribution z ∼q(i). Jensen’s inequality says that because log is a concave function, we can push it inside the expectation, and obtain a lower bound. log p(x; φ, µ) ≥ N X i=1 Eq(i) " log p(x(i) | z; φ)p(z; µ) q(i)(z) # [5.9] J ≜ N X i=1 Eq(i) h log p(x(i) | z; φ) + log p(z; µ) −log q(i)(z) i [5.10] = N X i=1 Eq(i) h log p(x(i), z; φ, µ) i + H(q(i)) [5.11] We will focus on Equation 5.10, which is the lower bound on the marginal log-likelihood of the observed data, log p(x). Equation 5.11 shows the connection to the information theoretic concept of entropy, H(q(i)) = −PK z=1 q(i)(z) log q(i)(z), which measures the av- erage amount of information produced by a draw from the distribution q(i). The lower bound J is a function of two groups of arguments: • the distributions q(i) for each instance; • the parameters µ and φ. The expectation-maximization (EM) algorithm maximizes the bound with respect to each of these arguments in turn, while holding the other fixed. The E-step The step in which we update q(i) is known as the E-step, because it updates the distribu- tion under which the expectation is computed. To derive this update, first write out the Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_117_Chunk121 |
100 CHAPTER 5. LEARNING WITHOUT SUPERVISION expectation in the lower bound as a sum, J = N X i=1 K X z=1 q(i)(z) h log p(x(i) | z; φ) + log p(z; µ) −log q(i)(z) i . [5.12] When optimizing this bound, we must also respect a set of “sum-to-one” constraints, PK z=1 q(i)(z) = 1 for all i. Just as in Na¨ıve Bayes, this constraint can be incorporated into a Lagrangian: Jq = N X i=1 K X z=1 q(i)(z) log p(x(i) | z; φ) + log p(z; µ) −log q(i)(z) + λ(i)(1 − K X z=1 q(i)(z)), [5.13] where λ(i) is the Lagrange multiplier for instance i. The Lagrangian is maximized by taking the derivative and solving for q(i): ∂Jq ∂q(i)(z) = log p(x(i) | z; φ) + log p(z; θ) −log q(i)(z) −1 −λ(i) [5.14] log q(i)(z) = log p(x(i) | z; φ) + log p(z; µ) −1 −λ(i) [5.15] q(i)(z) ∝p(x(i) | z; φ) × p(z; µ). [5.16] Applying the sum-to-one constraint gives an exact solution, q(i)(z) = p(x(i) | z; φ) × p(z; µ) PK z′=1 p(x(i) | z′; φ) × p(z′; µ) [5.17] =p(z | x(i); φ, µ). [5.18] After normalizing, each q(i) — which is the soft distribution over clusters for data x(i) — is set to the posterior probability p(z | x(i); φ, µ) under the current parameters. Although the Lagrange multipliers λ(i) were introduced as additional parameters, they drop out during normalization. The M-step Next, we hold fixed the soft assignments q(i), and maximize with respect to the pa- rameters, φ and µ. Let’s focus on the parameter φ, which parametrizes the likelihood p(x | z; φ), and leave µ for an exercise. The parameter φ is a distribution over words for each cluster, so it is optimized under the constraint that PV j=1 φz,j = 1. To incorporate this Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_118_Chunk122 |
5.1. UNSUPERVISED LEARNING 101 constraint, we introduce a set of Lagrange multiplers {λz}K z=1, and from the Lagrangian, Jφ = N X i=1 K X z=1 q(i)(z) log p(x(i) | z; φ) + log p(z; µ) −log q(i)(z) + K X z=1 λz(1 − V X j=1 φz,j). [5.19] The term log p(x(i) | z; φ) is the conditional log-likelihood for the multinomial, which expands to, log p(x(i) | z, φ) = C + V X j=1 xj log φz,j, [5.20] where C is a constant with respect to φ — see Equation 2.12 in § 2.2 for more discussion of this probability function. Setting the derivative of Jφ equal to zero, ∂Jφ ∂φz,j = N X i=1 q(i)(z) × x(i) j φz,j −λz [5.21] φz,j ∝ N X i=1 q(i)(z) × x(i) j . [5.22] Because φz is constrained to be a probability distribution, the exact solution is computed as, φz,j = PN i=1 q(i)(z) × x(i) j PV j′=1 PN i=1 q(i)(z) × x(i) j′ = Eq [count(z, j)] PV j′=1 Eq [count(z, j′)] , [5.23] where the counter j ∈{1, 2, . . . , V } indexes over base features, such as words. This update sets φz equal to the relative frequency estimate of the expected counts under the distribution q. As in supervised Na¨ıve Bayes, we can smooth these counts by adding a constant α. The update for µ is similar: µz ∝PN i=1 q(i)(z) = Eq [count(z)], which is the expected frequency of cluster z. These probabilities can also be smoothed. In sum, the M-step is just like Na¨ıve Bayes, but with expected counts rather than observed counts. The multinomial likelihood p(x | z) can be replaced with other probability distribu- tions: for example, for continuous observations, a Gaussian distribution can be used. In some cases, there is no closed-form update to the parameters of the likelihood. One ap- proach is to run gradient-based optimization at each M-step; another is to simply take a single step along the gradient step and then return to the E-step (Berg-Kirkpatrick et al., 2010). Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_119_Chunk123 |
102 CHAPTER 5. LEARNING WITHOUT SUPERVISION 0 2 4 6 8 iteration 430000 440000 450000 negative log-likelihood bound Figure 5.2: Sensitivity of expectation-maximization to initialization. Each line shows the progress of optimization from a different random initialization. 5.1.3 EM as an optimization algorithm Algorithms that update a global objective by alternating between updates to subsets of the parameters are called coordinate ascent algorithms. The objective J (the lower bound on the marginal likelihood of the data) is separately convex in q and (µ, φ), but it is not jointly convex in all terms; this condition is known as biconvexity. Each step of the expectation- maximization algorithm is guaranteed not to decrease the lower bound J, which means that EM will converge towards a solution at which no nearby points yield further im- provements. This solution is a local optimum — it is as good or better than any of its immediate neighbors, but is not guaranteed to be optimal among all possible configura- tions of (q, µ, φ). The fact that there is no guarantee of global optimality means that initialization is important: where you start can determine where you finish. To illustrate this point, Figure 5.2 shows the objective function for EM with ten different random initializations: while the objective function improves monotonically in each run, it converges to several different values.1 For the convex objectives that we encountered in chapter 2, it was not necessary to worry about initialization, because gradient-based optimization guaranteed to reach the global minimum. But in expectation-maximization — as in the deep neural networks from chapter 3 — initialization matters. In hard EM, each q(i) distribution assigns probability of 1 to a single label ˆz(i), and zero probability to all others (Neal and Hinton, 1998). This is similar in spirit to K-means clus- tering, and can outperform standard EM in some cases (Spitkovsky et al., 2010). Another variant of expectation-maximization incorporates stochastic gradient descent (SGD): after performing a local E-step at each instance x(i), we immediately make a gradient update to the parameters (µ, φ). This algorithm has been called incremental expectation maxi- mization (Neal and Hinton, 1998) and online expectation maximization (Sato and Ishii, 1The figure shows the upper bound on the negative log-likelihood, because optimization is typically framed as minimization rather than maximization. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_120_Chunk124 |
5.1. UNSUPERVISED LEARNING 103 2000; Capp´e and Moulines, 2009), and is especially useful when there is no closed-form optimum for the likelihood p(x | z), and in online settings where new data is constantly streamed in (see Liang and Klein, 2009, for a comparison for online EM variants). 5.1.4 How many clusters? So far, we have assumed that the number of clusters K is given. In some cases, this as- sumption is valid. For example, a lexical semantic resource like WORDNET might define the number of senses for a word. In other cases, the number of clusters could be a parame- ter for the user to tune: some readers want a coarse-grained clustering of news stories into three or four clusters, while others want a fine-grained clustering into twenty or more. But many times there is little extrinsic guidance for how to choose K. One solution is to choose the number of clusters to maximize a metric of clustering quality. The other parameters µ and φ are chosen to maximize the log-likelihood bound J, so this might seem a potential candidate for tuning K. However, J will never decrease with K: if it is possible to obtain a bound of JK with K clusters, then it is always possible to do at least as well with K + 1 clusters, by simply ignoring the additional cluster and setting its probability to zero in q and µ. It is therefore necessary to introduce a penalty for model complexity, so that fewer clusters are preferred. For example, the Akaike Infor- mation Crition (AIC; Akaike, 1974) is the linear combination of the number of parameters and the log-likelihood, AIC = 2M −2J, [5.24] where M is the number of parameters. In an expectation-maximization clustering algo- rithm, M = K × V + K. Since the number of parameters increases with the number of clusters K, the AIC may prefer more parsimonious models, even if they do not fit the data quite as well. Another choice is to maximize the predictive likelihood on heldout data. This data is not used to estimate the model parameters φ and µ, and so it is not the case that the likelihood on this data is guaranteed to increase with K. Figure 5.3 shows the negative log-likelihood on training and heldout data, as well as the AIC. *Bayesian nonparametrics An alternative approach is to treat the number of clusters as another latent variable. This requires statistical inference over a set of models with a variable number of clusters. This is not possible within the framework of expectation- maximization, but there are several alternative inference procedures which can be ap- plied, including Markov Chain Monte Carlo (MCMC), which is briefly discussed in § 5.5 (for more details, see Chapter 25 of Murphy, 2012). Bayesian nonparametrics have been applied to the problem of unsupervised word sense induction, learning not only the word senses but also the number of senses per word (Reisinger and Mooney, 2010). Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_121_Chunk125 |
104 CHAPTER 5. LEARNING WITHOUT SUPERVISION 10 20 30 40 50 Number of clusters 220000 240000 260000 Negative log-likelihood bound AIC 10 20 30 40 50 Number of clusters 75000 80000 85000 Out-of-sample negative log likelihood Figure 5.3: The negative log-likelihood and AIC for several runs of expectation- maximization, on synthetic data. Although the data was generated from a model with K = 10, the optimal number of clusters is ˆK = 15, according to AIC and the heldout log-likelihood. The training set log-likelihood continues to improve as K increases. 5.2 Applications of expectation-maximization EM is not really an “algorithm” like, say, quicksort. Rather, it is a framework for learning with missing data. The recipe for using EM on a problem of interest is: • Introduce latent variables z, such that it is easy to write the probability P(x, z). It should also be easy to estimate the associated parameters, given knowledge of z. • Derive the E-step updates for q(z), which is typically factored as q(z) = QN i=1 qz(i)(z(i)), where i is an index over instances. • The M-step updates typically correspond to the soft version of a probabilistic super- vised learning algorithm, like Na¨ıve Bayes. This section discusses a few of the many applications of this general framework. 5.2.1 Word sense induction The chapter began by considering the problem of word sense disambiguation when the senses are not known in advance. Expectation-maximization can be applied to this prob- lem by treating each cluster as a word sense. Each instance represents the use of an ambiguous word, and x(i) is a vector of counts for the other words that appear nearby: Sch¨utze (1998) uses all words within a 50-word window. The probability p(x(i) | z) can be set to the multinomial distribution, as in Na¨ıve Bayes. The EM algorithm can be applied directly to this data, yielding clusters that (hopefully) correspond to the word senses. Better performance can be obtained by first applying singular value decomposition (SVD) to the matrix of context-counts Cij = count(i, j), where count(i, j) is the count of word j in the context of instance i. Truncated singular value decomposition approximates Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_122_Chunk126 |
5.2. APPLICATIONS OF EXPECTATION-MAXIMIZATION 105 the matrix C as a product of three matrices, U, S, V, under the constraint that U and V are orthonormal, and S is diagonal: min U,S,V||C −USV⊤||F [5.25] s.t.U ∈RV ×K, UU⊤= I S = Diag(s1, s2, . . . , sK) V⊤∈RNp×K, VV⊤= I, where || · ||F is the Frobenius norm, ||X||F = qP i,j X2 i,j. The matrix U contains the left singular vectors of C, and the rows of this matrix can be used as low-dimensional representations of the count vectors ci. EM clustering can be made more robust by setting the instance descriptions x(i) equal to these rows, rather than using raw counts (Sch¨utze, 1998). However, because the instances are now dense vectors of continuous numbers, the probability p(x(i) | z) must be defined as a multivariate Gaussian distribution. In truncated singular value decomposition, the hyperparameter K is the truncation limit: when K is equal to the rank of C, the norm of the difference between the original matrix C and its reconstruction USV⊤will be zero. Lower values of K increase the recon- struction error, but yield vector representations that are smaller and easier to learn from. Singular value decomposition is discussed in more detail in chapter 14. 5.2.2 Semi-supervised learning Expectation-maximization can also be applied to the problem of semi-supervised learn- ing: learning from both labeled and unlabeled data in a single model. Semi-supervised learning makes use of annotated examples, ensuring that each label y corresponds to the desired concept. By adding unlabeled examples, it is possible to cover a greater fraction of the features than would appear in labeled data alone. Other methods for semi-supervised learning are discussed in § 5.3, but for now, let’s approach the problem within the frame- work of expectation-maximization (Nigam et al., 2000). Suppose we have labeled data {(x(i), y(i))}Nℓ i=1, and unlabeled data {x(i)}Nℓ+Nu i=Nℓ+1, where Nℓis the number of labeled instances and Nu is the number of unlabeled instances. We can learn from the combined data by maximizing a lower bound on the joint log-likelihood, L = Nℓ X i=1 log p(x(i), y(i); µ, φ) + Nℓ+Nu X j=Nℓ+1 log p(x(j); µ, φ) [5.26] = Nℓ X i=1 log p(x(i) | y(i); φ) + log p(y(i); µ) + Nℓ+Nu X j=Nℓ+1 log K X y=1 p(x(j), y; µ, φ). [5.27] Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_123_Chunk127 |
106 CHAPTER 5. LEARNING WITHOUT SUPERVISION Algorithm 9 Generative process for the Na¨ıve Bayes classifier with hidden components for Instance i ∈{1, 2, . . . , N} do: Draw the label y(i) ∼Categorical(µ); Draw the component z(i) ∼Categorical(βy(i)); Draw the word counts x(i) | y(i), z(i) ∼Multinomial(φz(i)). The left sum is identical to the objective in Na¨ıve Bayes; the right sum is the marginal log- likelihood for expectation-maximization clustering, from Equation 5.5. We can construct a lower bound on this log-likelihood by introducing distributions q(j) for all j ∈{Nℓ+ 1, . . . , Nℓ+ Nu}. The E-step updates these distributions; the M-step updates the parameters φ and µ, us- ing the expected counts from the unlabeled data and the observed counts from the labeled data. A critical issue in semi-supervised learning is how to balance the impact of the labeled and unlabeled data on the classifier weights, especially when the unlabeled data is much larger than the labeled dataset. The risk is that the unlabeled data will dominate, caus- ing the parameters to drift towards a “natural clustering” of the instances — which may not correspond to a good classifier for the labeled data. One solution is to heuristically reweight the two components of Equation 5.26, tuning the weight of the two components on a heldout development set (Nigam et al., 2000). 5.2.3 Multi-component modeling As a final application, let’s return to fully supervised classification. A classic dataset for text classification is 20 newsgroups, which contains posts to a set of online forums, called newsgroups. One of the newsgroups is comp.sys.mac.hardware, which discusses Ap- ple computing hardware. Suppose that within this newsgroup there are two kinds of posts: reviews of new hardware, and question-answer posts about hardware problems. The language in these components of the mac.hardware class might have little in com- mon; if so, it would be better to model these components separately, rather than treating their union as a single class. However, the component responsible for each instance is not directly observed. Recall that Na¨ıve Bayes is based on a generative process, which provides a stochastic explanation for the observed data. In Na¨ıve Bayes, each label is drawn from a categorical distribution with parameter µ, and each vector of word counts is drawn from a multi- nomial distribution with parameter φy. For multi-component modeling, we envision a slightly different generative process, incorporating both the observed label y(i) and the latent component z(i). This generative process is shown in Algorithm 9. A new parameter βy(i) defines the distribution of components, conditioned on the label y(i). The component, and not the class label, then parametrizes the distribution over words. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_124_Chunk128 |
5.3. SEMI-SUPERVISED LEARNING 107 (5.1) , Villeneuve a bel et bien r´eussi son pari de changer de perspectives tout en assurant une coh´erence `a la franchise.2 (5.2) / Il est ´egalement trop long et bancal dans sa narration, ti`ede dans ses intentions, et tiraill´e entre deux personnages et directions qui ne parviennent pas `a coexister en har- monie.3 (5.3) Denis Villeneuve a r´eussi une suite parfaitement maitris´ee4 (5.4) Long, bavard, hyper design, `a peine agit´e (le comble de l’action : une bagarre dans la flotte), m´etaphysique et, surtout, ennuyeux jusqu’`a la catalepsie.5 (5.5) Une suite d’une ´ecrasante puissance, mˆelant parfaitement le contemplatif au narratif.6 (5.6) Le film impitoyablement bavard finit quand mˆeme par se taire quand se l`eve l’esp`ece de bouquet final o`u semble se d´echaˆıner, comme en libre parcours de poulets d´ecapit´es, l’arm´ee des graphistes num´eriques griffant nerveusement la palette graphique entre ag- onie et orgasme.7 Table 5.1: Labeled and unlabeled reviews of the films Blade Runner 2049 and Transformers: The Last Knight. The labeled data includes (x(i), y(i)), but not z(i), so this is another case of missing data. Again, we sum over the missing data, applying Jensen’s inequality to as to obtain a lower bound on the log-likelihood, log p(x(i), y(i)) = log Kz X z=1 p(x(i), y(i), z; µ, φ, β) [5.28] ≥log p(y(i); µ) + Eq(i) Z|Y [log p(x(i) | z; φ) + log p(z | y(i); β) −log q(i)(z)]. [5.29] We are now ready to apply expectation-maximization. As usual, the E-step updates the distribution over the missing data, q(i) Z|Y . The M-step updates the parameters, βy,z = Eq [count(y, z)] PKz z′=1 Eq [count(y, z′)] [5.30] φz,j = Eq [count(z, j)] PV j′=1 Eq [count(z, j′)] . [5.31] 5.3 Semi-supervised learning In semi-supervised learning, the learner makes use of both labeled and unlabeled data. To see how this could help, suppose you want to do sentiment analysis in French. In Ta- Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_125_Chunk129 |
108 CHAPTER 5. LEARNING WITHOUT SUPERVISION ble 5.1, there are two labeled examples, one positive and one negative. From this data, a learner could conclude that r´eussi is positive and long is negative. This isn’t much! How- ever, we can propagate this information to the unlabeled data, and potentially learn more. • If we are confident that r´eussi is positive, then we might guess that (5.3) is also posi- tive. • That suggests that parfaitement is also positive. • We can then propagate this information to (5.5), and learn from the words in this example. • Similarly, we can propagate from the labeled data to (5.4), which we guess to be negative because it shares the word long. This suggests that bavard is also negative, which we propagate to (5.6). Instances (5.3) and (5.4) were “similar” to the labeled examples for positivity and negativ- ity, respectively. By using these instances to expand the models for each class, it became possible to correctly label instances (5.5) and (5.6), which didn’t share any important fea- tures with the original labeled data. This requires a key assumption: that similar instances will have similar labels. In § 5.2.2, we discussed how expectation-maximization can be applied to semi-supervised learning. Using the labeled data, the initial parameters φ would assign a high weight for r´eussi in the positive class, and a high weight for long in the negative class. These weights helped to shape the distributions q for instances (5.3) and (5.4) in the E-step. In the next iteration of the M-step, the parameters φ are updated with counts from these instances, making it possible to correctly label the instances (5.5) and (5.6). However, expectation-maximization has an important disadvantage: it requires using a generative classification model, which restricts the features that can be used for clas- sification. In this section, we explore non-probabilistic approaches, which impose fewer restrictions on the classification model. 5.3.1 Multi-view learning EM semi-supervised learning can be viewed as self-training: the labeled data guides the initial estimates of the classification parameters; these parameters are used to compute a label distribution over the unlabeled instances, q(i); the label distributions are used to update the parameters. The risk is that self-training drifts away from the original labeled data. This problem can be ameliorated by multi-view learning. Here we take the as- sumption that the features can be decomposed into multiple “views”, each of which is conditionally independent, given the label. For example, consider the problem of classi- fying a name as a person or location: one view is the name itself; another is the context in which it appears. This situation is illustrated in Table 5.2. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_126_Chunk130 |
5.3. SEMI-SUPERVISED LEARNING 109 x(1) x(2) y 1. Peachtree Street located on LOC 2. Dr. Walker said PER 3. Zanzibar located in ? →LOC 4. Zanzibar flew to ? →LOC 5. Dr. Robert recommended ? →PER 6. Oprah recommended ? →PER Table 5.2: Example of multiview learning for named entity classification Co-training is an iterative multi-view learning algorithm, in which there are separate classifiers for each view (Blum and Mitchell, 1998). At each iteration of the algorithm, each classifier predicts labels for a subset of the unlabeled instances, using only the features available in its view. These predictions are then used as ground truth to train the classifiers associated with the other views. In the example shown in Table 5.2, the classifier on x(1) might correctly label instance #5 as a person, because of the feature Dr; this instance would then serve as training data for the classifier on x(2), which would then be able to correctly label instance #6, thanks to the feature recommended. If the views are truly independent, this procedure is robust to drift. Furthermore, it imposes no restrictions on the classifiers that can be used for each view. Word-sense disambiguation is particularly suited to multi-view learning, thanks to the heuristic of “one sense per discourse”: if a polysemous word is used more than once in a given text or conversation, all usages refer to the same sense (Gale et al., 1992). This motivates a multi-view learning approach, in which one view corresponds to the local context (the surrounding words), and another view corresponds to the global context at the document level (Yarowsky, 1995). The local context view is first trained on a small seed dataset. We then identify its most confident predictions on unlabeled instances. The global context view is then used to extend these confident predictions to other instances within the same documents. These new instances are added to the training data to the local context classifier, which is retrained and then applied to the remaining unlabeled data. 5.3.2 Graph-based algorithms Another family of approaches to semi-supervised learning begins by constructing a graph, in which pairs of instances are linked with symmetric weights ωi,j, e.g., ωi,j = exp(−α × ||x(i) −x(j)||2). [5.32] The goal is to use this weighted graph to propagate labels from a small set of labeled instances to larger set of unlabeled instances. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_127_Chunk131 |
110 CHAPTER 5. LEARNING WITHOUT SUPERVISION In label propagation, this is done through a series of matrix operations (Zhu et al., 2003). Let Q be a matrix of size N × K, in which each row q(i) describes the labeling of instance i. When ground truth labels are available, then q(i) is an indicator vector, with q(i) y(i) = 1 and q(i) y′̸=y(i) = 0. Let us refer to the submatrix of rows containing labeled instances as QL, and the remaining rows as QU. The rows of QU are initialized to assign equal probabilities to all labels, qi,k = 1 K . Now, let Ti,j represent the “transition” probability of moving from node j to node i, Ti,j ≜Pr(j →i) = ωi,j PN k=1 ωk,j . [5.33] We compute values of Ti,j for all instances j and all unlabeled instances i, forming a matrix of size NU × N. If the dataset is large, this matrix may be expensive to store and manip- ulate; a solution is to sparsify it, by keeping only the κ largest values in each row, and setting all other values to zero. We can then “propagate” the label distributions to the unlabeled instances, ˜QU ←TQ [5.34] s ←˜QU1 [5.35] QU ←Diag(s)−1 ˜QU. [5.36] The expression ˜QU1 indicates multiplication of ˜QU by a column vector of ones, which is equivalent to computing the sum of each row of ˜QU. The matrix Diag(s) is a diagonal matrix with the elements of s on the diagonals. The product Diag(s)−1 ˜QU has the effect of normalizing the rows of ˜QU, so that each row of QU is a probability distribution over labels. 5.4 Domain adaptation In many practical scenarios, the labeled data differs in some key respect from the data to which the trained model is to be applied. A classic example is in consumer reviews: we may have labeled reviews of movies (the source domain), but we want to predict the reviews of appliances (the target domain). A similar issue arises with genre differences: most linguistically-annotated data is news text, but application domains range from social media to electronic health records. In general, there may be several source and target domains, each with their own properties; however, for simplicity, this discussion will focus mainly on the case of a single source and target domain. The simplest approach is “direct transfer”: train a classifier on the source domain, and apply it directly to the target domain. The accuracy of this approach depends on the extent to which features are shared across domains. In review text, words like outstanding and Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_128_Chunk132 |
5.4. DOMAIN ADAPTATION 111 disappointing will apply across both movies and appliances; but others, like terrifying, may have meanings that are domain-specific. As a result, direct transfer performs poorly: for example, an out-of-domain classifier (trained on book reviews) suffers twice the error rate of an in-domain classifier on reviews of kitchen appliances (Blitzer et al., 2007). Domain adaptation algorithms attempt to do better than direct transfer by learning from data in both domains. There are two main families of domain adaptation algorithms, depending on whether any labeled data is available in the target domain. 5.4.1 Supervised domain adaptation In supervised domain adaptation, there is a small amount of labeled data in the target domain, and a large amount of data in the source domain. The simplest approach would be to ignore domain differences, and simply merge the training data from the source and target domains. There are several other baseline approaches to dealing with this sce- nario (Daum´e III, 2007): Interpolation. Train a classifier for each domain, and combine their predictions, e.g., ˆy = argmax y λsΨs(x, y) + (1 −λs)Ψt(x, y), [5.37] where Ψs and Ψt are the scoring functions from the source and target domain clas- sifiers respectively, and λs is the interpolation weight. Prediction. Train a classifier on the source domain data, use its prediction as an additional feature in a classifier trained on the target domain data, ˆys = argmax y Ψs(x, y) [5.38] ˆyt = argmax y Ψt([x; ˆyS], y). [5.39] Priors. Train a classifier on the source domain data, and use its weights as a prior distri- bution on the weights of the classifier for the target domain data. This is equivalent to regularizing the target domain weights towards the weights of the source domain classifier (Chelba and Acero, 2006), ℓ(θt) = N X i=1 ℓ(i)(x(i), y(i); θt) + λ||θt −θs||2 2, [5.40] where ℓ(i) is the prediction loss on instance i, and λ is the regularization weight. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_129_Chunk133 |
112 CHAPTER 5. LEARNING WITHOUT SUPERVISION An effective and “frustratingly simple” alternative is EASYADAPT (Daum´e III, 2007), which creates copies of each feature: one for each domain and one for the cross-domain setting. For example, a negative review of the film Wonder Woman begins, As boring and flavorless as a three-day-old grilled cheese sandwich....8 The resulting bag-of-words feature vector would be, f(x, y, d) = {(boring, /, MOVIE) : 1, (boring, /, ∗) : 1, (flavorless, /, MOVIE) : 1, (flavorless, /, ∗) : 1, (three-day-old, /, MOVIE) : 1, (three-day-old, /, ∗) : 1, . . .}, with (boring, /, MOVIE) indicating the word boring appearing in a negative labeled doc- ument in the MOVIE domain, and (boring, /, ∗) indicating the same word in a negative labeled document in any domain. It is up to the learner to allocate weight between the domain-specific and cross-domain features: for words that facilitate prediction in both domains, the learner will use the cross-domain features; for words that are relevant only to a single domain, the domain-specific features will be used. Any discriminative classi- fier can be used with these augmented features.9 5.4.2 Unsupervised domain adaptation In unsupervised domain adaptation, there is no labeled data in the target domain. Un- supervised domain adaptation algorithms cope with this problem by trying to make the data from the source and target domains as similar as possible. This is typically done by learning a projection function, which puts the source and target data in a shared space, in which a learner can generalize across domains. This projection is learned from data in both domains, and is applied to the base features — for example, the bag-of-words in text classification. The projected features can then be used both for training and for prediction. Linear projection In linear projection, the cross-domain representation is constructed by a matrix-vector product, g(x(i)) = Ux(i). [5.41] The projected vectors g(x(i)) can then be used as base features during both training (from the source domain) and prediction (on the target domain). 8http://www.colesmithey.com/capsules/2017/06/wonder-woman.HTML, accessed October 9. 2017. 9EASYADAPT can be explained as a hierarchical Bayesian model, in which the weights for each domain are drawn from a shared prior (Finkel and Manning, 2009). Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_130_Chunk134 |
5.4. DOMAIN ADAPTATION 113 The projection matrix U can be learned in a number of different ways, but many ap- proaches focus on compressing and reconstructing the base features (Ando and Zhang, 2005). For example, we can define a set of pivot features, which are typically chosen be- cause they appear in both domains: in the case of review documents, pivot features might include evaluative adjectives like outstanding and disappointing (Blitzer et al., 2007). For each pivot feature j, we define an auxiliary problem of predicting whether the feature is present in each example, using the remaining base features. Let φj denote the weights of this classifier, and us horizontally concatenate the weights for each of the Np pivot features into a matrix Φ = [φ1, φ2, . . . , φNP ]. We then perform truncated singular value decomposition on Φ, as described in § 5.2.1, obtaining Φ ≈USV⊤. The rows of the matrix U summarize information about each base feature: indeed, the truncated singular value decomposition identifies a low-dimension basis for the weight matrix Φ, which in turn links base features to pivot features. Sup- pose that a base feature reliable occurs only in the target domain of appliance reviews. Nonetheless, it will have a positive weight towards some pivot features (e.g., outstanding, recommended), and a negative weight towards others (e.g., worthless, unpleasant). A base feature such as watchable might have the same associations with the pivot features, and therefore, ureliable ≈uwatchable. The matrix U can thus project the base features into a space in which this information is shared. Non-linear projection Non-linear transformations of the base features can be accomplished by implementing the transformation function as a deep neural network, which is trained from an auxiliary objective. Denoising objectives One possibility is to train a projection function to reconstruct a corrupted version of the original input. The original input can be corrupted in various ways: by the addition of random noise (Glorot et al., 2011; Chen et al., 2012), or by the deletion of features (Chen et al., 2012; Yang and Eisenstein, 2015). Denoising objectives share many properties of the linear projection method described above: they enable the projection function to be trained on large amounts of unlabeled data from the target do- main, and allow information to be shared across the feature space, thereby reducing sen- sitivity to rare and domain-specific features. Adversarial objectives The ultimate goal is for the transformed representations g(x(i)) to be domain-general. This can be made an explicit optimization criterion by comput- ing the similarity of transformed instances both within and between domains (Tzeng et al., 2015), or by formulating an auxiliary classification task, in which the domain it- self is treated as a label (Ganin et al., 2016). This setting is adversarial, because we want Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_131_Chunk135 |
114 CHAPTER 5. LEARNING WITHOUT SUPERVISION ℓd ℓy d(i) y(i) x g(x) Figure 5.4: A schematic view of adversarial domain adaptation. The loss ℓy is computed only for instances from the source domain, where labels y(i) are available. to learn a representation that makes this classifier perform poorly. At the same time, we want g(x(i)) to enable accurate predictions of the labels y(i). To formalize this idea, let d(i) represent the domain of instance i, and let ℓd(g(x(i)), d(i); θd) represent the loss of a classifier (typically a deep neural network) trained to predict d(i) from the transformed representation g(x(i)), using parameters θd. Analogously, let ℓy(g(x(i)), y(i); θy) represent the loss of a classifier trained to predict the label y(i) from g(x(i)), using param- eters θy. The transformation g can then be trained from two criteria: it should yield accu- rate predictions of the labels y(i), while making inaccurate predictions of the domains d(i). This can be formulated as a joint optimization problem, min θgθy,θd Nℓ+Nu X i=1 ℓd(g(x(i); θg), d(i); θd) − Nℓ X i=1 ℓy(g(x(i); θg), y(i); θy), [5.42] where Nℓis the number of labeled instances and Nu is the number of unlabeled instances, with the labeled instances appearing first in the dataset. This setup is shown in Figure 5.4. The loss can be optimized by stochastic gradient descent, jointly training the parameters of the non-linear transformation θg, and the parameters of the prediction models θd and θy. 5.5 *Other approaches to learning with latent variables Expectation-maximization provides a general approach to learning with latent variables, but it has limitations. One is the sensitivity to initialization; in practical applications, considerable attention may need to be devoted to finding a good initialization. A second issue is that EM tends to be easiest to apply in cases where the latent variables have a clear decomposition (in the cases we have considered, they decompose across the instances). For these reasons, it is worth briefly considering some alternatives to EM. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_132_Chunk136 |
5.5. *OTHER APPROACHES TO LEARNING WITH LATENT VARIABLES 115 5.5.1 Sampling In EM clustering, there is a distribution q(i) for the missing data related to each instance. The M-step consists of updating the parameters of this distribution. An alternative is to draw samples of the latent variables. If the sampling distribution is designed correctly, this procedure will eventually converge to drawing samples from the true posterior over the missing data, p(z(1:Nz) | x(1:Nx)). For example, in the case of clustering, the missing data z(1:Nz) is the set of cluster memberships, y(1:N), so we draw samples from the pos- terior distribution over clusterings of the data. If a single clustering is required, we can select the one with the highest conditional likelihood, ˆz = argmaxz p(z(1:Nz) | x(1:Nx)). This general family of algorithms is called Markov Chain Monte Carlo (MCMC): “Monte Carlo” because it is based on a series of random draws; “Markov Chain” because the sampling procedure must be designed such that each sample depends only on the previous sample, and not on the entire sampling history. Gibbs sampling is an MCMC algorithm in which each latent variable is sampled from its posterior distribution, z(n) | x, z(−n) ∼p(z(n) | x, z(−n)), [5.43] where z(−n) indicates {z\z(n)}, the set of all latent variables except for z(n). Repeatedly drawing samples over all latent variables constructs a Markov chain that is guaranteed to converge to a sequence of samples from p(z(1:Nz) | x(1:Nx)). In probabilistic clustering, the sampling distribution has the following form, p(z(i) | x, z(−i)) = p(x(i) | z(i); φ) × p(z(i); µ) PK z=1 p(x(i) | z; φ) × p(z; µ) [5.44] ∝Multinomial(x(i); φz(i)) × µz(i). [5.45] In this case, the sampling distribution does not depend on the other instances: the poste- rior distribution over each z(i) can be computed from x(i) and the parameters given the parameters φ and µ. In sampling algorithms, there are several choices for how to deal with the parameters. One possibility is to sample them too. To do this, we must add them to the generative story, by introducing a prior distribution. For the multinomial and categorical parameters in the EM clustering model, the Dirichlet distribution is a typical choice, since it defines a probability on exactly the set of vectors that can be parameters: vectors that sum to one and include only non-negative numbers.10 To incorporate this prior, the generative model must be augmented to indicate that each φz ∼Dirichlet(αφ), and µ ∼Dirichlet(αµ). The hyperparameters α are typically set to a constant vector α = [α, α, . . . , α]. When α is large, the Dirichlet distribution tends to 10If PK i θi = 1 and θi ≥0 for all i, then θ is said to be on the K −1 simplex. A Dirichlet distribution with Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_133_Chunk137 |
116 CHAPTER 5. LEARNING WITHOUT SUPERVISION generate vectors that are nearly uniform; when α is small, it tends to generate vectors that assign most of their probability mass to a few entries. Given prior distributions over φ and µ, we can now include them in Gibbs sampling, drawing values for these parameters from posterior distributions that are conditioned on the other variables in the model. Unfortunately, sampling φ and µ usually leads to slow “mixing”, meaning that adja- cent samples tend to be similar, so that a large number of samples is required to explore the space of random variables. The reason is that the sampling distributions for the pa- rameters are tightly constrained by the cluster memberships y(i), which in turn are tightly constrained by the parameters. There are two solutions that are frequently employed: • Empirical Bayesian methods maintain φ and µ as parameters rather than latent variables. They still employ sampling in the E-step of the EM algorithm, but they update the parameters using expected counts that are computed from the samples rather than from parametric distributions. This EM-MCMC hybrid is also known as Monte Carlo Expectation Maximization (MCEM; Wei and Tanner, 1990), and is well-suited for cases in which it is difficult to compute q(i) directly. • In collapsed Gibbs sampling, we analytically integrate φ and µ out of the model. The cluster memberships y(i) are the only remaining latent variable; we sample them from the compound distribution, p(y(i) | x(1:N), y(−i); αφ, αµ) = Z φ,µ p(φ, µ | y(−i), x(1:N); αφ, αµ)p(y(i) | x(1:N), y(−i), φ, µ)dφdµ. [5.48] For multinomial and Dirichlet distributions, this integral can be computed in closed form. MCMC algorithms are guaranteed to converge to the true posterior distribution over the latent variables, but there is no way to know how long this will take. In practice, the rate of convergence depends on initialization, just as expectation-maximization depends on initialization to avoid local optima. Thus, while Gibbs Sampling and other MCMC algorithms provide a powerful and flexible array of techniques for statistical inference in latent variable models, they are not a panacea for the problems experienced by EM. parameter α ∈RK + has support over the K −1 simplex, pDirichlet(θ | α) = 1 B(α) K Y i=1 θαi−1 i [5.46] B(α) = QK i=1 Γ(αi) Γ(PK i=1 αi) , [5.47] with Γ(·) indicating the gamma function, a generalization of the factorial function to non-negative reals. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_134_Chunk138 |
5.5. *OTHER APPROACHES TO LEARNING WITH LATENT VARIABLES 117 5.5.2 Spectral learning Another approach to learning with latent variables is based on the method of moments, which makes it possible to avoid the problem of non-convex log-likelihood. Write x(i) for the normalized vector of word counts in document i, so that x(i) = x(i)/ PV j=1 x(i) j . Then we can form a matrix of word-word co-occurrence probabilities, C = N X i=1 x(i)(x(i))⊤. [5.49] The expected value of this matrix under p(x | φ, µ), as E[C] = N X i=1 K X k=1 Pr(Z(i) = k; µ)φkφ⊤ k [5.50] = K X k Nµkφkφ⊤ k [5.51] =ΦDiag(Nµ)Φ⊤, [5.52] where Φ is formed by horizontally concatenating φ1 . . . φK, and Diag(Nµ) indicates a diagonal matrix with values Nµk at position (k, k). Setting C equal to its expectation gives, C =ΦDiag(Nµ)Φ⊤, [5.53] which is similar to the eigendecomposition C = QΛQ⊤. This suggests that simply by finding the eigenvectors and eigenvalues of C, we could obtain the parameters φ and µ, and this is what motivates the name spectral learning. While moment-matching and eigendecomposition are similar in form, they impose different constraints on the solutions: eigendecomposition requires orthonormality, so that QQ⊤= I; in estimating the parameters of a text clustering model, we require that µ and the columns of Φ are probability vectors. Spectral learning algorithms must therefore include a procedure for converting the solution into vectors that are non-negative and sum to one. One approach is to replace eigendecomposition (or the related singular value decomposition) with non-negative matrix factorization (Xu et al., 2003), which guarantees that the solutions are non-negative (Arora et al., 2013). After obtaining the parameters φ and µ, the distribution over clusters can be com- puted from Bayes’ rule: p(z(i) | x(i); φ, µ) ∝p(x(i) | z(i); φ) × p(z(i); µ). [5.54] Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_135_Chunk139 |
118 CHAPTER 5. LEARNING WITHOUT SUPERVISION Spectral learning yields provably good solutions without regard to initialization, and can be quite fast in practice. However, it is more difficult to apply to a broad family of genera- tive models than EM and Gibbs Sampling. For more on applying spectral learning across a range of latent variable models, see Anandkumar et al. (2014). Additional resources There are a number of other learning paradigms that deviate from supervised learning. • Active learning: the learner selects unlabeled instances and requests annotations (Set- tles, 2012). • Multiple instance learning: labels are applied to bags of instances, with a positive label applied if at least one instance in the bag meets the criterion (Dietterich et al., 1997; Maron and Lozano-P´erez, 1998). • Constraint-driven learning: supervision is provided in the form of explicit con- straints on the learner (Chang et al., 2007; Ganchev et al., 2010). • Distant supervision: noisy labels are generated from an external resource (Mintz et al., 2009, also see § 17.2.3). • Multitask learning: the learner induces a representation that can be used to solve multiple classification tasks (Collobert et al., 2011). • Transfer learning: the learner must solve a classification task that differs from the labeled data (Pan and Yang, 2010). Expectation-maximization was introduced by Dempster et al. (1977), and is discussed in more detail by Murphy (2012). Like most machine learning treatments, Murphy focuses on continuous observations and Gaussian likelihoods, rather than the discrete observa- tions typically encountered in natural language processing. Murphy (2012) also includes an excellent chapter on MCMC; for a textbook-length treatment, see Robert and Casella (2013). For still more on Bayesian latent variable models, see Barber (2012), and for ap- plications of Bayesian models to natural language processing, see Cohen (2016). Surveys are available for semi-supervised learning (Zhu and Goldberg, 2009) and domain adapta- tion (Søgaard, 2013), although both pre-date the current wave of interest in deep learning. Exercises 1. Derive the expectation maximization update for the parameter µ in the EM cluster- ing model. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_136_Chunk140 |
5.5. *OTHER APPROACHES TO LEARNING WITH LATENT VARIABLES 119 2. Derive the E-step and M-step updates for the following generative model. You may assume that the labels y(i) are observed, but z(i) m is not. • For each instance i, – Draw label y(i) ∼Categorical(µ) – For each token m ∈{1, 2, . . . , M(i)} ∗Draw z(i) m ∼Categorical(π) ∗If z(i) m = 0, draw the current token from a label-specific distribution, w(i) m ∼φy(i) ∗If z(i) m = 1, draw the current token from a document-specific distribu- tion, w(i) m ∼ν(i) 3. Using the iterative updates in Equations 5.34-5.36, compute the outcome of the label propagation algorithm for the following examples. ? 0 1 ? ? 0 1 ? 0 1 ? ? The value inside the node indicates the label, y(i) ∈{0, 1}, with y(i) =? for unlabeled nodes. The presence of an edge between two nodes indicates wi,j = 1, and the absence of an edge indicates wi,j = 0. For the third example, you need only compute the first three iterations, and then you can guess at the solution in the limit. 4. Use expectation-maximization clustering to train a word-sense induction system, applied to the word say. • Import NLTK, run NLTK.DOWNLOAD() and select SEMCOR. Import SEMCOR from NLTK.CORPUS. • The command SEMCOR.TAGGED SENTENCES(TAG=’SENSE’) returns an itera- tor over sense-tagged sentences in the corpus. Each sentence can be viewed as an iterator over TREE objects. For TREE objects that are sense-annotated words, you can access the annotation as TREE.LABEL(), and the word itself with TREE.LEAVES(). So SEMCOR.TAGGED SENTENCES(TAG=’SENSE’)[0][2].LABEL() would return the sense annotation of the third word in the first sentence. • Extract all sentences containing the senses SAY.V.01 and SAY.V.02. • Build bag-of-words vectors x(i), containing the counts of other words in those sentences, including all words that occur in at least two sentences. • Implement and run expectation-maximization clustering on the merged data. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_137_Chunk141 |
120 CHAPTER 5. LEARNING WITHOUT SUPERVISION • Compute the frequency with which each cluster includes instances of SAY.V.01 and SAY.V.02. In the remaining exercises, you will try out some approaches for semisupervised learn- ing and domain adaptation. You will need datasets in multiple domains. You can obtain product reviews in multiple domains here: https://www.cs.jhu.edu/˜mdredze/ datasets/sentiment/processed_acl.tar.gz. Choose a source and target domain, e.g. dvds and books, and divide the data for the target domain into training and test sets of equal size. 5. First, quantify the cost of cross-domain transfer. • Train a logistic regression classifier on the source domain training set, and eval- uate it on the target domain test set. • Train a logistic regression classifier on the target domain training set, and eval- uate it on the target domain test set. This it the “direct transfer” baseline. Compute the difference in accuracy, which is a measure of the transfer loss across domains. 6. Next, apply the label propagation algorithm from § 5.3.2. As a baseline, using only 5% of the target domain training set, train a classifier, and compute its accuracy on the target domain test set. Next, apply label propagation: • Compute the label matrix QL for the labeled data (5% of the target domain training set), with each row equal to an indicator vector for the label (positive or negative). • Iterate through the target domain instances, including both test and training data. At each instance i, compute all wij, using Equation 5.32, with α = 0.01. Use these values to fill in column i of the transition matrix T, setting all but the ten largest values to zero for each column i. Be sure to normalize the column so that the remaining values sum to one. You may need to use a sparse matrix for this to fit into memory. • Apply the iterative updates from Equations 5.34-5.36 to compute the outcome of the label propagation algorithm for the unlabeled examples. Select the test set instances from QU, and compute the accuracy of this method. Compare with the supervised classifier trained only on the 5% sample of the target domain training set. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_138_Chunk142 |
5.5. *OTHER APPROACHES TO LEARNING WITH LATENT VARIABLES 121 7. Using only 5% of the target domain training data (and all of the source domain train- ing data), implement one of the supervised domain adaptation baselines in § 5.4.1. See if this improves on the “direct transfer” baseline from the previous problem 8. Implement EASYADAPT (§ 5.4.1), again using 5% of the target domain training data and all of the source domain data. 9. Now try unsupervised domain adaptation, using the “linear projection” method described in § 5.4.2. Specifically: • Identify 500 pivot features as the words with the highest frequency in the (com- plete) training data for the source and target domains. Specifically, let xd i be the count of the word i in domain d: choose the 500 words with the largest values of min(xsource i , xtarget i ). • Train a classifier to predict each pivot feature from the remaining words in the document. • Arrange the features of these classifiers into a matrix Φ, and perform truncated singular value decomposition, with k = 20 • Train a classifier from the source domain data, using the combined features x(i) ⊕U⊤x(i) — these include the original bag-of-words features, plus the pro- jected features. • Apply this classifier to the target domain test set, and compute the accuracy. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_139_Chunk143 |
Part II Sequences and trees 123 | nlp_Page_141_Chunk144 |
Chapter 6 Language models In probabilistic classification, the problem is to compute the probability of a label, condi- tioned on the text. Let’s now consider the inverse problem: computing the probability of text itself. Specifically, we will consider models that assign probability to a sequence of word tokens, p(w1, w2, . . . , wM), with wm ∈V. The set V is a discrete vocabulary, V = {aardvark, abacus, . . . , zither}. [6.1] Why would you want to compute the probability of a word sequence? In many appli- cations, the goal is to produce word sequences as output: • In machine translation (chapter 18), we convert from text in a source language to text in a target language. • In speech recognition, we convert from audio signal to text. • In summarization (§ 16.3.4; § 19.2), we convert from long texts into short texts. • In dialogue systems (§ 19.3), we convert from the user’s input (and perhaps an external knowledge base) into a text response. In many of the systems for performing these tasks, there is a subcomponent that com- putes the probability of the output text. The purpose of this component is to generate texts that are more fluent. For example, suppose we want to translate a sentence from Spanish to English. (6.1) El cafe negro me gusta mucho. Here is a literal word-for-word translation (a gloss): (6.2) The coffee black me pleases much. 125 | nlp_Page_143_Chunk145 |
126 CHAPTER 6. LANGUAGE MODELS A good language model of English will tell us that the probability of this translation is low, in comparison with more grammatical alternatives, p(The coffee black me pleases much) < p(I love dark coffee). [6.2] How can we use this fact? Warren Weaver, one of the early leaders in machine trans- lation, viewed it as a problem of breaking a secret code (Weaver, 1955): When I look at an article in Russian, I say: ’This is really written in English, but it has been coded in some strange symbols. I will now proceed to decode.’ This observation motivates a generative model (like Na¨ıve Bayes): • The English sentence w(e) is generated from a language model, pe(w(e)). • The Spanish sentence w(s) is then generated from a translation model, ps|e(w(s) | w(e)). Given these two distributions, translation can be performed by Bayes’ rule: pe|s(w(e) | w(s)) ∝pe,s(w(e), w(s)) [6.3] =ps|e(w(s) | w(e)) × pe(w(e)). [6.4] This is sometimes called the noisy channel model, because it envisions English text turning into Spanish by passing through a noisy channel, ps|e. What is the advantage of modeling translation this way, as opposed to modeling pe|s directly? The crucial point is that the two distributions ps|e (the translation model) and pe (the language model) can be estimated from separate data. The translation model requires examples of correct trans- lations, but the language model requires only text in English. Such monolingual data is much more widely available. Furthermore, once estimated, the language model pe can be reused in any application that involves generating English text, including translation from other languages. 6.1 N-gram language models A simple approach to computing the probability of a sequence of tokens is to use a relative frequency estimate. Consider the quote, attributed to Picasso, “computers are useless, they can only give you answers.” One way to estimate the probability of this sentence is, p(Computers are useless, they can only give you answers) = count(Computers are useless, they can only give you answers) count(all sentences ever spoken) [6.5] Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_144_Chunk146 |
6.1. N-GRAM LANGUAGE MODELS 127 This estimator is unbiased: in the theoretical limit of infinite data, the estimate will be correct. But in practice, we are asking for accurate counts over an infinite number of events, since sequences of words can be arbitrarily long. Even with an aggressive upper bound of, say, M = 20 tokens in the sequence, the number of possible sequences is V 20, where V = |V|. A small vocabularly for English would have V = 105, so there are 10100 possible sequences. Clearly, this estimator is very data-hungry, and suffers from high vari- ance: even grammatical sentences will have probability zero if they have not occurred in the training data.1 We therefore need to introduce bias to have a chance of making reli- able estimates from finite training data. The language models that follow in this chapter introduce bias in various ways. We begin with n-gram language models, which compute the probability of a sequence as the product of probabilities of subsequences. The probability of a sequence p(w) = p(w1, w2, . . . , wM) can be refactored using the chain rule (see § A.2): p(w) =p(w1, w2, . . . , wM) [6.6] =p(w1) × p(w2 | w1) × p(w3 | w2, w1) × . . . × p(wM | wM−1, . . . , w1) [6.7] Each element in the product is the probability of a word given all its predecessors. We can think of this as a word prediction task: given the context Computers are, we want to com- pute a probability over the next token. The relative frequency estimate of the probability of the word useless in this context is, p(useless | computers are) = count(computers are useless) P x∈V count(computers are x) = count(computers are useless) count(computers are) . We haven’t made any approximations yet, and we could have just as well applied the chain rule in reverse order, p(w) = p(wM) × p(wM−1 | wM) × . . . × p(w1 | w2, . . . , wM), [6.8] or in any other order. But this means that we also haven’t really made any progress: to compute the conditional probability p(wM | wM−1, wM−2, . . . , w1), we would need to model V M−1 contexts. Such a distribution cannot be estimated from any realistic sample of text. To solve this problem, n-gram models make a crucial simplifying approximation: they condition on only the past n −1 words. p(wm | wm−1 . . . w1) ≈p(wm | wm−1, . . . , wm−n+1) [6.9] 1Chomsky famously argued that this is evidence against the very concept of probabilistic language mod- els: no such model could distinguish the grammatical sentence colorless green ideas sleep furiously from the ungrammatical permutation furiously sleep ideas green colorless. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_145_Chunk147 |
128 CHAPTER 6. LANGUAGE MODELS This means that the probability of a sentence w can be approximated as p(w1, . . . , wM) ≈ M Y m=1 p(wm | wm−1, . . . , wm−n+1) [6.10] To compute the probability of an entire sentence, it is convenient to pad the beginning and end with special symbols □and ■. Then the bigram (n = 2) approximation to the probability of I like black coffee is: p(I like black coffee) = p(I | □) × p(like | I) × p(black | like) × p(coffee | black) × p(■| coffee). [6.11] This model requires estimating and storing the probability of only V n events, which is exponential in the order of the n-gram, and not V M, which is exponential in the length of the sentence. The n-gram probabilities can be computed by relative frequency estimation, p(wm | wm−1, wm−2) = count(wm−2, wm−1, wm) P w′ count(wm−2, wm−1, w′) [6.12] The hyperparameter n controls the size of the context used in each conditional proba- bility. If this is misspecified, the language model will perform poorly. Let’s consider the potential problems concretely. When n is too small. Consider the following sentences: (6.3) Gorillas always like to groom their friends. (6.4) The computer that’s on the 3rd floor of our office building crashed. In each example, the words written in bold depend on each other: the likelihood of their depends on knowing that gorillas is plural, and the likelihood of crashed de- pends on knowing that the subject is a computer. If the n-grams are not big enough to capture this context, then the resulting language model would offer probabili- ties that are too low for these sentences, and too high for sentences that fail basic linguistic tests like number agreement. When n is too big. In this case, it is hard good estimates of the n-gram parameters from our dataset, because of data sparsity. To handle the gorilla example, it is necessary to model 6-grams, which means accounting for V 6 events. Under a very small vocab- ulary of V = 104, this means estimating the probability of 1024 distinct events. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_146_Chunk148 |
6.2. SMOOTHING AND DISCOUNTING 129 These two problems point to another bias-variance tradeoff (see § 2.2.4). A small n- gram size introduces high bias, and a large n-gram size introduces high variance. We can even have both problems at the same time! Language is full of long-range dependen- cies that we cannot capture because n is too small; at the same time, language datasets are full of rare phenomena, whose probabilities we fail to estimate accurately because n is too large. One solution is to try to keep n large, while still making low-variance esti- mates of the underlying parameters. To do this, we will introduce a different sort of bias: smoothing. 6.2 Smoothing and discounting Limited data is a persistent problem in estimating language models. In § 6.1, we pre- sented n-grams as a partial solution. Bit sparse data can be a problem even for low-order n-grams; at the same time, many linguistic phenomena, like subject-verb agreement, can- not be incorporated into language models without high-order n-grams. It is therefore necessary to add additional inductive biases to n-gram language models. This section covers some of the most intuitive and common approaches, but there are many more (see Chen and Goodman, 1999). 6.2.1 Smoothing A major concern in language modeling is to avoid the situation p(w) = 0, which could arise as a result of a single unseen n-gram. A similar problem arose in Na¨ıve Bayes, and the solution was smoothing: adding imaginary “pseudo” counts. The same idea can be applied to n-gram language models, as shown here in the bigram case, psmooth(wm | wm−1) = count(wm−1, wm) + α P w′∈V count(wm−1, w′) + V α. [6.13] This basic framework is called Lidstone smoothing, but special cases have other names: • Laplace smoothing corresponds to the case α = 1. • Jeffreys-Perks law corresponds to the case α = 0.5, which works well in practice and benefits from some theoretical justification (Manning and Sch¨utze, 1999). To ensure that the probabilities are properly normalized, anything that we add to the numerator (α) must also appear in the denominator (V α). This idea is reflected in the concept of effective counts: c∗ i = (ci + α) M M + V α, [6.14] Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_147_Chunk149 |
130 CHAPTER 6. LANGUAGE MODELS Lidstone smoothing, α = 0.1 Discounting, d = 0.1 counts unsmoothed probability effective counts smoothed probability effective counts smoothed probability impropriety 8 0.4 7.826 0.391 7.9 0.395 offense 5 0.25 4.928 0.246 4.9 0.245 damage 4 0.2 3.961 0.198 3.9 0.195 deficiencies 2 0.1 2.029 0.101 1.9 0.095 outbreak 1 0.05 1.063 0.053 0.9 0.045 infirmity 0 0 0.097 0.005 0.25 0.013 cephalopods 0 0 0.097 0.005 0.25 0.013 Table 6.1: Example of Lidstone smoothing and absolute discounting in a bigram language model, for the context (alleged, ), for a toy corpus with a total of twenty counts over the seven words shown. Note that discounting decreases the probability for all but the un- seen words, while Lidstone smoothing increases the effective counts and probabilities for deficiencies and outbreak. where ci is the count of event i, c∗ i is the effective count, and M = PV i=1 ci is the total num- ber of tokens in the dataset (w1, w2, . . . , wM). This term ensures that PV i=1 c∗ i = PV i=1 ci = M. The discount for each n-gram is then computed as, di = c∗ i ci = (ci + α) ci M (M + V α). 6.2.2 Discounting and backoff Discounting “borrows” probability mass from observed n-grams and redistributes it. In Lidstone smoothing, the borrowing is done by increasing the denominator of the relative frequency estimates. The borrowed probability mass is then redistributed by increasing the numerator for all n-grams. Another approach would be to borrow the same amount of probability mass from all observed n-grams, and redistribute it among only the unob- served n-grams. This is called absolute discounting. For example, suppose we set an absolute discount d = 0.1 in a bigram model, and then redistribute this probability mass equally over the unseen words. The resulting probabilities are shown in Table 6.1. Discounting reserves some probability mass from the observed data, and we need not redistribute this probability mass equally. Instead, we can backoff to a lower-order lan- guage model: if you have trigrams, use trigrams; if you don’t have trigrams, use bigrams; if you don’t even have bigrams, use unigrams. This is called Katz backoff. In the simple Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_148_Chunk150 |
6.2. SMOOTHING AND DISCOUNTING 131 case of backing off from bigrams to unigrams, the bigram probabilities are, c∗(i, j) =c(i, j) −d [6.15] pKatz(i | j) = c∗(i,j) c(j) if c(i, j) > 0 α(j) × punigram(i) P i′:c(i′,j)=0 punigram(i′) if c(i, j) = 0. [6.16] The term α(j) indicates the amount of probability mass that has been discounted for context j. This probability mass is then divided across all the unseen events, {i′ : c(i′, j) = 0}, proportional to the unigram probability of each word i′. The discount parameter d can be optimized to maximize performance (typically held-out log-likelihood) on a develop- ment set. 6.2.3 *Interpolation Backoff is one way to combine different order n-gram models. An alternative approach is interpolation: setting the probability of a word in context to a weighted sum of its probabilities across progressively shorter contexts. Instead of choosing a single n for the size of the n-gram, we can take the weighted average across several n-gram probabilities. For example, for an interpolated trigram model, pInterpolation(wm | wm−1, wm−2) = λ3p∗ 3(wm | wm−1, wm−2) + λ2p∗ 2(wm | wm−1) + λ1p∗ 1(wm). In this equation, p∗ n is the unsmoothed empirical probability given by an n-gram lan- guage model, and λn is the weight assigned to this model. To ensure that the interpolated p(w) is still a valid probability distribution, the values of λ must obey the constraint, Pnmax n=1 λn = 1. But how to find the specific values? An elegant solution is expectation-maximization. Recall from chapter 5 that we can think about EM as learning with missing data: we just need to choose missing data such that learning would be easy if it weren’t missing. What’s missing in this case? Think of each word wm as drawn from an n-gram of unknown size, zm ∈{1 . . . nmax}. This zm is the missing data that we are looking for. Therefore, the application of EM to this problem involves the following generative model: for Each token wm, m = 1, 2, . . . , M do: draw the n-gram size zm ∼Categorical(λ); draw wm ∼p∗ zm(wm | wm−1, . . . , wm−zm). Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_149_Chunk151 |
132 CHAPTER 6. LANGUAGE MODELS If the missing data {Zm} were known, then λ could be estimated as the relative fre- quency, λz =count(Zm = z) M [6.17] ∝ M X m=1 δ(Zm = z). [6.18] But since we do not know the values of the latent variables Zm, we impute a distribution qm in the E-step, which represents the degree of belief that word token wm was generated from a n-gram of order zm, qm(z) ≜Pr(Zm = z | w1:m; λ) [6.19] = p(wm | w1:m−1, Zm = z) × p(z) P z′ p(wm | w1:m−1, Zm = z′) × p(z′) [6.20] ∝p∗ z(wm | w1:m−1) × λz. [6.21] In the M-step, λ is computed by summing the expected counts under q, λz ∝ M X m=1 qm(z). [6.22] A solution is obtained by iterating between updates to q and λ. The complete algorithm is shown in Algorithm 10. Algorithm 10 Expectation-maximization for interpolated language modeling 1: procedure ESTIMATE INTERPOLATED n-GRAM (w1:M, {p∗ n}n∈1:nmax) 2: for z ∈{1, 2, . . . , nmax} do ▷Initialization 3: λz ← 1 nmax 4: repeat 5: for m ∈{1, 2, . . . , M} do ▷E-step 6: for z ∈{1, 2, . . . , nmax} do 7: qm(z) ←p∗ z(wm | w1:m−) × λz 8: qm ←Normalize(qm) 9: for z ∈{1, 2, . . . , nmax} do ▷M-step 10: λz ← 1 M PM m=1 qm(z) 11: until tired 12: return λ Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_150_Chunk152 |
6.3. RECURRENT NEURAL NETWORK LANGUAGE MODELS 133 6.2.4 *Kneser-Ney smoothing Kneser-Ney smoothing is based on absolute discounting, but it redistributes the result- ing probability mass in a different way from Katz backoff. Empirical evidence points to Kneser-Ney smoothing as the state-of-art for n-gram language modeling (Goodman, 2001). To motivate Kneser-Ney smoothing, consider the example: I recently visited . Which of the following is more likely: Francisco or Duluth? Now suppose that both bigrams visited Duluth and visited Francisco are unobserved in the training data, and furthermore, that the unigram probability p∗ 1(Francisco) is greater than p∗ 1(Duluth). Nonetheless we would still guess that p(visited Duluth) > p(visited Francisco), because Duluth is a more “versatile” word: it can occur in many contexts, while Francisco usually occurs in a single context, following the word San. This notion of versatility is the key to Kneser-Ney smoothing. Writing u for a context of undefined length, and count(w, u) as the count of word w in context u, we define the Kneser-Ney bigram probability as pKN(w | u) = (max(count(w,u)−d,0) count(u) , count(w, u) > 0 α(u) × pcontinuation(w), otherwise [6.23] pcontinuation(w) = |u : count(w, u) > 0| P w′∈V |u′ : count(w′, u′) > 0|. [6.24] Probability mass using absolute discounting d, which is taken from all unobserved n-grams. The total amount of discounting in context u is d × |w : count(w, u) > 0|, and we divide this probability mass among the unseen n-grams. To account for versatility, we define the continuation probability pcontinuation(w) as proportional to the number of ob- served contexts in which w appears. The numerator of the continuation probability is the number of contexts u in which w appears; the denominator normalizes the probability by summing the same quantity over all words w′. The coefficient α(u) is set to ensure that the probability distribution pKN(w | u) sums to one over the vocabulary w. The idea of modeling versatility by counting contexts may seem heuristic, but there is an elegant theoretical justification from Bayesian nonparametrics (Teh, 2006). Kneser-Ney smoothing on n-grams was the dominant language modeling technique before the arrival of neural language models. 6.3 Recurrent neural network language models N-gram language models have been largely supplanted by neural networks. These mod- els do not make the n-gram assumption of restricted context; indeed, they can incorporate arbitrarily distant contextual information, while remaining computationally and statisti- cally tractable. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_151_Chunk153 |
134 CHAPTER 6. LANGUAGE MODELS h0 h1 h2 h3 · · · x1 x2 x3 · · · w1 w2 w3 · · · Figure 6.1: The recurrent neural network language model, viewed as an “unrolled” com- putation graph. Solid lines indicate direct computation, dotted blue lines indicate proba- bilistic dependencies, circles indicate random variables, and squares indicate computation nodes. The first insight behind neural language models is to treat word prediction as a dis- criminative learning task.2 The goal is to compute the probability p(w | u), where w ∈V is a word, and u is the context, which depends on the previous words. Rather than directly estimating the word probabilities from (smoothed) relative frequencies, we can treat treat language modeling as a machine learning problem, and estimate parameters that maxi- mize the log conditional probability of a corpus. The second insight is to reparametrize the probability distribution p(w | u) as a func- tion of two dense K-dimensional numerical vectors, βw ∈RK, and vu ∈RK, p(w | u) = exp(βw · vu) P w′∈V exp(βw′ · vu), [6.25] where βw · vu represents a dot product. As usual, the denominator ensures that the prob- ability distribution is properly normalized. This vector of probabilities is equivalent to applying the softmax transformation (see § 3.1) to the vector of dot-products, p(· | u) = SoftMax([β1 · vu, β2 · vu, . . . , βV · vu]). [6.26] The word vectors βw are parameters of the model, and are estimated directly. The context vectors vu can be computed in various ways, depending on the model. A simple but effective neural language model can be built from a recurrent neural network (RNN; Mikolov et al., 2010). The basic idea is to recurrently update the context vectors while moving through the sequence. Let hm represent the contextual information at position m 2This idea predates neural language models (e.g., Rosenfeld, 1996; Roark et al., 2007). Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_152_Chunk154 |
6.3. RECURRENT NEURAL NETWORK LANGUAGE MODELS 135 in the sequence. RNN language models are defined, xm ≜φwm [6.27] hm =RNN(xm, hm−1) [6.28] p(wm+1 | w1, w2, . . . , wm) = exp(βwm+1 · hm) P w′∈V exp(βw′ · hm), [6.29] where φ is a matrix of word embeddings, and xm denotes the embedding for word wm. The conversion of wm to xm is sometimes known as a lookup layer, because we simply lookup the embeddings for each word in a table; see § 3.2.4. The Elman unit defines a simple recurrent operation (Elman, 1990), RNN(xm, hm−1) ≜g(Θhm−1 + xm), [6.30] where Θ ∈RK×K is the recurrence matrix and g is a non-linear transformation function, often defined as the elementwise hyperbolic tangent tanh (see § 3.1).3 The tanh acts as a squashing function, ensuring that each element of hm is constrained to the range [−1, 1]. Although each wm depends on only the context vector hm−1, this vector is in turn influenced by all previous tokens, w1, w2, . . . wm−1, through the recurrence operation: w1 affects h1, which affects h2, and so on, until the information is propagated all the way to hm−1, and then on to wm (see Figure 6.1). This is an important distinction from n-gram language models, where any information outside the n-word window is ignored. In prin- ciple, the RNN language model can handle long-range dependencies, such as number agreement over long spans of text — although it would be difficult to know where exactly in the vector hm this information is represented. The main limitation is that informa- tion is attenuated by repeated application of the squashing function g. Long short-term memories (LSTMs), described below, are a variant of RNNs that address this issue, us- ing memory cells to propagate information through the sequence without applying non- linearities (Hochreiter and Schmidhuber, 1997). The denominator in Equation 6.29 is a computational bottleneck, because it involves a sum over the entire vocabulary. One solution is to use a hierarchical softmax function, which computes the sum more efficiently by organizing the vocabulary into a tree (Mikolov et al., 2011). Another strategy is to optimize an alternative metric, such as noise-contrastive estimation (Gutmann and Hyv¨arinen, 2012), which learns by distinguishing observed in- stances from artificial instances generated from a noise distribution (Mnih and Teh, 2012). Both of these strategies are described in § 14.5.3. 3In the original Elman network, the sigmoid function was used in place of tanh. For an illuminating mathematical discussion of the advantages and disadvantages of various nonlinearities in recurrent neural networks, see the lecture notes from Cho (2015). Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_153_Chunk155 |
136 CHAPTER 6. LANGUAGE MODELS 6.3.1 Backpropagation through time The recurrent neural network language model has the following parameters: • φi ∈RK, the “input” word vectors (these are sometimes called word embeddings, since each word is embedded in a K-dimensional space; see chapter 14); • βi ∈RK, the “output” word vectors; • Θ ∈RK×K, the recurrence operator; • h0, the initial state. Each of these parameters can be estimated by formulating an objective function over the training corpus, L(w), and then applying backpropagation to obtain gradients on the parameters from a minibatch of training examples (see § 3.3.1). Gradient-based updates can be computed from an online learning algorithm such as stochastic gradient descent (see § 2.6.2). The application of backpropagation to recurrent neural networks is known as back- propagation through time, because the gradients on units at time m depend in turn on the gradients of units at earlier times n < m. Let ℓm+1 represent the negative log-likelihood of word m + 1, ℓm+1 = −log p(wm+1 | w1, w2, . . . , wm). [6.31] We require the gradient of this loss with respect to each parameter, such as θk,k′, an indi- vidual element in the recurrence matrix Θ. Since the loss depends on the parameters only through hm, we can apply the chain rule of differentiation, ∂ℓm+1 ∂θk,k′ =∂ℓm+1 ∂hm ∂hm ∂θk,k′ . [6.32] The vector hm depends on Θ in several ways. First, hm is computed by multiplying Θ by the previous state hm−1. But the previous state hm−1 also depends on Θ: hm =g(xm, hm−1) [6.33] ∂hm,k ∂θk,k′ =g′(xm,k + θk · hm−1)(hm−1,k′ + θk · ∂hm−1 ∂θk,k′ ), [6.34] where g′ is the local derivative of the nonlinear function g. The key point in this equation is that the derivative ∂hm ∂θk,k′ depends on ∂hm−1 ∂θk,k′ , which will depend in turn on ∂hm−2 ∂θk,k′ , and so on, until reaching the initial state h0. Each derivative ∂hm ∂θk,k′ will be reused many times: it appears in backpropagation from the loss ℓm, but also in all subsequent losses ℓn>m. Neural network toolkits such as Torch (Collobert et al., 2011) and DyNet (Neubig et al., 2017) compute the necessary Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_154_Chunk156 |
6.3. RECURRENT NEURAL NETWORK LANGUAGE MODELS 137 derivatives automatically, and cache them for future use. An important distinction from the feedforward neural networks considered in chapter 3 is that the size of the computa- tion graph is not fixed, but varies with the length of the input. This poses difficulties for toolkits that are designed around static computation graphs, such as TensorFlow (Abadi et al., 2016).4 6.3.2 Hyperparameters The RNN language model has several hyperparameters that must be tuned to ensure good performance. The model capacity is controlled by the size of the word and context vectors K, which play a role that is somewhat analogous to the size of the n-gram context. For datasets that are large with respect to the vocabulary (i.e., there is a large token-to-type ratio), we can afford to estimate a model with a large K, which enables more subtle dis- tinctions between words and contexts. When the dataset is relatively small, then K must be smaller too, or else the model may “memorize” the training data, and fail to generalize. Unfortunately, this general advice has not yet been formalized into any concrete formula for choosing K, and trial-and-error is still necessary. Overfitting can also be prevented by dropout, which involves randomly setting some elements of the computation to zero (Sri- vastava et al., 2014), forcing the learner not to rely too much on any particular dimension of the word or context vectors. The dropout rate must also be tuned on development data. 6.3.3 Gated recurrent neural networks In principle, recurrent neural networks can propagate information across infinitely long sequences. But in practice, repeated applications of the nonlinear recurrence function causes this information to be quickly attenuated. The same problem affects learning: back- propagation can lead to vanishing gradients that decay to zero, or exploding gradients that increase towards infinity (Bengio et al., 1994). The exploding gradient problem can be addressed by clipping gradients at some maximum value (Pascanu et al., 2013). The other issues must be addressed by altering the model itself. The long short-term memory (LSTM; Hochreiter and Schmidhuber, 1997) is a popular variant of RNNs that is more robust to these problems. This model augments the hidden state hm with a memory cell cm. The value of the memory cell at each time m is a gated sum of two quantities: its previous value cm−1, and an “update” ˜cm, which is computed from the current input xm and the previous hidden state hm−1. The next state hm is then computed from the memory cell. Because the memory cell is not passed through a non- linear squashing function during the update, it is possible for information to propagate through the network over long distances. 4See https://www.tensorflow.org/tutorials/recurrent (retrieved Feb 8, 2018). Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_155_Chunk157 |
138 CHAPTER 6. LANGUAGE MODELS hm hm+1 om om+1 cm fm+1 cm+1 im im+1 ˜cm ˜cm+1 xm xm+1 Figure 6.2: The long short-term memory (LSTM) architecture. Gates are shown in boxes with dotted edges. In an LSTM language model, each hm would be used to predict the next word wm+1. The gates are functions of the input and previous hidden state. They are computed from elementwise sigmoid activations, σ(x) = (1+exp(−x))−1, ensuring that their values will be in the range [0, 1]. They can therefore be viewed as soft, differentiable logic gates. The LSTM architecture is shown in Figure 6.2, and the complete update equations are: fm+1 =σ(Θ(h→f)hm + Θ(x→f)xm+1 + bf) forget gate [6.35] im+1 =σ(Θ(h→i)hm + Θ(x→i)xm+1 + bi) input gate [6.36] ˜cm+1 = tanh(Θ(h→c)hm + Θ(w→c)xm+1) update candidate [6.37] cm+1 =fm+1 ⊙cm + im+1 ⊙˜cm+1 memory cell update [6.38] om+1 =σ(Θ(h→o)hm + Θ(x→o)xm+1 + bo) output gate [6.39] hm+1 =om+1 ⊙tanh(cm+1) output. [6.40] The operator ⊙is an elementwise (Hadamard) product. Each gate is controlled by a vec- tor of weights, which parametrize the previous hidden state (e.g., Θ(h→f)) and the current input (e.g., Θ(x→f)), plus a vector offset (e.g., bf). The overall operation can be infor- mally summarized as (hm, cm) = LSTM(xm, (hm−1, cm−1)), with (hm, cm) representing the LSTM state after reading token m. The LSTM outperforms standard recurrent neural networks across a wide range of problems. It was first used for language modeling by Sundermeyer et al. (2012), but can be applied more generally: the vector hm can be treated as a complete representation of Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_156_Chunk158 |
6.4. EVALUATING LANGUAGE MODELS 139 the input sequence up to position m, and can be used for any labeling task on a sequence of tokens, as we will see in the next chapter. There are several LSTM variants, of which the Gated Recurrent Unit (Cho et al., 2014) is one of the more well known. Many software packages implement a variety of RNN architectures, so choosing between them is simple from a user’s perspective. Jozefowicz et al. (2015) provide an empirical comparison of various modeling choices circa 2015. 6.4 Evaluating language models Language modeling is not usually an application in itself: language models are typically components of larger systems, and they would ideally be evaluated extrinisically. This means evaluating whether the language model improves performance on the application task, such as machine translation or speech recognition. But this is often hard to do, and depends on details of the overall system which may be irrelevant to language modeling. In contrast, intrinsic evaluation is task-neutral. Better performance on intrinsic metrics may be expected to improve extrinsic metrics across a variety of tasks, but there is always the risk of over-optimizing the intrinsic metric. This section discusses some intrinsic met- rics, but keep in mind the importance of performing extrinsic evaluations to ensure that intrinsic performance gains carry over to real applications. 6.4.1 Held-out likelihood The goal of probabilistic language models is to accurately measure the probability of se- quences of word tokens. Therefore, an intrinsic evaluation metric is the likelihood that the language model assigns to held-out data, which is not used during training. Specifically, we compute, ℓ(w) = M X m=1 log p(wm | wm−1, . . . , w1), [6.41] treating the entire held-out corpus as a single stream of tokens. Typically, unknown words are mapped to the ⟨UNK⟩token. This means that we have to estimate some probability for ⟨UNK⟩on the training data. One way to do this is to fix the vocabulary V to the V −1 words with the highest counts in the training data, and then convert all other tokens to ⟨UNK⟩. Other strategies for dealing with out-of-vocabulary terms are discussed in § 6.5. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_157_Chunk159 |
140 CHAPTER 6. LANGUAGE MODELS 6.4.2 Perplexity Held-out likelihood is usually presented as perplexity, which is a deterministic transfor- mation of the log-likelihood into an information-theoretic quantity, Perplex(w) = 2−ℓ(w) M , [6.42] where M is the total number of tokens in the held-out corpus. Lower perplexities correspond to higher likelihoods, so lower scores are better on this metric — it is better to be less perplexed. Here are some special cases: • In the limit of a perfect language model, probability 1 is assigned to the held-out corpus, with Perplex(w) = 2−1 M log2 1 = 20 = 1. • In the opposite limit, probability zero is assigned to the held-out corpus, which cor- responds to an infinite perplexity, Perplex(w) = 2−1 M log2 0 = 2∞= ∞. • Assume a uniform, unigram model in which p(wi) = 1 V for all words in the vocab- ulary. Then, log2(w) = M X m=1 log2 1 V = − M X m=1 log2 V = −M log2 V Perplex(w) =2 1 M M log2 V =2log2 V =V. This is the “worst reasonable case” scenario, since you could build such a language model without even looking at the data. In practice, language models tend to give perplexities in the range between 1 and V . A small benchmark dataset is the Penn Treebank, which contains roughly a million to- kens; its vocabulary is limited to 10,000 words, with all other tokens mapped a special ⟨UNK⟩symbol. On this dataset, a well-smoothed 5-gram model achieves a perplexity of 141 (Mikolov and Zweig, Mikolov and Zweig), and an LSTM language model achieves perplexity of roughly 80 (Zaremba, Sutskever, and Vinyals, Zaremba et al.). Various en- hancements to the LSTM architecture can bring the perplexity below 60 (Merity et al., 2018). A larger-scale language modeling dataset is the 1B Word Benchmark (Chelba et al., 2013), which contains text from Wikipedia. On this dataset, perplexities of around 25 can be obtained by averaging together multiple LSTM language models (Jozefowicz et al., 2016). Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_158_Chunk160 |
6.5. OUT-OF-VOCABULARY WORDS 141 6.5 Out-of-vocabulary words So far, we have assumed a closed-vocabulary setting — the vocabulary V is assumed to be a finite set. In realistic application scenarios, this assumption may not hold. Consider, for example, the problem of translating newspaper articles. The following sentence appeared in a Reuters article on January 6, 2017:5 The report said U.S. intelligence agencies believe Russian military intelligence, the GRU, used intermediaries such as WikiLeaks, DCLeaks.com and the Guc- cifer 2.0 ”persona” to release emails... Suppose that you trained a language model on the Gigaword corpus,6 which was released in 2003. The bolded terms either did not exist at this date, or were not widely known; they are unlikely to be in the vocabulary. The same problem can occur for a variety of other terms: new technologies, previously unknown individuals, new words (e.g., hashtag), and numbers. One solution is to simply mark all such terms with a special token, ⟨UNK⟩. While training the language model, we decide in advance on the vocabulary (often the K most common terms), and mark all other terms in the training data as ⟨UNK⟩. If we do not want to determine the vocabulary size in advance, an alternative approach is to simply mark the first occurrence of each word type as ⟨UNK⟩. But is often better to make distinctions about the likelihood of various unknown words. This is particularly important in languages that have rich morphological systems, with many inflections for each word. For example, Portuguese is only moderately complex from a morphological perspective, yet each verb has dozens of inflected forms (see Fig- ure 4.3b). In such languages, there will be many word types that we do not encounter in a corpus, which are nonetheless predictable from the morphological rules of the language. To use a somewhat contrived English example, if transfenestrate is in the vocabulary, our language model should assign a non-zero probability to the past tense transfenestrated, even if it does not appear in the training data. One way to accomplish this is to supplement word-level language models with character- level language models. Such models can use n-grams or RNNs, but with a fixed vocab- ulary equal to the set of ASCII or Unicode characters. For example, Ling et al. (2015) propose an LSTM model over characters, and Kim (2014) employ a convolutional neural network. A more linguistically motivated approach is to segment words into meaningful subword units, known as morphemes (see chapter 9). For example, Botha and Blunsom 5Bayoumy, Y. and Strobel, W. (2017, January 6). U.S. intel report: Putin directed cy- ber campaign to help Trump. Reuters. Retrieved from http://www.reuters.com/article/ us-usa-russia-cyber-idUSKBN14Q1T8 on January 7, 2017. 6https://catalog.ldc.upenn.edu/LDC2003T05 Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_159_Chunk161 |
142 CHAPTER 6. LANGUAGE MODELS (2014) induce vector representations for morphemes, which they build into a log-bilinear language model; Bhatia et al. (2016) incorporate morpheme vectors into an LSTM. Additional resources A variety of neural network architectures have been applied to language modeling. No- table earlier non-recurrent architectures include the neural probabilistic language model (Ben- gio et al., 2003) and the log-bilinear language model (Mnih and Hinton, 2007). Much more detail on these models can be found in the text by Goodfellow et al. (2016). Exercises 1. Prove that n-gram language models give valid probabilities if the n-gram probabil- ities are valid. Specifically, assume that, V X wm p(wm | wm−1, wm−2, . . . , wm−n+1) = 1 [6.43] for all contexts (wm−1, wm−2, . . . , wm−n+1). Prove that P w pn(w) = 1 for all w ∈V∗, where pn is the probability under an n-gram language model. Your proof should proceed by induction. You should handle the start-of-string case p(w1 | □, . . . , □ | {z } n−1 ), but you need not handle the end-of-string token. 2. First, show that RNN language models are valid using a similar proof technique to the one in the previous problem. Next, let pr(w) indicate the probability of w under RNN r. An ensemble of RNN language models computes the probability, p(w) = 1 R R X r=1 pr(w). [6.44] Does an ensemble of RNN language models compute a valid probability? 3. Consider a unigram language model over a vocabulary of size V . Suppose that a word appears m times in a corpus with M tokens in total. With Lidstone smoothing of α, for what values of m is the smoothed probability greater than the unsmoothed probability? 4. Consider a simple language in which each token is drawn from the vocabulary V with probability 1 V , independent of all other tokens. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_160_Chunk162 |
6.5. OUT-OF-VOCABULARY WORDS 143 Given a corpus of size M, what is the expectation of the fraction of all possible bigrams that have zero count? You may assume V is large enough that 1 V ≈ 1 V −1. 5. Continuing the previous problem, determine the value of M such that the fraction of bigrams with zero count is at most ϵ ∈(0, 1). As a hint, you may use the approxi- mation ln(1 + α) ≈α for α ≈0. 6. In real languages, words probabilities are neither uniform nor independent. Assume that word probabilities are independent but not uniform, so that in general p(w) ̸= 1 V . Prove that the expected fraction of unseen bigrams will be higher than in the IID case. 7. Consider a recurrent neural network with a single hidden unit and a sigmoid acti- vation, hm = σ(θhm−1 + xm). Prove that if |θ| < 1, then the gradient ∂hm ∂hm−k goes to zero as k →∞.7 8. Zipf’s law states that if the word types in a corpus are sorted by frequency, then the frequency of the word at rank r is proportional to r−s, where s is a free parameter, usually around 1. (Another way to view Zipf’s law is that a plot of log frequency against log rank will be linear.) Solve for s using the counts of the first and second most frequent words, c1 and c2. 9. Download the wikitext-2 dataset.8 Read in the training data and compute word counts. Estimate the Zipf’s law coefficient by, ˆs = exp (log r) · (log c) || log r||2 2 , [6.45] where r = [1, 2, 3, . . .] is the vector of ranks of all words in the corpus, and c = [c1, c2, c3, . . .] is the vector of counts of all words in the corpus, sorted in descending order. Make a log-log plot of the observed counts, and the expected counts according to Zipf’s law. The sum P∞ r=1 rs = ζ(s) is the Riemann zeta function, available in python’s scipy library as scipy.special.zeta. 10. Using the Pytorch library, train an LSTM language model from the Wikitext train- ing corpus. After each epoch of training, compute its perplexity on the Wikitext validation corpus. Stop training when the perplexity stops improving. 7This proof generalizes to vector hidden units by considering the largest eigenvector of the matrix Θ (Pas- canu et al., 2013). 8Available at https://github.com/pytorch/examples/tree/master/word_language_ model/data/wikitext-2 in September 2018. The dataset is already tokenized, and already replaces rare words with ⟨UNK⟩, so no preprocessing is necessary. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_161_Chunk163 |
Chapter 7 Sequence labeling The goal of sequence labeling is to assign tags to words, or more generally, to assign discrete labels to discrete elements in a sequence. There are many applications of se- quence labeling in natural language processing, and chapter 8 presents an overview. For now, we’ll focus on the classic problem of part-of-speech tagging, which requires tagging each word by its grammatical category. Coarse-grained grammatical categories include NOUNs, which describe things, properties, or ideas, and VERBs, which describe actions and events. Consider a simple input: (7.1) They can fish. A dictionary of coarse-grained part-of-speech tags might include NOUN as the only valid tag for they, but both NOUN and VERB as potential tags for can and fish. A accurate se- quence labeling algorithm should select the verb tag for both can and fish in (7.1), but it should select noun for the same two words in the phrase can of fish. 7.1 Sequence labeling as classification One way to solve a tagging problem is to turn it into a classification problem. Let f((w, m), y) indicate the feature function for tag y at position m in the sequence w = (w1, w2, . . . , wM). A simple tagging model would have a single base feature, the word itself: f((w = they can fish, m = 1), N) =(they, N) [7.1] f((w = they can fish, m = 2), V) =(can, V) [7.2] f((w = they can fish, m = 3), V) =(fish, V). [7.3] Here the feature function takes three arguments as input: the sentence to be tagged (e.g., they can fish), the proposed tag (e.g., N or V), and the index of the token to which this tag 145 | nlp_Page_163_Chunk164 |
146 CHAPTER 7. SEQUENCE LABELING is applied. This simple feature function then returns a single feature: a tuple including the word to be tagged and the tag that has been proposed. If the vocabulary size is V and the number of tags is K, then there are V × K features. Each of these features must be assigned a weight. These weights can be learned from a labeled dataset using a clas- sification algorithm such as perceptron, but this isn’t necessary in this case: it would be equivalent to define the classification weights directly, with θw,y = 1 for the tag y most frequently associated with word w, and θw,y = 0 for all other tags. However, it is easy to see that this simple classification approach cannot correctly tag both they can fish and can of fish, because can and fish are grammatically ambiguous. To han- dle both of these cases, the tagger must rely on context, such as the surrounding words. We can build context into the feature set by incorporating the surrounding words as ad- ditional features: f((w = they can fish, 1), N) = {(wm = they, ym = N), (wm−1 = □, ym = N), (wm+1 = can, ym = N)} [7.4] f((w = they can fish, 2), V) = {(wm = can, ym = V), (wm−1 = they, ym = V), (wm+1 = fish, ym = V)} [7.5] f((w = they can fish, 3), V) = {(wm = fish, ym = V), (wm−1 = can, ym = V), (wm+1 = ■, ym = V)}. [7.6] These features contain enough information that a tagger should be able to choose the right tag for the word fish: words that come after can are likely to be verbs, so the feature (wm−1 = can, ym = V) should have a large positive weight. However, even with this enhanced feature set, it may be difficult to tag some se- quences correctly. One reason is that there are often relationships between the tags them- selves. For example, in English it is relatively rare for a verb to follow another verb — particularly if we differentiate MODAL verbs like can and should from more typical verbs, like give, transcend, and befuddle. We would like to incorporate preferences against tag se- quences like VERB-VERB, and in favor of tag sequences like NOUN-VERB. The need for such preferences is best illustrated by a garden path sentence: (7.2) The old man the boat. Grammatically, the word the is a DETERMINER. When you read the sentence, what part of speech did you first assign to old? Typically, this word is an ADJECTIVE — abbrevi- ated as J — which is a class of words that modify nouns. Similarly, man is usually a noun. The resulting sequence of tags is D J N D N. But this is a mistaken “garden path” inter- pretation, which ends up leading nowhere. It is unlikely that a determiner would directly Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_164_Chunk165 |
7.2. SEQUENCE LABELING AS STRUCTURE PREDICTION 147 follow a noun,1 and it is particularly unlikely that the entire sentence would lack a verb. The only possible verb in (7.2) is the word man, which can refer to the act of maintaining and piloting something — often boats. But if man is tagged as a verb, then old is seated between a determiner and a verb, and must be a noun. And indeed, adjectives often have a second interpretation as nouns when used in this way (e.g., the young, the restless). This reasoning, in which the labeling decisions are intertwined, cannot be applied in a setting where each tag is produced by an independent classification decision. 7.2 Sequence labeling as structure prediction As an alternative, think of the entire sequence of tags as a label itself. For a given sequence of words w = (w1, w2, . . . , wM), there is a set of possible taggings Y(w) = YM, where Y = {N, V, D, . . .} refers to the set of individual tags, and YM refers to the set of tag sequences of length M. We can then treat the sequence labeling problem as a classification problem in the label space Y(w), ˆy = argmax y∈Y(w) Ψ(w, y), [7.7] where y = (y1, y2, . . . , yM) is a sequence of M tags, and Ψ is a scoring function on pairs of sequences, V M × YM →R. Such a function can include features that capture the rela- tionships between tagging decisions, such as the preference that determiners not follow nouns, or that all sentences have verbs. Given that the label space is exponentially large in the length of the sequence M, can it ever be practical to perform tagging in this way? The problem of making a series of in- terconnected labeling decisions is known as inference. Because natural language is full of interrelated grammatical structures, inference is a crucial aspect of natural language pro- cessing. In English, it is not unusual to have sentences of length M = 20; part-of-speech tag sets vary in size from 10 to several hundred. Taking the low end of this range, we have |Y(w1:M)| ≈1020, one hundred billion billion possible tag sequences. Enumerating and scoring each of these sequences would require an amount of work that is exponential in the sequence length, so inference is intractable. However, the situation changes when we restrict the scoring function. Suppose we choose a function that decomposes into a sum of local parts, Ψ(w, y) = M+1 X m=1 ψ(w, ym, ym−1, m), [7.8] where each ψ(·) scores a local part of the tag sequence. Note that the sum goes up to M +1, so that we can include a score for a special end-of-sequence tag, ψ(w1:M, ♦, yM, M + 1). We also define a special tag to begin the sequence, y0 ≜♦. 1The main exception occurs with ditransitive verbs, such as They gave the winner a trophy. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_165_Chunk166 |
148 CHAPTER 7. SEQUENCE LABELING In a linear model, local scoring function can be defined as a dot product of weights and features, ψ(w1:M, ym, ym−1, m) = θ · f(w, ym, ym−1, m). [7.9] The feature vector f can consider the entire input w, and can look at pairs of adjacent tags. This is a step up from per-token classification: the weights can assign low scores to infelicitous tag pairs, such as noun-determiner, and high scores for frequent tag pairs, such as determiner-noun and noun-verb. In the example they can fish, a minimal feature function would include features for word-tag pairs (sometimes called emission features) and tag-tag pairs (sometimes called transition features): f(w = they can fish, y = N V V ) = M+1 X m=1 f(w, ym, ym−1, m) [7.10] =f(w, N, ♦, 1) + f(w, V, N, 2) + f(w, V, V, 3) + f(w, ♦, V, 4) [7.11] =(wm = they, ym = N) + (ym = N, ym−1 = ♦) + (wm = can, ym = V) + (ym = V, ym−1 = N) + (wm = fish, ym = V) + (ym = V, ym−1 = V) + (ym = ♦, ym−1 = V). [7.12] There are seven active features for this example: one for each word-tag pair, and one for each tag-tag pair, including a final tag yM+1 = ♦. These features capture the two main sources of information for part-of-speech tagging in English: which tags are appropriate for each word, and which tags tend to follow each other in sequence. Given appropriate weights for these features, taggers can achieve high accuracy, even for difficult cases like the old man the boat. We will now discuss how this restricted scoring function enables efficient inference, through the Viterbi algorithm (Viterbi, 1967). Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_166_Chunk167 |
7.3. THE VITERBI ALGORITHM 149 7.3 The Viterbi algorithm By decomposing the scoring function into a sum of local parts, it is possible to rewrite the tagging problem as follows: ˆy = argmax y∈Y(w) Ψ(w, y) [7.13] = argmax y1:M M+1 X m=1 ψ(w, ym, ym−1, m) [7.14] = argmax y1:M M+1 X m=1 sm(ym, ym−1), [7.15] where the final line simplifies the notation with the shorthand, sm(ym, ym−1) ≜ψ(w1:M, ym, ym−1, m). [7.16] This inference problem can be solved efficiently using dynamic programming, an al- gorithmic technique for reusing work in recurrent computations. We begin by solving an auxiliary problem: rather than finding the best tag sequence, we compute the score of the best tag sequence, max y1:M Ψ(w, y1:M) = max y1:M M+1 X m=1 sm(ym, ym−1). [7.17] This score involves a maximization over all tag sequences of length M, written maxy1:M . This maximization can be broken into two pieces, max y1:M Ψ(w, y1:M) = max yM max y1:M−1 M+1 X m=1 sm(ym, ym−1). [7.18] Within the sum, only the final term sM+1(♦, yM) depends on yM, so we can pull this term out of the second maximization, max y1:M Ψ(w, y1:M) = max yM sM+1(♦, yM) + max y1:M−1 M X m=1 sm(ym, ym−1) ! . [7.19] The second term in Equation 7.19 has the same form as our original problem, with M replaced by M−1. This indicates that the problem can be reformulated as a recurrence. We do this by defining an auxiliary variable called the Viterbi variable vm(k), representing Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_167_Chunk168 |
150 CHAPTER 7. SEQUENCE LABELING Algorithm 11 The Viterbi algorithm. Each sm(k, k′) is a local score for tag ym = k and ym−1 = k′. for k ∈{0, . . . K} do v1(k) = s1(k, ♦) for m ∈{2, . . . , M} do for k ∈{0, . . . , K} do vm(k) = maxk′ sm(k, k′) + vm−1(k′) bm(k) = argmaxk′ sm(k, k′) + vm−1(k′) yM = argmaxk sM+1(♦, k) + vM(k) for m ∈{M −1, . . . 1} do ym = bm(ym+1) return y1:M the score of the best sequence terminating in the tag k: vm(ym) ≜max y1:m−1 m X n=1 sn(yn, yn−1) [7.20] = max ym−1 sm(ym, ym−1) + max y1:m−2 m−1 X n=1 sn(yn, yn−1) [7.21] = max ym−1 sm(ym, ym−1) + vm−1(ym−1). [7.22] Each set of Viterbi variables is computed from the local score sm(ym, ym−1), and from the previous set of Viterbi variables. The initial condition of the recurrence is simply the score for the first tag, v1(y1) ≜s1(y1, ♦). [7.23] The maximum overall score for the sequence is then the final Viterbi variable, max y1:M Ψ(w1:M, y1:M) =vM+1(♦). [7.24] Thus, the score of the best labeling for the sequence can be computed in a single forward sweep: first compute all variables v1(·) from Equation 7.23, and then compute all variables v2(·) from the recurrence in Equation 7.22, continuing until the final variable vM+1(♦). The Viterbi variables can be arranged in a structure known as a trellis, shown in Fig- ure 7.1. Each column indexes a token m in the sequence, and each row indexes a tag in Y; every vm−1(k) is connected to every vm(k′), indicating that vm(k′) is computed from vm−1(k). Special nodes are set aside for the start and end states. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_168_Chunk169 |
7.3. THE VITERBI ALGORITHM 151 0 they can fish -10 N -3 -9 -9 V -12 -5 -11 Figure 7.1: The trellis representation of the Viterbi variables, for the example they can fish, using the weights shown in Table 7.1. The original goal was to find the best scoring sequence, not simply to compute its score. But by solving the auxiliary problem, we are almost there. Recall that each vm(k) represents the score of the best tag sequence ending in that tag k in position m. To compute this, we maximize over possible values of ym−1. By keeping track of the “argmax” tag that maximizes this choice at each step, we can walk backwards from the final tag, and recover the optimal tag sequence. This is indicated in Figure 7.1 by the thick lines, which we trace back from the final position. These backward pointers are written bm(k), indicating the optimal tag ym−1 on the path to Ym = k. The complete Viterbi algorithm is shown in Algorithm 11. When computing the initial Viterbi variables v1(·), the special tag ♦indicates the start of the sequence. When comput- ing the final tag YM, another special tag,♦indicates the end of the sequence. These special tags enable the use of transition features for the tags that begin and end the sequence: for example, conjunctions are unlikely to end sentences in English, so we would like a low score for sM+1(♦, CC); nouns are relatively likely to appear at the beginning of sentences, so we would like a high score for s1(N, ♦), assuming the noun tag is compatible with the first word token w1. Complexity If there are K tags and M positions in the sequence, then there are M × K Viterbi variables to compute. Computing each variable requires finding a maximum over K possible predecessor tags. The total time complexity of populating the trellis is there- fore O(MK2), with an additional factor for the number of active features at each position. After completing the trellis, we simply trace the backwards pointers to the beginning of the sequence, which takes O(M) operations. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_169_Chunk170 |
152 CHAPTER 7. SEQUENCE LABELING they can fish N −2 −3 −3 V −10 −1 −3 (a) Weights for emission features. N V ♦ ♦ −1 −2 −∞ N −3 −1 −1 V −1 −3 −1 (b) Weights for transition features. The “from” tags are on the columns, and the “to” tags are on the rows. Table 7.1: Feature weights for the example trellis shown in Figure 7.1. Emission weights from ♦and ♦are implicitly set to −∞. 7.3.1 Example Consider the minimal tagset {N, V}, corresponding to nouns and verbs. Even in this tagset, there is considerable ambiguity: for example, the words can and fish can each take both tags. Of the 2 × 2 × 2 = 8 possible taggings for the sentence they can fish, four are possible given these possible tags, and two are grammatical.2 The values in the trellis in Figure 7.1 are computed from the feature weights defined in Table 7.1. We begin with v1(N), which has only one possible predecessor, the start tag ♦. This score is therefore equal to s1(N, ♦) = −2 −1 = −3, which is the sum of the scores for the emission and transition features respectively; the backpointer is b1(N) = ♦. The score for v1(V) is computed in the same way: s1(V, ♦) = −10 −2 = −12, and again b1(V) = ♦. The backpointers are represented in the figure by thick lines. Things get more interesting at m = 2. The score v2(N) is computed by maximizing over the two possible predecessors, v2(N) = max(v1(N) + s2(N, N), v1(V) + s2(N, V)) [7.25] = max(−3 −3 −3, −12 −3 −1) = −9 [7.26] b2(N) =N. [7.27] This continues until reaching v4(♦), which is computed as, v4(♦) = max(v3(N) + s4(♦, N), v3(V) + s4(♦, V)) [7.28] = max(−9 + 0 −1, −11 + 0 −1) [7.29] = −10, [7.30] so b4(♦) = N. As there is no emission w4, the emission features have scores of zero. 2The tagging they/N can/V fish/N corresponds to the scenario of putting fish into cans, or perhaps of firing them. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_170_Chunk171 |
7.4. HIDDEN MARKOV MODELS 153 To compute the optimal tag sequence, we walk backwards from here, next checking b3(N) = V, and then b2(V) = N, and finally b1(N) = ♦. This yields y = (N, V, N), which corresponds to the linguistic interpretation of the fishes being put into cans. 7.3.2 Higher-order features The Viterbi algorithm was made possible by a restriction of the scoring function to local parts that consider only pairs of adjacent tags. We can think of this as a bigram language model over tags. A natural question is how to generalize Viterbi to tag trigrams, which would involve the following decomposition: Ψ(w, y) = M+2 X m=1 f(w, ym, ym−1, ym−2, m), [7.31] where y−1 = ♦and yM+2 = ♦. One solution is to create a new tagset Y(2) from the Cartesian product of the original tagset with itself, Y(2) = Y × Y. The tags in this product space are ordered pairs, rep- resenting adjacent tags at the token level: for example, the tag (N, V) would represent a noun followed by a verb. Transitions between such tags must be consistent: we can have a transition from (N, V) to (V, N) (corresponding to the tag sequence N V N), but not from (N, V) to (N, N), which would not correspond to any coherent tag sequence. This con- straint can be enforced in feature weights, with θ((a,b),(c,d)) = −∞if b ̸= c. The remaining feature weights can encode preferences for and against various tag trigrams. In the Cartesian product tag space, there are K2 tags, suggesting that the time com- plexity will increase to O(MK4). However, it is unnecessary to max over predecessor tag bigrams that are incompatible with the current tag bigram. By exploiting this constraint, it is possible to limit the time complexity to O(MK3). The space complexity grows to O(MK2), since the trellis must store all possible predecessors of each tag. In general, the time and space complexity of higher-order Viterbi grows exponentially with the order of the tag n-grams that are considered in the feature decomposition. 7.4 Hidden Markov Models The Viterbi sequence labeling algorithm is built on the scores sm(y, y′). We will now discuss how these scores can be estimated probabilistically. Recall from § 2.2 that the probabilistic Na¨ıve Bayes classifier selects the label y to maximize p(y | x) ∝p(y, x). In probabilistic sequence labeling, our goal is similar: select the tag sequence that maximizes p(y | w) ∝p(y, w). The locality restriction in Equation 7.8 can be viewed as a conditional independence assumption on the random variables y. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_171_Chunk172 |
154 CHAPTER 7. SEQUENCE LABELING Algorithm 12 Generative process for the hidden Markov model y0 ←♦, m ←1 repeat ym ∼Categorical(λym−1) ▷sample the current tag wm ∼Categorical(φym) ▷sample the current word until ym = ♦ ▷terminate when the stop symbol is generated Na¨ıve Bayes was introduced as a generative model — a probabilistic story that ex- plains the observed data as well as the hidden label. A similar story can be constructed for probabilistic sequence labeling: first, the tags are drawn from a prior distribution; next, the tokens are drawn from a conditional likelihood. However, for inference to be tractable, additional independence assumptions are required. First, the probability of each token depends only on its tag, and not on any other element in the sequence: p(w | y) = M Y m=1 p(wm | ym). [7.32] Second, each tag ym depends only on its predecessor, p(y) = M Y m=1 p(ym | ym−1), [7.33] where y0 = ♦in all cases. Due to this Markov assumption, probabilistic sequence labeling models are known as hidden Markov models (HMMs). The generative process for the hidden Markov model is shown in Algorithm 12. Given the parameters λ and φ, we can compute p(w, y) for any token sequence w and tag se- quence y. The HMM is often represented as a graphical model (Wainwright and Jordan, 2008), as shown in Figure 7.2. This representation makes the independence assumptions explicit: if a variable v1 is probabilistically conditioned on another variable v2, then there is an arrow v2 →v1 in the diagram. If there are no arrows between v1 and v2, they are conditionally independent, given each variable’s Markov blanket. In the hidden Markov model, the Markov blanket for each tag ym includes the “parent” ym−1, and the “children” ym+1 and wm.3 It is important to reflect on the implications of the HMM independence assumptions. A non-adjacent pair of tags ym and yn are conditionally independent; if m < n and we are given yn−1, then ym offers no additional information about yn. However, if we are not given any information about the tags in a sequence, then all tags are probabilistically coupled. 3In general graphical models, a variable’s Markov blanket includes its parents, children, and its children’s other parents (Murphy, 2012). Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_172_Chunk173 |
7.4. HIDDEN MARKOV MODELS 155 y1 y2 · · · yM w1 w2 · · · wM Figure 7.2: Graphical representation of the hidden Markov model. Arrows indicate prob- abilistic dependencies. 7.4.1 Estimation The hidden Markov model has two groups of parameters: Emission probabilities. The probability pe(wm | ym; φ) is the emission probability, since the words are treated as probabilistically “emitted”, conditioned on the tags. Transition probabilities. The probability pt(ym | ym−1; λ) is the transition probability, since it assigns probability to each possible tag-to-tag transition. Both of these groups of parameters are typically computed from smoothed relative frequency estimation on a labeled corpus (see § 6.2 for a review of smoothing). The un- smoothed probabilities are, φk,i ≜Pr(Wm = i | Ym = k) = count(Wm = i, Ym = k) count(Ym = k) λk,k′ ≜Pr(Ym = k′ | Ym−1 = k) = count(Ym = k′, Ym−1 = k) count(Ym−1 = k) . Smoothing is more important for the emission probability than the transition probability, because the vocabulary is much larger than the number of tags. 7.4.2 Inference The goal of inference in the hidden Markov model is to find the highest probability tag sequence, ˆy = argmax y p(y | w). [7.34] As in Na¨ıve Bayes, it is equivalent to find the tag sequence with the highest log-probability, since the logarithm is a monotonically increasing function. It is furthermore equivalent to maximize the joint probability p(y, w) = p(y | w) × p(w) ∝p(y | w), which is pro- portional to the conditional probability. Putting these observations together, the inference Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_173_Chunk174 |
156 CHAPTER 7. SEQUENCE LABELING problem can be reformulated as, ˆy = argmax y log p(y, w). [7.35] We can now apply the HMM independence assumptions: log p(y, w) = log p(y) + log p(w | y) [7.36] = M+1 X m=1 log pY (ym | ym−1) + log pW|Y (wm | ym) [7.37] = M+1 X m=1 log λym,ym−1 + log φym,wm [7.38] = M+1 X m=1 sm(ym, ym−1), [7.39] where, sm(ym, ym−1) ≜log λym,ym−1 + log φym,wm, [7.40] and, φ♦,w = ( 1, w = ■ 0, otherwise, [7.41] which ensures that the stop tag ♦can only be applied to the final token ■. This derivation shows that HMM inference can be viewed as an application of the Viterbi decoding algorithm, given an appropriately defined scoring function. The local score sm(ym, ym−1) can be interpreted probabilistically, sm(ym, ym−1) = log py(ym | ym−1) + log pw|y(wm | ym) [7.42] = log p(ym, wm | ym−1). [7.43] Now recall the definition of the Viterbi variables, vm(ym) = max ym−1 sm(ym, ym−1) + vm−1(ym−1) [7.44] = max ym−1 log p(ym, wm | ym−1) + vm−1(ym−1). [7.45] By setting vm−1(ym−1) = maxy1:m−2 log p(y1:m−1, w1:m−1), we obtain the recurrence, vm(ym) = max ym−1 log p(ym, wm | ym−1) + max y1:m−2 log p(y1:m−1, w1:m−1) [7.46] = max y1:m−1 log p(ym, wm | ym−1) + log p(y1:m−1, w1:m−1) [7.47] = max y1:m−1 log p(y1:m, w1:m). [7.48] Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_174_Chunk175 |
7.5. DISCRIMINATIVE SEQUENCE LABELING WITH FEATURES 157 In words, the Viterbi variable vm(ym) is the log probability of the best tag sequence ending in ym, joint with the word sequence w1:m. The log probability of the best complete tag sequence is therefore, max y1:M log p(y1:M+1, w1:M+1) = vM+1(♦) [7.49] *Viterbi as an example of the max-product algorithm The Viterbi algorithm can also be implemented using probabilities, rather than log-probabilities. In this case, each vm(ym) is equal to, vm(ym) = max y1:m−1 p(y1:m−1, ym, w1:m) [7.50] = max ym−1 p(ym, wm | ym−1) × max y1:m−2 p(y1:m−2, ym−1, w1:m−1) [7.51] = max ym−1 p(ym, wm | ym−1) × vm−1(ym−1) [7.52] =pw|y(wm | ym) × max ym−1 py(ym | ym−1) × vm−1(ym−1). [7.53] Each Viterbi variable is computed by maximizing over a set of products. Thus, the Viterbi algorithm is a special case of the max-product algorithm for inference in graphical mod- els (Wainwright and Jordan, 2008). However, the product of probabilities tends towards zero over long sequences, so the log-probability version of Viterbi is recommended in practical implementations. 7.5 Discriminative sequence labeling with features Today, hidden Markov models are rarely used for supervised sequence labeling. This is because HMMs are limited to only two phenomena: • word-tag compatibility, via the emission probability pW|Y (wm | ym); • local context, via the transition probability pY (ym | ym−1). The Viterbi algorithm permits the inclusion of richer information in the local scoring func- tion ψ(w1:M, ym, ym−1, m), which can be defined as a weighted sum of arbitrary local fea- tures, ψ(w, ym, ym−1, m) = θ · f(w, ym, ym−1, m), [7.54] where f is a locally-defined feature function, and θ is a vector of weights. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_175_Chunk176 |
158 CHAPTER 7. SEQUENCE LABELING The local decomposition of the scoring function Ψ is reflected in a corresponding de- composition of the feature function: Ψ(w, y) = M+1 X m=1 ψ(w, ym, ym−1, m) [7.55] = M+1 X m=1 θ · f(w, ym, ym−1, m) [7.56] =θ · M+1 X m=1 f(w, ym, ym−1, m) [7.57] =θ · f (global)(w, y1:M), [7.58] where f (global)(w, y) is a global feature vector, which is a sum of local feature vectors, f (global)(w, y) = M+1 X m=1 f(w1:M, ym, ym−1, m), [7.59] with yM+1 = ♦and y0 = ♦by construction. Let’s now consider what additional information these features might encode. Word affix features. Consider the problem of part-of-speech tagging on the first four lines of the poem Jabberwocky (Carroll, 1917): (7.3) ’Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe. Many of these words were made up by the author of the poem, so a corpus would offer no information about their probabilities of being associated with any particular part of speech. Yet it is not so hard to see what their grammatical roles might be in this passage. Context helps: for example, the word slithy follows the determiner the, so it is probably a noun or adjective. Which do you think is more likely? The suffix -thy is found in a number of adjectives, like frothy, healthy, pithy, worthy. It is also found in a handful of nouns — e.g., apathy, sympathy — but nearly all of these have the longer coda -pathy, unlike slithy. So the suffix gives some evidence that slithy is an adjective, and indeed it is: later in the text we find that it is a combination of the adjectives lithe and slimy.4 4Morphology is the study of how words are formed from smaller linguistic units. chapter 9 touches on computational approaches to morphological analysis. See Bender (2013) for an overview of the underlying linguistic principles, and Haspelmath and Sims (2013) or Lieber (2015) for a full treatment. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_176_Chunk177 |
7.5. DISCRIMINATIVE SEQUENCE LABELING WITH FEATURES 159 Fine-grained context. The hidden Markov model captures contextual information in the form of part-of-speech tag bigrams. But sometimes, the necessary contextual information is more specific. Consider the noun phrases this fish and these fish. Many part-of-speech tagsets distinguish between singular and plural nouns, but do not distinguish between singular and plural determiners; for example, the well known Penn Treebank tagset fol- lows these conventions. A hidden Markov model would be unable to correctly label fish as singular or plural in both of these cases, because it only has access to two features: the pre- ceding tag (determiner in both cases) and the word (fish in both cases). The classification- based tagger discussed in § 7.1 had the ability to use preceding and succeeding words as features, and it can also be incorporated into a Viterbi-based sequence labeler as a local feature. Example. Consider the tagging D J N (determiner, adjective, noun) for the sequence the slithy toves, so that w =the slithy toves y =D J N. Let’s create the feature vector for this example, assuming that we have word-tag features (indicated by W), tag-tag features (indicated by T), and suffix features (indicated by M). You can assume that you have access to a method for extracting the suffix -thy from slithy, -es from toves, and ∅from the, indicating that this word has no suffix.5 The resulting feature vector is, f(the slithy toves, D J N) =f(the slithy toves, D, ♦, 1) + f(the slithy toves, J, D, 2) + f(the slithy toves, N, J, 3) + f(the slithy toves, ♦, N, 4) ={(T : ♦, D), (W : the, D), (M : ∅, D), (T : D, J), (W : slithy, J), (M : -thy, J), (T : J, N), (W : toves, N), (M : -es, N) (T : N, ♦)}. These examples show that local features can incorporate information that lies beyond the scope of a hidden Markov model. Because the features are local, it is possible to apply the Viterbi algorithm to identify the optimal sequence of tags. The remaining question 5Such a system is called a morphological segmenter. The task of morphological segmentation is briefly described in § 9.1.4; a well known segmenter is MORFESSOR (Creutz and Lagus, 2007). In real applications, a typical approach is to include features for all orthographic suffixes up to some maximum number of charac- ters: for slithy, we would have suffix features for -y, -hy, and -thy. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_177_Chunk178 |
160 CHAPTER 7. SEQUENCE LABELING is how to estimate the weights on these features. § 2.3 presented three main types of discriminative classifiers: perceptron, support vector machine, and logistic regression. Each of these classifiers has a structured equivalent, enabling it to be trained from labeled sequences rather than individual tokens. 7.5.1 Structured perceptron The perceptron classifier is trained by increasing the weights for features that are asso- ciated with the correct label, and decreasing the weights for features that are associated with incorrectly predicted labels: ˆy = argmax y∈Y θ · f(x, y) [7.60] θ(t+1) ←θ(t) + f(x, y) −f(x, ˆy). [7.61] We can apply exactly the same update in the case of structure prediction, ˆy = argmax y∈Y(w) θ · f(w, y) [7.62] θ(t+1) ←θ(t) + f(w, y) −f(w, ˆy). [7.63] This learning algorithm is called structured perceptron, because it learns to predict the structured output y. The only difference is that instead of computing ˆy by enumerating the entire set Y, the Viterbi algorithm is used to efficiently search the set of possible tag- gings, YM. Structured perceptron can be applied to other structured outputs as long as efficient inference is possible. As in perceptron classification, weight averaging is crucial to get good performance (see § 2.3.2). Example For the example they can fish, suppose that the reference tag sequence is y(i) = N V V, but the tagger incorrectly returns the tag sequence ˆy = N V N. Assuming a model with features for emissions (wm, ym) and transitions (ym−1, ym), the corresponding struc- tured perceptron update is: θ(fish,V) ←θ(fish,V) + 1, θ(fish,N) ←θ(fish,N) −1 [7.64] θ(V,V) ←θ(V,V) + 1, θ(V,N) ←θ(V,N) −1 [7.65] θ(V,♦) ←θ(V,♦) + 1, θ(N,♦) ←θ(N,♦) −1. [7.66] 7.5.2 Structured support vector machines Large-margin classifiers such as the support vector machine improve on the perceptron by pushing the classification boundary away from the training instances. The same idea can Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_178_Chunk179 |
7.5. DISCRIMINATIVE SEQUENCE LABELING WITH FEATURES 161 be applied to sequence labeling. A support vector machine in which the output is a struc- tured object, such as a sequence, is called a structured support vector machine (Tsochan- taridis et al., 2004).6 In classification, we formalized the large-margin constraint as, ∀y ̸= y(i), θ · f(x, y(i)) −θ · f(x, y) ≥1, [7.67] requiring a margin of at least 1 between the scores for all labels y that are not equal to the correct label y(i). The weights θ are then learned by constrained optimization (see § 2.4.2). This idea can be applied to sequence labeling by formulating an equivalent set of con- straints for all possible labelings Y(w) for an input w. However, there are two problems. First, in sequence labeling, some predictions are more wrong than others: we may miss only one tag out of fifty, or we may get all fifty wrong. We would like our learning algo- rithm to be sensitive to this difference. Second, the number of constraints is equal to the number of possible labelings, which is exponentially large in the length of the sequence. The first problem can be addressed by adjusting the constraint to require larger mar- gins for more serious errors. Let c(y(i), ˆy) ≥0 represent the cost of predicting label ˆy when the true label is y(i). We can then generalize the margin constraint, ∀y, θ · f(w(i), y(i)) −θ · f(w(i), y) ≥c(y(i), y). [7.68] This cost-augmented margin constraint specializes to the constraint in Equation 7.67 if we choose the delta function c(y(i), y) = δ (() y(i) ̸= y). A more expressive cost function is the Hamming cost, c(y(i), y) = M X m=1 δ(y(i) m ̸= ym), [7.69] which computes the number of errors in y. By incorporating the cost function as the margin constraint, we require that the true labeling be seperated from the alternatives by a margin that is proportional to the number of incorrect tags in each alternative labeling. The second problem is that the number of constraints is exponential in the length of the sequence. This can be addressed by focusing on the prediction ˆy that maximally violates the margin constraint. This prediction can be identified by solving the following cost-augmented decoding problem: ˆy = argmax y̸=y(i) θ · f(w(i), y) −θ · f(w(i), y(i)) + c(y(i), y) [7.70] = argmax y̸=y(i) θ · f(w(i), y) + c(y(i), y), [7.71] 6This model is also known as a max-margin Markov network (Taskar et al., 2003), emphasizing that the scoring function is constructed from a sum of components, which are Markov independent. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_179_Chunk180 |
162 CHAPTER 7. SEQUENCE LABELING where in the second line we drop the term θ · f(w(i), y(i)), which is constant in y. We can now reformulate the margin constraint for sequence labeling, θ · f(w(i), y(i)) −max y∈Y(w) θ · f(w(i), y) + c(y(i), y) ≥0. [7.72] If the score for θ ·f(w(i), y(i)) is greater than the cost-augmented score for all alternatives, then the constraint will be met. The name “cost-augmented decoding” is due to the fact that the objective includes the standard decoding problem, maxˆy∈Y(w) θ · f(w, ˆy), plus an additional term for the cost. Essentially, we want to train against predictions that are strong and wrong: they should score highly according to the model, yet incur a large loss with respect to the ground truth. Training adjusts the weights to reduce the score of these predictions. For cost-augmented decoding to be tractable, the cost function must decompose into local parts, just as the feature function f(·) does. The Hamming cost, defined above, obeys this property. To perform cost-augmented decoding using the Hamming cost, we need only to add features fm(ym) = δ(ym ̸= y(i) m ), and assign a constant weight of 1 to these features. Decoding can then be performed using the Viterbi algorithm.7 As with large-margin classifiers, it is possible to formulate the learning problem in an unconstrained form, by combining a regularization term on the weights and a Lagrangian for the constraints: min θ 1 2||θ||2 2 −C X i θ · f(w(i), y(i)) − max y∈Y(w(i)) h θ · f(w(i), y) + c(y(i), y) i! , [7.73] In this formulation, C is a parameter that controls the tradeoff between the regulariza- tion term and the margin constraints. A number of optimization algorithms have been proposed for structured support vector machines, some of which are discussed in § 2.4.2. An empirical comparison by Kummerfeld et al. (2015) shows that stochastic subgradient descent — which is essentially a cost-augmented version of the structured perceptron — is highly competitive. 7.5.3 Conditional random fields The conditional random field (CRF; Lafferty et al., 2001) is a conditional probabilistic model for sequence labeling; just as structured perceptron is built on the perceptron clas- sifier, conditional random fields are built on the logistic regression classifier.8 The basic 7Are there cost functions that do not decompose into local parts? Suppose we want to assign a constant loss c to any prediction ˆy in which k or more predicted tags are incorrect, and zero loss otherwise. This loss function is combinatorial over the predictions, and thus we cannot decompose it into parts. 8The name “conditional random field” is derived from Markov random fields, a general class of models in which the probability of a configuration of variables is proportional to a product of scores across pairs (or Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_180_Chunk181 |
7.5. DISCRIMINATIVE SEQUENCE LABELING WITH FEATURES 163 probability model is, p(y | w) = exp(Ψ(w, y)) P y′∈Y(w) exp(Ψ(w, y′)). [7.74] This is almost identical to logistic regression (§ 2.5), but because the label space is now sequences of tags, we require efficient algorithms for both decoding (searching for the best tag sequence given a sequence of words w and a model θ) and for normalization (summing over all tag sequences). These algorithms will be based on the usual locality assumption on the scoring function, Ψ(w, y) = PM+1 m=1 ψ(w, ym, ym−1, m). Decoding in CRFs Decoding — finding the tag sequence ˆy that maximizes p(y | w) — is a direct applica- tion of the Viterbi algorithm. The key observation is that the decoding problem does not depend on the denominator of p(y | w), ˆy = argmax y log p(y | w) = argmax y Ψ(y, w) −log X y′∈Y(w) exp Ψ(y′, w) = argmax y Ψ(y, w) = argmax y M+1 X m=1 sm(ym, ym−1). This is identical to the decoding problem for structured perceptron, so the same Viterbi recurrence as defined in Equation 7.22 can be used. Learning in CRFs As with logistic regression, the weights θ are learned by minimizing the regularized neg- ative log-probability, ℓ=λ 2 ||θ||2 − N X i=1 log p(y(i) | w(i); θ) [7.75] =λ 2 ||θ||2 − N X i=1 θ · f(w(i), y(i)) + log X y′∈Y(w(i)) exp θ · f(w(i), y′) , [7.76] more generally, cliques) of variables in a factor graph. In sequence labeling, the pairs of variables include all adjacent tags (ym, ym−1). The probability is conditioned on the words w, which are always observed, motivating the term “conditional” in the name. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_181_Chunk182 |
164 CHAPTER 7. SEQUENCE LABELING where λ controls the amount of regularization. The final term in Equation 7.76 is a sum over all possible labelings. This term is the log of the denominator in Equation 7.74, some- times known as the partition function.9 There are |Y|M possible labelings of an input of size M, so we must again exploit the decomposition of the scoring function to compute this sum efficiently. The sum P y∈Yw(i) exp Ψ(y, w) can be computed efficiently using the forward recur- rence, which is closely related to the Viterbi recurrence. We first define a set of forward variables, αm(ym), which is equal to the sum of the scores of all paths leading to tag ym at position m: αm(ym) ≜ X y1:m−1 exp m X n=1 sn(yn, yn−1) [7.77] = X y1:m−1 m Y n=1 exp sn(yn, yn−1). [7.78] Note the similarity to the definition of the Viterbi variable, vm(ym) = maxy1:m−1 Pm n=1 sn(yn, yn−1). In the hidden Markov model, the Viterbi recurrence had an alternative interpretation as the max-product algorithm (see Equation 7.53); analogously, the forward recurrence is known as the sum-product algorithm, because of the form of [7.78]. The forward variable can also be computed through a recurrence: αm(ym) = X y1:m−1 m Y n=1 exp sn(yn, yn−1) [7.79] = X ym−1 (exp sm(ym, ym−1)) X y1:m−2 m−1 Y n=1 exp sn(yn, yn−1) [7.80] = X ym−1 (exp sm(ym, ym−1)) × αm−1(ym−1). [7.81] Using the forward recurrence, it is possible to compute the denominator of the condi- tional probability, X y∈Y(w) Ψ(w, y) = X y1:M (exp sM+1(♦, yM)) M Y m=1 exp sm(ym, ym−1) [7.82] =αM+1(♦). [7.83] 9The terminology of “potentials” and “partition functions” comes from statistical mechanics (Bishop, 2006). Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_182_Chunk183 |
7.5. DISCRIMINATIVE SEQUENCE LABELING WITH FEATURES 165 The conditional log-likelihood can be rewritten, ℓ=λ 2 ||θ||2 − N X i=1 θ · f(w(i), y(i)) + log αM+1(♦). [7.84] Probabilistic programming environments, such as TORCH (Collobert et al., 2011) and DYNET (Neubig et al., 2017), can compute the gradient of this objective using automatic differentiation. The programmer need only implement the forward algorithm as a com- putation graph. As in logistic regression, the gradient of the likelihood with respect to the parameters is a difference between observed and expected feature counts: dℓ dθj =λθj + N X i=1 E[fj(w(i), y)] −fj(w(i), y(i)), [7.85] where fj(w(i), y(i)) refers to the count of feature j for token sequence w(i) and tag se- quence y(i). The expected feature counts are computed “under the hood” when automatic differentiation is applied to Equation 7.84 (Eisner, 2016). Before the widespread use of automatic differentiation, it was common to compute the feature expectations from marginal tag probabilities p(ym | w). These marginal prob- abilities are sometimes useful on their own, and can be computed using the forward- backward algorithm. This algorithm combines the forward recurrence with an equivalent backward recurrence, which traverses the input from wM back to w1. *Forward-backward algorithm Marginal probabilities over tag bigrams can be written as,10 Pr(Ym−1 = k′, Ym = k | w) = P y:Ym=k,Ym−1=k′ QM n=1 exp sn(yn, yn−1) P y′ QM n=1 exp sn(y′n, y′ n−1) . [7.86] The numerator sums over all tag sequences that include the transition (Ym−1 = k′) → (Ym = k). Because we are only interested in sequences that include the tag bigram, this sum can be decomposed into three parts: the prefixes y1:m−1, terminating in Ym−1 = k′; the 10Recall the notational convention of upper-case letters for random variables, e.g. Ym, and lower case letters for specific values, e.g., ym, so that Ym = k is interpreted as the event of random variable Ym taking the value k. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_183_Chunk184 |
166 CHAPTER 7. SEQUENCE LABELING Ym−1 = k′ Ym = k αm−1(k′) exp sm(k, k′) βm(k) Figure 7.3: A schematic illustration of the computation of the marginal probability Pr(Ym−1 = k′, Ym = k), using the forward score αm−1(k′) and the backward score βm(k). transition (Ym−1 = k′) →(Ym = k); and the suffixes ym:M, beginning with the tag Ym = k: X y:Ym=k,Ym−1=k′ M Y n=1 exp sn(yn, yn−1) = X y1:m−1:Ym−1=k′ m−1 Y n=1 exp sn(yn, yn−1) × exp sm(k, k′) × X ym:M:Ym=k M+1 Y n=m+1 exp sn(yn, yn−1). [7.87] The result is product of three terms: a score that sums over all the ways to get to the position (Ym−1 = k′), a score for the transition from k′ to k, and a score that sums over all the ways of finishing the sequence from (Ym = k). The first term of Equation 7.87 is equal to the forward variable, αm−1(k′). The third term — the sum over ways to finish the sequence — can also be defined recursively, this time moving over the trellis from right to left, which is known as the backward recurrence: βm(k) ≜ X ym:M:Ym=k M+1 Y n=m exp sn(yn, yn−1) [7.88] = X k′∈Y exp sm+1(k′, k) X ym+1:M:Ym=k′ M+1 Y n=m+1 exp sn(yn, yn−1) [7.89] = X k′∈Y exp sm+1(k′, k) × βm+1(k′). [7.90] To understand this computation, compare with the forward recurrence in Equation 7.81. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_184_Chunk185 |
7.6. NEURAL SEQUENCE LABELING 167 In practice, numerical stability demands that we work in the log domain, log αm(k) = log X k′∈Y exp | nlp_Page_185_Chunk186 |
168 CHAPTER 7. SEQUENCE LABELING Using this transformation, it is possible to train the tagger from the negative log-likelihood of the tags, as in a conditional random field. Alternatively, a hinge loss or margin loss objective can be constructed from the raw scores ψm(y). The hidden state hm accounts for information in the input leading up to position m, but it ignores the subsequent tokens, which may also be relevant to the tag ym. This can be addressed by adding a second RNN, in which the input is reversed, running the recur- rence from wM to w1. This is known as a bidirectional recurrent neural network (Graves and Schmidhuber, 2005), and is specified as: ←− h m =g(xm, ←− h m+1), m = 1, 2, . . . , M. [7.96] The hidden states of the left-to-right RNN are denoted −→ h m. The left-to-right and right-to- left vectors are concatenated, hm = [←− h m; −→ h m]. The scoring function in Equation 7.93 is applied to this concatenated vector. Bidirectional RNN tagging has several attractive properties. Ideally, the representa- tion hm summarizes the useful information from the surrounding context, so that it is not necessary to design explicit features to capture this information. If the vector hm is an ad- equate summary of this context, then it may not even be necessary to perform the tagging jointly: in general, the gains offered by joint tagging of the entire sequence are diminished as the individual tagging model becomes more powerful. Using backpropagation, the word vectors x can be trained “end-to-end”, so that they capture word properties that are useful for the tagging task. Alternatively, if limited labeled data is available, we can use word embeddings that are “pre-trained” from unlabeled data, using a language modeling objective (as in § 6.3) or a related word embedding technique (see chapter 14). It is even possible to combine both fine-tuned and pre-trained embeddings in a single model. Neural structure prediction The bidirectional recurrent neural network incorporates in- formation from throughout the input, but each tagging decision is made independently. In some sequence labeling applications, there are very strong dependencies between tags: it may even be impossible for one tag to follow another. In such scenarios, the tagging decision must be made jointly across the entire sequence. Neural sequence labeling can be combined with the Viterbi algorithm by defining the local scores as: sm(ym, ym−1) = βym · hm + ηym−1,ym, [7.97] where hm is the RNN hidden state, βym is a vector associated with tag ym, and ηym−1,ym is a scalar parameter for the tag transition (ym−1, ym). These local scores can then be incorporated into the Viterbi algorithm for inference, and into the forward algorithm for training. This model is shown in Figure 7.4. It can be trained from the conditional log- likelihood objective defined in Equation 7.76, backpropagating to the tagging parameters Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_186_Chunk187 |
7.6. NEURAL SEQUENCE LABELING 169 ym−1 ym ym+1 ←− h m−1 ←− h m ←− h m+1 −→ h m−1 −→ h m −→ h m+1 xm−1 xm xm+1 Figure 7.4: Bidirectional LSTM for sequence labeling. The solid lines indicate computa- tion, the dashed lines indicate probabilistic dependency, and the dotted lines indicate the optional additional probabilistic dependencies between labels in the biLSTM-CRF. β and η, as well as the parameters of the RNN. This model is called the LSTM-CRF, due to its combination of aspects of the long short-term memory and conditional random field models (Huang et al., 2015). The LSTM-CRF is especially effective on the task of named entity recognition (Lample et al., 2016), a sequence labeling task that is described in detail in § 8.3. This task has strong dependencies between adjacent tags, so structure prediction is especially important. 7.6.2 Character-level models As in language modeling, rare and unseen words are a challenge: if we encounter a word that was not in the training data, then there is no obvious choice for the word embed- ding xm. One solution is to use a generic unseen word embedding for all such words. However, in many cases, properties of unseen words can be guessed from their spellings. For example, whimsical does not appear in the Universal Dependencies (UD) English Tree- bank, yet the suffix -al makes it likely to be adjective; by the same logic, unflinchingly is likely to be an adverb, and barnacle is likely to be a noun. In feature-based models, these morphological properties were handled by suffix fea- tures; in a neural network, they can be incorporated by constructing the embeddings of unseen words from their spellings or morphology. One way to do this is to incorporate an additional layer of bidirectional RNNs, one for each word in the vocabulary (Ling et al., 2015). For each such character-RNN, the inputs are the characters, and the output is the concatenation of the final states of the left-facing and right-facing passes, φw = Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_187_Chunk188 |
170 CHAPTER 7. SEQUENCE LABELING [−→ h (w) Nw; ←− h (w) 0 ], where −→ h (w) Nw is the final state of the right-facing pass for word w, and Nw is the number of characters in the word. The character RNN model is trained by back- propagation from the tagging objective. On the test data, the trained RNN is applied to out-of-vocabulary words (or all words), yielding inputs to the word-level tagging RNN. Other approaches to compositional word embeddings are described in § 14.7.1. 7.6.3 Convolutional Neural Networks for Sequence Labeling One disadvantage of recurrent neural networks is that the architecture requires iterating through the sequence of inputs and predictions: each hidden vector hm must be com- puted from the previous hidden vector hm−1, before predicting the tag ym. These iterative computations are difficult to parallelize, and fail to exploit the speedups offered by graph- ics processing units (GPUs) on operations such as matrix multiplication. Convolutional neural networks achieve better computational performance by predicting each label ym from a set of matrix operations on the neighboring word embeddings, xm−k:m+k (Col- lobert et al., 2011). Because there is no hidden state to update, the predictions for each ym can be computed in parallel. For more on convolutional neural networks, see § 3.4. Character-based word embeddings can also be computed using convolutional neural net- works (Santos and Zadrozny, 2014). 7.7 *Unsupervised sequence labeling In unsupervised sequence labeling, the goal is to induce a hidden Markov model from a corpus of unannotated text (w(1), w(2), . . . , w(N)), where each w(i) is a sequence of length M(i). This is an example of the general problem of structure induction, which is the unsupervised version of structure prediction. The tags that result from unsupervised se- quence labeling might be useful for some downstream task, or they might help us to better understand the language’s inherent structure. For part-of-speech tagging, it is common to use a tag dictionary that lists the allowed tags for each word, simplifying the prob- lem (Christodoulopoulos et al., 2010). Unsupervised learning in hidden Markov models can be performed using the Baum- Welch algorithm, which combines the forward-backward algorithm (§ 7.5.3) with expectation- maximization (EM; § 5.1.2). In the M-step, the HMM parameters from expected counts: Pr(W = i | Y = k) = φk,i =E[count(W = i, Y = k)] E[count(Y = k)] Pr(Ym = k | Ym−1 = k′) = λk′,k =E[count(Ym = k, Ym−1 = k′)] E[count(Ym−1 = k′)] Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_188_Chunk189 |
7.7. *UNSUPERVISED SEQUENCE LABELING 171 The expected counts are computed in the E-step, using the forward and backward recurrences. The local scores follow the usual definition for hidden Markov models, sm(k, k′) = log pE(wm | Ym = k; φ) + log pT (Ym = k | Ym−1 = k′; λ). [7.98] The expected transition counts for a single instance are, E[count(Ym = k, Ym−1 = k′) | w] = M X m=1 Pr(Ym−1 = k′, Ym = k | w) [7.99] = P y:Ym=k,Ym−1=k′ QM n=1 exp sn(yn, yn−1) P y′ QM n=1 exp sn(y′n, y′ n−1) . [7.100] As described in § 7.5.3, these marginal probabilities can be computed from the forward- backward recurrence, Pr(Ym−1 = k′, Ym = k | w) =αm−1(k′) × exp sm(k, k′) × βm(k) αM+1(♦) . [7.101] In a hidden Markov model, each element of the forward-backward computation has a special interpretation: αm−1(k′) =p(Ym−1 = k′, w1:m−1) [7.102] exp sm(k, k′) =p(Ym = k, wm | Ym−1 = k′) [7.103] βm(k) =p(wm+1:M | Ym = k). [7.104] Applying the conditional independence assumptions of the hidden Markov model (de- fined in Algorithm 12), the product is equal to the joint probability of the tag bigram and the entire input, αm−1(k′) × exp sm(k, k′) × βm(k) =p(Ym−1 = k′, w1:m−1) × p(Ym = k, wm | Ym−1 = k′) × p(wm+1:M | Ym = k) =p(Ym−1 = k′, Ym = k, w1:M). [7.105] Dividing by αM+1(♦) = p(w1:M) gives the desired probability, αm−1(k′) × sm(k, k′) × βm(k) αM+1(♦) =p(Ym−1 = k′, Ym = k, w1:M) p(w1:M) [7.106] = Pr(Ym−1 = k′, Ym = k | w1:M). [7.107] The expected emission counts can be computed in a similar manner, using the product αm(k) × βm(k). Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_189_Chunk190 |
172 CHAPTER 7. SEQUENCE LABELING 7.7.1 Linear dynamical systems The forward-backward algorithm can be viewed as Bayesian state estimation in a discrete state space. In a continuous state space, ym ∈RK, the equivalent algorithm is the Kalman smoother. It also computes marginals p(ym | x1:M), using a similar two-step algorithm of forward and backward passes. Instead of computing a trellis of values at each step, the Kalman smoother computes a probability density function qym(ym; µm, Σm), character- ized by a mean µm and a covariance Σm around the latent state. Connections between the Kalman smoother and the forward-backward algorithm are elucidated by Minka (1999) and Murphy (2012). 7.7.2 Alternative unsupervised learning methods As noted in § 5.5, expectation-maximization is just one of many techniques for structure induction. One alternative is to use Markov Chain Monte Carlo (MCMC) sampling al- gorithms, which are briefly described in § 5.5.1. For the specific case of sequence labeling, Gibbs sampling can be applied by iteratively sampling each tag ym conditioned on all the others (Finkel et al., 2005): p(ym | y−m, w1:M) ∝p(wm | ym)p(ym | y−m). [7.108] Gibbs Sampling has been applied to unsupervised part-of-speech tagging by Goldwater and Griffiths (2007). Beam sampling is a more sophisticated sampling algorithm, which randomly draws entire sequences y1:M, rather than individual tags ym; this algorithm was applied to unsupervised part-of-speech tagging by Van Gael et al. (2009). Spectral learning (see § 5.5.2) can also be applied to sequence labeling. By factoring matrices of co-occurrence counts of word bigrams and trigrams (Song et al., 2010; Hsu et al., 2012), it is possible to obtain globally optimal estimates of the transition and emission parameters, under mild assumptions. 7.7.3 Semiring notation and the generalized viterbi algorithm The Viterbi and Forward recurrences can each be performed over probabilities or log probabilities, yielding a total of four closely related recurrences. These four recurrence scan in fact be expressed as a single recurrence in a more general notation, known as semiring algebra. Let the symbols ⊕and ⊗represent generalized addition and multipli- cation respectively.11 Given these operators, a generalized Viterbi recurrence is denoted, vm(k) = M k′∈Y sm(k, k′) ⊗vm−1(k′). [7.109] 11In a semiring, the addition and multiplication operators must both obey associativity, and multiplication must distribute across addition; the addition operator must be commutative; there must be additive and multiplicative identities 0 and 1, such that a ⊕0 = a and a ⊗1 = a; and there must be a multiplicative annihilator 0, such that a ⊗0 = 0. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_190_Chunk191 |
7.7. *UNSUPERVISED SEQUENCE LABELING 173 Each recurrence that we have seen so far is a special case of this generalized Viterbi recurrence: • In the max-product Viterbi recurrence over probabilities, the ⊕operation corre- sponds to maximization, and the ⊗operation corresponds to multiplication. • In the forward recurrence over probabilities, the ⊕operation corresponds to addi- tion, and the ⊗operation corresponds to multiplication. • In the max-product Viterbi recurrence over log-probabilities, the ⊕operation corre- sponds to maximization, and the ⊗operation corresponds to addition.12 • In the forward recurrence over log-probabilities, the ⊕operation corresponds to log- addition, a ⊕b = log(ea + eb). The ⊗operation corresponds to addition. The mathematical abstraction offered by semiring notation can be applied to the soft- ware implementations of these algorithms, yielding concise and modular implementa- tions. For example, in the OPENFST library, generic operations are parametrized by the choice of semiring (Allauzen et al., 2007). Exercises 1. Extend the example in § 7.3.1 to the sentence they can can fish, meaning that “they can put fish into cans.” Build the trellis for this example using the weights in Table 7.1, and identify the best-scoring tag sequence. If the scores for noun and verb are tied, then you may assume that the backpointer always goes to noun. 2. Using the tagset Y = {N, V }, and the feature set f(w, ym, ym−1, m) = {(wm, ym), (ym, ym−1)}, show that there is no set of weights that give the correct tagging for both they can fish (N V V) and they can can fish (N V V N). 3. Work out what happens if you train a structured perceptron on the two exam- ples mentioned in the previous problem, using the transition and emission features (ym, ym−1) and (ym, wm). Initialize all weights at 0, and assume that the Viterbi algo- rithm always chooses N when the scores for the two tags are tied, so that the initial prediction for they can fish is N N N. 4. Consider the garden path sentence, The old man the boat. Given word-tag and tag-tag features, what inequality in the weights must hold for the correct tag sequence to outscore the garden path tag sequence for this example? 12This is sometimes called the tropical semiring, in honor of the Brazilian mathematician Imre Simon. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_191_Chunk192 |
174 CHAPTER 7. SEQUENCE LABELING 5. Using the weights in Table 7.1, explicitly compute the log-probabilities for all pos- sible taggings of the input fish can. Verify that the forward algorithm recovers the aggregate log probability. 6. Sketch out an algorithm for a variant of Viterbi that returns the top-n label se- quences. What is the time and space complexity of this algorithm? 7. Show how to compute the marginal probability Pr(ym−2 = k, ym = k′ | w1:M), in terms of the forward and backward variables, and the potentials sn(yn, yn−1). 8. Suppose you receive a stream of text, where some of tokens have been replaced at random with NOISE. For example: • Source: I try all things, I achieve what I can • Message received: I try NOISE NOISE, I NOISE what I NOISE Assume you have access to a pre-trained bigram language model, which gives prob- abilities p(wm | wm−1). These probabilities can be assumed to be non-zero for all bigrams. Show how to use the Viterbi algorithm to recover the source by maximizing the bigram language model log-probability. Specifically, set the scores sm(ym, ym−1) so that the Viterbi algorithm selects a sequence of words that maximizes the bigram language model log-probability, while leaving the non-noise tokens intact. Your solution should not modify the logic of the Viterbi algorithm, it should only set the scores sm(ym, ym−1). 9. Let α(·) and β(·) indicate the forward and backward variables as defined in § 7.5.3. Prove that αM+1(♦) = β0(♦) = P y αm(y)βm(y), ∀m ∈{1, 2, . . . , M}. 10. Consider an RNN tagging model with a tanh activation function on the hidden layer, and a hinge loss on the output. (The problem also works for the margin loss and negative log-likelihood.) Suppose you initialize all parameters to zero: this in- cludes the word embeddings that make up x, the transition matrix Θ, the output weights β, and the initial hidden state h0. a) Prove that for any data and for any gradient-based learning algorithm, all pa- rameters will be stuck at zero. b) Would a sigmoid activation function avoid this problem? Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_192_Chunk193 |
Chapter 8 Applications of sequence labeling Sequence labeling has applications throughout natural language processing. This chap- ter focuses on part-of-speech tagging, morpho-syntactic attribute tagging, named entity recognition, and tokenization. It also touches briefly on two applications to interactive settings: dialogue act recognition and the detection of code-switching points between languages. 8.1 Part-of-speech tagging The syntax of a language is the set of principles under which sequences of words are judged to be grammatically acceptable by fluent speakers. One of the most basic syntactic concepts is the part-of-speech (POS), which refers to the syntactic role of each word in a sentence. This concept was used informally in the previous chapter, and you may have some intuitions from your own study of English. For example, in the sentence We like vegetarian sandwiches, you may already know that we and sandwiches are nouns, like is a verb, and vegetarian is an adjective. These labels depend on the context in which the word appears: in she eats like a vegetarian, the word like is a preposition, and the word vegetarian is a noun. Parts-of-speech can help to disentangle or explain various linguistic problems. Recall Chomsky’s proposed distinction in chapter 6: (8.1) a. Colorless green ideas sleep furiously. b. * Ideas colorless furiously green sleep. One difference between these two examples is that the first contains part-of-speech tran- sitions that are typical in English: adjective to adjective, adjective to noun, noun to verb, and verb to adverb. The second example contains transitions that are unusual: noun to adjective and adjective to verb. The ambiguity in a headline like, 175 | nlp_Page_193_Chunk194 |
176 CHAPTER 8. APPLICATIONS OF SEQUENCE LABELING (8.2) Teacher Strikes Idle Children can also be explained in terms of parts of speech: in the interpretation that was likely intended, strikes is a noun and idle is a verb; in the alternative explanation, strikes is a verb and idle is an adjective. Part-of-speech tagging is often taken as a early step in a natural language processing pipeline. Indeed, parts-of-speech provide features that can be useful for many of the tasks that we will encounter later, such as parsing (chapter 10), coreference resolution (chapter 15), and relation extraction (chapter 17). 8.1.1 Parts-of-Speech The Universal Dependencies project (UD) is an effort to create syntactically-annotated corpora across many languages, using a single annotation standard (Nivre et al., 2016). As part of this effort, they have designed a part-of-speech tagset, which is meant to capture word classes across as many languages as possible.1 This section describes that inventory, giving rough definitions for each of tags, along with supporting examples. Part-of-speech tags are morphosyntactic, rather than semantic, categories. This means that they describe words in terms of how they pattern together and how they are inter- nally constructed (e.g., what suffixes and prefixes they include). For example, you may think of a noun as referring to objects or concepts, and verbs as referring to actions or events. But events can also be nouns: (8.3) . . . the howling of the shrieking storm. Here howling and shrieking are events, but grammatically they act as a noun and adjective respectively. The Universal Dependency part-of-speech tagset The UD tagset is broken up into three groups: open class tags, closed class tags, and “others.” Open class tags Nearly all languages contain nouns, verbs, adjectives, and adverbs.2 These are all open word classes, because new words can easily be added to them. The UD tagset includes two other tags that are open classes: proper nouns and interjections. • Nouns (UD tag: NOUN) tend to describe entities and concepts, e.g., 1The UD tagset builds on earlier work from Petrov et al. (2012), in which a set of twelve universal tags was identified by creating mappings from tagsets for individual languages. 2One prominent exception is Korean, which some linguists argue does not have adjectives Kim (2002). Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_194_Chunk195 |
8.1. PART-OF-SPEECH TAGGING 177 (8.4) Toes are scarce among veteran blubber men. In English, nouns tend to follow determiners and adjectives, and can play the subject role in the sentence. They can be marked for the plural number by an -s suffix. • Proper nouns (PROPN) are tokens in names, which uniquely specify a given entity, (8.5) “Moby Dick?” shouted Ahab. • Verbs (VERB), according to the UD guidelines, “typically signal events and ac- tions.” But they are also defined grammatically: they “can constitute a minimal predicate in a clause, and govern the number and types of other constituents which may occur in a clause.”3 (8.6) “Moby Dick?” shouted Ahab. (8.7) Shall we keep chasing this murderous fish? English verbs tend to come in between the subject and some number of direct ob- jects, depending on the verb. They can be marked for tense and aspect using suffixes such as -ed and -ing. (These suffixes are an example of inflectional morphology, which is discussed in more detail in § 9.1.4.) • Adjectives (ADJ) describe properties of entities, (8.8) a. Shall we keep chasing this murderous fish? b. Toes are scarce among veteran blubber men. In the second example, scarce is a predicative adjective, linked to the subject by the copula verb are. In contrast, murderous and veteran are attributive adjectives, modi- fying the noun phrase in which they are embedded. • Adverbs (ADV) describe properties of events, and may also modify adjectives or other adverbs: (8.9) a. It is not down on any map; true places never are. b. . . . treacherously hidden beneath the loveliest tints of azure c. Not drowned entirely, though. • Interjections (INTJ) are used in exclamations, e.g., (8.10) Aye aye! it was that accursed white whale that razed me. 3http://universaldependencies.org/u/pos/VERB.html Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_195_Chunk196 |
178 CHAPTER 8. APPLICATIONS OF SEQUENCE LABELING Closed class tags Closed word classes rarely receive new members. They are sometimes referred to as function words — as opposed to content words — as they have little lexical meaning of their own, but rather, help to organize the components of the sentence. • Adpositions (ADP) describe the relationship between a complement (usually a noun phrase) and another unit in the sentence, typically a noun or verb phrase. (8.11) a. Toes are scarce among veteran blubber men. b. It is not down on any map. c. Give not thyself up then. As the examples show, English generally uses prepositions, which are adpositions that appear before their complement. (An exception is ago, as in, we met three days ago). Postpositions are used in other languages, such as Japanese and Turkish. • Auxiliary verbs (AUX) are a closed class of verbs that add information such as tense, aspect, person, and number. (8.12) a. Shall we keep chasing this murderous fish? b. What the white whale was to Ahab, has been hinted. c. Ahab must use tools. d. Meditation and water are wedded forever. e. Toes are scarce among veteran blubber men. The final example is a copula verb, which is also tagged as an auxiliary in the UD corpus. • Coordinating conjunctions (CCONJ) express relationships between two words or phrases, which play a parallel role: (8.13) Meditation and water are wedded forever. • Subordinating conjunctions (SCONJ) link two clauses, making one syntactically subordinate to the other: (8.14) It is the easiest thing in the world for a man to look as if he had a great secret in him. Note that • Pronouns (PRON) are words that substitute for nouns or noun phrases. (8.15) a. Be it what it will, I’ll go to it laughing. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_196_Chunk197 |
8.1. PART-OF-SPEECH TAGGING 179 b. I try all things, I achieve what I can. The example includes the personal pronouns I and it, as well as the relative pronoun what. Other pronouns include myself, somebody, and nothing. • Determiners (DET) provide additional information about the nouns or noun phrases that they modify: (8.16) a. What the white whale was to Ahab, has been hinted. b. It is not down on any map. c. I try all things . . . d. Shall we keep chasing this murderous fish? Determiners include articles (the), possessive determiners (their), demonstratives (this murderous fish), and quantifiers (any map). • Numerals (NUM) are an infinite but closed class, which includes integers, fractions, and decimals, regardless of whether spelled out or written in numerical form. (8.17) a. How then can this one small heart beat. b. I am going to put him down for the three hundredth. • Particles (PART) are a catch-all of function words that combine with other words or phrases, but do not meet the conditions of the other tags. In English, this includes the infinitival to, the possessive marker, and negation. (8.18) a. Better to sleep with a sober cannibal than a drunk Christian. b. So man’s insanity is heaven’s sense c. It is not down on any map As the second example shows, the possessive marker is not considered part of the same token as the word that it modifies, so that man’s is split into two tokens. (Tok- enization is described in more detail in § 8.4.) A non-English example of a particle is the Japanese question marker ka:4 (8.19) Sensei Teacher desu is ka ? Is she a teacher? 4In this notation, the first line is the transliterated Japanese text, the second line is a token-to-token gloss, and the third line is the translation. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_197_Chunk198 |
180 CHAPTER 8. APPLICATIONS OF SEQUENCE LABELING Other The remaining UD tags include punctuation (PUN) and symbols (SYM). Punc- tuation is purely structural — e.g., commas, periods, colons — while symbols can carry content of their own. Examples of symbols include dollar and percentage symbols, math- ematical operators, emoticons, emojis, and internet addresses. A final catch-all tag is X, which is used for words that cannot be assigned another part-of-speech category. The X tag is also used in cases of code switching (between languages), described in § 8.5. Other tagsets Prior to the Universal Dependency treebank, part-of-speech tagging was performed us- ing language-specific tagsets. The dominant tagset for English was designed as part of the Penn Treebank (PTB), and it includes 45 tags — more than three times as many as the UD tagset. This granularity is reflected in distinctions between singular and plural nouns, verb tenses and aspects, possessive and non-possessive pronouns, comparative and superlative adjectives and adverbs (e.g., faster, fastest), and so on. The Brown corpus includes a tagset that is even more detailed, with 87 tags (Francis, 1964), including special tags for individual auxiliary verbs such as be, do, and have. Different languages make different distinctions, and so the PTB and Brown tagsets are not appropriate for a language such as Chinese, which does not mark the verb tense (Xia, 2000); nor for Spanish, which marks every combination of person and number in the verb ending; nor for German, which marks the case of each noun phrase. Each of these languages requires more detail than English in some areas of the tagset, and less in other areas. The strategy of the Universal Dependencies corpus is to design a coarse-grained tagset to be used across all languages, and then to additionally annotate language-specific morphosyntactic attributes, such as number, tense, and case. The attribute tagging task is described in more detail in § 8.2. Social media such as Twitter have been shown to require tagsets of their own (Gimpel et al., 2011). Such corpora contain some tokens that are not equivalent to anything en- countered in a typical written corpus: e.g., emoticons, URLs, and hashtags. Social media also includes dialectal words like gonna (‘going to’, e.g. We gonna be fine) and Ima (‘I’m going to’, e.g., Ima tell you one more time), which can be analyzed either as non-standard orthography (making tokenization impossible), or as lexical items in their own right. In either case, it is clear that existing tags like NOUN and VERB cannot handle cases like Ima, which combine aspects of the noun and verb. Gimpel et al. (2011) therefore propose a new set of tags to deal with these cases. 8.1.2 Accurate part-of-speech tagging Part-of-speech tagging is the problem of selecting the correct tag for each word in a sen- tence. Success is typically measured by accuracy on an annotated test set, which is simply the fraction of tokens that were tagged correctly. Jacob Eisenstein. Draft of November 13, 2018. | nlp_Page_198_Chunk199 |
8.1. PART-OF-SPEECH TAGGING 181 Baselines A simple baseline for part-of-speech tagging is to choose the most common tag for each word. For example, in the Universal Dependencies treebank, the word talk appears 96 times, and 85 of those times it is labeled as a VERB: therefore, this baseline will always predict VERB for this word. For words that do not appear in the training corpus, the base- line simply guesses the most common tag overall, which is NOUN. In the Penn Treebank, this simple baseline obtains accuracy above 92%. A more rigorous evaluation is the accu- racy on out-of-vocabulary words, which are not seen in the training data. Tagging these words correctly requires attention to the context and the word’s internal structure. Contemporary approaches Conditional random fields and structured perceptron perform at or near the state-of-the- art for part-of-speech tagging in English. For example, (Collins, 2002) achieved 97.1% accuracy on the Penn Treebank, using a structured perceptron with the following base features (originally introduced by Ratnaparkhi (1996)): • current word, wm • previous words, wm−1, wm−2 • next words, wm+1, wm+2 • previous tag, ym−1 • previous two tags, (ym−1, ym−2) • for rare words: – first k characters, up to k = 4 – last k characters, up to k = 4 – whether wm contains a number, uppercase character, or hyphen. Similar results for the PTB data have been achieved using conditional random fields (CRFs; Toutanova et al., 2003). More recent work has demonstrated the power of neural sequence models, such as the long short-term memory (LSTM) (§ 7.6). Plank et al. (2016) apply a CRF and a bidirec- tional LSTM to twenty-two languages in the UD corpus, achieving an average accuracy of 94.3% for the CRF, and 96.5% with the bi-LSTM. Their neural model employs three types of embeddings: fine-tuned word embeddings, which are updated during training; pre-trained word embeddings, which are never updated, but which help to tag out-of- vocabulary words; and character-based embeddings. The character-based embeddings are computed by running an LSTM on the individual characters in each word, thereby capturing common orthographic patterns such as prefixes, suffixes, and capitalization. Extensive evaluations show that these additional embeddings are crucial to their model’s success. Under contract with MIT Press, shared under CC-BY-NC-ND license. | nlp_Page_199_Chunk200 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.