01 / 28 · Text Foundations
What natural language processing is
Defining language tasks, representations, probabilistic objectives, decision costs, and the limits of small constructed examples.
On this page 6
A message says, “The lamp sparks at the switch.” An equipment library needs to route it to a safety check. Another message says, “Can I collect the lamp after six?” It needs a booking answer. Both contain lamp. A search for that word retrieves both; a useful decision requires more of the message and a definition of the decision itself.
The examples below use invented equipment-library messages. They are small enough to inspect completely. Their purpose is to expose the mechanics of a system, not to estimate the quality of a deployed service.
The problem: from text to decisions and back#
Natural language processing builds computational procedures whose inputs or outputs involve human language. A procedure can use rules, statistical models, or both. It may classify a message, identify a phrase, rank a document, or generate a response. These tasks differ in what counts as an acceptable output. The task categories in the Hugging Face course provide background; our equipment-library setting supplies the examples here.
We first choose the observation available at prediction time. Is it just the latest message, the complete conversation, or the conversation plus the equipment register? “It still does that” may be meaningful with the previous exchange and impossible to resolve from the last sentence alone. Adding a larger model cannot recover a particular missing conversation with certainty.
Next we choose an output contract. For routing, an output might be one of booking, return, inspection, or needs clarification. For extraction, it might be an item identifier and a collection date, with an explicit empty value when the information is absent. For a response, it might be text that must agree with the current reservation record. These are distinct contracts even when one model can attempt all of them.
Finally we specify an error. Sending a booking message to inspection wastes work; failing to flag a potentially unsafe lamp has a different consequence. A generated answer can be grammatical and still promise an unavailable item. A useful evaluation therefore connects the output to a decision, rather than treating fluency as a universal score.
The task boundary also determines where a human or another program intervenes. An extractor can propose a date while a calendar validator checks whether it exists. A classifier can abstain when required context is absent. The learned component need not take responsibility for every operation surrounding it.
What NLP is for#
Consider four output shapes for the same short request: “Return lamp L7 on Friday.”
| Output shape | Equipment-library example | What needs checking |
|---|---|---|
| A label or score | Route to the returns queue | The chosen label and its operational consequences |
| Locations and labels inside the input | Mark L7 as an item identifier | Both the span boundaries and the entity type |
| A score for each candidate | Rank return instructions for the request | Whether a useful document appears sufficiently high |
| A sequence | Translate the request or draft a reply | Meaning, supported facts, and the required format |
These shapes are a practical classification, not a claim that every language task has exactly one form. Question answering can extract a span, select a document, or generate text. A conversational system can perform several operations in sequence. A speech application adds an acoustic input, but the distinction between output contracts remains useful.
There is also a difference between producing a value and deciding whether to act on it. A probability of inspection is a model output. Routing every message whose probability exceeds a threshold is a decision rule. Changing the threshold changes the trade-off between missed cases and unnecessary inspections without changing the model parameters.
For a simplified binary decision, let be the probability that inspection is needed, the cost of missing such a case, and the cost of an unnecessary inspection. Assume both error costs are positive and correct decisions have zero cost. Choosing inspection has expected cost ; declining inspection has expected cost . We choose inspection when
This follows by moving to the right-hand side of the cost comparison. It requires probabilities suitable for the target population and the stated cost model. A score between zero and one is not automatically a calibrated probability. More complicated operational constraints may require a different decision rule.
One objective under most of it#
Many classification and language-modeling systems learn by assigning probability to observed answers. Suppose the training observations are pairs , where is the available input and is the recorded answer. A model with parameters assigns conditional probability .
Under the modeling assumption that the examples contribute independently conditional on the parameters, their likelihood is a product. Taking a logarithm turns that product into a sum. Minimizing the average negative log-likelihood gives
For a one-hot categorical target this is cross-entropy: all terms except the recorded class have target weight zero. The log-loss definition uses this connection. If the target itself is a distribution, several classes can contribute. The objective encourages probability on the observed target; it does not prove that the annotation is correct or that the target captures every acceptable answer.
Take four invented observations. Suppose a model assigns their recorded answers probabilities , , , and . The product is . The mean negative log-likelihood is therefore
The units are nats because the logarithm is natural. The third observation contributes , more than the first contributes . Increasing confidence in an already correct answer and reducing a confident mistake both affect this loss; a hard accuracy count alone does not record those changes.
For a sequence , the probability chain rule gives
The chain rule itself does not assume that adjacent tokens are independent. A model can approximate the conditional distribution using a short context or an entire available prefix. Training commonly uses the recorded prefix; generation uses the prefix generated so far. That distinction becomes important when an early generated mistake changes later inputs.
Exponentiating mean token negative log-likelihood gives perplexity. For the four probabilities above it is approximately . It is an effective uncertainty summary under the specified tokenization and evaluation set. It is not a percentage of correct answers. Per-token perplexities from different tokenizers are not directly comparable: changing the units changes both the number of predictions and the probabilities attached to them.
Not every later objective is this loss. Ranking losses, contrastive training, structured prediction, reinforcement learning, and decision-specific costs introduce other choices. The probability formulation is a reusable tool, not a requirement to squeeze every task into next-token prediction.
Why language is hard for a computer#
The same words can support different interpretations. “Move the lamp beside the tripod with the cracked handle” leaves attachment ambiguous: which item has the cracked handle? An equipment inventory might resolve it; the sentence alone may not. A system should distinguish uncertainty in the available evidence from a failure to search a large enough model.
Order changes relationships. “Return the lamp before the tripod” and “Return the tripod before the lamp” contain the same word counts and prescribe different actions. A representation that keeps only counts cannot separate them, regardless of the classifier placed after it. Later sequence models repair this particular information loss, while introducing their own data and computation requirements.
Morphology and new identifiers create another problem. lamp, lamps, and an unseen inventory code may each be a new string for a word dictionary. Decomposing strings into smaller units improves coverage, but a piece of a word does not necessarily have a stable meaning. A tokenizer is an encoding procedure; understanding a relationship remains a task for the system that uses the encoding.
A small vocabulary we can inspect#
Our four invented messages are return lamp, return tripod, reserve lamp, and reserve microphone. They contain eight word occurrences, called tokens, and five distinct word forms, called types. return, reserve, and lamp occur twice each; tripod and microphone occur once each.
Adding reserve lamps introduces a new type even though a reader sees a relationship between lamp and lamps. A vocabulary built from these four messages cannot reveal how frequent that plural is in future traffic. We can calculate the counts exactly, but we cannot turn this constructed collection into evidence about real language frequencies. In particular, a tiny list does not establish a power law or a general benchmark score.
The distribution also changes with the task. A collection of return requests emphasizes item names and dates; inspection requests emphasize faults. A model may learn a shortcut that succeeds in one collection and fails in another. Evaluation needs to represent the situation in which the system will actually receive messages.
Why learn the methods when a chat model exists#
A chat interface hides many choices that still affect the result: how text is encoded, how the prompt supplies context, which information the model can access, and how outputs are checked. Knowing the underlying methods lets us locate an error. A missing item identifier might be an extraction problem, an encoding problem, or simply absent input. Those diagnoses lead to different repairs.
A short rule can be preferable when the contract is narrow and explicit. A count-based model provides a useful baseline when labels correlate with a stable vocabulary. A large pretrained model can exploit broader patterns and follow varied instructions, but its output still needs evaluation on the chosen contract. Model size alone does not establish that a response used the current equipment register.
Baselines also make improvements interpretable. If a complex model only matches a dictionary rule on a small set, the extra system cost needs justification. If a rule misses negation and a contextual model handles it, inspect whether that improvement survives new wording and new conversations. The comparison requires an unchanged evaluation protocol.
The plan of the course#
We begin with the representation boundary: strings, normalization, tokens, and the corpus used to fit a vocabulary. Count vectors then provide a complete, inspectable text baseline. Language models add a probability distribution over sequences; learned word representations share evidence between related contexts.
Convolutions, recurrent networks, attention, and Transformers offer different ways to use order and context. Pretraining and adaptation change where their capabilities come from and how they are adjusted. Later tasks connect these components to classification, extraction, generation, retrieval, and systems that use external tools. Existing topic prerequisites determine the reading route; these are methodological connections, not a promise that each newer model dominates every earlier one.
What you should remember#
Define the input, output contract, and consequence of an error before choosing a model. A representation can discard distinctions that no later classifier can recover. Likelihood measures probability assigned to recorded answers; task success still needs its own evaluation. A complete system includes validation, context, and sometimes an abstention path.
Next#
Before fitting a model, we need to decide when two stored strings count as the same text. Text as data separates bytes, Unicode code points, normalization, and task-specific cleaning.
References#
- Hugging Face course contributors. Natural Language Processing and Large Language Models. Pinned course revision
8b893f0, sections on NLP tasks and context; consulted as background, with independently authored examples here. - Scikit-learn developers. Log loss. Version 1.9 documentation, categorical negative log-likelihood definition.
- Hugging Face course contributors. Tokenizers. Word, character, and subword representations; no source figures, examples, or code are reproduced.
All equipment-library inputs and calculations are newly authored for this project with Codex assistance. Reproducible calculations and saved results contain the complete constructed case.