Start with an example: Why text is harder than it looks
Consider two messages: “The delivery was late” and “The delivery was not late.” Only one short word changes, yet the meaning reverses. Now consider “The bank raised rates” and “We sat on the river bank.” The same word refers to different things.
A simple program may look for keywords, but language requires attention to context, word order, and sometimes knowledge outside the sentence. Natural language processing (NLP) is the area of AI that builds systems to process and generate language for tasks such as searching documents, identifying names, translating text, and answering questions.
Think of NLP as a family of problems rather than a single tool. A spam filter, a translation model, and a document search system may all process text, but they solve different tasks and need different evaluations.
Natural Language Processing (NLP) is a field of artificial intelligence concerned with computational methods for processing, analyzing, understanding, and generating human language. NLP systems work with written text and, when combined with speech technologies, spoken language. Typical tasks include classifying emails, extracting names from documents, translating sentences, answering questions, and producing text.
Human language is not a clean database field. The same word can have different meanings, different sentences can express the same idea, and the correct interpretation often depends on context. NLP studies how to turn this flexible, ambiguous form of communication into representations that computers can operate on.
1. Where NLP fits within artificial intelligence
NLP describes a problem domain, not one particular algorithm. An NLP solution might use manually written linguistic rules, a probabilistic model, a traditional machine-learning classifier, or a neural network such as a Transformer. These approaches can also be combined.
| Field or technique | Relationship to NLP |
|---|---|
| Artificial intelligence | Broad field concerned with intelligent computational systems; NLP is one application domain. |
| Machine learning | Learns patterns from language examples, often for classification, extraction, or ranking. |
| Deep learning | Uses neural networks to learn representations of text and contextual relationships. |
| Computational linguistics | Investigates language computationally, including linguistic theories and models; overlaps with NLP. |
| Information retrieval | Retrieves relevant documents or passages, often using NLP for query and document processing. |
| Speech processing | Converts or generates spoken signals; may pass recognized text to NLP components. |
| Large language models | Language models trained at scale; support many NLP tasks through prompting or adaptation. |
Important distinction: NLP is not synonymous with chatbots or large language models. Search engines, spell-checkers, document classifiers, and named-entity extractors are also NLP applications.
2. Why human language is difficult for computers
Language carries information at several levels:
- Morphology: how words are built from smaller meaningful parts, such as play, plays, and playing.
- Syntax: how words combine into grammatically structured expressions.
- Semantics: what words and expressions mean.
- Pragmatics: how situation, speaker intention, and shared knowledge affect meaning.
- Discourse: how meaning develops across sentences and longer conversations.
Consider the sentence:
I saw the person with the telescope.
It could mean that I used a telescope or that the person had a telescope. The words alone do not fully determine the intended meaning.
Other challenges include:
| Challenge | Example | Why it matters |
|---|---|---|
| Polysemy | Bank can mean a financial institution or riverbank. | A word’s meaning depends on context. |
| Synonymy | Purchase and buy often express similar actions. | Exact word matching misses related expressions. |
| Coreference | “Sara lost her key. She found it later.” | The system must relate pronouns to earlier entities. |
| Negation | “This medicine is not effective.” | Missing a small word reverses meaning. |
| Domain variation | “Model” means different things in fashion and machine learning. | Systems may not transfer well between domains. |
| Language variation | Dialects, mixed languages, spelling errors, and informal text | Real inputs rarely follow one perfect convention. |
| World knowledge | “The trophy did not fit in the suitcase because it was too large.” | Resolving “it” may require commonsense reasoning. |
Good NLP design begins by identifying which of these challenges affects the actual task rather than assuming all language needs to be fully understood.
3. The NLP processing workflow
A common workflow turns language input into an output that serves a defined application goal. The stages vary: a modern end-to-end neural system may learn several transformations internally instead of performing them as separate handcrafted steps.
For example, a support-ticket classifier may receive a message, normalize its text, transform it into numerical features, apply a trained classifier, and output a category such as billing or technical support. A language model performing a similar task may instead use its tokenizer and learned internal representations directly.
3.1 Define the task and output
Before choosing a model, specify what a correct result looks like:
- Input: one customer support message.
- Output: one category from a fixed list.
- Evaluation: compare predictions with human-reviewed labels on unseen messages.
- Constraints: supported languages, latency, cost, privacy, and handling uncertain cases.
This is a text classification problem, not a general language-understanding problem.
3.2 Prepare the text
Text preparation can involve Unicode handling, whitespace normalization, removing corrupt records, splitting documents, or correcting inconsistent annotations. More aggressive steps such as removing punctuation, lowercasing, or deleting stop words may help some traditional models but harm others. For example, removing not can reverse sentiment, and lowercasing can erase useful distinctions in named entities.
Keep a record of preprocessing decisions and apply the same transformations to new inputs during inference.
3.3 Convert language into representations
A computer needs a numerical representation of language. Common approaches include:
| Representation | Basic idea | Typical use |
|---|---|---|
| Bag of words | Count occurrences of vocabulary terms. | Simple document classification. |
| TF-IDF | Weight terms according to their frequency in a document and rarity across documents. | Search and traditional text classifiers. |
| Word embeddings | Represent words as dense numerical vectors. | Measuring learned relationships between terms. |
| Contextual embeddings | Represent words or tokens using their surrounding context. | Modern neural language tasks. |
| Token IDs | Map tokens to integer identifiers. | Inputs to neural text models and language models. |
Representations shape what a model can learn. A bag-of-words model generally loses word order. A contextual model can use surrounding words to distinguish meanings, although this does not guarantee correct interpretation.
4. Tokenization and vocabulary
Tokenization is the process of dividing text into units called tokens. A token may be a word, part of a word, a character, or another unit defined by a tokenizer.
For example, a simple word-level tokenizer might turn:
Input: "Students study machine learning."
Tokens: ["Students", "study", "machine", "learning", "."]
This is an illustration, not the output of every tokenizer. Subword tokenizers can split an unfamiliar word into smaller units, allowing models to reuse patterns and handle large vocabularies without storing every possible word as a separate entry.
A vocabulary maps supported tokens to identifiers. Many neural models convert token IDs into vectors using an embedding layer. A model’s vocabulary and tokenization rules must match those used for its training.
Do not equate tokens with words. Token counts depend on the specific tokenizer and language, and are important when estimating a model’s context usage or processing cost.
5. Essential NLP tasks
5.1 Text classification
Text classification assigns one or more categories to text. Examples include spam detection, ticket routing, sentiment analysis, and detecting a document’s topic.
- Binary classification: spam or not spam.
- Multiclass classification: one category among several.
- Multilabel classification: multiple applicable labels for the same document.
Sentiment analysis often classifies text as positive, negative, or neutral, but more detailed systems may estimate emotional tone or specific aspects. Sentiment is context-dependent; sarcasm and mixed opinions are particularly difficult.
5.2 Named entity recognition
Named Entity Recognition (NER) identifies spans of text that refer to entities such as people, organizations, locations, or dates and assigns labels to them.
Text: "Mina joined Northstar Labs in 2025."
Entities: Mina → PERSON
Northstar Labs → ORGANIZATION
2025 → DATE
The categories and boundaries depend on the application’s annotation scheme. Entity recognition does not, by itself, establish which unique real-world person or organization a mention refers to. That additional task is often called entity linking.
5.3 Part-of-speech tagging and parsing
Part-of-speech (POS) tagging assigns grammatical categories such as noun, verb, or adjective to words in context. Syntactic parsing attempts to represent how the elements of a sentence relate grammatically. These techniques are useful for linguistic analysis and certain structured extraction tasks, though many modern systems do not require an explicit parser as a separate preprocessing step.
5.4 Semantic similarity
Semantic similarity estimates how closely two texts relate in meaning. Dense text embeddings can support semantic search, duplicate-question detection, and grouping related documents. Similarity measures can still confuse topic overlap with actual equivalence; two statements about the same subject may contradict each other.
5.5 Machine translation
Machine translation converts text from one language into another while attempting to preserve meaning. Models must handle grammatical differences, ambiguous expressions, cultural context, specialized terminology, and names. Evaluation often combines automated measures with human assessment because a translation may be valid without matching one reference sentence word for word.
5.6 Question answering and summarization
Question answering returns information in response to a question, sometimes using a supplied passage or retrieved documents. Summarization compresses longer material while preserving its important information. Both can be extractive or generative, depending on the method.
Generated answers may sound convincing while introducing unsupported claims. For applications that depend on external documents, source retrieval, attribution, and human review can be important safeguards.
5.7 Language modeling and text generation
A language model assigns likelihoods to sequences or predicts language units based on context. Autoregressive language models generate text by predicting and selecting subsequent tokens. Language modeling enables many tasks through prompting, but fluent text is not equivalent to factual accuracy or reliable reasoning.
6. Traditional NLP and neural NLP
| Aspect | Traditional feature-based approach | Neural representation-learning approach |
|---|---|---|
| Text representation | Often manually selected features such as TF-IDF. | Learned embeddings and contextual representations. |
| Typical models | Naive Bayes, logistic regression, support vector machines. | RNNs, CNNs, Transformers, and other neural architectures. |
| Data requirements | Can work well with relatively small labeled datasets. | Often benefits from large-scale pretraining and task adaptation. |
| Compute requirements | Often lightweight for modest tasks. | Can require more memory and computation. |
| Strength | Simplicity, speed, and interpretable feature inspection. | Better handling of complex contextual patterns in many settings. |
| Limitations | Restricted representation of word order and context. | Resource cost, failure modes, and difficult-to-explain internal behavior. |
Neither family wins on every dataset. For small, well-defined text-classification tasks, TF-IDF with logistic regression is a strong baseline. For tasks requiring broad contextual understanding, multilingual generalization, or generation, pretrained Transformers are often more suitable. Compare candidates using the same representative evaluation setup.
7. Worked example: classify short messages with TF-IDF
The following example trains a small text classifier using scikit-learn. The dataset is intentionally tiny and synthetic, so it demonstrates a workflow rather than producing a dependable spam detector.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
train_texts = [
"claim your free prize now",
"limited offer win cash today",
"congratulations you have won a reward",
"click here for a special promotion",
"please review the meeting notes",
"the assignment deadline is tomorrow",
"can we reschedule our project discussion",
"attached is the updated course outline",
]
train_labels = [
"spam", "spam", "spam", "spam",
"normal", "normal", "normal", "normal",
]
classifier = Pipeline([
("tfidf", TfidfVectorizer(ngram_range=(1, 2))),
("model", LogisticRegression(max_iter=1000)),
])
classifier.fit(train_texts, train_labels)
new_messages = [
"review the updated assignment notes",
"win a free cash reward today",
]
predictions = classifier.predict(new_messages)
for message, label in zip(new_messages, predictions):
print(f"{label}: {message}")
What the code does:
TfidfVectorizerlearns a vocabulary from the training examples and transforms each message into a vector of weighted term features.LogisticRegressionlearns a relationship between those features and the two labels.Pipelineensures the same fitted vectorizer is applied to later messages.predictproduces a class label for each new input.
The example does not test the classifier’s generalization. For a real project, collect a larger, representative dataset, keep a separate test set, and choose metrics appropriate to the cost of missed spam and incorrectly blocked legitimate messages. Split the data before fitting text transformations, and check that near-duplicate messages do not leak across splits.
8. Evaluating an NLP system
The evaluation method should match the output format and the application risk.
| Task | Common evaluation measures | Important caution |
|---|---|---|
| Text classification | Precision, recall, F1-score, confusion matrix | Accuracy can be misleading when classes are imbalanced. |
| Entity extraction | Span-level precision, recall, and F1 | Boundaries and label conventions must match. |
| Search and ranking | Precision@K, Recall@K, NDCG | Relevance judgments and user intent matter. |
| Translation | BLEU, chrF, human assessment | Valid translations may differ from references. |
| Generated answers | Correctness, relevance, groundedness, human review | Fluent or similar-looking text may be wrong. |
| Summarization | Content coverage, faithfulness, human evaluation | A concise answer can omit or invent critical facts. |
Evaluate across realistic input conditions: different text lengths, domains, dialects, languages, typos, and unusual formatting. Test data should be separated from material used to train models or choose configurations. When the task changes, the evaluation design must change with it.
9. Multilingual NLP and language variation
English-only performance is not a reliable measure of how an NLP system will handle other languages. Languages differ in writing systems, word formation, word order, and access to labeled datasets. Code-switching, such as mixing English and Urdu within one message, adds further variation.
For multilingual applications, document which languages and varieties are supported. Test on representative examples from each target user group. A model described as multilingual may still perform very differently across languages or domains.
10. Practical limitations and responsible design
NLP systems inherit limitations from data, model design, and deployment conditions:
- Ambiguity: context may not resolve every possible interpretation.
- Bias: training data and labeling choices may systematically disadvantage particular groups or language varieties.
- Domain shift: performance on news articles may not predict performance on medical notes or informal messages.
- Privacy: text can contain names, credentials, health details, or other sensitive information.
- Unsupported generation: a system may generate claims that are not grounded in evidence.
- Adversarial input: users can intentionally manipulate text inputs or attempt prompt injection in systems that follow instructions from retrieved material.
- Operational constraints: latency, memory, costs, and model availability can affect a useful deployment.
Reduce risk by limiting collection of sensitive data, obtaining necessary permissions, using representative evaluation sets, monitoring deployed behavior, applying access controls, and providing human review for consequential decisions. A model’s output should be treated as an estimate or generated result, not as automatically verified truth.
11. Choosing an approach for an NLP problem
A useful selection process is:
- Specify the task. Is the output a class label, extracted span, retrieved document, translation, or free-form response?
- Check whether deterministic rules suffice. A fixed list of document patterns may not require machine learning.
- Establish a baseline. Try a simple rule-based method or TF-IDF classifier where appropriate.
- Identify context needs. If word order, long-range context, or generation is central, test a suitable pretrained neural model.
- Evaluate realistically. Compare quality, latency, cost, privacy, and failure modes rather than only benchmark scores.
- Plan monitoring. Real language use changes; monitor errors and update evaluation data as needed.
This approach prevents a common engineering mistake: selecting a large language model merely because the problem involves text.
12. Practice exercises
- Classify these tasks as classification, extraction, retrieval, translation, or generation: detecting scam messages; identifying dates in contracts; finding a relevant policy; rewriting a sentence in another language; drafting a reply.
- Explain why deleting the word not could harm sentiment analysis.
- Add three examples per class to the scikit-learn dataset, then compare the predictions before and after retraining. Do not treat the comparison as a reliable performance estimate.
- Create a separate test set for a larger document-classification dataset. Explain why the TF-IDF vocabulary must be learned only from the training data.
- Compare exact keyword search with semantic search for two queries that use different words to describe similar ideas.
- Identify possible privacy and evaluation concerns in a multilingual customer-support classifier.
13. Related PlainCS articles
Prerequisites
- What Is Artificial Intelligence?
- Machine Learning Paradigms
- Data Cleaning and Preprocessing
- Evaluating Machine Learning Models
Continue learning
- Text Processing, Tokenization, and Embeddings
- Information Retrieval and Search
- The Transformer Architecture
- Large Language Models: Foundations and Capabilities
- Retrieval-Augmented Generation
- AI Knowledge Map
Some continuation links refer to articles planned in the PlainCS knowledge map and will work when those pages are published.
14. References and further reading
- Jurafsky and Martin, Speech and Language Processing, textbook on language processing, linguistic structure, and statistical and neural NLP.
- Stanford CS224N: Natural Language Processing with Deep Learning, course material on modern neural NLP methods.
- Scikit-learn: Working with Text Data, documentation for traditional text-classification pipelines.
- Hugging Face NLP Course, hands-on material on tokenization, Transformers, and common NLP tasks.
- Google Machine Learning Crash Course, foundations for model training and evaluation.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.