Papers
The project's theory in plain words
Automata, formal languages, and quality metrics without a single formula: what the machine has to do, how it does it, and what it pays for its troubles. Written for a student team building a grammatical error detector, and for anyone who needs the gist rather than a proof.
- Level 1. You cannot do the work without this
- Level 2. For the theory chapter
- Level 3. Name and cite, no proof required
- What automata courses leave out, but your project needs: evaluation metrics
- Before the automaton and after the detector: three things no course teaches you
- Team self-check
- How to get the sources
- The minimum path if an automata course passed you by
- Glossary: what it is called in the textbook and in lectures
This guide is written for you and your advisor. For your thesis project, you are building a program that looks for grammatical errors in English text - for instance, catching the agreement error in "She walk to school". For a program like that to run fast and reliably, it needs automata theory under the hood.
Not every degree program offers an automata theory course, and where it does exist, it is often an elective. So we wrote this text to work for any team. If you have taken the course, you will recognize familiar exam topics right away and see how they come alive in a real problem. If the course passed you by, do not worry: everything you need to read and understand is explained here in plain language. Better yet, each item below is framed not as a dry textbook topic, but as a concrete skill: what you should be able to do with your own hands and explain out loud.
All the material is split into three levels:
- Level 1 is mandatory for the whole team; without it, you simply cannot build the project.
- Level 2 is for those of you who are writing the theory chapter of the thesis.
- Level 3 is background knowledge: in your thesis, it is enough to state these facts in your own words and cite the literature, without proving anything.
If you want to look into textbooks, pick the two books that sit on the syllabus of almost every automata course. The formal version of this guide, available right alongside this one, gives full bibliographic details for all the research papers and books, and at the very end there is a list showing which sources are freely available online and which ones require a university library subscription. In this plain-language walkthrough, we have stripped out all the citations, author names, and formulas so that nothing gets between you and the core ideas.
Level 1. You cannot do the work without this
1. Single-track and branching automata, and why they can do the exact same things
Your grammar error pattern is a small step-by-step machine. Its job is to read a sentence from left to right and press a red button if it runs into an error inside.
How does it do that? It does not look at the English words themselves, but at their grammatical labels: "article a", "plural noun", "verb", "other word". The full set of labels that the machine is capable of telling apart is called its alphabet. The machine reads one label after another, and at each step it moves from one internal position to another. These positions are its entire memory of what it has already seen. In theory they are called states, and a machine like this with a finite supply of positions is called a finite automaton.
When you say at your defense, "our matcher only sees the immediate neighbor", you are not arguing about lines of code. You are making a claim about the states of your automaton: how many there are and what they remember. That is why any argument about what your program can or cannot do has to be conducted in the language of automata.
Let us step through a machine like this on a live example. Suppose we want to catch the error "article a right before a plural", as in "I see a cats". Our automaton only needs three labels in its alphabet: the class "article a", the class "plural noun", and the class "other word". And it needs three states:
- State one, the start state: we have not seen the article "a" yet, or we have already forgotten about it. In comes the word "I" with the label "other word" - the machine thinks "nothing interesting" and stays in state one. In comes "see" ("other word") - it stays in state one again. In comes "a" ("article a") - the machine perks up and steps into state two.
- State two, waiting for trouble: we just saw the article "a". If an ordinary word from the "other word" class came next, it would be a false alarm, and the machine would go back to state one. If another "article a" came along, it would stay in state two. But in our phrase, in comes "cats" - the label "plural noun". The machine steps into state three.
- State three, the winning state (called an accepting state): error caught! We saw "article a", and right after it, a "plural noun".
This automaton has three states, and at any moment it sits inat most and at least one - exact one - of them. For any incoming label, it has ровно one arrow telling it where to step next. A machine like this, which never hesitates and never guesses, is called a single-track, or deterministic finite automaton.
However, it is often handy to write rules for a different kind of machine - one that can branch at an ambiguous spot and check several guesses in parallel. For example, upon seeing a certain word, it can leave one copy of itself waiting in the old state while another copy steps forward: what if the part of the phrase we need has just begun? A branching machine like this is called a nondeterministic finite automaton.
Look at the phrase "a big red cats", where extra words have slipped in between the article and the noun. Suppose our branching machine, while in state two and remembering "article a", is allowed on any "other word" to keep one copy of itself in place to wait further, and on a "plural noun" to step into the winning state three. In comes "a" - one copy stays in state one in case a new article shows up later in the text, while a second copy steps into state two. In come "big" and "red" (labeled "other word") - the second copy simply waits them out in state two, and when "cats" comes next, it steps into state three and hits the red button.
The key fact here is this: branching and single-track automata have the exact same power. Any branching machine can be rebuilt into a single-track machine that catches the exact same phrases.
How is that done? In a very straightforward way. Since a branching machine can be in several of its states at once (holding a bundle of guesses in its head), we force the new single-track machine to remember that entire bundle as a single state of its own. We declare every possible set of states of the old branching machine to be one separate state of the new single-track machine. This trick is called the subset construction.
Let us check on the same live example, "a big red cats", how the two machines do the same job. Where the branching machine split in two after the word "a" and sat in state one and state two at the same time, our new single-track machine simply moves into a single combined state labeled "one and two". When the words "big" and "red" arrive, the single-track machine follows its one and only arrow to stay in that combined state, with no branching at all. When "cats" arrives, it steps into the combined state "one and three", sees the winning state three inside it, and presses the red button in the exact same way.
After this conversion, the machine becomes completely deterministic, but you pay for it in size. Look at how the number of states grows. If the branching machine had three states, you can form eight different combinations out of them - so the deterministic machine will have up to eight states. Add a fourth state, and you get sixteen combinations. With every new state in the branching machine, the number of possible combinations doubles. For ten states there are already over a thousand combinations; for twenty, over a million. When a quantity multiplies at every step and balloons like an avalanche, it is called exponential growth.
Your mandatory skill for this section: take one of our working patterns, draw the automaton for it by hand, and state firmly how many states it has.
2. Operations on error patterns and what they cost
All the sentences on which a single finite automaton hits the red button together form a formal language. And any language for which a finite automaton can be built at all is called a regular language.
Regular languages have a wonderful property: if you take such languages and perform natural operations on them - merging two languages into one (union), keeping only the sentences common to both (intersection), throwing out the sentences of one language from another (set difference), or turning a language inside out by taking all sentences that are NOT in it (complementation) - the result is a regular language again and again. That means you can build a finite automaton for the result too! For intersection, union, and difference, it works like this: we take two automata and run them on the sentence at the same time, keeping track of the pair of their states at once. This technique is called the product construction. And the property itself - that these operations never take us outside the class of regular languages - is called closure.
In our project this is not abstract theory, it is the very core of the work. Every fix to an error pattern is one operation or another on languages:
- "Deviation from a construction" is the difference of two languages. We take the language of all sentences where the grammatical trigger shows up at all, and subtract from it the language of sentences where that construction is built correctly. Whatever is left after the subtraction is pure errors.
Here is what this looks like in your project on real sentences. Suppose the first automaton catches the trigger itself - any sentence where the "article a" occurs at all: it will fire both on the correct "I see a cat" and on the erroneous "I see a cats". The second automaton is tuned only to the correct build, where the "article a" is followed by a singular noun, and so it will fire only on "I see a cat". When we run the product construction and subtract the second language from the first, the sentence "I see a cat" is filtered out, while "I see a cats" remains in the difference as a pure error.
- A negative condition ("there is no determiner to the left of the noun", as in the erroneous sentence "I bought car") is complementation. We describe what the presence of a determiner looks like, and then turn the condition inside out.
- Restricting the scope of a pattern is the intersection of two languages: both the rule itself and the condition on the position in the sentence must fire.
- A gap between two anchor words is splicing a chunk of arbitrary alphabet labels in between them (chaining chunks together in sequence like this is called concatenation).
You need to be especially careful with gaps between anchors. There are three different ways to specify a gap, and you must keep them strictly separate in your head:
- A gap of an exact number of symbols: for example, there must be exactly three arbitrary words between the two anchors, no more and no less.
- A gap no longer than a given number of symbols (the union of gaps from length zero up to a chosen ceiling): for example, there may be zero, one, two, or three words between the anchors. This is a fixed-width window.
- A gap of arbitrary length (marked with a star in textbooks): there may be any number of arbitrary words between the anchors - none at all, or twenty.
Compare all three gaps on the same pair of anchors: the class "article a" and the class "plural noun". A pattern with a gap of exactly two words will catch the sentence "I see a big red cats", where between "a" and "cats" stand the two words "big" and "red", but will miss "I see a cats" and "I see a big cats". A pattern with a window of at most two words will catch all three of these sentences (they have zero, one, and two words between the anchors), but will give up on "I see a very big red cats", where there are already three extra words. And a pattern with a gap of arbitrary length will hit the red button on all four sentences, no matter how many words wedge themselves between "a" and "cats".
A very common mistake in projects is to use a fixed length or a narrow window where real life calls for an arbitrary-length gap with a star. Look at the sentence "The boy who sat next to my old friends are tired". Here the subject "boy" is singular and the verb "are" is plural - a glaring error. But seven unrelated words have squeezed in between the anchors "boy" and "are": "who sat next to my old friends". If your pattern only sees the immediate neighbor (a window of width one) or even a three-word window, it will miss this error. To reach from the subject to the verb across any relative clause, you have to splice an arbitrary-length gap between the anchors.
In the end, two of the three defects measured in our project map directly onto operations on regular languages:
- Patterns lack a negative condition - this is cured by the complementation operation.
- The matcher only sees the immediate neighbor - this is a narrow fixed-width window where concatenation with an arbitrary-length gap is needed.
(Our third defect - when the alphabet itself lacks the needed grammatical classes - is not an operation on languages, but an impoverished alphabet; we will talk about it in section three.)
The main takeaway: all three of these operations - complementation, intersection, and concatenation with an arbitrary gap - preserve the regularity of the language! We never leave the world of finite automata.
But you have to pay for operations in automaton size, and at your defense you must state this cost without getting confused. You need to be especially precise about the cost of complementation.
Suppose our pattern is already represented as a complete deterministic automaton (complete means that from every state there are arrows defined for every single label in the alphabet, so the machine never gets stuck). How much does it cost to turn it inside out, that is, to build the complement? Almost nothing! We just walk through all the states and flip the flags: the states that were accepting (the ones shouting "error!") we make ordinary, and all the ordinary ones we make accepting. The number of states has not changed at all, and the work required is proportional to the number of states in the automaton (when the cost grows simply in proportion to the size of the problem, with no doubling and no avalanches, we say it grows linearly).
Let's look at a small three-state machine that checks whether the article "a" is left hanging without a noun in a phrase like "I see a". In the first state, the machine is waiting for an article; in the second, it has already seen the tag "article a" and is waiting for the tag "singular noun"; and the third state is a dead end where it falls if the article is followed by, say, the tag "verb" in an erroneous phrase like "I see a go". If the red error light originally came on in the second and third states, then to build the complement we just flip the flags in three steps: we make the first state accepting, and the second and third states non-accepting. We started with three states and we still have three, and this inside-out machine now accepts only those strings where the article is safely closed by a noun or never showed up at all.
So where does all the talk about a runaway, exponential blow-up during complementation come from? Right here. The blow-up happens when your original error description is branching - that is, written as a nondeterministic automaton or a regular expression. You cannot turn a branching machine inside out just by flipping flags: if one of its branches finds an error on a phrase while a parallel branch finds no error on the very same phrase, simply flipping the flags will give the wrong answer. That is why the standard route requires you to first turn the branching automaton into a deterministic one using that very subset construction from section one! And as we have already seen, in the worst case that construction blows up the number of states like an avalanche: turning ten states into over a thousand, and twenty into over a million. Only after that do you flip the flags on the bloated deterministic automaton.
Let's trace this step by step on a branching automaton that looks for the error "article before a plural" anywhere in a sentence, and therefore splits in two on every word while in the start state: one branch stays behind to keep waiting, while the other steps out to check a suspicious spot. Feed it the erroneous phrase "a cats": on the tag "article a", the first branch steps into the checking state, and then on the tag "plural noun" it lands in an accepting state and cries error, whereas the second parallel branch simply stays in the non-accepting start state both times. If we naively flip the flags in this branching machine, the start state becomes accepting! Then, on that very same erroneous phrase "a cats", the second branch will finish its run in the new accepting state, and the inverted automaton will declare the exact same phrase both erroneous and error-free at the same time.
So in your thesis text and at your defense, state this strictly: the runaway (exponential) growth happens "under the standard construction via a deterministic automaton". It is the price of a specific chosen route, not a law of nature implying no other path exists. In other models of computation, complementation works differently: for instance, in so-called alternating automata - which can branch not only by the rule "at least one branch" but also by the rule "all branches at once" - complementation comes down to simply swapping one branching rule for the other (exchanging quantifiers) and costs peanuts. Still, there is no such thing as a free lunch: the heavy cost does not vanish there, it just moves elsewhere - into testing whether the resulting language is empty (whether the automaton can catch even a single phrase). You should be able to state this trade-off calmly out loud ahead of time, rather than discovering it in surprise the first time your program hangs on a run.
Your mandatory skill for this section: for every pattern extension you propose, name which language operation it is, whether the language stays regular, and what price you will pay for that operation.
3. The limit of your alphabet, the Myhill-Nerode theorem, and automaton minimization
Two completely different arguments live in this section. People mix them up all the time, and telling them apart at your thesis defense is vital. One says that your automaton is blind because its set of input tags is too poor. The other is about how much memory a sighted automaton needs in order to work without extra clutter.
First argument: blindness from a poor alphabet, or feature loss.
Take two English phrases: the correct "I saw a cat" and the erroneous "I saw a cats". Our automaton does not read the English words themselves, but their grammatical tags - word classes. Suppose we built a very poor tag set that only knows parts of speech without their grammatical number: "pronoun", "verb", "article", "noun".
Let's watch step by step what happens before the automaton even runs. The words are translated into classes:
- The first phrase, "I saw a cat", turns into the string: "pronoun", "verb", "article", "noun".
- The second phrase, "I saw a cats", turns into the exact same string: "pronoun", "verb", "article", "noun".
To your machine, this is literally the exact same input word! Yet the right answers must be different: on the first phrase the machine should stay quiet, and on the second it should sound the alarm. But no decision rule in the world - not a finite automaton, not a complex grammar, not a giant language model - can give different answers to the exact same input. If a device does not flip a coin, it will always give the exact same answer to the exact same query. And if it does flip a coin, it cannot guess reliably.
When translating a living word into a coarse class, we lost the singular/plural feature. In strict theory, that is what it is called: a feature-loss argument under the "word-to-class" projection.
Remember the main thing: the Myhill-Nerode theorem has nothing whatsoever to do with this trouble! Why do people mix them up? Because Nerode's theorem talks about indistinguishability of strings. Here is how it actually works: take two phrase beginnings. Append the exact same tail to both - any tail you like. If, for every shared tail, the two resulting full phrases always behave the same way (both are valid or both have an error), then to the automaton those two beginnings are indistinguishable, or, in technical terms, equivalent. Notice that Nerode's definition does not require the two beginnings to be different words! And of course any word is indistinguishable from itself - append the same tail to two copies of one string and you get two identical phrases with the same fate. That is an empty truth; nothing follows from it. Nerode's theorem only gets teeth when you take different strings of classes and prove that the automaton is forced to tell them apart. Whereas in our example with "cat" and "cats", the string of classes came out the exact same.
Look at two different sentence beginnings: "The small cat" and "My old dog". In a sharp-eyed alphabet, these are different strings of classes, yet both end with a singular subject head. No matter what common continuation we attach to them - whether a correct one like "runs fast" or an incorrect one like "are tired" with a plural verb - the fate of both complete sentences will always be the same: "The small cat runs fast" and "My old dog runs fast" are both correct, while "The small cat are tired" and "My old dog are tired" both contain the exact same agreement error. So for an automaton catching this error, these two beginnings are completely indistinguishable, and it is entitled to route them to the exact same memory state.
A tough practical conclusion follows from this. If fundamentally different phrases have merged into a single string of classes, adding new states to the automaton is useless. Making the memory structure more complex makes no sense if the eyes cannot see anything. This family of errors can only be cured by enriching the alphabet: you need to introduce morphological features (splitting the classes into "singular noun" and "plural noun"), base word forms (lemmas), or finer subclasses. Until the alphabet is enriched, some examples remain indistinguishable in principle.
But be careful not to jump to extreme conclusions! Losing a feature only means that you will not be able to parse every single case in the language without error. It does not mean at all that your detector's quality will stop growing. On that exact same poor alphabet, you can and should keep improving the rules until you hit the ceiling of this representation.
Here is how this looks in your project on that very same poor alphabet of four coarse classes without a number feature: "pronoun", "verb", "article", "noun". True, such an alphabet will not let you catch the error in "I saw a cats", but if another gross error frequently appears in the texts - an article before a verb, as in "I saw a go" - then your string of tags will look like "pronoun", "verb", "article", "verb". For this error, the number feature is not needed at all: you simply add a rule to the automaton forbidding the "verb" tag from coming right after the "article" tag, and your detector's quality grows noticeably without any redesign of the alphabet.
The nicest thing is that you can measure this ceiling in exact numbers before you even write the automaton itself! For a good thesis, this is a ready-made, standalone result: you show in advance how much information is lost at the text tagging stage.
How does this calculation work for the simplest metric - accuracy (the share of correct decisions)? You take a tagged text corpus, translate all examples into strings of your alphabet, and sort them into piles (classes) that have the exact same input representation. Inside a single pile, all examples look identical to the automaton. This means any deterministic rule can make only one decision for the entire pile: either declare all examples in it erroneous, or declare them all correct. To make as few mistakes as possible, a smart algorithm will side with the majority in each pile: if there are more real errors in it, it will call the whole pile erroneous; if there are more correct examples, it will call the whole pile clean (and if a rule is random and flips a coin, this very same limit will bound its average score).
So you simply take the larger of the two numbers (erroneous or correct cases) in each pile, add up these maximums across all piles, and divide by the total sample size. That gives you the exact accuracy ceiling for a given representation on a given corpus. This is not a universal limit for the English language in general, but an honest assessment of your current tagging scheme on your data.
Look at how this works on a phrase: suppose your coarse alphabet does not distinguish noun number and turns both the correct chunk "a cat" and the erroneous chunk "a cats" into the exact same string of tags: the class "article a" followed by the class "noun". All such spots from the corpus will land in one common pile. The automaton only looks at the string of two tags, so to it, "a cat" and "a cats" inside this pile are completely indistinguishable: it physically cannot raise an alarm on "a cats" and stay silent on "a cat".
For this number to make sense and not get torn apart at your thesis defense, you must strictly follow three conditions:
- First, declare your unit of observation - that is, what exactly you count as a single test case. Under no circumstances is this the entire sentence! A long sentence has several test spots, and the right answers in them differ (at the beginning of the sentence an article is used correctly, while at the end there is an error). The unit of observation must be a specific check site: a window around the candidate word of the exact width that your rule sees (the word itself plus a few neighbors).
- Remember the huge class imbalance in the data. In real text, grammatical errors are hundreds of times rarer than correct spots. Because of this, accuracy is high all by itself: a lazy majority-class rule that never triggers at all and says "there are no errors anywhere" will already be right almost all the time and yield a score close to one. So right next to your ceiling, always report the score of this lazy baseline rule. Only the difference between them has value, not the pretty number near one hundred percent itself.
- Calculate the ceiling specifically for the quality metric by which your work is evaluated. Accuracy is a crude metric. In our task, the main evaluation score is a special weighted measure (we will cover it in detail in section twenty) that combines precision and recall, valuing precision over recall: it penalizes a false alarm more heavily than a missed error. For this metric, the ceiling across the very same piles is calculated differently.
Let us see how this works on the sentence "I see a cat and a dogs". If the unit of observation were the whole sentence, we would have to give one single answer for two different situations. Instead, we slice the sentence into separate two-word windows around each article: the first window "a cat" gets the label "clean" in our annotation, while the second window "a dogs" gets the label "error", and they go into our piles as two independent test cases.
Let us figure out how to find the ceiling for our main weighted metric. When triggered, each pile of identical strings brings us some number of true hits and some number of false alarms. We need to decide which piles to declare "erroneous" (turning the alarm on for them) and which to leave alone so that the final weighted score is as high as possible. There is no need to blindly try out all possible combinations of piles - there are far too many of them. It turns out that when the total number of errors in the corpus is known, our metric works in such a way that it pays to take all piles where the density (share) of errors is above a single common threshold, and discard all piles where the share is below that threshold.
Why is that? Imagine you have already gathered a basket of buckets and got some current score on our weighted measure. If you check the math, you will see a simple rule: a new bucket will improve your score if and only if the share of true errors inside that bucket is strictly greater than four-fifths of your current score (in terms of division, this is the same as dividing your current score by one and a quarter). This threshold depends only on the score you have reached so far, and it is the same for every candidate bucket. That means that in the best possible selection, every bucket you take will have an error share above the final threshold, and every bucket you leave out will be below it.
This gives us a fast, exact recipe for finding the ceiling in a single pass:
- In each bucket of identical input strings, find the error rate: divide the number of error cases by the total number of cases in that bucket (errors plus correct uses). Be careful: you cannot just divide the number of errors by the number of correct cases! If you run into a pure bucket where every single case is an error and there are zero correct ones, dividing by zero makes no sense, even though such pure error buckets are the most valuable of all and must go first.
- Line up all the buckets in descending order of this error rate - from the "dirtiest" to the "cleanest".
- Walk down this line from top to bottom, adding one bucket at a time to your trigger list (in other words, checking the prefixes of this ordered list). At each step, recalculate the weighted measure and pick the best result.
Let us run through this recipe on a live example. Suppose your entire corpus has exactly one hundred test windows, and ten true errors are hiding among them. Your impoverished alphabet has lumped all one hundred windows into just three buckets of identical strings:
- First bucket (ten windows): it holds six true errors and four correct passages. The error rate here is six tenths.
- Second bucket (also ten windows): it holds three errors and seven correct passages. The error rate is three tenths.
- Third bucket (the remaining eighty windows): it holds just one error and seventy-nine correct passages. The error rate is tiny - one eightieth.
First, for comparison, let us look at the simple share of right decisions (accuracy). The lazy rule "there are never any errors" will get all ninety correct passages out of a hundred right - its score is nine tenths. A smart rule will pick the majority in each bucket: in the first bucket it will call everything an error (six right answers), and in the second and third it will call everything correct (seven and seventy-nine right answers). In total, that comes to ninety-two right answers out of a hundred. The gain over the lazy rule is just two hundredths!
Now let us find the ceiling for our main weighted measure. The buckets are already lined up by decreasing error rate (six tenths, three tenths, one eightieth). We walk down the line from top to bottom:
- Step zero: we take no buckets at all. Zero true hits, zero false alarms. By a special convention (which you must state explicitly in your thesis!), an empty selection gets a score of zero.
- Step one: we take only the first bucket. We caught six true errors out of ten and raised four false alarms. We calculate the weighted measure - it comes out to exactly six tenths. What is the threshold for the next bucket now? Four-fifths of six tenths is nearly a half (forty-eight hundredths). We look at the second bucket: its error rate is only three tenths! That is below the threshold. So adding the second bucket will only hurt our score because of all the false alarms.
- Step two: just to check, let us add the second bucket anyway. Now we have nine caught errors and eleven false alarms. Because of the penalty for false alarms, the weighted measure drops to five tenths. Our threshold rule worked like a charm!
- Step three: we take all three buckets. We caught all ten errors, but raised ninety false alarms. The score collapses to roughly one eighth.
The conclusion is rock solid: until you enrich the alphabet, no detector in the world will get a weighted measure above six tenths on this corpus. This short calculation is well worth including in full in your thesis. And this calculation runs at lightning speed: sorting the examples into buckets using a lookup table (hashing) with a fixed window size takes time that grows purely in line with the total number of examples in the corpus. Ordering the buckets takes a bit more work, but it depends only on the number of buckets themselves, not on the size of the corpus. And walking down the ordered line is just a single straight pass through the list of buckets. Just do not forget to explicitly state three edge cases in your paper: if there are no gold-standard errors in the corpus at all, the measure is undefined; to an empty set of buckets we assign zero by convention; and if several buckets happen to have the exact same error rate, you can put them in any order relative to each other - it will not affect the final score.
Argument two: the Myhill-Nerode theorem proper and automaton minimization.
Now let us leave the impoverished alphabet behind. Suppose our alphabet is rich and distinguishes everything we need. Then the real Myhill-Nerode theorem comes into play. Here is what it says: if we partition all possible input strings into groups (equivalence classes) so that inside any one group, any two strings behave identically no matter how the sentence continues, then the number of such groups is equal to the exact number of states in the smallest - minimal - deterministic automaton for our pattern.
Let us test this on a live example: catching an error like "a cats", where a plural noun accidentally follows the article "a". No matter what sentence beginnings come in as input, by their future fate they fall into exactly three groups: the first group is strings like "I see", where the article "a" has not appeared yet and we are still waiting for it; the second group is strings like "I see a" or "he took a", which end with the article "a" and will trigger an alarm if the very next step brings the class "plural noun"; the third group is strings like "a cats", where the error has already happened and the red button is pressed for good. The beginnings "I see a" and "he took a" sit in the same group because any continuation acts on them the same way: add "cats" to both and both become an error; add "cat" and both stay clean. That means the minimal deterministic automaton for this pattern needs just three states.
Why do we need this in practice? Three powerful consequences grow out of it:
- First, it gives us rock-solid lower bounds. If you find five different sentence beginnings, each with its own distinct fate under continuation, you have proved that no matter how clever you are, you cannot express this pattern in fewer than five states.
- Second, if there are infinitely many such beginnings with distinct fates (for instance, if the automaton has to remember the exact number of open parentheses, and there can be arbitrarily many of them), then the language is not regular at all - no finite automaton can handle it.
- Third, the minimal automaton for any regular language is unique up to renaming the states (in computer science, this is called canonicity). This gives us an exact tool for comparison: to find out whether two differently written rules define the same language, we do not need to guess or argue by hand-waving. We just build the minimal automata for both rules and check whether their diagrams match.
Look at five short beginnings of an English phrase: an empty beginning with no words, the single word "I", the opening "I see", the opening with an article "I see a", and the ready-made error "I see a cats". Each of these five fragments has its own fate: after "I see a", the arrival of the plural noun "cats" immediately makes the phrase erroneous, whereas after "I see" the very same word "cats" is completely legal; after "I" we expect a verb, at the empty beginning we expect a subject, and in the fifth case the alarm has already gone off and no further words will cancel it. If the automaton had only four states, some two of these five beginnings would inevitably land in the same state, and the machine would mix up their continuations.
But two crucial caveats await you here, without which the conclusions in your thesis will be overstated and wrong.
First caveat: the uniqueness of the minimal automaton settles the question of whether two specific languages (two specific patterns) are equal, but by itself it does not prove that two different ways of describing languages have the same expressive power in general (for instance, automata and regular expressions) - in theory, that requires a separate argument.
Second caveat, and for your project it is far more important: all of classical minimization and equivalence testing for automata is written for a recognizer. And your grammatical error detector is not a recognizer! Feel the difference. What does a recognizer do? It reads a sentence from start to finish and at the end simply lights up a single bulb: "yes, the sentence matches the pattern" or "no, it does not". And what is your detector required to do? It must return a set of specific hits: point out the exact boundaries of the erroneous fragment in the text (the span) plus the ID of the rule that fired.
Imagine that you have two versions of a detector and you feed them the phrase "Yesterday I see a cats". Both detectors might fire on this sentence. As recognizers of sentences with errors, they are completely identical! But the first detector will point its finger at the verb "see" (wrong tense), while the second will point at "a cats" (disagreed article). When you start measuring performance - the number of true hits, false alarms, and misses (which we will cover in sections seventeen and twenty-six) - these two detectors will give completely different numbers! They are different programs.
That is why you cannot prove that two versions of your code do the same thing by using ordinary recognizer automata. First, you must honestly declare your output model. There are two ways: either you bake the error boundary markers right into the input alphabet (so that the position of the error becomes part of the string being checked), or you use an automaton with output - a finite-state transducer (which will be explained in section nine). And only within the chosen model do you test whether two machines are equal. Until the output model is declared, the phrase "the two versions of our detector are equivalent" has no testable meaning whatsoever. You must choose and describe this model before the very first claim that two implementations are equal appears in your thesis.
Let us check on the same sentence "Yesterday I see a cats" how both ways look. In the first way, we feed the machine text with boundary tags already inserted: the first version checks a string where the start and end error markers wrap the word "see", while the second checks a string where the same markers wrap the fragment "a cats", and these are simply two different input strings that the same automaton cannot both accept. In the second way, both machines read the clean phrase "Yesterday I see a cats" without any tags, but during the reading steps they emit different answers to the outside: the first spits out an alarm signal right on the word "see", while the second stays silent until the article and emits its signal on the pair "a cats".
In the end, for this part of the theory you need a clear skill: take one family of errors, carry through to the end one of the two arguments (about losing a feature, or about the number of states via Nerode), state outright which argument it is, and be able to shrink the automaton down to the minimal one.
And one last thing - how much time does this shrinking (minimization) of an automaton take? How do we shrink an automaton at all: we look for twin states from which, no matter what text is read next, the machine behaves identically, and we glue them into a single state. In standard textbooks, the size of the input alphabet is often treated as a tiny constant and simply dropped from speed estimates. You must not do that under any circumstances! Your alphabet consists of word classes, and when you add parts of speech, number, tense, and subclasses to it, the alphabet swells to hundreds and thousands of symbols. So you must keep the alphabet size in plain sight in your running-time estimates. Distinguish between two classical ways of shrinking:
- Moore's algorithm works by step-by-step refinement: first we roughly divide all states into just two groups (accepting and non-accepting), and then at each step we check whether states in the same group behave differently when reading some symbol of the alphabet, and we split the groups into smaller and smaller pieces until the splitting stops. Its running time depends on the size of the alphabet and grows as the square of the number of states: if there are ten times as many states, there will be roughly a hundred times as much work for the same alphabet. (By the way, the table-filling method familiar from lectures, where you build a table of all pairs of states and cross out distinguishable pairs, we cite strictly from the main textbook; we have not held Moore's original paper in our hands, so we will neither attribute this table method to Moore personally nor deny his contribution - and we advise you to cite it just as carefully).
- Hopcroft's algorithm does the same splitting of groups, but is much cleverer about choosing which groups and symbols to check for splitting, so as to avoid extra work. Because of this, as the number of states grows, its running time grows much more moderately - almost in proportion to the number of states, with only a small overhead (ten times as many states means only about thirty-something times as much work), but all of this is still multiplied by the size of the input alphabet. In Hopcroft's paper itself, the speed estimate contains a separate multiplier letter, and many students think it is just some tiny constant. In fact, in the original report that letter stands for the exact number of input symbols of the automaton, that is, your entire swollen alphabet of word classes.
Let's put actual numbers to what this costs in your project as your automaton and alphabet grow. Say your automaton grows from a hundred states to a thousand, and a detailed alphabet of word classes covering all tenses and numbers expands from fifty labels to five hundred. Multiplying by a tenfold larger alphabet adds a tenfold cost to both methods, but on top of that, a tenfold increase in states under Moore's method multiplies the work by another hundred - so in the end you pay a thousand times more than before. With Hopcroft's method, a tenfold increase in states only adds a factor of thirty-something, so together with the tenfold larger alphabet, the total workload grows by a bit over three hundred times instead of a thousand.
4. When the automaton's memory is not enough at all.
A finite automaton is called finite for a reason: its memory is strictly limited to a fixed, preset number of states. But some tasks require memory with no upper bound at all. For instance, when a machine has to keep an exact count (checking that a text has the exact same number of elements of two different types, when there could be thousands of them) or track unlimited nesting of agreements inside one another. In such cases, your error detector cannot be a finite automaton at all. The language is no longer regular. And if you prove this rigorously in your thesis - that too is an excellent scientific result.
You prove this kind of impossibility using a tool called the pumping lemma. Here is the plain-English idea behind it. Imagine an automaton has only ten states, and we feed it a long, grammatical sentence of twenty words. As it steps through the words, the automaton will inevitably land on at least one of its ten states twice. And since it has returned to the exact same state, its path has formed a loop! The machine has no memory of how it got into that state. So the chunk of text that fell along this loop can be repeated a hundred times in a row, or dropped altogether - the automaton will simply go around the same ring and still be forced to accept the sentence as grammatical. Repeating this loop is what we call pumping. If repeating the loop breaks the grammatical agreement in the sentence (say, there are now more subjects than verbs), yet any imaginary automaton is forced by the loop to accept the sentence anyway - we have a contradiction. That means no finite automaton for this task can exist in nature.
Take for example an English construction with center-embedded relative clauses: "The cat that the dog that the man saw chased ran", where three subjects "cat", "dog", "man" line up, followed by their three exact verbs in reverse order: "saw", "chased", "ran". If an imaginary automaton with a small supply of states reads a long chain of such subjects in the first half of the sentence, it will inevitably go through a loop - say, on the chunk "that the dog". Pump that loop once more and we get the sentence "The cat that the dog that the dog that the man saw chased ran": now there are four subjects and still only three verbs, the sentence has fallen apart, yet the automaton did not even notice because after the extra lap around the loop it ended up in the exact same state.
There is a fine line here that is easy to trip over. Many people think: if you can insert any number of words between a subject and its verb, an automaton will fail. That is a mistake! Ordinary agreement across an arbitrarily long linear insertion - where a feature sits on the left, followed by any number of unrelated words, and the agreeing word sits on the right - is completely regular.
Let's see what the machine has to do and how it does it on an ungrammatical sentence: "The books that I bought yesterday at the old market is interesting". The machine needs to catch the mismatch between the subject "books" and the verb "is". Step by step, it works like this:
- The word "books" arrives - the machine thinks: "I see a plural subject, I need to wait for a matching verb" and moves into the state of waiting for a plural verb.
- Next come the words of the linear insertion: "that", "I", "bought", "yesterday", and so on - even a million words. The machine does not count them or remember them! It simply stays in place in the exact same state, holding on to a single finite feature in memory: "the subject was plural".
- Finally, the singular verb "is" arrives - the machine sees that this does not match its current state, steps into the error state, and raises the alarm.
The length of the insertion does not scare the automaton, because a finite feature easily fits into a single state. That is why the class of tier-based strictly local languages from section seven, which was invented specifically for agreement across long stretches of inserted material, lies entirely inside the regular languages.
An automaton breaks not from the length of a sentence, but from having to store an unbounded amount of information: keeping a count or remembering unlimited nesting. Picture a Russian-doll sentence: "The cats that the dog which the man feeds chase run". Here one clause is embedded inside another, and that one inside a third. First come three subjects in a row ("cats", "dog", "man"), and then come their verbs in reverse order ("feeds" for the man, "chase" for the dog, "run" for the cats). To check whether grammatical number agrees in all pairs, it is not enough for the machine to remember just the last word - it has to remember the entire stack of unresolved subjects in their exact order. If this Russian doll can grow deeper without limit, no finite number of states will ever be enough.
When applying the pumping lemma, keep three rules firmly in mind so you do not make typical mistakes that stand out immediately in a thesis:
- The lemma only works in one direction. If you pump a loop and get a contradiction - you have proved that the language is not regular. But if you fail to get a contradiction - that in no way proves that the language is regular! Regularity can only be proved constructively: you must either exhibit the automaton or regular expression itself, or use the closure properties from section two.
- The mere fact that clauses can be embedded inside one another in English does not by itself prove non-regularity. You have to prove it honestly: that detecting the error itself requires bottomless memory - either via the pumping lemma on a specific family of sentences, or by showing an infinite number of equivalence classes under the Myhill-Nerode theorem.
- If the language is actually regular, and your particular automaton fails to catch the error, the pumping lemma has nothing to do with it. The failure of your automaton on a regular language is proved using one of the two arguments from section three (an overly coarse alphabet of word classes or a shortage of states).
Look at a sentence with the same triple Russian-doll nesting as at the start of the chapter: "The cats that the dog which the man feeds chase a mouse". The clauses here are nested three levels deep, but imagine your detector is only looking for a simple article error in the text, like in the chunk "a cats". To catch "a cats" or make sure that "a mouse" is clean, the machine does not need to remember the stack of cats, dog, and man at all - it simply looks at two adjacent words, and two states are plenty for that, no matter how deep the nesting goes.
But what if we say: "In real speech, nobody builds infinite nesting dolls! Let's cap the nesting depth at a specific limit"? That is a great engineering move. It corresponds to a distinct cell in our theory: bounded nesting. As soon as the maximum depth of the nesting doll is bounded by a fixed number, the language becomes regular again! The state of the automaton simply stores the current stack of unclosed features, up to a height no greater than this limit.
Let's check on a live example how the machine steps through the sentence "The cats that the dog chases run", assuming we allow a depth of up to two and distinguish two features - singular and plural. At the start, the stack is empty; the subject "cats" arrives with a plural tag - the automaton moves to the state "one plural on the stack". Next, after the word "that", a second subject "dog" arrives with a singular tag - the automaton steps into the state "plural on the bottom, singular on top". Now comes the singular verb "chases": it matches the top of the stack, closes it, and the machine returns to the state "one plural on the stack". Finally, the plural verb "run" arrives, closes the last subject, and the automaton safely returns to the empty stack state - the agreement matches.
However, the price for this is a number of states that grows like an avalanche with each new level of depth. Still, at your thesis defense you cannot simply say the words "nested agreement" - that statement will not count as a theorem. You need to formulate the problem strictly, as a formally defined language. Take the language of balanced bracket sequences with several types of brackets, where the nesting depth does not exceed a given limit. Here, an opening bracket is our grammatical feature (for example, a subject of the required type), and a closing bracket is the word that agrees with it (a predicate of the same type).
Let's see how a complete minimal deterministic automaton works for such a bracket nesting doll. It must remember every possible stack of open brackets, from empty up to the tallest one. Therefore, it will have exactly one state for each reachable stack of valid height, plus one more trap state (or dead state) that the machine falls into at the very first error. For example, if there is only one type of bracket, the automaton simply counts the depth from zero to the limit: it will have exactly two more states than the maximum depth (counting the empty stack, all depth levels, and the trap state).
And if there are several types of brackets, the avalanche begins. Why is this a strict lower bound on the size of the most economical automaton, rather than just our own bloated construction? This is proved using the Myhill-Nerode method from point three, and the proof requires three conditions - all three hold here:
- First: every such stack is reachable - you can drive the machine into it simply by feeding the required opening brackets one after another.
- Second: every stack has its own valid completion - you need to close all of its brackets in strictly reverse order.
- Third: this completion will not work for any other stack! The very first bracket type mismatch or leftover non-empty remainder will immediately send the automaton into the trap state.
Here is what this looks like in your project for two different sentence beginnings: "The cats that the dog..." and "The cat that the dog...". By the time the word "dog" is read, the first phrase has brought the automaton to the state with the stack "plural on the bottom, singular on top", while the second has brought it to the state "singular on the bottom, singular on top". If we now feed the continuation "...chases run", then in the first phrase the verb "chases" pops the top singular, the verb "run" pops the bottom plural, and the stack empties without errors. But the exact same continuation "...chases run" for the second phrase, after popping the top singular, will pit the plural verb "run" against the singular subject "cat" remaining at the bottom - and the machine will immediately fall into the trap state.
Since every stack has its own unique continuation, these states cannot be merged. Let's look at specific numbers to see what this memory costs (all these values for two, three, and four feature types and depths from one to five have been rigorously verified by computer minimization of automata):
- Suppose we have two feature types (for example, singular and plural) and we allow a nesting depth of up to two. Let's count the possible stacks: the empty stack (one state), stacks of height one (two states - singular or plural), stacks of height two (four combinations), plus one trap state. In total, we get eight states.
- Take three feature types and allow a nesting depth of up to three - the minimal automaton will already require forty-one states.
- Keep the same three feature types, but increase the allowed nesting depth by just two steps, up to five - and the number of states in the minimal automaton skyrockets to three hundred and sixty-five!
And one last important note: applying this bracket math to grammatical agreement in your thesis is legitimate precisely when the agreeing word on the right is required to recognize the exact type of its paired feature on the left - that is, when pairs are matched strictly in order of nesting. If your task only requires checking that a word belongs to some finite class, without matching nested pairs, then the problem is much simpler and does not require hundreds of states like these.
The takeaway for your thesis is simple: bounding the nesting depth saves the day and brings the problem back inside regular languages. However, you must state your chosen depth limit explicitly - and along with it, honestly state the price in states that your automaton pays for this depth.
Level 2. For the theory chapter
5. How to turn a text rule into a working machine
This step is needed by those of you who are writing a compiler for error patterns. When a person comes up with a rule for finding an error, they write it down as a convenient text string - a pattern, which in theory is called a regular expression. But a computer cannot search for errors directly from a text notation. It needs a clear diagram made of state circles and transition arrows - in other words, a finite automaton.
Here is what this looks like in your project: you notice the error "I see a cats" in a student's text and realize that the article "a" must not stand before a plural noun. For a human, the easiest way to record this observation is in a single line: first comes the class "article a", followed immediately by the class "plural noun". For the compiler, such a text string is the input pattern, but for now it is just letters in a file, not a working circuit.
The statement that any text rule-pattern and a finite automaton describe the exact same sets of strings, and that you can always convert one into the other, is called Kleene's theorem. It serves as a reliable bridge between your human notation of a rule and the machine that will scan the text. And the specific step-by-step recipe for turning the written rule into a diagram with arrows is called Thompson's construction.
Let's test this balance on a live example with the error "many milk". Suppose you write a text pattern where the word "many" is immediately followed by the class "uncountable noun", and you translate it into a finite automaton made of three circles and two arrows. Both representations will catch the exact same pieces of text. Feed in the sentence "She drank many milk": the text pattern will match the word pair "many milk", and the automaton built from it will likewise step from the start circle along the "many" arrow, then along the "uncountable noun" arrow, and set off the alarm in the final circle. On the correct sentence "She drank much milk", both will stay silent.
What does the builder program have to do with this recipe? It takes your text rule and builds a working automaton out of it with no human help. How does it do that? It breaks the rule down into the smallest building blocks, draws a tiny piece made of two circles and an arrow for each one, and then simply glues these pieces together like a construction set.
Let's walk through an example. Suppose you wrote a pattern to find an extra article before an uncountable noun: first comes the class "indefinite article", immediately followed by the word "advice" or the word "information". The builder takes this rule and starts construction:
- for the class "indefinite article", it places an entry circle and an exit circle, and connects them with an arrow labeled "indefinite article"
- for the choice between the words "advice" and "information", it makes a fork with two parallel paths, where the top arrow says "advice" and the bottom one says "information", after which both paths merge back into a single circle
- then it firmly glues the exit of the first piece to the entry of the second piece to form a single chain
In the end, the computer gets a ready-to-use automaton diagram. Now we feed in the English sentence "He gave me an advice". The machine reads the words one by one. On the words "He", "gave", "me", it just waits at the start. Then comes the word "an". The machine sees: this is the class "indefinite article"! It steps along the first arrow and stops right in front of the fork. Next comes the word "advice". The machine happily steps along the top path of the fork and lands in the final circle. Alarm triggered - the error "an advice" is caught!
6. What we can know for sure about our rules and how much it costs
Once our rules are turned into automata, we can ask the computer important questions about how they behave and get exact, guaranteed answers. Properties of rules that a computer is guaranteed to check in a finite number of steps are known in computer science as decidable properties of regular languages. There are four main questions like this:
- will our rule catch at least one error in the world, or did we accidentally write a contradictory condition where the final state can never be reached at all (this is called the emptiness check, or reachability check)
- will the rule trigger on this specific sentence (this is the membership check)
- did two students use different words to write two rules that actually catch the exact same thing (this is the equivalence check)
- is it true that a new, improved rule catches everything the old one caught, plus new cases on top of that (this is the inclusion check)
See how easy it is to accidentally create a dead rule like that in a project. Suppose you wanted to catch the error in the phrase "many water" and required the very same word to carry both the tag "plural noun" and the tag "uncountable noun" at the same time. In reality, no English word will ever get that double tag from the tagger. So the arrow to the final state is left without a single matching word, the automaton will never step along it, and the reachability check will immediately show that the path to the final state is empty.
Let's test this on a live example from your work. Suppose the first student wrote a rule that waits for the word "a" and then explicitly lists three cases using a fork: "dogs", "cats", or "birds". The second student was too lazy to list the animals and after "a" put a single general transition for the class "plural animate noun", which in your test dictionary contains those exact three words. The rules look completely different in the code, but the computer builds both automata and confirms: on the errors "a dogs", "a cats", and "a birds" both reach the final state, and both reject everything else - meaning the rules are completely equivalent.
The last question is the most important one for your thesis. At your defense, you often say: "we expanded our pattern, and now it covers more errors". In strict terms, this is a claim about the inclusion of one language in another. And instead of arguing with the committee in words, you can strictly verify this claim on a computer. But here is the catch: the cost of this check depends directly on the form in which your rules are written.
Remember that automata come in two kinds. The first kind is when from every circle, for every word, there is at most one arrow, so the machine never hesitates and always follows a single path. Such an automaton is called unambiguous, or a deterministic automaton. The second kind is when several arrows for the very same word can leave a single circle, or when there are wordless jump transitions, like the ones we got after gluing forks together. There the machine has to branch out and check several guesses at once. This is a branching, or nondeterministic automaton.
Here is what this looks like on a small machine designed to find the error "a fast cars". Suppose from the state "saw an article" two arrows leave for the exact same class "pre-noun word": one leads to the circle "waiting for another modifier", and the second leads straight to the circle "waiting for a plural noun". When the word "fast" arrives, the automaton does not know whether this is the last modifier or if another one will follow, so it splits its guess in two and steps into both circles at once.
Now, if both of your rules have already been converted into deterministic automata, checking inclusion is very cheap and fast. What does the checking machine need to do? Find at least one counterexample - that is, a phrase that the old rule catches, but the new one somehow misses. And how does it do that? It builds a single shared verification grid by running both automata in parallel, in lockstep, step by step, and then simply checks whether it is possible to travel through this shared grid to a situation where "the old automaton caught the error, but the new one did not". In computer science, this parallel grid is called the product automaton, and searching for a path in it is called an emptiness check.
Let's see how this works step by step on a small example. Suppose your old rule looked for a simple pair: the class "determiner" immediately followed by the class "noun", catching the phrase "a cat". Its deterministic automaton had just three states: start, "saw a determiner", and final. You decided to expand the rule and allowed inserting one word of the class "adjective" in the middle, so it would catch not only "a cat", but also "a big cat". The new deterministic automaton now has four states.
Now we run the check:
- the computer builds a combined grid of state pairs from the first and second automata; since the first has three states and the second has four, there are exactly twelve possible pairs in the grid
- we feed in the phrase "a cat" and track the pair of states across both automata at once
- the word "a" of the "determiner" class arrives: both the old and the new automaton step forward in sync and wait to see what comes next
- the word "cat" of the "noun" class arrives: the old automaton steps into its final state, and since the new automaton can also do without an adjective, it steps into its final state as well
- no matter how much we wander through all twelve nodes of our combined grid, we will never hit a node where the first automaton is already in a final state while the second is not; this means the counterexample region is empty, and the new rule really does cover the old one completely
Why did we say this is fast on deterministic automata? Look at how the grid size grows: the automata had three and four states - the combined grid got twelve nodes; if each had ten states - there would be a hundred nodes; if each had a hundred - there would be ten thousand. The problem size grows moderately, which is quite manageable for any computer. In theory, this kind of moderate, predictable growth is called polynomial time.
It is a completely different story if you were too lazy to convert the rules into deterministic automata and try to directly compare two branching, nondeterministic automata or two long text pattern expressions. To make sure the new branching rule has not missed anything from the old one, at every step the checking machine will have to keep track of not just a single pair of states, but all possible sets of guesses of the new automaton at once. And we already know how that ends: for a three-state automaton there are eight such sets, for ten states - already over a thousand, for twenty - over a million! The number of options grows like an avalanche, the computer's memory fills up instantly, and the program can hang for hours or days. In complexity theory, such heavy problems that eat up all available memory are called PSPACE-complete (complete for the class of problems solvable in polynomial space).
From this comes a simple practical rule for your thesis. If you want to prove to the committee that a new rule covers more than an old one - do not argue, check it strictly. On deterministic automata, this check will cost less than any argument and take a fraction of a second. But if the rules are written as regular expressions or branching automata, take a close look at their size first, otherwise you risk not getting an answer before your defense.
7. The inner floors of regular languages.
All our rules are regular, but inside this huge world there are simpler, narrower regions. Together they form a system called the subregular hierarchy. This is not covered in a standard university course, so it is a great place for your own research contribution rather than a retelling of a textbook. In your thesis, your team is required to define these classes and measure one transition between two of them in practice. All the complex algebra and bounds below are for reference - just so that a statement in your thesis text does not accidentally turn out to be false. You do not need to prove these statements.
First, let us get acquainted with the classes themselves, from the simple ones to the trickier ones:
- Strictly local languages. Imagine a machine that looks at the text only through a narrow sliding window of fixed width - say, two words wide. The machine only has a blacklist of forbidden pairs (or, which is the same thing, a whitelist of allowed ones). It slides the window across the sentence step by step. If not a single forbidden pair falls into the window - the sentence is accepted.
Look at the phrase "She bought a cats today" to see how such a two-word window works. Suppose the blacklist holds just one forbidden pair: the "singular determiner" class followed immediately by the "plural noun" class. The machine places the window at the start: the pair "She bought" is not on the blacklist, so we move on. The next pair, "bought a", is also clean, but at the third step the chunk "a cats" falls into the window - our exact forbidden combination, and the machine immediately rejects the sentence.
- Locally testable languages. This machine also looks at the text through a sliding window of fixed width. But it can do more: not only forbid bad adjacent chunks, but also require that some needed chunk must appear in the text at least once.
- Strictly piecewise languages. Here the machine no longer looks at adjacent chunks. It tracks the order of words at any distance - scattered sequences. It has a list of forbidden sequences. For example, it is forbidden for a word of one class to appear somewhere in the text, and later - even ten words away - a word of another class.
Let us test this on a live example with the phrase "Yesterday he goes home". A narrow two-word window will not notice anything here: the pairs "Yesterday he", "he goes", and "goes home" look completely legal on their own. But a machine for a strictly piecewise language keeps a scattered pair on its blacklist: first a word of the "past tense marker" class, and somewhere further to the right in the text - a word of the "present tense verb" class. It sees "Yesterday" at the very beginning, remembers it, and at the word "goes", no matter how many words stand between them, raises the alarm.
- Piecewise testable languages. These also track scattered sequences of words up to a certain length across the text, but they can not only forbid them, they can also require them to be present. Strictly piecewise languages are a proper, narrower subset of them, and their properties and checking complexity are different.
- Star-free languages. These are languages that can be described without the operation of infinite repetition (that very Kleene star from regular expressions), using only concatenation of chunks and logical operations: union, intersection, and complement.
- Tier-based strictly local languages. First, the machine puts on blinders: it throws out all the words in the sentence that are irrelevant to the case, and pushes the remaining important words right next to each other. Then, along this compressed track - the tier - it runs an ordinary sliding window with a list of forbidden chunks.
Here is how this looks in your project on the phrase "She gave me a really good advice". An ordinary two-word window will not catch the error, because the words "really" and "good" have wedged themselves between the article "a" and the uncountable noun "advice". But if we leave only the "determiner" and "noun" classes on the tier, and temporarily cross out all verbs, pronouns, adverbs, and adjectives, all that remains of the sentence is the short track "a advice". A two-word window slides along it and instantly catches the forbidden adjacent pair.
In practice, everyone falls into the exact same traps here. Let us break down the two main mistakes that almost everyone makes.
First mistake: thinking that if your detector looks at the text through a window of fixed width, its language is automatically strictly local. That is not true! Let us check this on a simple example. Take the language of sentences that contain the class "determiner" followed immediately, right next to it, by the class "noun" (as in the erroneous chunk "an advice"). A window two words wide moves along the sentence "He gave me an advice yesterday". Step one: "He gave" - nothing. Step two: "gave me" - nothing. Step three: "me an" - nothing. Step four: "an advice" - we caught the adjacent pair "determiner" and "noun"! A window two words wide spotted it easily.
Yet the language of all sentences containing such an adjacent pair is not strictly local for any window width! Why? Because strictly local languages have a defining property - closure under suffix substitution. It works like this. If two valid sentences share the same overlap whose length is one less than the window width, we are allowed to cut the tail off the second sentence and stitch it after the overlap onto the first one - and the new hybrid sentence must remain in the language. After all, at the seam, the sliding window will not see a single new chunk that it did not already see in the two original sentences!
Now let us see what happens to our language with a window two words wide. Here the overlap must be one word long. Take two strings of classes that both belong to our language (both contain the adjacent pair "determiner - noun"):
- First string: just the pair "determiner - noun". Let its overlap be the first "determiner"; then the beginning before it is empty, and the tail after it is "noun".
- Second string: the three words "determiner - noun - determiner". Let its overlap be the last "determiner". Then the beginning before it is the pair "determiner - noun", and the tail after it is empty.
Both strings are in the language. They share a common overlap - a single "determiner". Now we take the beginning from the first string (empty), the overlap itself ("determiner"), and stitch on the tail from the second string (empty). What do we get? A single word: "determiner"! It has no pair with a noun, so it falls outside the language. The overlap rule broke, which means the language is not strictly local for a two-word window. And no matter what window width you pick, we can break the rule in the exact same way just by making the overlap out of the required number of determiners in a row.
The point is simple: a strictly local language only specifies a list of allowed chunks and cannot require that a certain chunk must appear in the sentence. A locally testable language, on the other hand, can require presence! That is why the language "the sentence contains an adjacent pair of determiner and noun" is locally testable with a two-word window. By contrast, its opposite (complement) - the language "nowhere in the sentence is there an adjacent pair of determiner and noun" - really is strictly local with a two-word window, because it is defined by a single forbidden factor.
From this follows a crucial takeaway for all your work. Always keep in mind and distinguish four different objects:
- the language of valid English constructions,
- the language of the erroneous chunks themselves,
- the language of full sentences containing an error,
- the local detection mechanism itself.
Your detector, which triggers and raises an alarm when it sees a forbidden factor inside a long sentence, defines precisely the third object - the language of sentences containing an error. And this third object lives on the locally testable side, not on the strictly local side! The first question of your self-check asks about this exact thing.
Look at the sentence "She bought a apples yesterday" to see how these four things diverge. The first object, the language of valid constructions, contains the clean sentence "She bought apples yesterday". The second object, the language of the erroneous chunks themselves, contains only the short adjacent pair "a apples". The third object includes the entire long sentence "She bought a apples yesterday", along with a million other long sentences where this pair has snuck in. And the fourth object is your sliding window of width two: it steps from left to right, calmly lets the pair "She bought" pass, then the pair "bought a", but at the step "a apples" it sees the forbidden adjacency of a determiner and a plural noun and hits the red button, sending the whole sentence into the third language.
There is an exact rule here with a mandatory condition, and in your thesis defense you need to state this condition out loud. The rule goes like this: if your alphabet of word classes has at least two different symbols, then the language "the sentence contains such-and-such non-empty adjacent chunk" is not strictly local for any window width. This is always proved by the exact same overlap trick: we can always pick a word-class symbol from the alphabet such that our target chunk is not made of repetitions of that symbol, build an overlap out of it, and splice together a dud string where the required chunk is missing.
However, the proviso about having at least two symbols in the alphabet is not just there for decoration: without it, the rule becomes false! If our entire alphabet consisted of just one class, "determiner", then the condition "contains a determiner" would simply mean "any non-empty sentence". Such a language does not violate suffix substitution and fits nicely into the strictly local class with a window of width two (this has been verified by computer) - that is where the exact boundary of the rule lies. And one more subtlety: if you require a chunk to appear at a rigidly fixed position (for example, "the sentence begins with a determiner" or consists of a single "determiner - noun" pair), then such a language is also strictly local for any alphabet, because we simply forbid all other sentence beginnings. So keep the phrase "the strict side only knows how to forbid" as a handy hint for where to look, but in the thesis itself rely on the exact rule with its alphabet-size condition, and test suffix substitution for your specific language.
Let us check on a live example why suffix substitution does not break anything here. Suppose the language requires a sentence to start with a determiner, and the window has a width of two words (counting the special start-of-sentence marker). Take two sentences from this language: "a cat" and "the big dog", and let the shared one-word overlap be the determiner "a", if in the second sentence we replace "the" with "a" - giving us "a cat" and "a big dog". We cut the tail "big dog" from the second sentence and stitch it onto the overlap of the first in place of the word "cat": out comes the hybrid "a big dog", which still starts with a determiner and stays in the language. And if we pick an overlap in the middle of the sentence, then splicing the tail will not touch the very beginning of the sentence at all, and the first-word requirement will hold up once again.
Second mistake: thinking that strictly local and piecewise testable languages are two rungs on the same ladder, with the piecewise ones simply one floor up. In reality, neither of these two branches is contained in the other - they are incomparable! The local branch (strictly local and locally testable) looks at contiguous, unbroken chunks of text. The piecewise branch (strictly piecewise and piecewise testable) looks at scattered sequences of words with anything allowed in between. Papers written in English hide a dangerous terminological trap here: a scattered sequence is called a "subsequence" or "subword" (which people are often tempted to confuse with "substring"), while a contiguous chunk is called a "factor". If you read "subword" or "subsequence" as a contiguous "substring", you end up with a false theorem!
Let us use concrete witness strings to see that neither branch fits inside the other. First, in one direction: the language "nowhere in the text is there a contiguous determiner - noun pair" (which we already know is strictly local with a two-word window) is not piecewise testable for any length of scattered subsequences!
Let us check this for subsequences of length up to two. We add a third class - "adjective". Now take two sentences with the following sequences of classes:
- First: "determiner - adjective - noun - determiner" (for example, "a big cat that"). There is no contiguous "determiner - noun" pair here, so the sentence is in our language.
- Second: "determiner - adjective - determiner - noun - determiner" (for example, "a big a cat that"). Here, right in the middle, stands a contiguous "determiner - noun" pair, so this sentence is not in the language.
Now let us look through the eyes of a piecewise machine and list all scattered subsequences of one and two words that can be pulled out of the first and second sentences while keeping their left-to-right order. The single words are the same in both: determiner, adjective, noun. And what pairs can we pull out if we are allowed to jump over any words? In both the first and the second sentence, a determiner appears both before an adjective and after it, both before a noun and after it, and twice with itself; an adjective appears before a noun. If you carefully write out all possible scattered pairs, the two sentences will have the exact same set, down to the last letter! That means no machine that looks only at scattered subsequences of length up to two can tell these two sentences apart.
For scattered subsequences of length three, we take the same pair of sentences and simply prepend one more "determiner - adjective" chunk to the beginning of each. In science, though, you cannot just say "and so on" - you have to exhibit an infinite family of examples for any given subsequence length. Here is how we build it: we repeat the pair "determiner - adjective" as many times as the maximum subsequence length, and at the end we append "noun - determiner" to the first sentence, and "determiner - noun - determiner" to the second. The first sentence has no contiguous forbidden pair; the second one does. Yet thanks to the long comb of alternating determiners and adjectives at the start, we can pick out any scattered combination of these two classes of the required length, or take a slightly shorter combination and cap it off at the end with the noun, or take one a step shorter still and cap it off with the noun and the final determiner.
The sets of all scattered subsequences for the two sentences will match completely (this has been strictly proved and additionally verified by computer up to length seven inclusive). A local machine spots the difference instantly, while a piecewise machine is blind, no matter what subsequence length you give it!
Now let us turn in the opposite direction. Take a language with a gap: "somewhere in the sentence there is a determiner, and later on, after any number of arbitrary words, stands a noun". Keep this separate from the contiguous-pair language we talked about in the first mistake - they are completely different languages! Our new language with an arbitrary gap belongs to the piecewise testable class for subsequences of length two.
Here is how this looks on English phrases and how a piecewise machine handles it. Take the long phrase "a very old and sleepy cat": four extra words are stuck between the determiner "a" and the noun "cat". If we scanned this with a local window of width two or three words, at each step it would see only small contiguous fragments like "a very" or "old and", and it would never find out whether the determiner ever got its noun. A piecewise machine for subsequences of length two, by contrast, simply gathers into a bag all scattered pairs where one word stands to the left of the other, finds the pair "determiner, and somewhere to the right, noun" among them, and immediately lets the phrase into the language.
A common mistake is to call this gap language strictly piecewise. Do not fall for it! The exact same logic applies here as in the first mistake, only on the piecewise branch: presence lives on the testable side, while the strict side only knows how to forbid. Strictly piecewise languages also have their own defining family property: if a sentence is in the language, we are free to cross out any words from it anywhere we like, and the remaining stub must stay in the language (after all, deleting words cannot create a new forbidden subsequence!). Our gap language breaks this rule right away on a two-word example: the sequence "determiner - noun" is in the language, but if you cross out the noun, you are left with a lone "determiner", which is no longer in the language. Therefore, the gap language is not strictly piecewise for any subsequence length. What is strictly piecewise of length two is, once again, its complement: "nowhere after a determiner does a noun appear" - a single forbidden scattered pair.
On the other hand, our gap language ("somewhere a determiner, and later a noun") is not locally testable for any sliding-window width! Why? Because no matter how wide a window you pick - whether five words or a hundred - we can always push the determiner and the noun apart with such a long cushion of adjectives that the two will never fall into the window together.
The exact family of witness strings for any window width works like this. We take three key words - one "determiner" and two "nouns" - and insert cushions made of the "adjective" class between them, as well as at the very end. Each cushion consists of a run of adjectives whose length equals the exact width of our window.
- In the first sentence, the key words come in this order: noun, then (after a cushion of adjectives) determiner, then (after a cushion) noun, and at the end a closing cushion of adjectives. Here the determiner comes before the second noun - so the sentence is in our language.
- In the second sentence, the key words are rearranged: first a noun, then (after a cushion) another noun, and only then (after a cushion) the determiner followed by the closing cushion of adjectives. Here there are no nouns left after the determiner - so the sentence is not in the language.
Now, what will the sliding window of a locally testable machine see as it scans across these two long sentences? Because there is a buffer of adjectives as wide as the window itself between any two key words, the window can never cover two key words at once! At any position, the window sees either pure adjectives, or a single key word (a determiner or a noun) flanked on both sides by adjectives. The beginning and the end of both sentences (up to one word short of the window width) are also identical: both start with a noun followed by a buffer of adjectives, and both end with a pure buffer of adjectives. As a result, the set of all contiguous chunks that the sliding window can spot is completely identical for both sentences (this has been proven mathematically and verified by computer for window widths from one to eight words). A local machine simply cannot tell them apart!
Let us verify this by eye with the smallest possible window of two words. Suppose our noun is "cats", our determiner is "this", and our buffer of two adjectives in a row is "big old". Then the first sentence looks like this: "cats big old this big old cats big old", and the second looks like this: "cats big old cats big old this big old". Slide a two-word frame across the first sentence from start to finish and write down every pair you see: "cats big", "big old", "old this", "this big", "old cats". Now slide the same frame across the second sentence - you will write down the exact same list of five pairs, with not a single new pair and not a single one missing, even though the first sentence has a determiner before a noun and the second one does not.
So never write in your thesis: "we allowed skipping extra words and thereby moved from the strictly local class to the piecewise testable class". That statement is wrong twice over: it tries to tell the language class from the look of your code change, and it assumes a single ladder of classes that does not exist in nature. Worse still, if you mix conditions on contiguous chunks with conditions on scattered words inside the same detector, your resulting language may fall out of both the locally testable and the piecewise testable classes altogether!
How should you write this up in your thesis so that it counts as a genuine, indisputable scientific contribution? You take the specific language of a single rule before you expand it, and the language of the same rule after you expand it. For instance, at first your rule looked for a contiguous faulty pair right next to each other (and its language of sentences containing the error was locally testable with a window of two), and then you allowed an arbitrary gap between the words (and the language became piecewise testable of length two). You rigorously prove membership in these classes - either using the algebra described below or with dedicated software. And then you run both versions on a text corpus and measure the cost of this shift in the number of false alarms (since a rule with an unbounded gap will inevitably start snaring unrelated words from opposite ends of a long sentence).
That gives your thesis a rock-solid, testable claim: "the language of such-and-such rule was locally testable with a window of two, became piecewise testable of length two, and the cost of this transition on such-and-such dataset was so many false alarms". That is the line separating serious research from a plain report saying you added word-skipping to a template.
Look at a completely grammatical sentence to see where this cost comes from. Suppose a rule looks for the singular determiner "this" followed by a plural noun. As long as the window was narrow, it caught the actual error "this books" and left long, grammatical sentences alone. The moment you allow an arbitrary gap, the machine reads the flawless sentence "This boy loves old books", sees the tag "this" right at the start, remembers it, tunes out the next three words, and triggers a false alarm on the final word "books", because it mistakes the object at the end of the clause for a noun belonging to the opening determiner.
Let us talk separately about tier-based strictly local languages. Originally, this class was invented for the sound patterns of language (phonology), where consonants or vowels affect each other at a distance while ignoring the sounds in between. Our grammatical agreement across intervening words (for example, subject-verb agreement in "The cats on the mat sleeps", where the prepositional phrase "on the mat" wedges itself between the plural noun "cats" and the faulty singular verb "sleeps") is built the exact same way structurally. The machine simply fails to project the preposition, article, and noun of the prepositional phrase onto the main tier; only the subject and the predicate make it onto the tier, where they stand right next to each other, and a narrow two-word window catches the error right away.
But be sure to state honestly in your thesis that applying this tier-based class to sentence syntax is your own adaptation of the model, not what the authors originally designed it for in their paper. And state out loud the main condition under which this transfer works, because in real English it is far from always met! A tier-based machine works only when all of the inserted material is completely irrelevant to our rule and does not get projected onto the tier at all.
What happens if a relative clause with its own subject and its own predicate is inserted between our subject and predicate? For example: "The cats that the boy loves sleep". For a tier that selects nouns and verbs, the words "boy" and "loves" are not irrelevant - they are candidates of the very same class! They will all leak onto the tier, line up there in the sequence "first noun - second noun - second verb - first verb", block the outer words from seeing each other, and a simple sliding window on the tier will break down.
Moreover, if such a Russian doll of nested relative clauses has no limit on its depth, the language can fall not only out of the tier-based class, but out of the regular languages altogether! This happens under one clear condition (which you also need to state): when we require each verb to agree strictly with its own noun in order of nesting (the first with the last, the second with the second-to-last, and so on), and the agreement feature has at least two distinct values (such as singular and plural). A finite automaton simply does not have enough memory to count the depth of an endlessly nested Russian doll like that. If, on the other hand, the rule is simpler and only checks that words belong to a finite list of classes without trying to pair up each nested subject with its distant verb, then the nesting pattern by itself does not make the language non-regular - it stays completely regular. Therefore, in your thesis you must state clearly which specific parts of speech and insertions your model treats as invisible, and test on real texts how often that assumption breaks down.
How do scientists know for sure which exact class a language belongs to without reading tea leaves? There are precise algebraic theorems for this. Here is how they work. From any deterministic automaton, you can build a kind of algebraic passport for the language - a finite multiplication table showing how different pieces of text move the states of the automaton into one another. If we only take non-empty pieces of text, this table is called the syntactic semigroup of the language; if we also add the empty step (which changes nothing, like multiplying by one in arithmetic), the table is called the syntactic monoid. By looking into this multiplication table, you can give the language an exact diagnosis:
Here is what a single entry of this table looks like on a tiny automaton with three states: the first (waiting for an error to start), the second (we saw the dangerous determiner "this"), and the third (we caught the error and hit the red button). Any piece of text for such an automaton is simply a transfer rule from each state to some other state: for example, the arrival of the plural noun "cats" leaves the first state as the first, leaves the third as the third, and moves the second into the third. If another word of the same kind comes after "cats", nothing in the transition table will shift any further: from the first state we still land in the first, and from the second and third we land in the third. This means that for the language's passport, a single tag "cats" and a chain of "cats" plus "cats" are the exact same action, and the entire infinite mass of English phrases collapses into a finite number of such standard transfers.
- Star-free languages. A language falls into this class if and only if its syntactic monoid is finite and contains no nontrivial closed subgroup cycles (scientists call this property aperiodicity; you must never leave out the word "finite" in this statement!). Schützenberger discovered this connection to the multiplication table, and later McNaughton and Papert proved that these exact same languages are precisely those described by first-order logic formulas with the "one word comes before another word" relation. That is why the full four-part statement is properly called the Schützenberger-McNaughton-Papert theorem, and you should not attribute it to the first author alone. How hard is it for a computer to check this aperiodicity? Even if the input is already a ready-made deterministic automaton, the problem is very hard (it is PSPACE-complete; so in your thesis, always specify which exact automaton model is given as input, otherwise your complexity estimate will sound milder than it really is).
Look at a live example with the double negative error in the sentence "I do not see nothing". If you check this rule with an automaton, the machine reads from left to right: on the word "not" it moves into the "saw a negation" state, on the word "see" it stays there, and on the word "nothing" it falls into an error trap with no way back - there is not a single closed loop in the transition table. And in the language of first-order logic, this exact same rule is written as one transparent requirement: there exist two positions in the sentence, the first comes strictly before the second, and both positions hold words from the negation class.
- Piecewise testable languages. A language is piecewise testable if and only if its syntactic monoid is finite and has a special property of having no symmetric loops (in algebra, this is called being J-trivial, after Green's relations). Now, as for how hard it is for a computer to check this property from an automaton - people often get confused here, because there are actually four completely different questions hidden inside! First, we can ask: "is the language piecewise testable at all, for some chain length?" or "is it piecewise testable for this specific given chain length?". Second, we can feed the checking algorithm either a deterministic automaton or a nondeterministic automaton. Take note: all the complexity bounds below only hold when the language is given specifically as an automaton, and not, say, as a regular expression!
Let us look at all four cells of this complexity table. If we ask "is the language piecewise testable at all?", then for a deterministic automaton the problem is easy to solve (in nondeterministic logarithmic space, NL), whereas for a nondeterministic automaton it becomes super-hard again and requires polynomial space, PSPACE (by the way, take this fact from the summary table inside the body of Masopust's paper, because the author did not include that sentence in the abstract).
If instead we ask about a specific given length of scattered chains, the picture gets even more interesting. For a nondeterministic automaton as input, the problem remains intractable even over a single-letter alphabet, and for any fixed or arbitrary alphabet it requires that same polynomial space (PSPACE). And what about a deterministic automaton as input for a specific chain length? If we allow the alphabet to grow without bound along with the problem size, then for chains of length one the check is very easy (in deterministic logarithmic space, L), for lengths two and three it is slightly harder (in nondeterministic logarithmic space, NL), and starting from length four and above the problem suddenly becomes intractable (it jumps into coNP-complete; this subtle result was proved by Klíma, Kunc, and Polák in a paper that circulated as a manuscript for a long time, and do not confuse them with the authors of survey papers!).
However, for our thesis, the biggest and best news lies in the reason behind this hardness. The proof of high complexity for length four and above requires an infinite, growing alphabet! You and I, on the other hand, have chosen and fixed our alphabet of grammatical word classes in advance. And as soon as the alphabet is fixed, in the cell "deterministic automaton as input, fixed alphabet", checking piecewise testability for any specific chain length runs in moderate (polynomial) time! In other words, all that scary brute-force complexity does not apply to our rule classification task at all.
Let us do a quick headcount to see why that scary jump in complexity for chains of length four does not affect us. Imagine we are checking a rule for a scattered chain of four tags - say, for tense disagreement in the sentence "Yesterday he says that she will come". If our tag alphabet were fixed at just ten grammatical classes, there would be ровно ten thousand different four-tuples of such tags, and for a deterministic automaton a computer would check all of them in a fraction of a second. The brute-force abyss only opens up in the theoretical problem where, as the automaton grows, you are allowed to endlessly add new tags to the alphabet - a hundred, a thousand, a million - which causes the number of possible four-tuples to explode.
- Locally testable languages. McNaughton and Papert introduced this concept and immediately posed the question: how do you recognize such a language from its automaton? Several researchers independently found the exact algebraic recipe (Zalcstein, Brzozowski and Simon, and McNaughton himself), and it was later proved that, given a ready deterministic automaton, a computer can check membership in this class quickly, in moderate polynomial time.
However, a very common trap awaits you here - a mistake people make even in published papers. The algebraic condition for locally testable languages is stated only on the syntactic semigroup (that multiplication table without the empty step - it must have the properties of local idempotency and commutativity). It is impossible in principle to state an exact condition for this class using the syntactic monoid (the table that includes the identity element from the empty step)! And this is not because researchers overlooked something, but because of how the class itself is built.
You can see this from a short example that is easy to check on a computer. Take two languages:
- The first language lives over a single-letter alphabet "a" and consists of just one single-letter word, "a". As we already know, a language consisting of a single fixed word is strictly local with a window of size two (which means it is also locally testable).
- The second language lives over a two-letter alphabet, "a" and "b". It allows words that contain exactly one letter "a", with any number of letters "b" to the left and right of it (zero, or a hundred, it does not matter). This language is not locally testable for any window width! After all, if the window width is, say, five, then two long words - one with a single letter "a" flanked by five "b"s on each side, and another with two "a"s separated and flanked by the same groups of five "b"s - have the exact same set of contiguous chunks up to length five, and the same prefixes and suffixes of length four (verified up to width five inclusive). The first word is in the language and the second is not, yet a sliding window cannot tell them apart.
And now for the trick: if we build the syntactic monoids (the multiplication tables with the empty word as the identity) for the first and second languages, these tables turn out to be completely identical, like twin brothers! Both tables will have just three elements: the identity, the element from the letter "a", and zero (where everything with two "a"s collapses, because repeating the letter "a" squared gives zero). The whole difference between the languages was the letter "b", but in the second language, inserting "b" has no effect at all on the presence of "a", so in the multiplication table the letter "b" merges with the empty word and turns into that very same identity element! As a result, the monoids of the two languages are indistinguishable, even though one language is locally testable and the other is not. This means no rule that looks only at the monoid can ever separate them. Never write in your thesis that local testability is equivalent to a condition on the syntactic monoid!
For the strict classes (strictly local and strictly piecewise), the exact verification speed has also been calculated, and the most recent bounds were recently compiled in a paper by Lambert. It shows that checking strictly piecewise languages takes linear time (growing in direct proportion to the input size), while checking strictly local ones takes fifth-degree polynomial time (the input size multiplied by itself five times, because the algebraic condition being checked ties together five variables). However, you can copy these bounds into your thesis only with two mandatory caveats! First, the input size there is not the number of states in your automaton, but the size of a special algebraic structure of the language (the syntactic semigroup equipped with a union operation).
Second, the algorithm there takes this structure ready-made as its input, whereas extracting it from an ordinary deterministic automaton requires the computer to do separate heavy work first. If you measure complexity directly from the input deterministic automaton, that same paper lists very different bounds: on a trimmed canonical automaton the procedure grows like an avalanche (exponentially), if the graph of all state subsets is precomputed it runs in linear time, and the classical bound in terms of the number of automaton states gives quadratic time (the size of the automaton multiplied by itself). So here is the golden rule: whenever you quote any speed bound, state clearly up front what exactly is being fed to the algorithm as input!
Feel the difference in concrete numbers for a single small rule. Suppose your deterministic automaton that catches the error "a cats" has only four states. If you measure classical complexity directly by the number of states in the automaton, the quadratic bound gives about sixteen steps of work. But if the algorithm requires a ready-made algebraic structure as input and spends fifth-power time on it, and this multiplication table happens to contain, say, ten elements, then multiplying ten by itself five times is already a hundred thousand operations - not counting the heavy preliminary work of assembling the table itself from the four states.
The good news is that you will not have to code all this algebra by hand. There is a free, ready-made toolkit with an interpreter (we will name it in the glossary at the end) where you simply feed in the description of your automaton, and it builds the semigroup on its own and outputs a verdict on which classes of our hierarchy the language belongs to. Just one important practical warning: because the program builds that semigroup multiplication table under the hood, never feed it one giant combined automaton glued together from all one hundred and eighty-two of your rules over a large alphabet! The multiplication table will blow up to such a size that the computer will simply freeze, running out of time and memory. Feed the rules for classification strictly one pattern at a time.
Now for what a survey of the research literature gives you for your background chapter. When we searched for papers across four independent directions, we could not find a single research paper where the classes of our subregular hierarchy met learner corpora or the task of automatic grammatical error detection. This is your goldmine and an unclaimed research niche.
But you need to phrase this in your thesis very carefully: frame it as an honest report of what your search turned up, not a bold claim of absolute world priority! Using the word "first" in serious science demands a strictly documented protocol: you would have to provide a full list of bibliographic databases, your exact search query strings, the exact dates of your searches, and strict inclusion criteria for the papers you selected. You really should put such a protocol together anyway (it will come in handy for your literature review chapter), but until you have it, stick to a calm, bulletproof wording in your thesis: "in the publications we reviewed, no direct overlap between these two lines of work was found". Use those exact words! Do not write "these two bodies of literature do not cite each other" - to make that claim, you would have to comb through every cross-reference list in the world, and we have not done that. Careful phrasing does not take anything away from the value of your finding, and it completely shields you during your defense against a trick question that is impossible to answer.
And when you stake out this open niche, be sure to play fair and credit your main intellectual predecessor for the automaton technique itself. More than twenty years ago, Sofkova Hashemi published a paper on detecting grammatical errors in children's writing using finite automata. The names of our subregular classes had not been coined yet, but the engineering idea was the exact same one: they wrote the grammar using only positive rules, built two automata of different strictness (one broad and permissive, the other narrow and strict), and found errors in the text by subtracting one automaton from the other. You should cite this paper first.
And finally, one last question: what if we do not want to write all the rules by hand, and instead want the computer to learn the rule automata straight from a text corpus? Our hierarchy has a strict mathematical path paved for this too! It has been proven that strictly local and strictly piecewise languages with a window width or subsequence length fixed in advance, as well as tier-based strictly local languages with a two-word window, can be learned automatically from positive examples alone (that is, by reading only grammatical texts!). For your error detection task this is hugely important, because there are millions of correct English texts around, whereas annotated learner corpora with errors are always in painfully short supply.
Let us see how a machine learns a strictly local rule with a two-word window on its own from correct texts. Suppose it is fed the grammatically clean sentences "I see a cat", "She took an apple", and "They bought the cats". The algorithm chops them into pairs of adjacent tags and stores them in memory as allowed transitions: the class "article a" before the class "singular noun", the class "article an" before the class "word starting with a vowel", the class "article the" before the class "plural noun". Because an error like "a cats" will never show up in correct texts, the pair combining the class "article a" with the class "plural noun" will never make it into the allowed list - and on its very first test run, the resulting automaton will reject the sentence "I see a cats", even though it never saw a single error during training.
But if you write about this in your thesis, keep your phrasing crystal clear on two points, or you will accidentally promise the committee more than the theorem guarantees:
- First, the word "learnable" here means what is called identification in the limit. Here is what that means: the algorithm processes each individual new example quickly (in reasonable polynomial time), and if the stream of grammatical sentences is thorough enough, sooner or later the algorithm's hypothesis will converge to the right grammar and stop changing. But this theorem does not promise fast probabilistic learning from a small sample, and it gives no estimate whatsoever of how many thousands of sentences you will have to feed the machine before it sees all the combinations it needs and stabilizes.
- Second, the condition that the window width (or the maximum length of a scattered subsequence) is strictly fixed in advance is vital here. If you do not cap the window width up front and try to learn "a strictly local language for just any window width", the union of all such languages across all possible window widths forms an overly rich, so-called superfinite family (it contains every possible finite list of words plus at least one infinite language). And by Gold's famous fundamental theorem, no superfinite family of languages can be identified in the limit from positive examples alone - the machine will never know whether it is time to stop or whether even longer dependencies are still waiting ahead! This means you must choose and declare your window width (say, two or three words) in advance, before training begins. In your thesis, this is a deliberate architectural decision, not a minor detail of your code.
Let us test this trap on a concrete example with window width. Suppose we did not fix the window in advance, and fed the algorithm a thousand correct sentences that included "I see a cat" and "I see a big cat", but never once included the long sequence "a very old lazy cat". If the machine decides that the language is finite and consists of that exact thousand sentences it saw, it will be wrong and will reject any new grammatical sentence. And if it starts guessing the window width on the fly - two words, three words, five words - it will never know whether a five-word sequence is missing because the grammar forbids it, or simply because it has not shown up in the corpus yet.
8. How to look ahead in the text without losing track of what came before
When you write rules for detecting grammatical errors, you constantly want to peek at neighboring words without moving the cursor. For example, suppose you are looking for the ungrammatical phrase "I saw a apple". You need to catch the article "a", but only if it is immediately followed by a word starting with a vowel letter. In regular expressions, checking the neighbor to the right without consuming the word itself is called lookahead. It can be positive - when we require something specific to be on the right - or negative - when we require something specific not to be on the right.
An ordinary automaton reads text strictly from left to right, word by word, and never goes back. Yet here we need to stop in the middle of a phrase, let our eyes dart ahead, check a condition, and then return to where we were and keep reading. It feels as if this breaks the very nature of finite automata. But the key fact for your theory chapter is this: lookahead does not take us outside the class of regular languages. The language stays regular, which means that for any such rule, you can still build an ordinary finite automaton.
Let's test the phrase "I saw a apple" to see how an ordinary finite automaton gets by without moving backward. The machine moves from left to right: it reads "I", it reads "saw", and when it sees the label "article a", it simply moves into a special waiting state and remembers both requirements at once - that the article has already been caught and that the next word must be a word starting with a vowel. At the next step, the word "apple" arrives with the label "word starting with a vowel", both conditions are met on the very same transition, and the automaton immediately turns on the error signal without ever moving the cursor back.
But at what cost? At a thesis defense, it is very easy to scare the committee here if you lump all the estimates of automaton size together. The secret is that the price depends on the design of the machine you translate your rule into. That is why you must always state the size together with the model of the automaton.
Let's look at three kinds of machines to see how they handle lookahead and how much memory they ask for in return:
- The first model can split in two with the requirement "let both branches succeed at once". Imagine that the machine is reading the phrase "I saw a apple", reaches the article "a", and sends a scout ahead. The main branch continues parsing the text according to the main rule, while in parallel the scout checks the lookahead condition - whether a word starting with a vowel really comes next. For the rule to fire, both checks must succeed at the same time. If the lookahead is negative, the machine requires the scout to fail instead. In other words, at branching points this machine can apply the ordinary logical connectives "and", "or", and "not". In theory, such a mechanism is called a Boolean or alternating finite automaton. Translating a rule with lookahead into such a machine costs almost nothing: it will have no more states than the length of your rule plus three. If your expression has five steps, the machine will have at most eight states; if it has ten steps - thirteen states. This is a very modest, linear growth.
- The second model is our familiar branching, or nondeterministic, finite automaton. It can only guess one successful path out of several - that is, it works on the "or" principle, and is not allowed to demand "let both branches succeed at once". To teach it to do the job of a Boolean automaton, we have to create separate states for combinations of parallel checks. Removing this alternation - moving from logical "and" to pure "or" - causes an avalanche-like, exponential growth in the number of states. At each new step of the expression, the number of possible combinations for the scouts can double. In research papers, this avalanche is not even singled out as a special result for lookahead - it is the standard general price for turning any Boolean automaton into a simply branching one.
- The third model is the unambiguous, or deterministic, finite automaton, where at each step ровно one transition is allowed and there are no forks at all. To build such a machine for a rule with lookahead, we first have to turn the Boolean automaton into a branching one, and then make that branching automaton unambiguous. And as you already remember, an unambiguous machine must remember all the guesses of the branching one at once within a single state of its own. You get an avalanche on top of an avalanche - in mathematics this is called double exponential growth. The upper bound on the number of states here is such that the number of possibilities doubles as many times as the number of states that already piled up in the first avalanche, plus one more state. From below, this growth is also hemmed in by a double avalanche, even if a slightly gentler one. Let's look at real numbers to see what this upper bound looks like: for a tiny rule of length three, an unambiguous machine can end up with up to two hundred and fifty-seven states. Add just one step to the rule, bringing it to length four - and the ceiling shoots up to sixty-five thousand five hundred and thirty-seven states!
Here is what this looks like in a simple state count when translating from a Boolean automaton into a branching one. Suppose the scout running ahead from the article "a" in search of the word "apple" faces a condition of just three steps. In a Boolean automaton, six states would easily be enough for these three steps, because the branches work in parallel. But a branching automaton is forced to merge parallel checks into a single thread: for the scout's first step it needs to remember two options (success or failure), for two steps - already four combinations, for three - eight, and if the rule grows to ten steps, the number of states just for the scout's combinations will pass a thousand.
All of these estimates have strict boundaries that need to be stated out loud.
First, this works only when the regular expressions have no backreferences. A backreference is the ability of an expression to remember a piece of text and then demand the exact same piece a bit further on. For example, this is how you catch an accidental word repetition in the phrase "I saw the the cat": the rule remembers the first word "the" and looks for a copy of it right after. Now, if you add lookahead to regular expressions that have backreferences, their expressive power actually increases. This is the exact opposite result, and the dividing line here is precisely the presence of backreferences.
Second, all the estimates mentioned above are proved only for lookahead. They do not carry over to lookbehind. In real software engines, the behavior and complexity of lookbehind depend on how the program is actually written: in what order it matches characters and whether it requires you to fix the width of the backward step in advance. If you use lookbehind in an existing engine, in your thesis you need to cite the documentation and architecture of that engine, not theorems about lookahead.
Look at the phrase "this big old house", where two adjectives at once have wedged themselves between the determiner "this" and the noun "house". If you want to check for a determiner on the left using lookbehind, one software engine will require you to hard-code the width of the step in letters or words in advance, and on a phrase with three or four adjectives such a rule will simply break. Another engine will allow a step of unlimited length, but at every noun it meets it will rewind the text tape to the left all the way back to the beginning of the sentence, causing the time needed to check a long paragraph to jump sharply.
But here is the most interesting part. For a typical grammar task like "check that there is no determiner to the left of the noun", no lookbehind is needed in theory at all! This language remains regular even without any limit on how far to the left the determiner might have stood (in grammar, that is the term for articles and demonstrative words like "a", "the", "this").
What does a machine need to do for such a check? Simply read the sentence from left to right and remember ровно one thing: whether it has already seen a determiner or not. For this, a tiny unambiguous automaton with one bit of memory - "haven't seen one" and "have already seen one" - is enough. This is ordinary concatenation of languages and taking the complement, which we talked about in section two.
Yet right here, a dangerous confusion of concepts awaits rule authors. Listen closely to two sentences that look identical at first glance:
- "The sentence contains a noun with no determiner to the left of it".
- "It is not true that a determiner appears somewhere to the left of a noun in the sentence".
These are two completely different languages! The first wording is positional negation tied to one specific word: we point our finger at a noun and check the entire text to the left of it. The second wording negates the whole sentence at once: we take the language of all sentences that contain at least one "determiner followed somewhere by a noun" pair, and we flip the automaton's answer.
To see the difference in action, let us take a short phrase with an error right at the start: "Boy saw a cat". Someone forgot to put an article before the word "Boy", whereas before the word "cat" the article "a" is right where it belongs. For clarity, let us keep only the word classes we care about: the word "Boy" has the class "noun", we skip the verb "saw", the word "a" has the class "determiner", and the word "cat" again has the class "noun". That gives us a string of three tags: "noun", then "determiner", then "noun". Let us run this string through both of our machines:
- The first machine looks for at least one bare noun. It starts in the state "no determiner seen yet". On the very first step, it receives the word "Boy" - class "noun". The machine checks its memory: no determiner has appeared so far! The condition is met right away. The machine moves to an accepting state, and anything at all can follow - articles, verbs, whatever. The first machine accepts our sentence and quite rightly raises an alarm.
- The second machine first tries to find a place in the sentence where a determiner stands to the left of a noun, so that it can then say "no". It reads the first word, "Boy" - not a determiner, keep waiting. It reads the word "a" - class "determiner", great, remember that! It reads the word "cat" - class "noun", coming after the determiner "a". So the sentence does contain a valid pair, "a cat"! And since such a pair was found in the sentence, the statement "it is not true that a determiner stands to the left of a noun" becomes false. The second machine rejects our string and misses the error in the word "Boy".
See how easy it is to slip up? On the very same short phrase, "Boy saw a cat", the first rule caught the error while the second stayed silent. If you have a computer check all strings of length up to five built from three different word classes, it will find a hundred and thirteen such distinguishing strings right away! These two rules produce different automata and completely different false alarms. That is why, before you build an automaton, you must state clearly in your thesis which of the two meanings your rule actually encodes.
9. Automata that rewrite text, and finding errors by subtracting grammars
All the machines we have talked about so far worked like strict gatekeepers: they read a string of words and simply lit up a bulb at the end - "yes, accepted" or "no, rejected". But a finite automaton can be taught to do more. Picture a machine with two tapes: it reads the input text from one tape and immediately prints modified output text onto the other. At each step, its instruction does not just say "read this letter", it says "read this letter, and print that one in return". Such a machine is called a finite-state transducer, and the correspondence between all the input and output strings it can translate into one another is called a regular relation.
The main advantage of such transducers is that you can snap them together into a chain, one after another, like building blocks. The output of the first transducer is fed straight into the input of the second, the output of the second into the third. And this entire long pipeline can be mathematically fused into a single final transducer! In theory, this property is called closure under composition.
Let us test this on a live example with the verb "try", to which we want to attach the tag "third-person singular". In our pipeline, the first transducer only handles spelling alternations at the end of the stem: it copies "t" and "r", and changes the letter "y" before the tag into the two letters "ie", producing the intermediate string "trie" with the "third person" tag still attached at the end. The second transducer takes this string, copies the letters "t", "r", "i", "e", and replaces the tag itself with the ending "s", yielding the final word "tries". A single transducer fused from the two will do this entire job in one pass without any intermediate tape: it will read "t", "r", and upon seeing the pair consisting of the letter "y" and the "third person" tag, it will immediately print "ies" to the output.
Where might this be useful in your project? Suppose your detector catches a common mistake in English - dropping the verb ending in the third-person singular, as in the incorrect phrase "He walk every day" instead of "He walks every day". To make the program know all valid verb forms, you could, of course, load a huge dictionary list of tens of thousands of words into it. Or you can do something more elegant and state the rules for building these forms with one small finite-state transducer (this is one possible approach, though not the only one).
Let us trace step by step how such a transducer turns the base form of a verb into the third-person form:
- Feed it the stem "walk" followed by a special service tag, "third-person singular". The machine reads the first letter "w" and prints "w" to the output. It reads "a" - prints "a". Reads "l" - prints "l". Reads "k" - prints "k". And on the last step, it sees the service tag "third person", consumes it, and prints the letter "s" to the output instead. On the output tape, we get the finished word "walks".
- Now let us feed the same transducer the stem "go" with the same "third person" tag. The machine copies the letter "g", then reads the letter "o", copies it to the output, but at the same time moves into a special state: "the word ended in a sibilant or the letter o". From this state, when it sees the "third person" tag, the machine prints two letters to the output instead - "es". The output is the valid form "goes".
If you were doing the practical part of your thesis using specialized software packages for finite automata and transducers, you would meet another neat trick there. In those ready-made tools, the operations of language complement and the difference of two languages are available as a single built-in command.
Because of this, people using these tools often catch grammatical errors not by writing a trap for a specific mistake, but by subtracting one positive grammar from another. Here is how it works. First, you describe a broad language: "all phrases where a pronoun is followed by a verb in any form". This includes both the correct "He walks" and the erroneous "He walk". Next, you describe a second, strict language: "all phrases where the subject and verb properly agree in number and person". This language contains "He walks", but not "He walk". After that, you give the tool a single command: subtract the strict language from the broad language. Everything correct cancels out, and what remains after subtraction are purely the grammatical errors - including our "He walk"!
Here, however, it is crucial not to confuse human convenience with computer work. Saying that "set difference is a single built-in operation" means only one thing: the tool's developers have already written this function and given you a handy button. It does not mean the operation is computationally free! To subtract one language from another, the program still has to take the complement of the second language internally, and to do that, it must convert a branching, nondeterministic automaton into a deterministic one. The computer will pay that entire explosive price in the number of states - which we discussed in detail in point two - in full. It will just do so silently, behind the scenes.
Let's put actual numbers to what this subtraction costs. Suppose your strict grammar for proper agreement is written as a nondeterministic automaton with just twenty states, where transitions overlap for safety. When you press the subtraction button, the program behind the scenes first builds a deterministic automaton for this second language. In the worst case, instead of twenty states, over a million states appear in the computer's memory. For your fingers, it was a single line of code, while at that very moment RAM is filling up with a gigantic transition table.
Our own educational matcher does not have a built-in language subtraction operation; we build our rules directly. So all of point nine is optional for your thesis: it simply shows the committee that you know about a major neighboring highway in computational linguistics, even if you took a different road yourself.
Level 3. Name and cite, no proof required
10. Stack memory and nested constructions. An ordinary finite automaton only remembers the state it is in right now. It has no scratchpad to write down long counts; its memory is strictly limited by the number of states. Yet natural language has constructions nested inside one another like Russian nesting dolls. To parse them, a machine needs extra memory arranged like a stack of plates on a table: you can only put a new plate on the very top, and you can only take the top plate off. In theory, this kind of memory is called a stack (or pushdown store), and a machine equipped with it is called a pushdown automaton. The languages it can parse are defined by what are called context-free grammars.
Let's see how this machine works on an English sentence with nested relative clauses: "The cat that the dog that the man bought chased ran". The machine needs to check whether every subject got its own verb. It reads the text from left to right, and whenever it sees a new subject, it pushes it onto the stack: first "cat" goes to the bottom, "dog" goes on top of it, and "man" goes to the very top. Then come the verbs. At each verb, the machine pops the top word off the stack and checks if they go together. The verb "bought" arrives - the machine pops the top word "man" (the man bought). The verb "chased" arrives - the machine pops the next word "dog" (the dog chased). The verb "ran" arrives - "cat" leaves the bottom of the stack (the cat ran).
The sentence is over and the stack is empty - which means everything agrees properly. If the author had mistakenly written "The cat that the dog chased", the verbs would run out after "chased", leaving a lonely "cat" sitting at the bottom of the stack without an action. That is how the machine catches the error. With deep nesting, an ordinary finite automaton will simply lose count because it runs out of states.
In your thesis, you need all this theory for just one sentence: "this requires stack memory". You are not required to prove anything, but you must phrase your thought very carefully. If you find that a construction is too complex for a finite automaton (meaning the language is non-regular), only one thing follows: an ordinary finite automaton is not enough here. Claiming that a pushdown automaton *is* enough for the task is a separate, independent statement. You cannot present it as an automatic consequence of the simple automaton failing, because there are tasks where even a single stack cannot save you.
Look at a live example where even stack memory gives up. Suppose we are checking whether a long chunk of text is repeated word for word, as in the accidental duplication "the black cat ran away the black cat ran away". To check the first half against the second in the same order, the machine needs to pull words from the bottom of its memory: first "the", then "black", then "cat". But a stack only gives back whatever is on the very top - the last word pushed was "away", so it will be the first to come out, and the comparison with the start of the second half will fail immediately.
11. Four different "impossibles" and a ban on the word "undecidable". A Turing machine is an imaginary computer with an infinite tape of memory that can compute anything that can be solved by an algorithm at all. High theory is built around it: classes of problems that such a computer always solves, classes of problems where it might hang forever on invalid input, and Rice's theorem on why one program cannot figure out an arbitrary property of another program. None of this heavy artillery is used in your thesis at all.
Look at any phrase from your dataset, such as the erroneous sentence "She have two cats". It has only four words and twenty letters, it is strictly finite, and your automaton reads it strictly from left to right without backtracking: it sees the tag "third-person singular pronoun", moves to a state waiting for a matching verb, hits the verb "have", and immediately raises an alarm. The machine is guaranteed to reach the period in four steps and halt; it has nowhere to get stuck in an infinite loop and no reason to ask for an infinite memory tape.
However, there is one strict request for you. Never write the word "undecidable" in your thesis when you mean "a finite automaton cannot handle this". For the professors and researchers who will read your thesis, that term has long been firmly reserved for a completely different concept. If you call an ordinary grammar check undecidable, they will read it as a blunder.
In our field, you need to clearly distinguish four different troubles and call them by four different names:
- a language is non-regular - the problem is fundamentally beyond a finite automaton because its memory structure is not enough;
- a property is inexpressible in the formalism - the rule cannot be written using the features of our specific pattern language;
- the cases are indistinguishable in the given input representation - we ourselves stripped away and lost the required feature while preparing the text, so the automaton sees two different phrases as completely identical;
- the problem is algorithmically undecidable - no decision algorithm exists for it in nature at all, not even for the most powerful computer with infinite memory (this is the territory of Rice's theorem).
In your work, you only need the first three concepts. The fourth has nothing whatsoever to do with finding errors in English text.
Let's test this on the trickiest task in your project - suppose we are checking nested agreement in the phrase "The book that the students read was interesting". Even if your finite automaton of five or ten states does not have enough memory to link the subject "book" with the distant verb "was", any ordinary algorithm with a stack memory can easily count three subjects and three verbs in a split second and give the exact answer. Since an algorithm for checking any text exists in nature and always halts with an answer, there is and can be no algorithmic undecidability here.
Let's look at the first three cases using real examples so you can feel the difference. First case: checking subject-verb agreement at any depth of nesting, as in the erroneous phrase "The boy who the girls who the teacher praise like smiles" (here the verb "praise" goes with the singular "the teacher", so it should be "praises"). As we saw in the previous section, you cannot do without a stack memory here, so this language is non-regular. Second case: suppose our rule language only lets us look at two adjacent words, and we want to catch a tautology - the repetition of the very same word within a whole paragraph. A finite automaton could actually remember this, but our notation for writing rules does not let us look that far ahead.
That means this property is not expressible in our formalism. Third case: before running the automaton, we replaced all the words simply with part-of-speech names without indicating number. Then the correct phrase "dogs bark" and the erroneous "dog bark" will turn into the exact same sequence of two tags for the machine: "noun" and "verb". For the automaton, these two cases have become indistinguishable on the given input. And not one of these three everyday difficulties can be called algorithmic undecidability!
Here is what this looks like on a concrete phrase: take the sentence with an unwanted repetition, "The interesting book was really interesting". A three-state automaton would catch it easily: on the first word "interesting", it would step from the start state into the state "already saw this adjective", ignore the words "book", "was", and "really" while staying in that same state, and on the second word "interesting", move into the error state. But if your pattern language can only check pairs of adjacent words, you will be able to write a ban on "interesting interesting" right next to each other, whereas across three words the pattern simply will not reach - the automaton itself can have that kind of memory, but your way of writing rules does not let you specify it.
12. Multi-pattern matching in a single pass and the Aho-Corasick algorithm. Imagine you have not just one rule for finding errors, but two hundred at once. Running the entire text two hundred times in a row against each rule one by one is slow and foolish. The Aho-Corasick algorithm solves this problem: it stitches all the patterns together into a single shared tree-automaton and searches for all of them at the same time in a single left-to-right pass through the text.
Let's test this on a tiny machine with two rules: the first catches the error "a cats", and the second catches the error "a dogs". Both patterns start with the class "article a", so in the shared tree-automaton they will share a single first step. When the phrase "I see a dogs" is fed in as input, the machine skips the first two words, takes one step forward on the word "a" along both rules at once, and on the word "dogs" picks the second branch and hits the red button. We read the four-word phrase just once and checked both patterns at the same time without ever going back to the beginning.
In their original paper, the authors of this algorithm evaluate its speed very carefully and divide the work into two stages. The first stage is building the automaton: the time it takes to assemble grows moderately, in direct proportion to the total length of all your patterns (add up the lengths of all the rules and you get the amount of work). The second stage is reading the text itself: the number of state-to-state transitions here is always strictly less than twice the length of the text. If the text has a hundred words, the automaton will make fewer than two hundred transitions; if a thousand words - fewer than two thousand. And most importantly: this number of transitions does not depend at all on how many patterns you compiled into it - whether ten or ten thousand! Textbooks often give a simplified summary: that the running time is proportional to the length of the text plus the number of matches. But in your thesis you must cite the exact breakdown given by the authors (preprocessing separately, number of transitions separately) and remember the authors' caveat: the actual seconds of runtime depend on how fast your program can execute a single transition inside a state.
Let's calculate this cost with concrete numbers. Suppose your set has ten short rules of three tag-steps each - their total length is thirty steps, and building the tree will take about thirty simple operations. If you write another hundred and eighty-two rules of the same length, the total sum will grow to five hundred and seventy-six steps, and the preprocessing build time will increase by that exact same factor, with no explosive growth at all.
In our project, one hundred and eighty-two rules check forty-nine thousand eight hundred and twenty-six texts in about three minutes on an ordinary machine. That gives around forty-seven thousand "rule-per-text" decisions per second. It sounds impressive, but you must never put those "three minutes" into your thesis on their own! Without details, that number means nothing. For a benchmark to become a scientific fact, four clarifications must stand right next to it:
- the total volume of all the texts in individual word tokens (after all, forty-nine thousand texts could be short notes of a hundred words each, or they could be articles of three thousand words each);
- whether those three minutes include the preliminary grammatical tagging of each word, or whether only the pure run of the automaton over ready-made tags was measured;
- the computer's hardware specifications and the number of parallel threads;
- which specific software matching engine was running under the hood.
We do not have those four pieces of information next to the number right now, so the benchmark either goes into the thesis with all four explanations, or it does not go in at all. Moreover, those three minutes are no proof at all of the power of the Aho-Corasick algorithm. If you divide forty-seven thousand decisions by one hundred and eighty-two rules, you get about two hundred and sixty texts per second. Even the most ordinary one-by-one rule pass can easily give you that kind of speed. The real value of Aho-Corasick is that the pass speed does not drop as the number of rules grows. And to prove that for your program, you need a separate experiment: measure the time on ten rules, then on a hundred, then on two hundred, and show that the pass time barely changed.
When you promise that speed does not depend on the number of rules, you must state two strict limits of the algorithm yourself, or else you will be promising too much.
First limit: Aho-Corasick can only search for a finite set of fixed strings. However, it is easy to overestimate this limit and get scared too soon. If your tagger gives each word in the text exactly one class tag, then these tags simply work like letters of an alphabet. Then a rule made of a fixed sequence of tags is just an ordinary fixed word for Aho-Corasick, and nothing needs to be changed. For example, say we are looking for article agreement errors in the phrase "I saw a big dogs yesterday". Suppose we have two patterns: a two-tag sequence "indefinite article - plural noun" (catches "a dogs") and a three-tag sequence "indefinite article - adjective - plural noun" (catches "a big dogs").
The total length of the patterns here is five tags. The tagger turns our six-word sentence into a sequence of six single tags. The Aho-Corasick automaton reads these six tags in a row, makes fewer than twelve transitions, and right on the word "dogs" happily reports that the second pattern has matched. But everything changes if a pattern stops being a fixed string! This happens when a single word in the text is assigned several possible tags at once (turning the input into a branching lattice of options), or when the rule itself contains complex conditions: an "either-or" choice, a negation ("any word except a verb"), a check for complex features, or a gap of arbitrary length ("skip a few arbitrary words").
Then you either have to expand the rule beforehand into a huge batch of simple fixed strings (and you must honestly calculate just how many strings it will blow up into), or build the combined automaton in a completely different way.
Let's do a quick count of how fast such a rule blows up. Suppose you want to catch an error like "a big old dogs" or "a really big dogs", and you allow anywhere from zero to three words between the indefinite article and the plural noun, each being either an adjective or an adverb. If you expand this condition into fixed strings for Aho-Corasick, a gap of zero words gives one string, one word in between gives two strings, two words give four, and three words give eight strings. One tiny rule with a choice and a short gap has turned into fifteen separate patterns with a total length of sixty-four tags. And if you put a negation like "any tag except a verb" into the gap, with a tagger alphabet of thirty tags, a gap of just three words will make a single rule explode into more than twenty-four thousand fixed strings.
Second limit: only the number of transition steps through the text is independent of the number of rules, not the total running time of the program! After all, when the automaton finds an error, it has to format it and add it to the output list. The more rules you load, the more errors they will find in the text, and the more time will be spent simply outputting the matches. That is why you should promise independence from the number of rules only for the text scan itself, not for the entire run. The full complexity bound, which is what you should write in your thesis, is made up of three parts: the total length of all patterns (to build the automaton) plus the length of the text being checked (to step through it) plus the number of matches actually found (to output them). In our example with the phrase "I saw a big dogs yesterday", the total work consists of five steps to build the two patterns, no more than twelve steps across the six words of text, and one output operation for the found error "a big dogs".
But remember: this neat bound only holds when your program looks up the next transition instantly in a single operation and outputs matches using ready-made lists. If, at every word, your program searches for the right arrow by slowly scanning through all outgoing transitions from a state, the bound breaks down right away. Your main job at your defense is to state how the running time of your program grows as the number of rules grows, and to back this up with an actual benchmark rather than general talk.
Let's count the steps to see how it breaks down. Imagine your detector has loaded a thousand different error patterns that start with twenty-five different part-of-speech tags, so twenty-five arrows leave the start state of the automaton. If transitions are stored in a simple direct-lookup table indexed by the tag number, then on the first word of "I saw a big dogs yesterday" the program grabs the cell for the pronoun "I" right away in a single operation. But if outgoing transitions are stored as a simple list of "tag - next state" pairs, the program will have to scan this list in order at each of the six words in the sentence until it hits the right arrow. As a result, instead of six instant steps through the text, the machine will do up to a hundred and fifty checks, and the text scanning time will start growing along with the branching factor of your rule set.
13. Smart shifting without backtracking and the failure function. The direct ancestor and closest relative of the method we just covered is the Knuth-Morris-Pratt algorithm, which searches a text for a single pattern, but does so using the exact same core trick. This trick is called the failure function (or suffix links). The idea is simple: if we start matching a pattern against the text, read a few matching words, and stumble on the next word - we never need to rewind the text and start matching all over again from the next word. After all, we have already read a piece of the text, and it matched the beginning of our pattern, which means we know for sure what words were just there! Using this knowledge, we can lay down fallback arrows ahead of time; when a mismatch happens, they instantly jump us to the right spot in the pattern, while we keep reading the text strictly forward.
See how this fallback arrow is laid down ahead of time, before reading any text at all, on a four-tag pattern: "article a - singular noun - article a - plural noun". The third step of our pattern is the tag "article a" again, the exact same as the very first step. So from the third state we draw a fallback arrow back to the first state ahead of time: if at the fourth step the text has a valid singular noun instead of an erroneous plural one (say, in the phrase "a cat a dog"), the machine follows the failure arrow, instantly realizes that the piece "a dog" has already started with the article it just read, steps straight into the second state on the word "dog", and keeps reading the text strictly forward.
Let's look at how this machine thinks at a specific step. Suppose we are catching an agreement error in a noun chain, like in the incorrect phrase "stone wall collapse" (here the writer forgot to put the verb in the singular form "collapses"). Our pattern consists of three tags in a row: "singular noun - singular noun - plural verb". Now suppose the input is a slightly longer four-word phrase: "old stone wall collapse", where the tagger mistakenly marked the word "old" as a noun too. That gives us a text of four tags: "noun - noun - noun - plural verb".
How will a naive search behave? It will line the pattern up with the first word "old", successfully read two nouns ("old stone"), and wait for a verb in the third spot, only to see a third noun, "wall". Failure! The naive search will rewind the text back to the second word, "stone", and start trying the whole pattern over from the very beginning. Now how does a machine with a failure function work? When it reaches the third word "wall" and does not see the verb it wants, it looks at its emergency failure arrow. That arrow tells it the following. You just successfully read two nouns in a row, and now another noun has come in. That means the last two words ("stone wall") already make up the first two steps of your pattern! Do not dare go backward in the text. Just stay in the state where you are waiting for the third word, and keep reading. At the fourth step, the word "collapse" (a plural verb) comes in, and the machine records a hit right away. Not a single step backward in the text was ever taken.
To make this clear, let's count how many times each method checks tags on a slightly longer six-word phrase, "good old brick stone wall collapse", where the tagger marked the first five words as singular nouns and the last one as a plural verb. A naive search will try the pattern starting at the first word, stumble on the third ("brick"), rewind the text to the second word ("old"), stumble again on the fourth ("stone"), rewind to the third ("brick"), stumble on the fifth ("wall"), rewind to the fourth, and only on its fourth attempt reach the end - twelve checks in total on six words. A machine with a failure function will read each of the six words exactly once, hop three times along the emergency arrow back into the state waiting for the third word, and on the sixth step catch the error "stone wall collapse", taking just six text reads instead of twelve.
There is an instructive story from the history of computer science here that students often get tripped up on. People sometimes say: "Hold on, the Aho and Corasick paper came out in a journal in 1975, whereas the famous journal paper by Knuth, Morris, and Pratt only appeared in 1977! So Aho and Corasick invented it all earlier and could not possibly have built on their algorithm." That reasoning is dead wrong. If you simply open the Aho and Corasick paper itself and read the introduction, it says in plain English: "Our approach combines the ideas of the Knuth-Morris-Pratt algorithm with those of finite state machines." Their first algorithm is explicitly described as modeled after it, and the failure function is explained as a generalization of the shift table from that work.
How did the dates turn out that way? Very simply: Aho and Corasick cite a preliminary Stanford University technical report that Knuth, Morris, and Pratt put out back in 1974, a year before the Aho and Corasick paper. It just took another three years for that work to make it into a printed journal. The lesson for your thesis is ironclad: the priority of ideas in science is not determined by journal publication dates, and you have to actually open and read the papers you cite with your own eyes.
14. Tracking guesses in parallel with Thompson's construction versus catastrophic backtracking. When you write a rule as a regular expression or a branching automaton, it almost always has forks in it: the very same word in the text can take the machine down different paths. To run such a rule on a computer, programmers use one of two completely different engines: either a backtracking search, or Thompson's simulation. Anyone who writes regular expressions for an error detector has to know for sure which of these two engines is under the hood. Because on certain rules, the first engine falls into catastrophic backtracking and freezes your entire test bench solid on a single sentence.
Let's see how this disaster happens. Suppose you decide to catch an error in a chain of adjectives before a verb, and you carelessly write a rule with a nested repetition: "a group of one or more adjectives, repeated one or more times, followed by a verb". Now a normal phrase with no verb at the end comes into your program, say a description of a house: "a big old red brick house". Suppose the tagger marked the four words in the middle ("big old red brick") as adjectives, and the last word "house" as a noun.
What does a backtracking engine do? It works like a stubborn traveler in a maze who only walks down one path at a time. First it greedily grabs all four adjectives into one big group, steps forward to the last word "house", expects a verb there, and sees a noun instead. Dead end! So the machine backtracks through the text and says to itself: what if I split these four adjectives into two groups - first three together ("big old red"), and then one by itself ("brick") - maybe a verb will show up after that. It checks the word "house" again - and hits a dead end again! It backtracks once more and tries splitting the four words into two groups of two, then one group of two and two groups of one, and then four separate groups of one word each.
For four adjectives, there are eight of these pointless ways to slice them up. For ten adjectives, the number of combinations to try passes five hundred. And if a long sentence happens to have a chain of twenty words that match the repeated part, while the required ending of the rule never shows up, the number of dead-end branches tops half a million; at thirty words, it passes half a billion! The machine will spend hours going through every conceivable way of slicing the exact same words into pieces, even though the wrong word "house" is sitting at the end no matter what. Your test bench will hang.
So how does Thompson's simulation work? This machine never backtracks through the text and never guesses a single path. Instead, it keeps track of all possible guesses at once, in a single list! After reading the first adjective "big", it jots down in its notepad a list of all automaton states it could have reached. After reading the second word "old", it takes that list and, in a single step, builds a new list of states for the second word. If two different branches lead to the very same automaton state, Thompson simply merges them into a single line on the list and doesn't spawn duplicates. After all, the automaton has a limited number of states - say, in our rule there are only five. That means Thompson's list at each word of the text will hold no more than five states! Over four words it will perform about twenty simple operations, reach the word "house", see that the list of possible continuations is now empty, and immediately reply: "no match". Even on thirty words it will perform just a hundred and fifty operations instead of half a billion, and it will never hang.
The amount of work in Thompson's algorithm comes from simply multiplying the length of the text by the size of the rule itself (that is, by the number of states in the nondeterministic automaton). Textbooks often say that Thompson's algorithm runs "in proportion to the length of the text". That is true, but only as long as you have a single fixed rule! For our expandable rule system, you must keep an important caveat in mind: when you add new rules, the second factor - the size of the automaton itself - grows, and the total running time grows with it.
Let's run the numbers for your test bench. Suppose the text being checked has a thousand words, and the system currently holds one small five-state rule: Thompson's algorithm will take about five thousand steps. Now you add nineteen more rules of the same size to the database, and the combined nondeterministic automaton grows to a hundred states. The text is still the same thousand words, but at each word Thompson now maintains a list of a hundred possible states and spends a hundred thousand operations - twenty times as many.
This nice speed bound for Thompson's algorithm comes with three more important conditions that you should definitely mention in your thesis:
- the size of the alphabet (how many different word tags exist in the language in total) does not appear in this bound, but that is not a law of nature - it is thanks to Thompson's special way of building the automaton: in his construction, at most two arrows leave each state, so a step from one state always costs a single elementary operation regardless of how rich the alphabet is; if instead you specify a nondeterministic automaton using a general transition table over all symbols at once, then at every step you will have to scan the entire alphabet, and its size will immediately pop up as an extra factor;
- epsilon transitions (arrows that let you jump from state to state for free, without reading a new word from the text) must be traversed carefully at every step, marking states you have already visited so you don't go around the same loops twice, otherwise the fast time bound breaks down right away;
- the bound assumes that checking a single input word against an arrow of the automaton happens instantaneously, in one elementary operation.
The last condition is the most sensitive one for our project, and it does not come for free at all! If an arrow of the automaton carries not just a ready-made word-class number, but a complex test on its grammatical features (such a test question is called a predicate - for example, "check that the word is a past-tense verb, is not on the exception list, and starts with a consonant"), then at every step the program spends time evaluating that question. And the cost of that check necessarily enters the final speed bound as a separate factor - don't forget to mention it at your defense.
Look at how this plays out on the single word "went". When the arrow simply holds the class number for "verb", the program compares two numbers in a single operation and moves on. But if the arrow carries a compound question made of three conditions, then on that very same word "went" the machine first digs into the grammatical tag to check for past tense, then searches a fifty-line exception list for the word, and finally checks the first letter "w". Instead of a single operation, just one transition along an arrow costs dozens of operations, and this is repeated for every state on Thompson's list and at every word of the text.
15. State explosion when eliminating branching, and the lazy automaton with a cache. At the start of the course we talked about the complement operation: that is when you have a rule describing valid phrases, and you want to turn it inside out so that the automaton catches everything else - that is, phrases with errors. Here in your thesis you need to phrase things with great care, otherwise you will start contradicting yourself. You often hear the careless remark: "complementation isn't free, it causes a state explosion". That statement is wrong! What is expensive is not complementation at all, but determinization - that is, turning a nondeterministic automaton into a deterministic one.
Judge for yourself. If you already hold a complete deterministic automaton (where from every state, on any word, there is ровно one outgoing arrow), turning it inside out costs almost nothing. You simply walk through its list of states once and flip the answer flags to their opposites: every state where the machine signaled "match found" you declare ordinary, and every ordinary state you make an accepting one. The time spent here is tiny, strictly proportional to the number of states that already exist. There is no explosion in sight.
Let's test this on a small deterministic automaton with three states that catches a valid pair consisting of the article "a" and a singular noun, like "a cat". In the First and Second states the success flag is off, in the winning Third state it is on, and a fourth trap state catches all forbidden continuations like "a cats" and also has its flag off. To turn this automaton inside out and start catching errors, we simply flip the flags in four steps: we turn off the Third state and turn on the First, the Second, and the trap state. The automaton hasn't grown by a single state, yet now on the valid phrase "a cat" it stays silent in the Third state, while on the erroneous "a cats" it falls into the trap and immediately sets off the alarm.
Where does the trouble come from, then? It shows up when your original rule is written as a regular expression or a nondeterministic automaton. On a nondeterministic automaton you cannot simply swap the flags: after all, if along one branch the machine reaches a dead end while along another it reaches success, swapping the flags will make it signal an error on a perfectly valid phrase. Therefore, to take the complement, you are forced to convert the nondeterministic automaton into a deterministic one first. And a deterministic machine, as we recall, is not allowed to hesitate or follow two arrows at once. That means it has to remember, inside a single state of its own, a whole set of states of the nondeterministic machine at once - all the spots where that machine could possibly be right now.
Every combination, every possible set of states from the old branching machine is forced to become a separate, standalone state in the new deterministic machine! Let's do a quick count of where this leads: if a tiny branching automaton had just three states, you can make eight different sets out of them. If there were ten states - you get over a thousand possible sets. And if there were twenty states - you end up with over a million sets! With every new state you add, the number of possible combinations doubles, growing like an avalanche. In exact science, this runaway growth is called an exponential explosion.
Look for yourself at the valid phrase "dogs bark" and our three-state branching automaton, where only State Three was an accepting state. On the first word, "dogs", the machine splits in two: one branch stays in State One, and the second steps into State Two. On the second word, "bark", the first branch just sits in State One, while the second moves into the accepting State Three - in the original automaton, at least one branch reached success, so the phrase "dogs bark" is accepted as valid. But if we mindlessly swap the flags and declare State One and State Two to be the alarm states, then on that exact same valid phrase "dogs bark", the first branch will finish in State One and immediately raise a false alarm!
Let's watch with our own eyes how these sets are born, using a small example. Suppose our tagger divides words into just two rough classes: "noun" and "verb". We want to catch word chains where the second-to-last word is definitely a noun (for instance, so we can later check phrase endings like "dogs bark"). A branching automaton solves this using just three states - let's call them State One (the start state), State Two (second-to-last word read), and State Three (the final, accepting state). It works by guessing: sitting in State One, it lets any words pass through while staying put; but every time it sees a noun, it simultaneously spawns a second guessing branch and steps into State Two ("what if this noun right here is the second-to-last word?"). From State Two, on any next word (whether a noun or a verb), it steps into the accepting State Three. There are no arrows leading out of State Three - if the text hasn't ended yet, that old guess simply burns out.
Now let's turn this tiny three-state machine into a deterministic automaton, so we can later turn it inside out (to find all phrases where the second-to-last word is not a noun). The deterministic automaton starts working with a list containing just a single item: "One".
- If a verb comes in, the list doesn't change - we stay in the set "One only".
- If a noun comes in, the branching machine could have stayed put, or it could have stepped forward. So the deterministic machine moves into a new combined set-state: "One and Two".
- Suppose we are sitting in the set "One and Two", and a verb comes in. From State One, a verb leads back to State One, and from State Two it leads to State Three. That means our machine moves into a new set: "One and Three".
- And what if another noun comes in while we are in the set "One and Two"? Then from State One we land in One and Two, and from State Two we land in Three. We glue all of that together and get a big set of three states at once: "One, Two, and Three".
Look at that: all four of these sets ("One only", "One and Two", "One and Three", "One, Two, and Three") have become separate states in our new deterministic automaton. If we were checking for a noun not in the second-to-last spot, but ten words from the end, then eleven states in the branching machine would blow up into more than a thousand states in the deterministic one! On the bright side, now that our deterministic automaton of four sets is built, taking its complement is as easy as pie: previously, the accepting sets were the ones that contained State Three inside them (namely, the sets "One and Three" and "One, Two, and Three"). With a single move, we swap the flags: now the other two sets ("One only" and "One and Two") become the accepting ones. And those are the exact states that will catch every phrase where the second-to-last word is not a noun.
Let's test this on a live example and see how this inverted automaton reads the phrase "run fast" (a verb followed by an adverb). The machine starts in the set "One only", stays in that same set "One only" on the verb "run" because moving to State Two is only allowed on a noun, and on the adverb "fast" it again stays in the set "One only". Reading is finished, and after we swapped the flags, the set "One only" became an accepting state for us - so the automaton accepts the phrase and rightly confirms that the second-to-last word was not a noun.
To keep this avalanche of sets from clogging up all the computer's memory before it even starts reading text, in practice we use a clever trick - a lazy automaton with memory (often called a cache). The idea is not to precalculate all the millions of possible sets out of thin air ahead of time. Instead, the machine builds new set-states right on the fly as it reads real English text, and saves the sets it has already built into fast memory. For example, if the short phrase "dogs bark" (a noun followed by a verb) comes in as input, the lazy machine will start with the set "One only", on the word "dogs" it will calculate and remember the set "One and Two" for the first time, and on the word "bark" it will calculate and remember the set "One and Three". The fourth set ("One, Two, and Three") wasn't needed at all on this sentence - there were no two nouns in a row! So the lazy machine won't even waste time and memory creating it. In real texts, most of the wild combinations that are theoretically possible never actually show up, and a lazy automaton saves the program from a memory explosion.
16. Text alignment and where gold-standard error annotation comes from. To measure how well your error detector works, you need to compare its answers against the right answers given by a human - against a gold-standard annotation. But where does the gold-standard annotation in test corpora come from in the first place? In our field, a corpus is very often prepared like this: they take an original student essay with errors, put the exact same essay next to it after it has been corrected by a teacher, and then run a special program that matches up the two chains of words and automatically extracts a list of the errors that were made. This operation of matching up two chains of words is what we call alignment.
Alignment is done using a classic method from algorithm design - dynamic programming, which finds what is called the Levenshtein distance. What does this machine have to do? It takes two sentences, say the original one with an error, "He go to school yesterday", and the corrected one, "He went to school yesterday", and it has to find the cheapest way to turn the first sentence into the second using the simplest possible edits: substitutions, insertions, or deletions of individual words. How does it do that? The machine builds a table where, step by step, it lines up the words of the first sentence against the words of the second, relying on shorter segments it has already calculated so it does not have to try every option blindly. It sees that the word "He" matches the word "He" (no edits needed), then in the second position the word "go" has turned into "went" (one substitution), and the tail "to school yesterday" matches word for word again. This is how the machine automatically extracts a reference error: on the text segment around the second word, "go" was replaced with "went". Specialists call such a highlighted segment of text from one boundary to another a span.
The standard evaluation tool in our field, the one used today to compute the final numbers in papers, is built right on top of this kind of automatic alignment (the scoring tool itself came out in 2017, and the alignment algorithm inside it is taken from a 2016 paper by the same authors). However, in the simplest textbook Levenshtein algorithm, any substitution of any word costs the exact same amount - say, one arbitrary coin. If you count that crudely, the machine will often get confused by complex edits: when an author swaps words around or replaces one word with two, a naive algorithm does not care which words get glued to which into a single error. That is why our standard evaluation tool uses an extended Damerau-Levenshtein algorithm (which can also handle transpositions of adjacent elements), and most importantly, the cost of each operation there is not a flat one, but smart and linguistic.
When this algorithm decides whether to link the word "go" from the original text with the word "went" from the corrected text, it looks into their grammatical nature: what part of speech they are and what their base dictionary form (called a lemma) is. It sees that both "go" and "went" are verbs, and their base dictionary form is the exact same ("go"). That means they are blood brothers! The cost of matching them is set to pennies, and the algorithm confidently links them into a single grammatical verb-tense error, rather than declaring a random deletion of one word and an independent insertion of another. On top of that, special merging rules run to glue adjacent minor edits into one meaningful error (for instance, when "go" is replaced by the two words "had gone").
Look at a sentence to see how blind counting leads to a dead end: suppose a student wrote "He fast ran", and the teacher corrected it to "He quickly ran out". Here the adverb "fast" was replaced with "quickly", and after the verb "ran" the particle "out" was inserted. But if every substitution and every insertion costs exactly one coin, it is no more expensive for a naive algorithm to declare that "fast" was deleted, "ran" was replaced with "quickly", and "ran" and "out" were tacked onto the end. The cost in coins for this nonsense would be the exact same, and instead of two clear errors, your reference set would end up with mush.
For your thesis, you need to firmly grasp three things about how this works:
- automatic alignment of two texts is a common, popular way to get reference annotations, but it is far from the only possible way in existence; there is also fully manual annotation done according to a strict specification manual, where a human linguist reads the original text and manually marks the error boundaries and assigns their types; with that kind of manual annotation, no alignment and no dynamic programming are needed at all, and in your thesis you must clearly state which of the two methods was used to get the annotations in your test dataset;
- never confuse two completely different steps: step one is extracting reference errors from a pair of texts (this is where alignment works), and step two is comparing your detector's outputs against a ready-made reference standard; once the reference text segments are known, evaluating your detector is not string alignment at all, but a simple comparison of the start and end coordinates of the segments, which we will cover in the next section;
- if your test dataset was in fact created by automatically aligning original and corrected texts, remember that the alignment algorithm itself sometimes makes mistakes on complex rephrasings, and these flaws in the reference standard can quietly skew your final precision and recall scores; on the other hand, if your annotations are ready-made by hand according to a manual, then this whole section does not apply to your measurements at all - you jump straight to the next section.
17. When a detected error segment counts as a hit against the reference standard.
When your detector checks a text, it highlights a suspicious piece from one word to another. Specialists call such a highlighted segment of text a span. The main practical question of any evaluation goes like this: when does a span found by your program count as matching a correct answer in the reference annotation? The rule for counting a match is your own deliberate decision, and you must declare it strictly before your very first measurement. If you change the rule halfway through, all your "before and after" comparisons become meaningless and void.
In the standard evaluation program we will discuss below, there are three different scoring modes, and the numbers they produce are completely different:
Here is how this looks in your project on the exact same sentence, "I see a cats". Suppose the reference standard marks the two words "a cats" as the error span with the correction "cats", while your detector highlighted only the single word "cats" and offered no correction. In the first mode (span-level correction) and in the second mode (span-level detection), you will get zero hits because the boundaries of the segment "cats" did not match the reference segment "a cats", whereas in the third mode (token-level detection), the word "cats" will count as a match and earn you one guessed word out of two.
- span-level correction mode, which is on by default: an edit counts only if both the boundaries of the span itself and the proposed correction string match to the letter;
- span-level detection mode: the program checks only for an exact match of the span boundaries and ignores the correction itself;
- token-level detection mode: matches are checked at the level of individual word tokens, meaning a partial overlap between segments also counts.
Our detector does not suggest corrections; it only points out a suspicious span. That means the default evaluation mode does not suit us at all. Our choice is either span-level matching or token-level matching. You must state the chosen mode explicitly in words in your report, rather than leaving the default settings. Next to the mode, be sure to state the exact version of the evaluation tool and the version of the annotation language model it runs on. From version to version, the authors changed both the error-type tags and the span boundaries themselves, so numbers obtained on different versions cannot be compared.
Let us look at a concrete example to see why these two modes give different numbers. The difference between them is not just about strictness, but about the very unit of counting: in one case we count whole spans, and in the other we count individual matching tokens. Take the English sentence with an error "He has been go there every day", where instead of a pile-up of verbs there should simply be "goes". There are seven words here. Suppose the authors of the gold-standard annotation marked the entire erroneous three-word verb phrase "has been go" as a single span. Your detector, however, only noticed the mismatched pair "been go" and marked a two-word span. Let us see what the evaluation tool will say:
- in span-level mode, the boundaries did not match: your two-word span is not equal to the gold three-word span. You get zero true positives, one false positive from the detector, and one false negative (missed gold span). Both precision and recall are zero. A complete failure out of nowhere;
- in token-level mode, counting is done by tokens. The gold standard covered three words, your detector covered two words, and both of your words ("been" and "go") fell inside the gold span. That means two out of the two words you found are correct - that is one hundred percent precision! And out of the three gold words, you caught two - that is two-thirds recall, or sixty-seven percent.
Do you see what a chasm that is? On the exact same detector output, one mode gives you a flat zero, while the other praises you for one hundred percent precision. That is precisely why you cannot write your own script for intersecting spans and simply declare in words that it is equivalent to the standard evaluation tool. Equivalence must be proven in practice: run both tools on the exact same examples with partial overlap and honestly report the numerical discrepancy if one shows up.
There is also an important technical caveat, without which your very first run will grind to a halt. The standard evaluation tool compares two files in a special tabular format that records edit coordinates. It comes bundled with a helper utility that builds such a file automatically from a "source text - corrected text" pair. However, our detector does not output corrected text, so you cannot run it through this utility! You will have to either save your detector's output directly into this special format with span coordinates yourself, or compute span intersections with your own script strictly following the same rules. And be sure to make certain that the tokenization of the text into individual word tokens is completely identical between the gold standard and your detector. If in the phrase "He don't know" one tool splits "don't" at the apostrophe into two parts ("do" and "n't"), while the other leaves it as a single piece, the coordinates of all subsequent words in the sentence will shift by one. In span-level mode, such a discrepancy at an apostrophe or a hyphen will instantly give you zero precision.
Look at the phrase "He don't know clear answer", where an article is missing before "clear answer". The gold standard splits "don't" into two pieces, so the words "clear" and "answer" get positions four through six in it. Your detector treats "don't" as a single word, correctly finds the exact same error on the words "clear answer", but records its coordinates as three through five. The evaluation tool checks the boundaries three-to-five against the gold boundaries four-to-six, sees a mismatch, and gives you zero true positives and one false positive, even though the detector found the exact right thing.
Finally, along with the mode, you need to state the rules in advance for three tricky edge cases; otherwise, your very first run will produce numbers that no one can reproduce:
- omission of a required word, for example when the preposition "to" is forgotten in the phrase "He went school". For annotation, this is an insertion - that is, a span of length zero squeezed between the words "went" and "school". The usual span-intersection rule does not work on length zero, so the matching rule for insertions must be defined separately;
- identical spans from different rules: if two of your rules fired simultaneously on the exact same piece "been go" and output two identical spans, whether to count this as one detector hit or as two;
- one-to-two overlap: if one long span from your detector covered two small gold spans at once (or conversely, two of your spans fell inside a single gold span), how many hits to credit - one or two.
Here is what this looks like on the phrase "I have two brother and three sister", where the plural ending is missing on two nouns. The gold-standard annotators marked two separate short spans here: "two brother" and "three sister". Meanwhile, your broad rule for coordinated phrases with numerals captured the entire group "two brother and three sister" as a single long five-word span. If you do not specify in advance in your evaluation script whether to count such coverage as two caught gold spans, as one, or as zero altogether, your numbers when calculating recall will diverge from the standard tool.
18. How to quickly check that two automata do the same thing.
Suppose two students independently built two deterministic automata to search for the exact same error - say, a singular article before a plural noun, as in the phrase "I see a cats". On the surface, the diagrams turned out differently: the first student has three states, while the second has four because they accidentally drew an extra detour path. How can a machine quickly check that these two automata always work the same way - that is, catch the exact same errors on any possible text? When two automata do the same thing, we say that they are equivalent. What comes to our aid here is a data structure called a disjoint-set data structure (or union-find), and the Hopcroft-Karp algorithm built upon it.
Picture this process as sorting the states of both automata into boxes. What must the checking machine do? It must try to merge the states of the first and second automata into common groups so that states in the same group behave indistinguishably. And it does this step by step as follows:
- at first, every state of both automata sits in its own separate box;
- the start states of both automata must correspond to each other, because both automata begin reading the text from them. Therefore, the machine immediately dumps both start states into one shared box and puts this pair into a queue for checking;
- next, the machine pulls a pair of states from the queue and looks at where the arrows lead from them for every possible word class. For example, take the class "article a". From the start state of the first automaton, the arrow leads to its second state, and from the start state of the second automaton, it leads to its second state. Since both automata took a step on the exact same word, they must land in places that mean the same thing! The machine checks whether these new states are already in the same box. If they are still in different boxes, it dumps those two boxes together into one shared box and puts the new pair into the queue for further checking;
- right after that, the machine checks the arrows for the class "plural noun". In the first automaton, the arrow from the start loops back to the start, while in the second automaton it goes to that extra fourth state. The machine immediately dumps this fourth state into the shared box with the start states.
Step by step, the machine merges boxes like this until the queue is empty. Trouble happens in only one case: if a final state of one automaton (which shouts "error found!") and a regular, non-final state of the other automaton (which stays silent) end up in the same shared box. That means there is some text where one automaton will fire and the other will not. When that happens, the machine stops right away and says: the automata are different. And if the queue runs dry and no such conflict ever happened in any box - the automata do the exact same thing.
Let us test on a live example how the machine catches such a difference. Suppose the second student got careless and forgot to draw an arrow for the class "plural noun" from their second state to the third, final state, and instead looped that arrow back to the start. The checking machine pulls out the box holding both second states from the queue and steps out of them on the class "plural noun", just as if reading the chunk "a cats". The first automaton moves to its third, final state, while the second automaton goes back to the start, which is a regular silent state. The machine tries to dump them into one box, immediately sees a shouting final state and a silent start state in the same box, and right away gives the answer: the automata work differently, because on the phrase "I see a cats" the first one will fire and the second one will stay silent.
In Hopcroft and Karp's original report, the running time of this algorithm is stated as linear: the checking time grows in proportion to the number of word classes in the alphabet multiplied by the total number of states. That means if you have twice as many states, the job will take roughly twice as long, because the authors relied on a simple linear merging of lists. The famous "nearly linear" bound, where the unbelievably slow-growing inverse Ackermann function shows up, came later - from the exact analysis of the disjoint-set data structure carried out by Tarjan. So you should not credit that bound to Hopcroft and Karp themselves in your thesis.
Let us count the steps for your task. Suppose your part-of-speech tagging uses thirty word classes, and you are comparing two small automata with three and four states - seven states in total. Then the checking machine will have to go through thirty arrows for at most seven box merges, which means doing around two hundred and ten simple checks. And if you merge several rules into larger automata and the total number of states doubles - from seven to fourteen with the same thirty word classes - then the number of arrow checks will double as well, to roughly four hundred and twenty, with no explosive growth at all.
19. How to build a fast word-form dictionary using a letter tree and hashing.
Before your automata can start hunting for grammar errors across word classes, the detector has to turn every raw English word from the text into a set of grammatical features, or check it against a list of exceptions. For instance, in the sentence "She gave me a good advice", the error lies in the fact that the word "advice" is uncountable in English, so you cannot put the article "a" in front of it. To catch this error, the machine needs to look up the properties of the word "advice" in a massive dictionary of word forms in an instant. There are two basic ways to set up a fast dictionary like this in memory: using hashing or using tries.
The first way is hashing, that is, a hash table. The machine takes the letters of the word "advice", runs a special arithmetic rule to compute an address number from these letters in one go, and jumps straight to the right memory cell, where the card for this word is stored with the tag "uncountable noun".
The second way is to build a trie, also called a prefix tree. This is a tree where each step down from the root is the next letter of the word:
- when the word "advice" comes in, the machine stands at the root of the tree and follows the arrows letter by letter: first along the arrow for the letter "a", from there along the arrow for the letter "d", then "v", "i", "c", and finally lands in the node after the letter "e";
- in total it takes six steps - as many as there are letters in the word - and the lookup speed does not depend at all on whether your dictionary holds a hundred words or a million;
- at the final node after the letter "e", there is a flag: "end of word, this is an uncountable noun".
At the same time, all words that share a beginning - say, "advice" and "adviser" - travel along the exact same shared branch "a" - "d" - "v" - "i" and split only at the fifth letter, which saves a great deal of memory. And the neatest part is that such a trie is already a ready-made deterministic finite automaton in its own right, one that reads a word letter by letter and recognizes a finite list of words from a dictionary.
Let us test on a live example how this automaton rejects an unfamiliar word. Suppose the input is the typo "advise" instead of the noun "advice": the machine starts in the root state, moves to the first state on the letter "a", then follows "d", "v", "i" to reach the fourth state, but from the fourth state there is simply no arrow labeled "s" in our dictionary of uncountable nouns. The automaton stops right away and reports that the word is not on this list - and in every state it had at most one path for the next letter, just as a deterministic automaton should.
What automata courses leave out, but your project needs: evaluation metrics
This part is not about automata or algorithms. Neither of your two courses covers these things in its syllabus, yet without them your thesis simply will not pass, because this is how people measure what your detector and your data are actually worth.
20. Precision, recall, and a combined score weighted toward caution.
Imagine your detector is checking the sentence "He go to school every day and he like it". It has two real errors: "go" instead of "goes" and "like" instead of "likes". Suppose the machine fired twice: it rightly flagged "go", missed the second real violation, and instead found fault with the completely correct word "every".
How do you judge performance like that at a glance? To do this, you calculate two simple ratios.
The first fraction answers the question: how much can you trust the machine when it raises an alarm? Our detector went off twice, and only once for a good reason. That means half of its alarms were right. This fraction of true alarms out of all the machine's alarms is called precision.
The second fraction answers the question: what share of the real errors did the machine manage to catch at all? There were two errors in the sentence, and the detector found one - that is, half of them. This fraction of found errors out of all the real errors in the text is called recall.
Precision on its own is only half the story. It is easy to get one hundred percent precision if, across an entire novel with hundreds of errors, you only trigger once on the most obvious case. And it is easy to get one hundred percent recall: just underline every single word in the text in red - then not a single error will slip by, but a check like that is worthless. That is why the two fractions are combined into a single overall score, called a combined measure (or F-measure).
There are different ways to combine them. You can value precision and recall equally - that is the balanced combined measure. Or you can give one side more weight. A tunable importance weight controls this balance: if we set it to one half, we get the half-weight measure, which values precision much higher than recall.
Look at how it works with real numbers. Take a text with ten hidden errors and run a very cautious detector on it. It triggered only twice, but hit the bullseye both times. Its precision is flawless - one hundred percent, while its recall is modest - just twenty percent, two errors out of ten. If we judge it by the balanced measure, where both fractions are equal, this cautious detector gets about thirty-three percent. But if we judge it by the half-weight measure, its score immediately jumps to about fifty-six percent. The measure generously rewarded the machine for not raising false alarms.
Why did it become the rule in our field of computational linguistics, starting in 2014, to use this exact measure weighted toward precision? At an open international shared task on automatic grammatical error correction, it was chosen with this explanation: the measure emphasizes precision twice as much as recall, because offering a person a wrong correction is worse than saying nothing and offering none at all. Along the way, remember an important detail from the history of the subject: the popular automatic edit-matching scorer was invented two years before that competition, and in its first paper that scorer computed the ordinary balanced measure. The entire field switched to the half-weight measure specifically at the 2014 competition.
Here you will run into a seeming contradiction in textbooks and papers. Some authors write that the half-weight measure values precision "twice" as much as recall, while others say "four times" as much. Be aware: this is neither a typo nor loose wording. It is the exact same mathematical property of the measure itself, just viewed at two different operating points.
How does this work in plain terms? The combined measure changes smoothly: nudge precision or recall up a little, and the overall score nudges up a little too. We can look at how sensitive the final score is to a tiny step in precision compared to the exact same step in recall. It turns out that this ratio of sensitivities is not fixed in one place; it depends on what precision and recall your system has right now:
- If your detector currently has the same precision and recall (say, fifty percent each, as in our first example with "He go"), then at this point a step in precision gives four times the gain in the overall score as the same step in recall. The sensitivity to recall versus precision here is in a one-to-four ratio - and that is where the phrase "four times" comes from.
- Now let us move to a different point - where recall is exactly half of precision (for instance, eighty percent precision and forty percent recall). At this exact point, the sensitivities even out to one-to-one: here, a user is willing to trade one percent of recall for exactly one percent of precision. This point of fair trade is defined by recall being half of precision - and that is what the classic reading of the weight as an importance ratio refers to, which is where the word "twice" comes from.
Let us work this out with concrete numbers around that point where both precision and recall are fifty percent, and the half-weight measure is also exactly fifty percent. If you tweak your rules and raise recall by five percent - to fifty-five, keeping precision at fifty - then the half-weight combined measure will grow to about fifty-one percent, a gain of just one percent. But if instead you raise precision by the same five percent - to fifty-five, with recall at fifty - then the combined score jumps straight to fifty-four percent, giving a four percent gain, which is four times as much.
So both sources are right, and the difference between them is a difference in the operating point from which they look at the system, not a clash between a formula and words. When citing the organizers of the 2014 competition, write "twice" in their words. And if you are talking about the marginal trade-off when precision and recall are equal, state the one-to-four ratio and be sure to specify that point of equality itself. You must not mix up these two cases, nor declare either one of them a mistake.
But the most important thing for your thesis defense is this qualification. Practical importance and the true cost of errors in our system is a third quantity altogether, and we assign it ourselves. The competition organizers' argument that a wrong correction is worse than silence was made about programs that offer a person a ready-made word replacement. Yet your detector does not offer any corrections at all! It only points out a suspicious spot in the text.
Because of this, the cost of a false alarm in your machine is completely different. When the first, fast stage of your detector mistakenly raises an alarm on a correct word, it does not ruin the author's text. Instead, it wastes the limited budget of calls to the heavy and slow second stage of checking, which we will discuss later in the handbook. Therefore, in your thesis, you cannot justify choosing the half-weight measure just by quoting someone else. You need to back it up with your own argument and state it out loud. Out loud, it sounds like this: choosing the half weight is our engineering decision about how much a false alarm costs compared to a missed error in our two-stage architecture, not a direct consequence of the academic literature. The literature gives us only one thing here: in this field it is standard practice to measure quality with this exact measure, and thanks to that, our results can be directly compared with those of others.
Here is what this looks like in your project in raw counts. Suppose a page of text comes in for checking with ten real errors hidden in it, and your time budget allows your heavy second stage to inspect no more than twenty suspicious spots. If the first stage catches eight real errors while raising only two false alarms on perfectly fine phrases like "every day", the second stage will easily check all ten spots and use only half of its budget. But if the first stage chases high recall and catches all ten errors while also raising thirty false alarms, then twenty calls out of forty simply will not fit into the limit, and genuine errors will go unchecked.
21. Inter-annotator agreement and why we cannot demand a strict threshold for it.
To test a detector, you need texts where the errors have been marked in advance by real people - human annotators. But language is a living thing, and when two people independently check the exact same student text, they will inevitably disagree. For example, in the sentence "I arrived to the station", one reviewer will underline the preposition "to" as an error (strict grammar requires "at"), while the other will let it slide and decide it is acceptable in casual speech.
How can we tell how much two annotators actually agree with each other? If we just calculate the percentage of matching answers, we will fool ourselves, because a huge share of those matches will happen purely by chance. To strip away this randomness, we use a special measure of chance-corrected agreement called Cohen's kappa. If the annotators work in complete agreement, it equals one; if their matches are no better than a coin toss, it drops toward zero.
Remember this right away and for good: we do not require any strict threshold like "kappa must be at least zero point six" in your project. And this is a matter of principle. If we set a requirement like that, it would doom your thesis to failure for a reason completely beyond your team's control - the very nature of language and student errors.
Look at the numbers researchers have gotten in real measurements on similar tasks (all of these figures are good to know, and it is important to understand clearly what exactly was being measured):
- The simplest judgment, "is the sentence correct or not", on texts written by English learners. Three pairs of annotators checked one hundred sentences per pair (counted across the sentences that the second reviewer checked after the first). Simple observed agreement between the humans was quite decent - from fifty-six to seventy-eight percent. Yet the kappa for these three pairs turned out to be just zero point one six, zero point four zero, and zero point two three!
- Marking preposition errors in student texts. Two specially trained annotators checked one thousand three hundred and thirty-six text fragments twice. The kappa between them ranged from zero point four one one to zero point seven eight six, with an overall value of zero point six three zero.
- Filling in a missing preposition in reference text written by native speakers (researchers took encyclopedia articles, blanked out the prepositions, and asked the exact same trained annotators to put them back in). Here, kappa was zero point seven at an observed agreement of zero point seven six.
The last two measurements were taken by the same authors in the same study, and you must never confuse them. The first measurement (on student texts) is a task like ours, while the second (putting a preposition into smooth encyclopedia text) is noticeably easier than ours. Moreover, in both tasks, disagreements between humans are very often justified by the meaning of the text itself, where different interpretations are possible.
Look at a sentence from a student essay: "The picture on the wall was painted by my sister". The first annotator leaves the preposition "on" alone as completely correct, understanding the phrase to mean "a picture hanging on the wall". The second annotator changes "on" to "of", deciding that the student is describing a photograph or drawing of the wall itself. Both readings make sense, both prepositions are grammatical in their own way, and yet a disagreement gets logged in the inter-annotator agreement table.
Since demanding a high threshold is pointless, we ask something else of you: measure kappa honestly on your own data, and on that exact same sample, measure human-versus-human performance.
But before you calculate anything, you must explicitly declare your unit of analysis. The thing is, by design, Cohen's kappa only works when you have a fixed, predetermined list of items, and two people simply sort those items into boxes ("error" or "correct"). How does your annotator work, though? They read continuous text and highlight spans with free boundaries - wherever they want to draw the box, they draw it. Imagine the sentence "He have been working". One annotator highlights a one-word span, "have", while the other grabs the whole verb phrase, "have been". They end up with a different set of items being checked! That is why, until you firmly declare what counts as a single item in your tally (a whole sentence, an individual word, or a specific grammatical construction under test), your kappa number cannot be compared to anyone else's number - or even to your own on a different sample.
The second caveat is even more important for our work: when one category appears vastly more often than the other, Cohen's kappa behaves in a completely counterintuitive way. Even when visible agreement between humans is very high, kappa suddenly turns out to be close to zero! In science, this phenomenon is well known and is called the prevalence paradox.
Let us see this paradox with our own eyes on a small example. In any normal text, there are orders of magnitude more correct words than erroneous ones - the class imbalance we are dealing with is guaranteed to be gigantic. Suppose a hundred-word text contains just two real errors. Two annotators check these hundred words. For ninety-six of the words, both agree: "everything is clean here". On the remaining four words, they disagree. Look at what happened: the humans gave the exact same answer in ninety-six cases out of a hundred! Their visible agreement is huge - ninety-six percent. But when we start subtracting chance agreement according to the rules of kappa, the math reasons like this: since both annotators almost always say "correct", they matched on those ninety-six words purely by chance, simply because they both keep saying the same thing all the time. As a result, kappa crashes to nearly zero.
That is precisely why, for annotated text spans with free boundaries, Cohen's kappa cannot be our primary metric. Human agreement on such free spans is measured differently: either we calculate our familiar composite score of one annotator against the other (treating one person as the gold standard and the second as the system under test), or we use a special agreement measure - Krippendorff's alpha, which is built from the ground up to handle floating span boundaries.
Finally, you should know a very strong argument against the whole idea of demanding exact agreement from human annotators. In a well-known 2015 study, researchers took ten annotators and gave them the exact same texts to correct. Not a single one of the ten matched any other person completely! From this, the authors drew a sober conclusion: when an error in a sentence can be corrected in several equally valid ways, any agreement metric that demands a literal match between answers tells you very little about real quality.
Let us test this on a live example: a student wrote "I have many homeworks". The first annotator sees an uncountable noun put in the plural, changes both words, and writes "much homework". The second decides to keep the plural and replaces the noun with a countable one: "many assignments". The third simply drops the determiner and puts "a lot of homework". All three caught the exact same error and produced flawless English, yet a literal comparison of their answers gives zero matches.
From that same 2015 paper, we take an important practical benchmark. If you evaluate one human against the other nine reference annotators using the half-weighted composite F-measure, human-to-human agreement is about seventy-three percent (more precisely - 72.58 percent; be sure to verify this number yourself against the table in the original paper before putting it into your thesis!). For comparison: the top computer systems at the 2014 shared task performed at sixty-seven to seventy-three percent of that human level.
Just handle that seventy-three percent figure very carefully, and follow three rules:
- Do not call this number by the grand name "human ceiling". That is a careless label. What we have here is not some universal upper limit of the human mind, but merely an empirical benchmark of agreement obtained on one specific collection of texts, under one specific set of annotation guidelines, and from one specific group of ten people.
- Remember that the 2015 paper measured full error correction, whereas our task is only error detection. You cannot carry a number over from correction to detection directly, without a separate and solid argument.
- And never cite that 2015 paper as a source for a Cohen's kappa value: the authors did not compute their own kappa in that work at all.
Here is what that difference looks like in your project on the sentence "She gave me an advices". In the detection task, both annotators just need to draw a box around the span "an advices" and hit the red button - their answers match completely. In full correction, however, one reviewer will write "some advice" above it, a second will write "a piece of advice", and a third will simply leave "advice". Where detection had one hundred percent agreement, correction ends up with three different answers.
22. How much can we trust our numbers: margins of error
Imagine your detector has checked a test corpus and posted a precision of eighty percent. Is that high or low? And more importantly - how solid is that number? If we were handed another batch of similar student essays, would we get seventy-nine percent, or drop straight to sixty? Without error bounds - in statistics they are called confidence intervals - any number you report hangs in thin air. If a new version of your program raises quality by two percentage points, without an interval there is no way to tell whether you genuinely improved the algorithm or just got lucky on this particular set of texts.
The best-known papers in our field and the standard evaluation scripts do not compute such bounds at all - their tables just show bare numbers for precision, recall, and the precision-weighted composite measure. The authors of one popular automatic error-type annotation tool did use repeated random resampling of the corpus, but only to answer the question "is the difference between two systems due to chance", not to put a spread around the score itself. Only in rare papers will you see honest ninety-five percent confidence intervals. In your thesis, they are mandatory: without them, a two-point gain is indistinguishable from random noise.
How do you build such an interval? For a simple proportion - where we divide the number of successes by the total number of trials - there is the classic Wilson interval. Precision and recall are indeed proportions. The precision-weighted composite measure is no longer a proportion; it combines two proportions into a single number, so the Wilson method cannot be applied to it directly. But that is not even the main trouble. Even for plain precision and recall, the Wilson interval is not enough for us, and here is why.
The Wilson method is built as if every time the detector fires, it is a separate, completely independent coin toss with the exact same chance of success. This is called a binomial model. Now look at real text. A student does not know how to use English articles, and in a single essay writes phrases like "I bought cat", "Cat was big", "I gave milk to cat" twenty times in a row. Are those twenty independent coin tosses? No, that is one and the same habit of one and the same person. Errors within a single essay, and even more so within a single author, are tightly linked to one another - as statisticians say, they are correlated.
What happens if we turn a blind eye to this and compute a Wilson interval anyway? We fool ourselves. The computer will think it holds twenty completely separate, independent pieces of evidence in our favor, and it will output an interval that is far too narrow - attributing extra certainty to our score that is not really there. Both this section of our handbook and the next one recognize this link between errors within an author, so our methods must be consistent with each other.
Let us do a raw count to see how this illusion arises. Suppose the detector fires one hundred times on the test corpus, and eighty of those alarms are correct: those exact eighty times when four students each dropped an article twenty times in phrases like "I bought cat". The Wilson method sees a hundred separate, independent coins and produces a narrow band around eighty percent - roughly plus or minus eight percentage points. Yet in reality, you only tested this habit on four people: if we replaced just one such author in the corpus with a student who uses articles properly, our precision would immediately drop by ten points - something the narrow binomial interval gives no warning of at all.
Let us make an important caveat. A standard binomial interval turns out narrower than the true one when the correlation within a single author is positive - that is, when errors of the same kind travel in packs, which is exactly what we see with real students. Correlation by itself does not set the direction: if it happened to be negative (making an article error meant the student would definitely get it right next time), the binomial interval would instead come out wider than the true one. So this narrowing of the interval is our reasonable assumption about the nature of student writing, not an eternal law of nature. You should check it right on your corpus by calculating how strongly errors correlate within each author.
Since individual errors are linked, we have no right to shuffle them one by one. We need a different tool. The main method in your work for precision, recall, the F-measure, and for comparing two versions of the detector is the cluster bootstrap.
First let us unpack these words. A cluster is an indivisible bundle, a folder of texts written by one person. And bootstrap is a method of repeatedly reassembling your data at random. What does the computer have to do, and how does it do it?
Suppose your test corpus has fifty different authors. You take fifty folders and put all the essays by one specific student into each folder. You are not allowed to open or split a folder - that is our cluster. Next, the computer runs a lottery. It randomly draws one folder from your pile, copies all its texts into a temporary corpus, and puts the folder back into the pile. It draws like this fifty times until it collects a new corpus of fifty folders. Because the folders go back into the pile every time, in the new set some author's essays will show up three times, while someone else will not be picked at all. On this new artificial corpus, the computer recalculates precision, recall, and the F-measure, and writes the three numbers down in a column.
The computer repeats this fifty-draw lottery, say, ten thousand times. In the end, your table holds ten thousand slightly different quality scores. You chop off the most extreme outliers at the top and bottom, and the boundaries of the remaining ninety-five percent of values give you your honest interval. Because all sentences like "I bought cat" from a single student always traveled together in the same folder, we completely preserved their internal link and did not give ourselves credit for fake precision.
Let us trace this last step right on the table of ten thousand rows. The computer lines up all ten thousand precision scores in one long row from smallest to largest. To leave exactly ninety-five percent in the middle, we trim five percent off the edges: the two hundred and fifty lowest numbers from the bottom and the two hundred and fifty highest from the top. If the two-hundred-and-fiftieth spot from the bottom in the sorted list holds the number seventy-one percent, and the two-hundred-and-fiftieth spot from the top holds eighty-seven percent, then the range from seventy-one to eighty-seven percent goes into your thesis as your honest confidence interval.
Sometimes authors are not labeled in an existing corpus - there are only individual essays. Then you have to treat a single essay as your indivisible folder. But make sure to write in your thesis: switching from author to essay does not solve the problem, it only sweeps it under the rug! Two essays by the very same person will end up in different folders, the hidden link between folders will remain, and your interval will once again come out narrower than the true one. Write this down as an honest limitation of your work, not as a free choice of counting unit. And keep the Wilson interval in your thesis as an extra reference estimate, just state its conditions right next to it: it holds true only if we treat all errors as independent coin tosses.
We also need to talk explicitly about what exactly we divide by when calculating proportions - the denominators. For recall and precision, they behave in completely different ways. When you calculate recall, you divide the errors you found by the total number of true errors in the gold-standard annotation. That number is rock solid; it is fixed by the corpus in advance and does not depend on your detector. When you calculate precision, however, you divide the true hits by the total number of times the detector itself fired. But how many times the detector decides to fire is a random outcome in itself! That is why for precision, the Wilson interval is built conditionally: we are basically saying "given that the detector fired the exact number of times we observed". And by the way, do not confuse quality with the proportion of sentences where the detector raised an alarm at all: that is simply its firing rate, it is not a quality metric, and we will need it later, in section twenty-seven.
Let us test this difference on a live example from a corpus. Suppose the test essays contain one hundred true errors - say, one hundred missing articles in sentences like "Cat was big" - and this number one hundred is set in stone before your program even runs. You run the first version of your detector: it raises an alarm fifty times, forty of them terecht - when calculating recall you divide forty by the fixed hundred, and when calculating precision you divide the same forty by the fifty alarms. Then you tweak a rule in your program slightly, and on the very same text the detector now fires eighty times: the denominator for recall stays the same hundred, while the denominator for precision jumps from fifty to eighty simply at the whim of your machine.
One more correction to a common line students often write: "for the F-measure, only bootstrap works". That is not true. The F-measure changes smoothly and gradually as precision and recall change, so you can derive its boundaries mathematically without any lottery at all - in statistics this is called the delta method. But the delta method comes with a heavy price here, and you need to understand it. Precision and recall do not live separate lives: they share the top part of the fraction - those very errors that were rightly caught. That means the delta method will require calculating how they vary together (statisticians call this covariance), and you will still have to plug in a spread estimate adjusted for folder clusters, otherwise we fall right back into the same trap of "independent" articles that we worked so hard to escape. So we do not declare bootstrap the only possible way in nature. We choose it deliberately: it does not require taking complicated derivatives, and it naturally carries over the grouping by author.
So that any reviewer can repeat your folder lottery and get the exact same boundaries, you cannot just drop the two words "cluster bootstrap" into your thesis. It is a full step-by-step protocol, and you must state the whole thing, point by point:
- How many times the machine resampled the random corpus, and what starting number (called the random seed) kicked off the random generator. A computer does not produce true randomness. It produces a long sequence of numbers using a hardwired rule, and that sequence depends completely on the starting seed. If you do not write the seed down, you will not be able to reproduce your own tables tomorrow on your own machine. Also, you do not pick the number of resamples out of habit. You check it against the error of the lottery itself (called Monte Carlo error). You do this directly: run the bootstrap twice with two different random seeds on the exact same data. The gap between the interval bounds in the first and second runs must be noticeably smaller than the improvement in detector quality you want to prove in your thesis. One thousand resamples is usually too few for the tails of the interval - the bounds still wobble noticeably. Ten thousand is usually enough. But the phrase "we used ten thousand" must be the result of your two-run check, not a rule pulled out of thin air.
- How many cluster folders there were in total and how big they were: how many authors, how many essays per author, the middle folder size (the median), and the largest one. If your corpus has only twenty authors, then no matter how many tens of thousands of times you reshuffle those twenty folders, a narrow interval will still be unreliable. An interval built from twenty authors and an interval built from two hundred authors have completely different weight, and the reader cannot see that from the final bounds alone.
- How exactly the interval bounds were cut from the ten thousand resulting numbers. There is the simple percentile method (just chop off the top two and a half percent and the bottom two and a half percent of values at the tails), and there is the bias-corrected and accelerated method, which adjusts for bias and skewness. This choice is not just for show. When reference errors in the corpus are scarce, the distribution of the summary metric comes out heavily lopsided, skewed to one side. Simply chopping off the tails on a skewed distribution gives a shifted estimate, whereas the adjusted method corrects for this skew and acceleration.
- How the numbers were averaged across the corpus: pooled together (micro-average) or by author (macro-average). In the first case, we dump all detector triggers across all students into one pile and divide once. In the second, we calculate precision and recall for each author separately, and then take the arithmetic mean across all authors. The numbers will come out different, because the second method gives huge weight to short essays of just three sentences.
- What the program did if the denominator turned into zero during a random resample. Picture this: a random sample happens to draw only short, clean essays, the detector does not trigger even once, and when calculating precision you have to divide zero true positives by zero triggers. Precision is undefined at that point. You either discard such an unlucky sample, or you agree beforehand to set precision on it to zero or one - and you must record this decision in your paper.
- Pairing when comparing two versions of the program. When you check whether a new version of the detector is better than the old one, both versions must be tested on the exact same random sets of authors. At each of the ten thousand steps, you take the drawn stack of folders, run the old detector on it, immediately run the new one on the very same stack, and take the difference. Otherwise the comparison loses its pairing, and you end up measuring the noise of the lottery itself instead of the difference between the programs.
Let us run the numbers from your project. Suppose you want to prove that the new version of your detector gives a gain of two percentage points. You run one thousand resamples with the first random seed and get an upper interval bound of seventy-two points, and with a second seed on the same texts it shifts to seventy-three and a half. The lottery itself wobbles by a point and a half - you cannot prove a two-point gain against such a shaky backdrop. You increase the number of resamples to ten thousand, do two runs again, and now the two upper bounds differ by only one tenth of a point - now your estimate stands on solid ground.
Let us test this on two students. The first wrote a long essay and made ten errors, and your detector found all ten - recall is one hundred percent. The second wrote three short sentences, made one error in the sentence "I has a dog", and the detector missed it - recall is zero percent. If we pool everything together, we divide ten found errors by eleven real ones and get over ninety percent recall. But if we average by author, we add the first student's one hundred percent and the second student's zero percent, divide by two, and get just fifty percent: a single miss in a short note crashed the entire score.
Look how easy it is to fool yourself out of nowhere here. Suppose you are testing two completely identical versions of a program, but you were too lazy to pair them up and ran the random resampling for each one separately. For the first version, the random draw happened to pick more authors with simple errors like "She have a cat", which the program catches easily, while the second version happened to get folders with hard cases that it misses. In the end, the first version will show a three-point lead over its own exact copy - and that entire gain was conjured up by folder shuffling, not by your rules.
Write it down just like that in your thesis: confidence intervals are almost never found in the literature on our topic; we introduce them because without them a two-point gain is indistinguishable from random noise, and we use a cluster method because errors made by the same author are tied to one another.
23. How to compare two versions of a detector on the same text without fooling yourself
Imagine you added a new rule to your detector. You ran the old and new versions on the exact same set of texts, and the share of detected errors went up by two percentage points. How do you know whether the new version genuinely works better, rather than just getting lucky on a couple of spots? Without a strict check, a real two-point gain and a random fluctuation from simply shuffling examples look completely identical.
Because both versions were tested on the exact same texts, every checked spot gives us a pair of answers: what the old version said and what the new version said. Such data is called paired. When algorithms can only be run on a test set once, out of five well-known statistical tests only one keeps the risk of a false alarm within reasonable limits. This is McNemar's test. Our detectors work deterministically: there is no randomness in them from initial settings or automatic training. But we ourselves chose the examples we used to tune the rules by hand. That randomness of choice remains, and we need a test against it (while an honest workflow from the next section will close this loophole for good).
How does McNemar's test work in plain terms? Suppose our corpus contains one hundred real errors. On each error, both versions of the detector give a simple answer: found or missed. The test completely ignores the errors where both versions acted the same way - where both found the error or both missed it. It only cares about the places where the two versions disagreed:
- The first group of disagreements: errors that the old version found, but the new version somehow missed after your edit. Suppose there are four of these - for instance, the new version stopped catching the error in the phrase "He don't know".
- The second group of disagreements: errors that the old version missed, but the new one managed to catch. Suppose there are sixteen of these - for example, a new rule learned to spot the error in "She have a cat".
Next, the test compares the gap between these two groups against their combined size. If you describe this step in the formal text of your thesis, be careful with your wording. You take the difference between the two groups, first subtract one from it (this is called the continuity correction), then multiply that result by itself, and divide by the sum of both groups. When written out in words, this is easy to misread: it can sound as if you should first multiply the difference by itself and only then subtract one. With our numbers - four lost errors against sixteen newly found ones - the final score comes out to just over six. In statistics, you check this number against the threshold of the chi-square distribution with one degree of freedom. For the usual confidence level (five hundredths), this threshold is three point eight four. Our number crossed the threshold - which means the new version really does catch errors better than the old one, and it is not by chance.
But McNemar's test has strict limits. You must state them yourself in your thesis, otherwise you will easily apply the test where it gives false results:
- If there are very few disagreements, the usual check against the three point eight four threshold stops working, and you need an exact binomial test.
- The outcome on each piece you check must be strictly binary: only "yes" or "no". If you count how many error spans were found in a sentence - zero, one, two, or three - McNemar's scheme no longer fits. And if the detector only clipped the edge of an error span (we looked at this kind of partial overlap earlier), that is not yet a "yes" or "no" answer. You must declare a firm rule in advance, before taking any measurements: whether to count such a near-hit as a find or a miss.
- All observations must be independent of one another. If your sample contains several sentences from a single essay by the same student, they are linked by the shared hand of their author. Classic papers on McNemar's test do not cover this case, so citing someone else's authority will not protect you - you will have to mention this dependency directly in your thesis.
And here is the biggest limitation, which makes it easiest to slip up. McNemar's test needs a shared list of test items nailed down in advance, the exact same list for both versions.
When we measure recall (the share of found errors among all real ones), we have such a shared list: it is all the gold-standard errors marked by a human. Each version of the detector either found each error on that list or did not. But even here, a trap awaits in the scoring program. If the program checks the text word by word, the list of reference words is fixed firmly and never changes. However, if it checks the text by whole spans, the program might redraw the boundaries of the reference spans depending on what your detector output! As soon as the reference segmentation shifts from one version to the next, the pairs fall apart, and you cannot use McNemar's test.
To precision (the share of true hits among all alarms raised by the detector), McNemar's test cannot be applied at all. The old version fired fifty times in certain places in the text, while the new version fired sixty-five times in completely different places. There is no shared list of trials here, and nothing to build pairs from.
Look at a single sentence, "The boy go to school every days", to see why pairs cannot form here. The old version underlined only the word "go" - that is one alarm, and it is a true one. You added new rules, and on the very same sentence the new version stayed silent on the word "go", underlined the correct word "school" as a false alarm, and then rightly caught the error in "every days". The old version had one hit in one place, while the new version had two hits on completely different words: it is impossible to line them up against each other as answers to the same question.
What does this mean for your work? Do not put McNemar's test at the center of your chapter on evaluation. Your main tool for comparing two versions across all three measures at once - precision, recall, and the combined score weighted toward precision - should be paired bootstrap or a permutation test over large independent chunks: by author or by whole essay. Never run it on individual sentences, or you will bring back the exact same problem of linked observations that we worked so hard to avoid in the previous section. Keep McNemar's test as a good secondary check only for recall, and only where the list of gold-standard errors is firmly fixed, the answers are strictly binary, and the texts are not linked by a shared author.
24. Honest measurement protocol and guarding against overfitting
All the numbers and checks from the previous sections mean nothing at all if you break the order of the measurements themselves. Before you even start tweaking the rules in your detector, you must declare in writing how you are splitting your text corpus into three parts:
Here is what this looks like in your project with concrete numbers. Suppose you have a corpus of one thousand student essays. Before writing a single line of code, you lock in the split: the first six hundred texts go into the open set for finding examples like "He go to school", the next two hundred texts become the validation set for nightly runs of your automaton, and the last two hundred texts are placed in a separate folder that your test script will not touch until the very week before your defense.
- which part you look at to read the text and tune your rules by hand;
- which part you use to take intermediate measurements as you work;
- which part stays under lock and key until the very end and is opened just once - to get the final number for your thesis.
Here an iron rule applies: one edit to the detector, one measurement. If you look at the errors in a text, write a rule for them, and measure your success on that very same text, you have not measured the quality of your detector - you have measured overfitting to a known answer.
Let us see on a live example how easy it is to fall into this trap. You open ten texts, notice three similar errors - "She have a cat", "He have a dog", and "It have a tail" - immediately add a transition to your automaton that forbids the word "have" after third-person singular pronouns, and run the detector again on the same ten texts. The machine happily catches all three cases and shows one hundred percent precision, but in reality you have simply written a cheat sheet into your rules for phrases you already knew, and on a new text with the words "My friend have a car" your automaton will stay silent.
Also, you must split the corpus by author, not just randomly by individual texts (assuming, of course, the corpus actually marks who wrote which text). This is the exact same grouping into clusters we talked about earlier, and the unit of splitting has to be the same here.
Why can't you just shuffle all the essays and randomly scoop a quarter of them into the held-out test set? Imagine one student makes the same pet mistake over and over - say, writing "I am agree with you" instead of the correct "I agree with you". If three of their essays end up in your tuning set and two in the held-out test set, you will spot this phrase while tuning and happily add a rule to your automaton specifically for the combination "am agree". Later, you unlock the held-out set, and your automaton flawlessly catches the remaining two instances from that same student. Your final score goes up, but you are fooling yourself. One person's signature habits simply leaked across the boundary between splits, and your held-out set stopped being truly held-out.
What is more, even splitting by author is only a reasonable assumption, not an ironclad guarantee of independence. Students in the same class usually write essays for the same prompt, and the same teacher grades and annotates them. For example, a whole class gets an assignment about summer vacation, and half the kids write the exact same error, "In last summer I went to the sea", sticking an extra preposition at the start. Here, a connection pops up between different authors. So look closely at what metadata your corpus gives you about the texts:
- if classes, schools, or prompt IDs are marked, be sure to state in your thesis which exact level you chose as your independent unit for splitting, and why;
- if the corpus has no such metadata, honestly state this in your paper as a limitation of your study.
Look at how the numbers shift when you change the splitting unit. If your corpus has 120 students who each wrote five essays on three different topics, splitting by author gives you 120 clusters of five texts each to distribute across your sets. But if you decide to split by prompt ID so that topic-bound phrases like "In last summer I went to the sea" do not end up on both sides of the boundary, you are left with just three huge clusters of 200 essays each. Two will go into tuning and validation, and the third will go entirely under lock and key.
Before the automaton and after the detector: three things no course teaches you
Your thesis assignment puts these three questions right in your face, yet university courses usually stay silent about them. This is not high theory. But if you miss even one of them, all your pretty charts and tables will end up measuring something completely different from what you promised in your introduction.
25. Where word classes come from, and who is to blame for input errors.
Your rule automaton cannot read raw English words. It expects a sequence of grammatical tags as input: the "pronoun" class, the "modal verb" class, the "plural noun" class. But the user sends you plain text made of words. That means there has to be a separate program sitting in front of your automaton that hangs a grammatical tag on every word. That program is called a part-of-speech tagger. And here is the catch: that tagger is fallible too, and it makes mistakes.
English is full of common words you cannot figure out without context: "run", "can", and "that" can be verbs, nouns, or conjunctions. When a tagger reads clean text, it guesses the part of speech from the neighboring words. But the text coming into your system has grammatical errors in it! On a broken sentence, the tagger gets confused and misfires more often than on a clean one. By the way, you cannot just drop this claim into your thesis on faith: you either need to back it up with a citation to someone else's published paper, or verify it with your own measurements on your texts. And you certainly cannot write a vague sentence in your report like "almost every word in English is ambiguous". The exact share of words that have multiple parts of speech in your data is a specific number - you have to actually count it on your texts and report it.
Look at the erroneous sentence "He have a book". In correct English, the pronoun "He" is never followed by the verb form "have", though it is often followed by an auxiliary verb and a participle. Meanwhile, the word "book" is listed in the dictionary not just as a noun, but also as a verb (as in booking a room). Thrown off by the error in "have", the tagger tries to salvage a coherent reading and tags the last word as a "verb" instead of a "singular noun" - even though on the well-formed sentence "He has a book", it has no trouble recognizing "book" as an ordinary noun.
Let us see what happens inside the machine on a concrete example. Suppose we get a five-word sentence: "They can fish in April". The word "can" might be a modal verb (able to), a noun (a tin can), or an ordinary main verb (to put food into cans). The word "fish" can be a verb (to catch fish) or a noun (the animal). The tagger looks at the words, makes its best guess, and feeds a single chain of tags to your automaton. If the tagger guesses wrong on "can" and labels it a noun, your automaton will see the sequence "pronoun - noun - noun" and flash a red light where there was no error at all, or else miss a real error.
So it turns out that some of your false alarms and frustrating misses are not caused by your automaton at all, but by the tagger standing at the front door. In your thesis, you need to clearly separate these two sources of error. You have two honest ways to set up this input stage:
- The first way: the tagger outputs exactly one tag per word, its single best guess. In that case, you must separately measure how often the tagger itself gets things wrong on your texts, and report that accuracy figure directly in your thesis.
- The second way: you do not force the tagger to guess. Instead, you pull all possible tags for each word straight from the dictionary. Then, at the word "can", the path splits into a three-way fork, and at "fish" it splits into two more. The input to your automaton is no longer a single thread; it becomes a branching, loop-free network where all paths run left to right from the start of the sentence to the end. This network of possibilities is called a lattice (essentially, it is a small acyclic automaton that holds every possible reading of a single sentence). To check an error rule against this network, your system has to overlay the rule automaton onto the lattice and find their shared paths - which is what we call automaton intersection. This approach never drops the right tag, but it runs slower and costs more.
Let us check this by counting the paths through our sentence "They can fish in April". As long as the tagger gave one tag per word, there was only a single path through these five words, and your automaton took ровно five steps. But once the lattice opens up three options at "can" and two more at "fish", even if the remaining words are completely unambiguous, our short sentence now has six different parse paths running through it. And if two other neighboring words each bring three options from the dictionary, the number of end-to-end paths through this tiny network shoots up to fifty-four.
Whichever of the two routes you choose, you must state it plainly in your paper. And if you choose a lattice, that alone is not enough: you also have to agree in advance on when exactly to sound the alarm. After all, several different parsing paths now run through the lattice for the sentence "They can fish in April". Is it enough for an error pattern to trigger on at least one path, or must the error show up on every path at once? In logic, this kind of selection condition is called a quantifier: the first rule is the "there exists a path" condition, and the second is "for every path".
Let us see the difference between them on that same perfectly sound sentence, "They can fish in April". Among the six paths in its lattice lies one absurd path where both "can" and "fish" are taken as nouns. On this single path, your automaton - which looks for the error of two nouns in a row without a link - is guaranteed to light up its red warning lamp. Under the "there exists a path" condition, that one trigger is enough for the detector to declare a correct sentence wrong. Under the "for every path" condition, it will look at the remaining five paths, see a modal verb in place of "can" with no error at all, and refrain from raising a false alarm.
And there is more! Your detector cannot just blink a light saying "something is wrong in this sentence"; it must point a finger at the exact piece of text containing the error - a highlighted stretch from one word to another like this is called a text span. As soon as the machine is required to name the location, our condition doubles: both parsing paths and positions in the sentence enter into it. And here the order of words in the rule changes everything. Look at the two different conditions you can demand:
- First condition: on every parsing path, at least some suspicious span was found (for every path, there exists a span with an error).
- Second condition: there is one specific span of text where the error is visible under every parse at once (there exists a span that yields an error on every path).
Let us run this on our five-word sentence. Suppose that along the first parsing path the automaton spots an error on the second word, and along the second path, on the fifth word. What will our conditions say? The first condition will happily trigger: after all, no path was left without an error; something turned up everywhere! The second condition will stay silent: there is not a single word in the sentence where the error holds on both paths at once. See what a gulf lies between them? That is why you cannot just toss the word "exists" into your report - you must write out the whole order in full words and declare it before you start measuring quality.
Your choice of condition hits your final numbers directly. If you decide to raise an alarm whenever an error is found on at least one path of the lattice, then compared to a single tagger your detector will find no fewer real errors, but it will also produce no fewer false alarms (whether they actually go up or stay the same depends on your texts, but they cannot drop). Why is that? Because now even the rarest, most exotic dictionary reading of a word sets off the alarm. This property - where expanding the input guarantees that the number of triggers will not drop - is called monotonicity.
Look at the perfectly grammatical sentence "The old man the boat", where the word "man" serves as a rare verb meaning "to staff" or "to operate". A single tagger confidently hangs the familiar label "singular noun" on "man"; the rule looks for a predicate after it, sees no direct agreement error, and stays silent. In a dictionary lattice, however, the word "man" has a second path besides the noun - "plural verb". The automaton runs down this rare path, sees the subject "The old" or an article before it that does not fit such a verb form at all, and raises a false alarm right where the single tagger would have walked on by.
Still, this neat property has a catch - two of them, in fact. First, it rests on a hidden assumption: we quietly assume that the one path a single tagger would have chosen is necessarily present inside our dictionary lattice as well. What if the tagger panicked and hung such a rare label on a word that your dictionary does not list it for that word at all? Then the lattice does not expand the tagger's choice; it replaces it with a different set, and you can no longer compare them as "a wide view versus a narrow view". You need to check this assumption with a simple count: take a thousand words from your text and count how many of them have the single tagger's label actually present in the dictionary list for that word. Suppose 960 words out of a thousand match - report that share right next to your argument about numbers not dropping.
Second, the guarantee that triggers will not decrease holds fast only for the raw triggers of the automaton itself. As soon as rules for merging neighboring spans and rules for matching against the gold standard kick in after the automaton, that ironclad guarantee vanishes. An extra trigger on a new path might simply stick to a neighboring span, merge with it into a single blot, and add neither a new true hit nor a new false alarm. So while non-decreasing numbers on raw triggers are guaranteed by the very logic of the device, whether your final true hits and false alarms actually go up can only ever be checked by a live test on real texts.
Let us test this on a live example with the broken sentence "He have went home". On the single tagger's path, only the first rule triggered and highlighted the span from the second word to the third ("have went"). When we switched to a dictionary lattice, a second rule woke up on a new path as well and highlighted the third word ("went"). The automaton now had two raw triggers instead of one, but then the merging of nested pieces kicked in: the short span on the third word simply dissolved inside the longer span from the second word to the third, leaving the exact same single alarm blot at the output after merging.
And one last thing at the input stage that people often forget: slicing the text into individual words and punctuation marks. This operation is called tokenization, and the slicing program itself is a tokenizer. You must slice the text into words using strictly the exact same tokenizer both in the gold-standard annotation and inside your detector. If the gold standard counts "don't" as two words while your detector counts it as one, all the word numbers will drift, the boundaries of highlighted spans will come apart, and your measurements will turn into a pumpkin.
Here is how this looks in your project on the sentence "I don't know this rules". The error is right at the end - the word "this" does not agree with the word "rules". The gold-standard tokenizer splits "don't" into two parts ("do" and "n't"), so in the reference data the whole sentence has six words, and the error is recorded on the span from the fifth to the sixth word. Meanwhile, your detector's tokenizer keeps "don't" as a single piece, sees only five words in the sentence, quite rightly finds the error on the words "this rules", and outputs a span from the fourth to the fifth word. During evaluation, the scoring program compares your answer "fourth to fifth" against the reference "fifth to sixth", sees a boundary mismatch, and penalizes you for a miss right where your automaton worked flawlessly.
26. What to do when rules fight over the same spot.
Your system has one hundred and eighty-two rules. Each of them is a separate little automaton that runs along the sentence and knows nothing about the others. Naturally, on real text these rules will constantly bump elbows: the error spans they flag will overlap or sit completely inside one another.
Let us see how this happens in practice. Suppose a clumsy four-word sentence comes in: "He have went home". Your first rule catches subject-verb disagreement on the words "He have" and flags a suspicious span from the second to the third word ("have went"). The second rule checks irregular verbs after "have", sees the awful "have went" instead of "have gone", and flags a span on the third word ("went"). And there they collide: one span covers words two to three, while the other sits right inside it on word three.
Before you go to compare the machine's answers against the gold standard and count how many times you hit the bullseye, how many times you raised a false alarm, and how many real errors you missed, your system must decide what to do with this dogpile on the third word. The rule for clearing such logjams is called an overlap resolution policy. You have three honest options to choose from:
- Merge all overlapping and nested pieces into one long combined span. In our example, both triggers will merge into a single span from the second to the third word. The huge advantage of this merging is that the result does not depend at all on the order in which your one hundred and eighty-two rules were checked.
- Pick only one trigger based on a pre-written priority list of rules, and suppress the rest at that spot. Here, of course, the result depends entirely on how you ranked the priorities in your table.
- Count every trigger as a separate error, or keep only the "first triggered" rule and discard anyone who arrived at that spot later. And here you must be careful: a "first come, first served" rule depends directly on the order in which the rules are written as lines in your text file!
Think about what that threatens. If you do not declare a policy in advance and silently leave it as "first triggered wins", then the moment you accidentally swap two lines in your rule file, the number of false alarms on the exact same text will change! Comparing yesterday's and today's versions of your detector will become completely pointless. That is why, in your thesis, you first declare your chosen policy out loud, and from that policy it is immediately clear whether you are required to nail down the order of rules in your file for good or not. This is a fundamental design choice, not a minor programming detail.
Let us return to our sentence "He have went home" and imagine that in the gold standard the error is marked strictly on the third word ("went"). Yesterday, the rule for irregular verbs sat higher up in your text file: it fired first, grabbed the third word, suppressed its rival, and the evaluation credited you with an exact match against the reference. Today, you tidied up the file and moved the subject-verb agreement rule to the top: now it stands first in line, flags the span from the second to the third word ("have went"), and the rule for the third word is discarded as arriving too late. Under strict boundary matching, the span from the second to the third word no longer matches the reference third word - and yesterday's true positive turns out of nowhere into both a false alarm and a missed error.
27. The budget for calling on big brother, and the contract between stages.
Under the terms of your assignment, the fast automaton checks the entire stream of text, whereas the heavy, smart language model is called in to help in no more than five cases out of a hundred. What does this mean for how the machine is built? It means that your first stage - the automaton - has a strict quota, a tight budget for "phoning a friend". And you must measure the quality of the automaton with an eye on that wallet.
Usually, standalone grammar detectors are evaluated with a special combined quality measure where precision is valued twice as high as recall - meaning the machine gets its knuckles rapped hard for every false alarm. But in our two-stage pipeline, the automaton has a completely different job! It does not need to squeeze out spotless precision on its own. Its goal is to catch as large a share of real errors as possible (that is, to deliver maximum recall) while staying within its five-percent limit on referrals upstairs. After all, we are deliberately building a two-story system counting on the second stage - the language model - to look at the doubtful spots passed up to it, weed out the false alarms on its own, and supply the needed precision.
If you start tuning the first stage using the standard strict measure that penalizes extra triggers, you will be punishing your automaton for the exact thing it was put there to do - passing doubts upstairs! You will be solving the wrong problem. Of course, our hope that the language model will neatly clean everything up is itself only a working assumption. You cannot take it on faith: on hard cases, the model might drop the ball too. Whether this whole setup pays off is something only a live measurement of the entire pipeline can show.
From this grow three strict requirements for your thesis, without which your report will not be accepted.
First requirement: you must describe in plain words the rule by which your automaton decides that it is "in doubt" in the first place. After all, an ordinary deterministic automaton is a straightforward machine; it has no internal confidence scale from zero to a hundred, it only knows how to light up a bulb or stay silent. That means you yourself invent and tune the rule for selecting doubtful spots to send upstairs (for example, by the type of rule that fired or by the length of the string), and you must present that rule.
Second requirement: you must clearly state the denominator of your five-percent quota. Put simply: five percent of what, exactly? What are we taking as one hundred percent? The assignment prompt does not say, and yet you can calculate one hundred percent from completely different things:
- From the total number of documents (texts) being checked.
- From the total number of sentences.
- From the total number of individual words and punctuation marks in the text.
- From the total number of times your automaton triggers.
- From the total number of grammatical constructions in the text that your rules are hunting for in the first place.
Let's do a quick back-of-the-envelope calculation to see the difference here. Suppose your test set has exactly one thousand sentences (containing ten thousand words), and your automaton lights up two hundred times. If we take all sentences as our one hundred percent, then five percent of a thousand is fifty calls to the language model. But if we take only the automaton's triggers as our one hundred percent, then five percent of two hundred is just ten calls! The budget differs by a factor of five. Until you yourself declare which one hundred percent you are taking a share of, the phrase "we call the model in no more than five percent of cases" means nothing at all. It is impossible to verify.
The third requirement: you need to plot a graph where one axis shows the fraction of cases sent to the model, and the other shows the fraction of true errors caught (that is, recall). This curve will make it immediately obvious whether you stayed within the five-percent budget or not. And right here you must be extremely careful: there are two kinds of recall in this task. They measure different things, and confusing them is a fatal mistake.
- The first quantity is selection recall. It shows what fraction of all true gold-standard errors made it into that five-percent basket you sent to the language model. This metric evaluates your first stage as a sieve: how well the automaton fishes the right stones out of the stream.
- The second quantity is system recall. It shows what fraction of all true errors your entire two-story structure ultimately found after the language model delivered its verdict.
Do you see the difference? A great sieve does not guarantee a great final output: your automaton might honestly put a tricky error into the basket and send it upstairs, and the language model will look at it and mistakenly say "everything is clean here".
Therefore, before doing any tuning or plotting any graphs, you must declare the architectural contract between the first and second stages. The absolute ceiling of what your system can achieve depends on this agreement. Two different architectures are possible here:
- Architecture one: the language model double-checks only the places where the automaton has already raised an alarm. In this setup, the second stage works strictly as a censoring filter: it can only cancel the automaton's false alarms, but it cannot find an error where the automaton stayed silent. This means the final recall of your entire system can never rise above the recall of the automaton itself, no matter how brilliant a language model you plug in! On the bright side, the goal of the first stage is crystal clear here: squeeze out maximum recall within the five-percent budget.
- Architecture two: we allow sending to the language model not only the automaton's triggers, but also certain suspicious places where the automaton's rules stayed silent (selected by some separate indicator of doubt). Then the hard ceiling of the first architecture is lifted: the model can find errors outside the automaton's rules as well. But you have to pay for this twice. First, the five-percent budget must now accommodate all packages sent upstairs, not just the double-checking of alarms. Second, your first stage gets a brand-new second job - somehow sniffing out suspicious places while the rules stay silent.
Look at how this double price plays out in numbers from our text with one hundred errors. Suppose the five-percent basket holds exactly eighty snippets of text, and your automaton, following its rules, again found sixty true errors: it kept twenty obvious ones downstairs, and prepared forty doubtful ones along with forty false alarms to be sent upstairs. In the first architecture, these eighty snippets would fill the entire basket, and the language model would receive all forty of the automaton's questionable triggers. But in the second architecture, you decided to give twenty spots in the basket to quiet, suspicious phrases like "He gave me some good advices", where there is no article "a" and the automaton stayed silent. To fit into the same five percent, you will have to throw twenty actual triggers of the automaton itself out of the package, and some of the errors it already caught will never even make it to verification.
Let's trace the difference between the two recalls with a live count for the first architecture. Suppose exactly one hundred true errors are hidden in the test text. Your automaton ran through the text and found sixty of them (plus a bunch of extra junk on top). That means the recall of the automaton itself is sixty out of a hundred; for the first architecture, this is the ceiling above which the whole system will never jump. Next: the automaton kept twenty completely obvious triggers for itself without any verification, while you packed the remaining, doubtful triggers into the five-percent quota and sent them to the language model. Suppose the remaining forty true errors ended up inside this dispatched batch. Then the selection recall in the transmitted batch is forty out of a hundred. The language model opened the package, cleaned out the junk, confirmed thirty-five true errors, and mistakenly rejected five. As a result, on the transmitted batch the model gave thirty-five out of a hundred, and the whole system in total (twenty kept downstairs plus thirty-five confirmed upstairs) found fifty-five errors out of a hundred. That is the system recall.
Until the contract between the stages is named, it is completely unclear what quantity your automaton is fighting for. Therefore, in your report, you first declare the contract, and then calculate both recalls separately and call them by their proper names.
Team self-check
Six questions for your team before you start. If you can answer them easily right now - you have mastered the material. If you stumble on something - you know exactly which topic to reread.
1. Three similar rules, their automata, and the cost of a gap between words
Let's take three simple finder rules and build the smallest deterministic automaton for each. All words in the text are now divided into three classes for us: the "determiner" class (for example, the article "a"), the "noun" class (for example, the misspelled word "advices"), and the "other word" class (everything else).
- The first rule looks for an adjacent pair in the text: first comes the "determiner" class, and right after it, without a single word in between - the "noun" class. Such a rule will catch the error in the phrase "He gave me a advices", because "advices" stands immediately after "a".
- The second rule looks for a pair with an arbitrary gap: somewhere in the text the "determiner" class appeared, and later, after any number of other words - the "noun" class. It will trigger on the phrase "He gave me a very good advices", stepping right over the words "very good".
- The third rule checks that the entire input text consists of exactly two words: the first is the "determiner" class, the second is the "noun" class. Just a short string "a advices" and not a single word around it.
To make a fair size comparison between the machines for these three rules, you must use complete automata. A complete automaton is a machine where every state has an outgoing arrow for every possible word class - including arrows leading to a special trap state, where the machine falls and can never leave once the text has no chance of matching. If you leave some arrows out, comparing the number of states is pointless.
Let us step through all three machines and count their states:
- The machine for the adjacent pair. In the start state, it waits for the "determiner" class. The word "He" arrives (class "other word") - the machine stays at the start. Then "a" arrives (class "determiner") - the machine steps into the second state, "just saw a determiner". If the next word is "very" (class "other word"), the chain breaks, and the machine drops back to the start. If another determiner comes along, it stays in the second state. But in the sentence "He gave me a advices", the next word is "advices" (class "noun"), so the machine moves to the third, winning state: "pair found". Since an error has already been spotted in the text, any further words keep the machine in this third state. No trap state is needed here: from any point, you can still reach a win. That gives three states in total.
- The machine for the pair with a gap. At the start, it likewise waits for the "determiner" class and skips past "He gave me". Upon seeing "a", it steps into the second state, "already saw a determiner". From here on, though, it behaves differently! When the words "very" and "good" (class "other word") arrive in "He gave me a very good advices", the machine does not reset to the start. Instead, it calmly loops in the second state and patiently waits for a noun. Once "advices" arrives, it steps into the third, winning state, and stays there until the end of the text. Again, no trap state is needed. The total is the exact same three states!
- The machine for a text of exact length two. At the start, it waits for the "determiner" class. It sees "a" and steps into the second state, "first word is right". Next, it sees "advices" and steps into the third, winning state, "read the exact two words needed". What if the first word is "He"? Or the second word after "a" is "very"? Or a third word arrives after the valid pair "a advices"? In all these cases, the text can never again become a two-word string of the required kind. The machine follows those arrows straight into a fourth state - the trap state - and loops there until the end. That makes four states in total.
Look at what we got: the first two rules have three states each, and the third has four. The number of states in the automaton does not distinguish an adjacent pair from a gapped pair at all! How do they differ, then? They belong to different classes inside the regular languages - such narrow families are called subregular classes. When a machine only tracks which short chunks of a fixed length appear in the text (like our two-word sliding window for an adjacent pair), the language is called locally threshold testable. And when a machine tracks the order of words at any distance from one another (first came a determiner, and somewhere later a noun), the language is called piecewise testable. Naming the class for each of the three rules and explaining why it belongs there is the easiest question to trip up on. Be sure to state which of these three languages your own rule defines.
Let us test this difference on the sentence "A boy gave me good advices". If we only look at the text through a sliding window of two adjacent words, we will see the consecutive pairs "A boy", "boy gave", "gave me", "me good", and "good advices" - in none of these windows do the "determiner" class and the erroneous word "advices" sit next to each other, so for the first rule and its locally threshold testable language, this sentence is clean. The second rule, however, looks for a subsequence at any distance: it spots the word "A" at the very beginning, skips over "boy gave me good", and catches "advices" at the very end. For a piecewise testable language, only the order of these two milestones across the whole sentence matters, so on the exact same sentence the second machine will hit the red button.
Now connect these three rules to fast dictionary pattern matching - the Aho-Corasick algorithm. This algorithm can scan the text in a single pass and search for a whole set of ready-made sequences at once, but only if each sequence is given as a solid keyword without gaps. Because of this, our first rule (an adjacent pair of a determiner followed right away by a noun) goes straight into an Aho-Corasick automaton as a single intact keyword. The second rule (a pair with an arbitrary gap), however, cannot be put in without expanding it first! To squeeze a gap into the Aho-Corasick algorithm, you would have to expand that hole in advance into all possible chains of intervening words of every length - and there are infinitely many of them.
Here is what it looks like when you try to build a pattern dictionary for our second rule. To catch the gapless error in "He gave me a advices", you put one two-class sequence into the dictionary: "determiner" followed directly by "noun". To catch a one-word gap, as in "He gave me a good advices", you have to add a second sequence of three elements: "determiner", "other word", "noun". For "He gave me a very good advices", you need a third sequence of four elements, and for "He gave me a really very good advices", a fourth one of five. No matter how many thousands of such patterns you load into the Aho-Corasick automaton ahead of time, there will always be a sentence with one more extra word in the middle that your dictionary will miss.
And here is the main rule of good practice on the team. If you decide to relax your rule and allow other words in between, do not say at your defense, "we just added a gap". State it precisely, along with the cost of moving from one class to another: our language used to be locally threshold testable with a window of two words, and it became piecewise testable with a chain length of two words, and the price of this shift is such-and-such many extra false alarms on such-and-such validation text sample.
Look at a live example to see where this cost comes from. While your rule was locally threshold testable with a two-word window, it looked for the class "singular article" followed right away by "plural noun", so it only caught solid chunks like "a cats". When you made the language piecewise testable with a chain length of two words, the automaton started waiting for those same two classes anywhere in the sentence, as long as the first came before the second. As a result, it caught the erroneous gapped phrase "a very cats", but along the way it raised a false alarm on the completely valid sentence "A dog chased cats", where the article "A" belongs to "dog" and the word "cats" sits at the very end. If on a validation sample of one thousand sentences your new rule caught ten real errors with a gap, but brought in two hundred false positives like this, then those two hundred extra alarms are the exact price of your shift.
2. Identical chains of word classes and the limits of your detector
Come up with two English phrases that look completely identical to the automaton once the words are replaced by their grammatical classes, even though one phrase is correct and the other contains an error.
Take, for instance, our rough tagging system that just has a "determiner" class and a "noun" class. The phrase "a cat" turns into the sequence: "determiner" class, followed by "noun" class. And the erroneous phrase "a cats" turns into the exact same sequence: "determiner" class, followed by "noun" class. Or, if the tagging is a bit more detailed and splits nouns by number, take two phrases with the uncountable word "advice" and the countable word "device": to a standard part-of-speech tagger, the erroneous phrase "an advice" and the flawless phrase "a device" both look like the exact same sequence: "singular article" class, followed by "singular noun" class.
What does a pair of phrases like this prove? A very simple, hard truth: no automaton, no matter how clever, working on top of your chosen sequence of classes can catch the error in one phrase while leaving the other alone. In both cases, the machine is fed the exact same sequence of symbols! The machine is simply blind to the difference between them.
And what does this pair of phrases not prove? It does not prove at all that English grammar cannot be described by automata, or that finite automata are useless here. The problem is not with how the automaton works, but with your input alphabet - you yourself erased the necessary information when you lumped the countable word "device" and the uncountable word "advice" into a single shared class, "singular noun".
That is why the famous Myhill-Nerode theorem has nothing to do with this. What does the Myhill-Nerode theorem say? It helps you find the smallest automaton for an alphabet you have already chosen: it takes two different strings of symbols from that alphabet and checks whether they can be distinguished by appending some continuation to the end. Here, though, our strings of symbols are not different - in our alphabet, they are literally the exact same string! No math in the world can tell identical strings apart. What you need here is not to multiply the states of the automaton, but to change the alphabet of classes itself.
Let's check how this works when the strings of symbols actually are different. Take two short strings from our alphabet of classes: the first consists of a single "singular article" class (like after the word "a"), and the second consists of a single "singular noun" class (like after the word "cat"). Now append the exact same continuation to both strings - the "plural noun" class, such as the word "dogs". The first sequence turns into the erroneous phrase "a dogs" and drives the error-detecting automaton into an accepting state, while the second becomes the fragment "cat dogs", where there is no article error, and stays in a non-accepting state. Since the exact same continuation sends these two different sequences to different answers, the theorem tells us that the automaton must remember the difference between them using two separate states.
3. Two different meanings of the phrase "no determiner to the left" and the price of negation
Suppose you are writing a rule to find a missing article, and you need the condition "there is no determiner to the left of the noun". Before building the machine, you have to state clearly which language you actually mean, because that everyday phrase hides two completely different meanings!
- First language: "there is a noun in the text that has no determiner to its left".
- Second language: "it is not true that a determiner appears somewhere to the left of a noun in the text".
Do those sound like the same thing? Let's test them on a short three-word phrase: first comes the "noun" class, then the "determiner" class, and then the "noun" class again - for example, the text fragment "cats a dog".
What will the first rule say? It looks at the first word, "cats". Is it a noun? Yes. Is there any determiner to the left of it in this phrase? No, it is the very first word! So the required noun has been found, and the first rule fires on the string "cats a dog".
And what will the second rule say? First, it checks the statement "a determiner appears somewhere to the left of a noun in the text". In our string "cats a dog", we have the word "a", and to the right of it sits the word "dog". So the statement turns out to be true! But the second rule starts with "it is not true that...". Since the inner statement is true, negating it gives false, and the second rule will not fire on the string "cats a dog". See that? On the exact same three-word sequence, two interpretations of the same plain-language phrase give opposite answers!
Now let's look at how the second rule is built in terms of operations on languages. When we say "it is not true that the string belongs to the language", we are taking all possible word sequences and throwing out the ones that matched the original condition. This operation on languages is called complementation (or negation).
Will a regular language stay regular if you take its complement? Yes, it definitely will. To make a machine look for the complement, you just take the existing automaton and swap its accepting and non-accepting states: everything that used to be accepted is now rejected, and vice versa.
But what is the price you pay for this operation? You can only swap accepting and non-accepting states in a deterministic and complete automaton! If your original machine was branching (nondeterministic) - meaning it could make several guesses at once on a single word - you cannot just recolor its states. If you did, the machine would start accepting strings where at least one guessing branch hit a dead end, even if another branch found the error. So before taking the complement, you have to force the branching automaton to become deterministic. And at every step, a deterministic machine has to remember not just one state, but the entire set of current guesses that the branching machine is making all at once. If a small branching machine had three states, there are already eight different sets of them; if it had ten states, there are over a thousand sets; if twenty, over a million!
This explosive growth in the number of states when converting to a deterministic machine (called a combinatorial explosion, or exponential blowup), plus having to add a trap state to make the automaton complete, is the price you pay for a seemingly harmless "no" in your rule.
Let us run such a branching machine step by step on our phrase "cats a dog" to see this failure with our own eyes. Suppose the original automaton looks for a determiner standing to the left of a noun: in the start state, at each word, it both stays put (first guess - the determiner we want is still ahead) and, if it sees a determiner, steps into the second state to wait for a noun, and once it sees one, moves into the third, accepting state. On the string "cats a dog", one branch will step into the second state on the word "a" and reach the accepting third state on the word "dog", while another branch will sit in the first, non-accepting state through all three words. If we now simply swap the colors of the states, the third state becomes non-accepting, while the first becomes accepting! And then the recolored branching machine will accept the string "cats a dog" thanks to that very lazy branch that stayed in the first state, even though the string contains the piece "a dog" and should not have been accepted.
4. Partial overlap of error boundaries and the rules of fair measurement
Imagine a situation during the testing of your detector: in a ten-word sentence, a human expert (our gold standard) marked an error on the span from the fourth to the sixth word inclusive - for example, the three words "a very advices". Your detector, however, fired only on the fifth word ("very"). Question for the team: does this count as a hit?
The main rule of honest research: you must state and justify your answer before you run the evaluation and see the final numbers! If you look at the results first and then decide whether to count such half-matches, you will be fitting the answer to the number you want.
Let us see how such fitting happens on concrete numbers when testing one hundred sentences, each containing exactly one error like "She gave me a very advices today". Suppose that in sixty sentences your detector highlighted the entire span "a very advices", and in thirty more cases it caught only the single word "very". If you did not agree on the rules in advance and first looked at the sad sixty hits out of a hundred, you will be sorely tempted to declare after the fact that catching the word "very" is a full victory and report ninety caught errors.
The standard evaluation tool for grammatical error correction in English has different strictness modes for error boundaries (text segments known as spans).
- In the standard, strict boundary-matching mode, a hit is counted only when the start and end of your mark match the start and end of the gold standard exactly. In this mode, firing on the fifth word when the gold standard spans the fourth through the sixth word is a miss! Worse still, you get a double penalty: the tool records one false positive (you wrongly underlined the fifth word on its own) and one false negative (you failed to find the true span from the fourth to the sixth word).
- If, however, you agreed in advance with your advisor that your goal is simply to draw the reader's attention to the right place in the phrase, you can choose a lenient boundary-overlap mode (or evaluate at the level of individual tokens). In that mode, any overlap between your mark and the gold-standard span counts as a hit, and word number five earns you a point. Which mode you choose and why it fits your task, though, must be locked in beforehand.
Let us calculate this double damage on a corpus of ten sentences with one error in each, where in nine phrases the detector highlighted the exact gold-standard boundaries, and in the tenth phrase, "He needs a good informations right now", it underlined only the word "informations" instead of the gold span "a good informations". Your program gets credit for only nine true positives, even though you noticed something wrong in all ten sentences. For the tenth phrase, the evaluation tool hands out two penalty points at once: one false negative for the missed span "a good informations" and one false positive for the isolated word "informations".
Let us return to the same set of ten sentences where, in the tenth phrase "He needs a good informations right now", your detector marked only the word "informations" inside the gold-standard span "a good informations". Because the word you highlighted lies right inside the boundaries of the expert annotation, in the lenient boundary-overlap mode the tool will count it as a full tenth hit. As a result, instead of nine true positives and two penalties, your report will quite legitimately show ten found errors out of ten and zero penalties.
5. Recall went up, precision went down - did things actually get better?
Suppose you added new rules to your detector. After that, recall (the share of real errors found among all errors in the text) grew from twelve percent to nineteen percent, while precision (the share of real errors among all times your detector fired) dropped from forty percent to thirty-six percent. How can you tell whether you came out ahead or behind overall?
In our field, precision is valued twice as much as recall: it is better to miss someone's error than to underline a perfectly good word in red and confuse the person. For this reason, we use a combined quality measure weighted toward precision. Given two known numbers - precision and recall - this combined measure before and after your changes is computed completely unambiguously (when recall rises from twelve to nineteen percent and precision drops from forty to thirty-six percent, the combined measure goes up noticeably).
There is a catch, though! By itself, this number means nothing until you state plainly what stood in the denominators of your fractions and how you averaged the results across different texts. After all, a test set contains many essays by different authors: one person wrote a long text and made fifty errors, while another wrote a short one and made two. There are two ways to calculate overall precision and recall:
- The first way is to dump all errors and all detector firings from all texts into one big pot and divide once. This is called the micro-average. Here, long texts by poor writers will carry much more weight than short texts by proficient ones.
- The second way is to calculate precision and recall separately for each author, and then take the arithmetic mean of those percentages. This is called the macro-average. Here, every author affects the final score equally, regardless of how long their text is.
Micro-averaging and macro-averaging on the very same data give different numbers! And from the bare statement "precision became thirty-six percent, recall nineteen", there is no way to tell which of the two methods produced those percentages.
Let's do the math using those two authors from the previous paragraph. Suppose the first one made fifty errors in a long essay, and your detector caught ten of them (recall on the first author is twenty percent), while the second made just two errors in a short essay, and the detector caught both (recall on the second author is one hundred percent). If you lump everything together into one pot for a micro-average, you get twelve errors caught out of fifty-two, which is about twenty-three percent recall. But if you take the macro-average - that is, simply average the first author's twenty percent and the second author's one hundred percent - recall shoots right up to sixty percent, even though the detector and the texts haven't changed at all.
And even when you have honestly stated your averaging method and calculated that the overall quality score went up, that difference by itself still does not prove that your detector actually got better! Why? Because on a small sample of texts, a gain of a couple of percent could have happened by pure chance - your new rules just got lucky and hit a few frequent typos in a couple of long essays. To rightfully call this difference a real improvement, you need an extra statistical check: a paired significance test on the exact same texts (such as McNemar's test or a paired permutation test), which will show that such a lead in favor of the new detector version is extremely unlikely to happen by chance.
Here is what this looks like in your project with concrete numbers. Suppose that across the entire test set, the old and new versions of your detector behaved the same almost everywhere, and disagreed in only twelve places: in seven cases the new version caught an error like "a cats" that the old one missed, and in five cases, conversely, it falsely underlined a correct word in red that the old one left alone. A seven-to-five lead easily comes up when you just flip a coin, so McNemar's test on that score will tell you there is no proven improvement. On the other hand, if on the same texts the new version had won in forty disputed places and lost in only five, the test would confirm that a lead like that almost never happens by accident.
6. What we tune on, what we test on, and the shared-author trap
The last question before you start is the most important one for the integrity of your whole thesis. Which texts do you use to design and tune your rules (the training and development sets), and which texts do you use to measure the final quality score for your report (the evaluation, or test set)?
Suppose you honestly split all the texts you have into two separate folders: you used the first folder to study errors and tweak your automata, and you kept the second folder locked right up until defense day, measuring your final quality on it just once. However, the texts in both folders were written by the exact same people (for instance, you took five essays from each student, put four into the tuning folder, and put the fifth into the test folder).
If you did this, you need to clearly understand what you actually measured. You measured how well your rules learned the personal habits, favorite words, and typical mistakes of these specific authors! If one student stubbornly writes "a advices" in every single essay, you spotted it in the tuning folder, added a rule specifically for that word, and happily caught the exact same error in their fifth essay from the test folder.
What does your pretty final score not mean in this case? It does not mean at all that your detector will show the same quality on texts written by new, unfamiliar people who weren't in your sample! To honestly measure how the system works on the English language in general, rather than on twenty students you know, you must split your dataset strictly by author: every single text by a given person must go either entirely into tuning or entirely into final testing.
Let's check this with a live example using that same student who loves the word "advices". In the tuning folder, you saw them write "a advices" four times, hard-coded a reaction to that exact word into your automaton, and got a one-hundred-percent hit rate on that same student's fifth essay in the test folder. But then, after your defense, someone runs your detector on essays from a new cohort where nobody writes "a advices", and instead the new authors write "an informations" and "a furnitures". The rule tailored to your old acquaintance stays silent, and the pretty precision from your presentation slides instantly falls apart.
How to get the sources
A bibliography won't turn into a thesis by itself if you can't actually open and read the papers. So let's sort out right away where to get the texts, so you don't waste time on dead-end searches and locked doors.
A lot of material is in open access, and you don't even need a university network password for it. Imagine you need to understand how your test set is built, where people make mistakes and write "He go to school" instead of the correct "He goes to school", and how programs catch and score such slips in the first place. You just go to the free open archive of computational linguistics papers and download the core works on our topic without any registration. There you will find the proceedings of the shared task on error correction, papers on the standard match scorer, and papers on the automatic annotator that sorts corrections into buckets by error type on its own. You will also find papers on the formal language classes used to describe such rules. Beyond this main archive, other things we need are also freely available right on the web:
- open-access issues of journals on universal computer science and theoretical linguistics with recent surveys
- an author-posted draft chapter on syntactic semigroups and a public preprint archive of scientific papers
- older university technical reports on fast algorithms for automata and an author's copy of a paper on the statistical comparison of algorithms
- the classic paper on the Aho-Corasick algorithm for spotting a whole set of words in a text at once, available as an open copy right on the journal's website
The second group of papers is closed to random passersby, but available through your institution's subscription. You log in through your student single sign-on system, and the publishers let you in for free. This opens up four major research databases:
- the first database holds foundational mathematical papers on the structure of finite automata and testable languages
- in the second database, you will find classic works on piecewise testable languages and the famous paper on McNemar's statistical test, which you will need to fairly compare two different error detectors on the exact same texts
- through the third and fourth journal archive databases, you can pull an older statistics paper on calculating confidence intervals, so you can gauge how reliable your numbers are
- a dedicated mathematical reference database will help you quickly verify the publication details of every paper without typos when formatting your thesis bibliography
Still, some things might be missing from your subscription, and you need to know this ahead of time so you do not hit a wall on the night before the deadline. Many university subscriptions do not cover two major engineering libraries in electronics and computer science. Out of our entire reading list, this hits just one work - a paper on a fast algorithm that checks in reasonable time whether an automaton is locally testable. It is a very short paper, just seven pages long, but you will have to find it outside your standard subscription. On the bright side, the Aho and Corasick paper mentioned earlier, even though it came out in a journal from one of those unsubscribed associations, has been placed in an open section by the publisher, so you will have no trouble getting it.
And finally, the old foundational book on counter-free automata is not included in any electronic subscription anywhere in the world. You will have to borrow a physical copy from a regular library, order it from another city via interlibrary loan, or read a scanned copy in an open internet archive that checks out digital copies to readers for a limited time, just like a paper book in a reading room.
The minimum path if an automata course passed you by
Do not panic if you have never taken a course in automata theory, or if it has long since faded from your memory. To build our project for finding grammatical errors in English text with confidence, you do not need to cram thick textbooks from cover to cover. It is enough to work through just four topics from a basic textbook and solve some simple exercises on them. At a relaxed pace, this will take you one or two weeks.
Here is your minimum route, where each topic directly supports a piece of our practical work:
- Topic one: how simple text-checking machines work, and how to turn branching diagrams into single-path ones. Our machine needs to read an English sentence word by word and catch grammatical glitches in it. Here is how it does that: it has a set of circles, called states, and arrows between them. Suppose the faulty phrase "A boys run" comes in as input. The machine takes the first word, "A", recognizes it as a singular article, and follows an arrow to the state "waiting for a singular noun". Next comes the plural word "boys". The machine spots the mismatch, steps into the alarm state "error caught", and signals a breakdown. A machine like this, where every circle has exactly one clear path for every word, is called a single-path or deterministic finite automaton. However, people often find it easier to sketch a rough diagram where several guessing arrows leave the same circle for the very same word - this is called a branching or nondeterministic finite automaton. A special technique called the subset construction shows how to turn any branching diagram into a strict, single-path one. To do this, the new single-path machine simply remembers not just one guess, but the whole bundle of states that the branching machine could have stepped into.
- Topic two: how to glue simple machines together. Imagine you have built one small machine that only watches articles and catches the error in the chunk "a boys". Right next to it, you have built a second machine that checks subject-verb agreement and rejects the chunk "boys runs". We need our program to check everything at once. This topic explains how to snap two separate diagrams together into one combined automaton, like building blocks. The glued-together machine will read the phrase "A boys runs" in a single pass and catch both errors. The fact that gluing two such automata together is guaranteed to produce another working automaton of the exact same kind is known in theory as a closure property.
- Topic three: how to strip all the excess out of a machine. When you write checking rules by hand or glue several diagrams together, the automaton often gets bloated. It ends up with twin circles that do the exact same job and wait for the exact same words. Using a pattern known as the Myhill-Nerode relation, you can easily find these duplicate states and collapse them into one. This process of shrinking a diagram down to the smallest possible size is called minimization. After a cleanup like that, the machine takes up less memory and runs through text faster, while catching the exact same errors in English phrases.
- Topic four: where our machines hit their ceiling. Every finite automaton has its memory strictly limited by the number of its state circles. Because of this, it cannot count to infinity. Imagine a complex English sentence where a parenthesis opens, another one opens inside it, and then another, and at the end all of those parentheses have to close in turn, in the exact same number. To check a sentence like that, a machine has to keep count of every open parenthesis. But if there are more nested parentheses than the machine has circles, its memory will overflow. It will inevitably loop back around and lose count. This topic covers a technique called pumping - it gives a plain, hands-on demonstration of this looping trap and helps you immediately see which long-distance links in a text are beyond the reach of simple automata.
See how this works on the phrase "The cut hurts". The word "cut" in English can be either a noun or a verb, so a rough branching automaton draws two guessing arrows out of the same circle: one leads to the state "seeing a subject", and the other to the state "seeing a predicate". When we convert the diagram into a single-path one, the new automaton takes no forks after the word "cut", stepping instead into a single shared circle with the double label "seeing a subject or a predicate". And when the verb "hurts" comes along next, the machine checks both saved guesses at once: the option with two verbs in a row drops out, while the "subject plus predicate" option fits together perfectly.
Here is how this looks in your project when catching errors like "a cats" and "an apples". You might accidentally create a separate circle for the word "a" labeled "waiting for a singular after the article a", and a second, identical circle for the word "an" labeled "waiting for a singular after the article an". From that point on, though, both branches behave in the exact same way: if a plural word like "cats" or "apples" comes next, both will set off the alarm in the exact same way. Minimization will notice that the future of these two circles does not differ by a single step, and will merge them into one shared state: "waiting for a singular after an indefinite article".
Let us test this on a tiny machine that has only three memory circles: "no parentheses", "one open", and "two open". Suppose the input is the sentence "The boy (who lives next door (and owns a dog (that barks))) runs", where three parentheses open in a row. On the first and second opening parentheses, the machine dutifully steps from the first circle into the second and third, but on the third parenthesis it runs out of free circles and is forced to loop back to one of the old ones - say, back to the circle "one open". As a result, the automaton completely forgets the true number of open parentheses, and at the end of the sentence it misses a glaring error if two of the three closing parentheses are left out.
These four topics are all you need for the entire first level of your thesis, which is its mandatory part. You will be able to build automata for finding errors on your own, combine them into a unified system, compress them to a compact size, and clearly understand which language constructions are beyond their reach.
The second level, however, is a completely different story. It is not just a list of extra topics you can read through over a weekend, but a solid skill in mathematical proof. You should only take on the theoretical chapter of the thesis if you have honestly assessed your strengths and realized that you know how to prove statements rigorously and enjoy doing it. If your heart is not in proofs - that is completely fine. Without this theoretical chapter, your thesis still remains completely finished and full-fledged on the engineering side.
Glossary: what it is called in the textbook and in lectures
The textbook by Hopcroft, Motwani, and Ullman - HMU - the classic textbook on automata theory and formal languages from your course syllabus.
Sipser's textbook - Sipser - the second main textbook from the course syllabus, which explains the theory of computation through intuitive ideas.
Deterministic finite automaton - DFA (Deterministic Finite Automaton) - a step-by-step machine with a finite number of states that is in exactly one state at any given moment and knows uniquely where to step next for the current symbol.
Nondeterministic finite automaton - NFA (Nondeterministic Finite Automaton) - a finite automaton that can branch from a single state on the very same symbol into several states at once, checking multiple guesses in parallel.
The "article a" class - ART_A - a conventional grammatical class label for the indefinite article "a" in the input alphabet of an automaton.
The "plural noun" class - NOUN_PL - a conventional grammatical class label for plural nouns in the input alphabet of an automaton.
The "other word" class - OTHER - a conventional label for all remaining words that do not fall into the target classes of a given pattern.
- Finite automaton - FA (Finite Automaton) - an abstract machine with a finite number of states that reads a string of symbols and transitions from state to state.
- Unambiguous (deterministic) finite automaton - DFA (Deterministic Finite Automaton) - an automaton in which there is at most one transition from each state on each symbol of the alphabet.
- Finite-state transducer - FST (Finite-State Transducer) - a finite automaton that does not merely accept or reject an input string, but also produces output symbols at each step (for example, marking the boundaries of an error).
- True positive (correct hit) - TP (True Positive) - a case where the detector rightly pointed out an actual error in the text.
- False positive (false alarm) - FP (False Positive) - a case where the detector pointed out an error in a place where the text is actually correct.
- False negative (missed error) - FN (False Negative) - a case where there was a real error in the text, but the detector missed it.
- Precision - P (Precision) - the share of real errors among all the places flagged by the detector.
- Recall - R (Recall) - the share of errors found by the detector among all the real errors present in the reference corpus.
- Weighted F-measure prioritizing precision - F0.5 (F0.5-score / F0.5-measure) - a single quality score for a detector that combines precision and recall in such a way that precision is valued twice as much as recall.
- Proportion of correct decisions - Accuracy - the ratio of all correct answers by the classifier (both correct flags and correct silences) to the total number of places checked.
- Span (text interval) - Span - a specific stretch of text (from one position to another) that the detector highlights as the location of a detected error.
- The textbook by Hopcroft, Motwani, and Ullman - HMU (Hopcroft, Motwani, Ullman) - the classic textbook on automata theory, formal languages, and computation.
Tier-based strictly local language - TSL (Tier-based Strictly Local) - a subclass of regular languages that makes it possible to check word agreement across any distance by ignoring irrelevant intervening words.
Deterministic finite automaton (DFA) - DFA - a non-branching automaton where at most one transition leads from each state on each symbol.
Nondeterministic finite automaton (NFA) - NFA - a branching automaton where several transitions at once can lead from a single state on a single symbol.
The class of polynomial-space problems - PSPACE - a family of very hard computational problems that require an amount of memory growing moderately with the input size, while the running time can grow explosively.
Unambiguous (deterministic) finite automaton - DFA - an automaton in which at most one transition leads from each state on each input symbol.
Branching (nondeterministic) finite automaton - NFA - an automaton in which several paths at once, or transitions that do not read a symbol, can lead from a single state on a single symbol.
Strictly local languages with a fixed-width window - SL (SL-k) - a class of languages defined solely by a list of allowed (or forbidden) contiguous chunks of text of a given length.
Locally testable languages with a fixed-width window - LT (LT-k) - a class of languages that look at contiguous chunks of text of a given length and can require either the absence or the mandatory presence of a chunk.
Strictly piecewise languages - SP (SP-k) - a class of languages defined by a list of forbidden scattered sequences of symbols (at any distance from one another) up to a given length.
Piecewise testable languages - PT (PT-k) - a class of languages that check for the presence or absence of scattered sequences of symbols up to a given length.
Star-free languages - SF (star-free) - regular languages that can be defined using union, intersection, complement, and concatenation without the operation of unbounded repetition.
Tier-based strictly local languages - TSL (TSL-2) - languages in which all words irrelevant to the rule are crossed out from the text before checking it with a sliding window.
First-order logic with order - FO(<) - a language of logical formulas with word positions and the "comes earlier" relation, which describes precisely the star-free languages.
Logarithmic space - LOGSPACE - a class of problems that a computer can solve using a tiny amount of memory that grows as the logarithm of the input size.
Nondeterministic logarithmic space - NL (NL-complete) - a class of problems solvable by a branching machine in logarithmic memory (complete problems are the hardest ones in this class).
Complement of the class of brute-force search problems - coNP (coNP-complete) - a class of problems where a short counterexample to a "yes" answer can be checked quickly, while finding the answer itself may require heavy brute-force search.
Polynomial space - PSPACE (PSPACE-complete) - a class of very hard problems that require memory growing as a power of the input size, while the running time can grow explosively.
Automata classification tool and interpreter - Language Toolkit (plebby) - a ready-made program that takes a given automaton, builds its algebraic structure, and determines which classes of the subregular hierarchy it belongs to.
Probably Approximately Correct learning - PAC (Probably Approximately Correct) - a strict model of machine learning requiring an algorithm to find a good hypothesis quickly and with high probability from a reasonably sized sample.
Bibliographic databases of scientific papers - ACL Anthology, Scopus, Web of Science, Google Scholar, DBLP - the world's main electronic catalogs and archives of publications in computational linguistics and computer science.
Scientific conferences and journals on computational linguistics and automata theory - ACL, TACL, NODALIDA, MFCS, DLT, MoL, LNCS - the leading venues whose proceedings publish the foundational theorems on subregular classes and finite-state grammar checking.
Open preprint archive and code repositories - arXiv, GitHub, Hackage - open online platforms hosting full texts of mathematical papers and the source code for automata analysis tools.
Deterministic finite automaton - DFA - an automaton in which there is at most one transition out of any state for any given input symbol.
Nondeterministic (branching) finite automaton - NFA - an automaton in which you can step from a single state into several possible states at once on the very same input symbol.
Lookahead - lookahead - a check in a regular expression that inspects what sits to the right of the current position in the text without moving the reading pointer itself.
Lookbehind - lookbehind - a check in a regular expression that inspects what sits to the left of the current position in the text.
Backreferences - backreferences - a mechanism in regular expressions that remembers a matched piece of text and requires that exact same piece to repeat later in the text.
Xerox finite-state tool - XFST - a classic software suite for building morphological analyzers and rules based on finite automata and transducers.
Foma finite-state library - Foma - an open-source software tool and compiler for creating finite automata and finite-state transducers, compatible in its language with the Xerox suite.
Helsinki Finite-State Transducer toolkit - HFST - an open-source software library for compiling and running morphological dictionaries and grammatical rules on finite-state transducers.
- empty transition (free transition) - epsilon-transition - a transition of an automaton from one state to another without reading the next symbol from the input text.
- closure under empty transitions - epsilon-closure - the set of all states in an automaton that can be reached from the current states exclusively by following free empty arrows.
- Knuth-Morris-Pratt algorithm - KMP (Knuth-Morris-Pratt algorithm) - an algorithm that searches for a single pattern in a text quickly without backing up, by precomputing a failure table.
- decidable languages - class R (Recursive languages, Decidable languages) - the class of formal languages and problems for which there exists an algorithm (a Turing machine) that always halts and gives a definite "yes" or "no" answer.
- recursively enumerable languages - class RE (Recursively Enumerable languages) - the class of problems for which an algorithm is guaranteed to halt with a "yes" answer on valid inputs, but may loop forever on invalid ones.
- complements of recursively enumerable languages - class co-RE (complement of Recursively Enumerable) - the class of problems for which an algorithm is guaranteed to halt with a "no" answer on invalid inputs, but may loop forever on valid ones.
- text segment - span - a highlighted fragment of text with exact start and end coordinates (usually by word or character indices) marking the location of an error.
- base dictionary form of a word - lemma - the basic form of a word in a dictionary (for example, the infinitive for a verb or the singular for a noun), used during linguistic alignment.
- automatic error annotation and correction evaluation tool - ERRANT (ERRor ANnotation Toolkit) - the standard program in English grammar checking that extracts edits by linguistically aligning the original and corrected texts and classifies the error types.
- span-based correction mode - span-based correction - the default evaluation mode, which requires an exact match of both the span boundaries and the replacement string.
- span-based detection mode - span-based detection (the -ds flag) - an evaluation mode that checks for an exact match of the span boundaries while ignoring the correction itself.
- token-based detection mode - token-based detection (the -dt flag) - an evaluation mode in which matches are counted word by word (by tokens) and partial overlap of spans is allowed.
- natural language processing library - spaCy - a software package used inside the evaluation tool to split text into words and identify parts of speech.
- edit annotation format - M2 - a special plain-text file format that stores source sentences along with the coordinates of spans and their corrections.
- edit file building utility - errant_parallel - a program from the evaluation package that generates an annotation file from a "source text - corrected text" pair.
- disjoint-set data structure - union-find (Disjoint Set Union, DSU) - a data structure for quickly merging elements into groups and checking whether two elements belong to the same group.
- deterministic finite automaton - DFA (Deterministic Finite Automaton) - an automaton in which there is at most one transition out of each state for each symbol.
- prefix tree - trie - a tree for storing a dictionary in which transitions along branches correspond to individual letters, and words with a common prefix share a common path from the root.
- balanced summary measure - F1 - an overall quality score that combines precision and recall with equal weight.
- half-weighted summary measure - F0.5 - an overall quality score in which precision is valued higher than recall (the relative importance weight is one-half).
- edit match scorer - M2 (MaxMatch) - the standard program for scoring error correction quality by matching sequences of edits.
- error correction shared task - CoNLL-2014 (Conference on Computational Natural Language Learning Shared Task) - an open international competition for automatic grammatical error correction systems where the half-weighted measure became the standard.
- English as a Second Language - ESL (English as a Second Language) - texts and errors produced by people for whom English is not their native language.
- Natural Language Processing - NLP (Natural Language Processing) - the field of computer science and linguistics concerned with the automatic analysis of human speech and text.
- Grammatical Error Correction - GEC (Grammatical Error Correction) - the task in which a computer system must not only find an error in a text, but also replace it with the correct form.
- Grammatical Error Detection - GED - a task where a computer system only has to point out the location of an error in the text, without offering a ready correction.
- Precision-weighted F-measure - F0.5 (F0.5-score) - a single quality score that combines precision and recall so that precision is valued twice as much as recall.
- True Positives - TP - cases where the detector flagged an error and that error really was in the reference.
- Word alignment and error scoring tool - M2 (MaxMatch scorer) - a classic tool for evaluating error correction that looks for a chain of edits with the maximum match.
- Open competition on error correction - CoNLL-2014 (Conference on Natural Language Learning shared task) - a well-known competition track from 2014 whose corpus is still used to compare detectors today.
- Bias-corrected and accelerated interval - BCa (Bias-Corrected and accelerated bootstrap interval) - a method for calculating the bounds of a bootstrap interval that adjusts the estimate if the distribution is skewed to one side.
- Error correction scoring tool - ERRANT - a standard tool that automatically identifies error boundaries in the text, determines their type, and compares the detector's output against the reference.
- Token-level evaluation mode - -dt - a scorer setting where matches against the reference are checked on each individual word or punctuation mark.
- Span-level evaluation mode - -ds - a scorer setting where errors are checked as whole highlighted chunks of text from the start to the end of the error.
Recall - the share of real errors from the reference that the detector or the whole system managed to find.
Determiner - D - a class of words before a noun that includes articles, demonstratives, and possessive pronouns.
Noun - N - a class of words denoting objects and concepts; in our task, it is often checked for agreement with a determiner.
Other word - O (Other) - any token in the text that does not belong to the classes checked by a given rule.
Locally threshold testable language - LT (Locally Threshold Testable, for example LT-2) - a subregular class of languages where string membership is determined strictly by how many times short sequences of a fixed length appear in it (with a two-word window - LT-2).
Piecewise testable language - PT (Piecewise Testable, for example PT-2) - a subregular class of languages that checks the order in which symbols appear at any distance from one another (for sequences of length two - PT-2).
Summary quality measure weighting precision twice as high as recall - F0.5 (F-score with parameter 0.5) - a single score for detector performance that combines precision and recall, but penalizes false alarms more heavily than missed errors.
Part-of-speech tagging - POS (Part-of-Speech tagging) - automatically assigning each word in a text to its grammatical class.
Branching (nondeterministic) finite automaton - NFA (Nondeterministic Finite Automaton) - a state machine that can have multiple transition options for a single symbol and pursue several parsing branches at the same time.
Computational linguistics archive - ACL Anthology - an open digital library of all the major papers and shared tasks on natural language processing.
Error correction shared task track - CoNLL-2014 - an open international test for programs that look for grammatical errors in English essays.
Transactions of the Association for Computational Linguistics - TACL - a leading academic journal publishing work on language theory and processing algorithms.
Preprint archive - arXiv - a free open website where researchers upload drafts of their papers before they appear in print journals.
Single sign-on system - Athens - a service that lets students and staff access paid academic databases using their institutional login.
Journal of Computer and System Sciences - JCSS - an academic journal in theoretical computer science where classic papers on automata were published.
Theoretical Computer Science - TCS - a major mathematics journal publishing work on formal languages and algorithmic complexity.
Lecture Notes in Computer Science - LNCS - a famous book series that publishes conference proceedings and monographs in computer science.
Institute of Electrical and Electronics Engineers digital library - IEEE Xplore - a huge database of technical papers that is not included in every university subscription.
Association for Computing Machinery digital library - ACM Digital Library - the main database of papers on programming and computer science, also not included in our subscription.
Communications of the ACM - CACM - the flagship journal of the Association for Computing Machinery, whose open section hosts the paper on the Aho-Corasick algorithm.
Digital archive of books and texts - Internet Archive - a non-profit online library where you can borrow scanned old books for a limited time.
- Deterministic finite automaton - DFA - an unambiguous machine of states and transitions where at every step, for every word, there is exactly one path.
- Nondeterministic finite automaton - NFA - a branching machine that can step from a single state on a single word along several guess-paths at once.
All articles
Free practice for every rule
Every grammar rule on the site has a trainer behind it. It is free and needs no sign-up.