Skip to content
ImagineWorld

Text Classification Using Traditional ML Techniques

node_idnode-book_mastering-nlp-from-foundations-to-agents_chapter-05-text-classification-using-traditional-ml-techniques
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleText Classification Using Traditional ML Techniques
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Text Classification Using Traditional ML Techniques

Section titled “Chapter 5 — Text Classification Using Traditional ML Techniques”

In this chapter, we’ll delve into the fascinating world of text classification, a foundational task in natural language processing (NLP) and machine learning (ML) that deals with assigning labels to text documents as per their predefined classes. As organizations accumulate vast amounts of unstructured text, they face challenges in extracting actionable insights, filtering irrelevant or harmful content, and managing information at scale. Manual review processes are slow, inconsistent, and costly, and traditional rule-based systems cannot keep pace with the diversity and volume of modern data streams. Text classification emerged as the practical remedy to these limitations because it provides a systematic way to assign meaning and priority to raw text. As a result, accurate and efficient classification now underpins applications such as sentiment analysis, spam detection, and document organization across domains ranging from customer service to cybersecurity. This chapter provides a comprehensive overview of the methodologies employed in text classification, catering to readers from diverse backgrounds and skill levels.

We’ll begin by exploring the various types of text classification tasks and their unique characteristics, offering insights into the challenges and opportunities each type presents. Next, we’ll introduce the concept of N-grams and discuss how they can be utilized as features for text classification, capturing not only individual words but also the local context and word sequences within the text. We’ll then examine the widely used term frequency-inverse document frequency (TF-IDF) method, which assigns weights to words based on their frequency in a document and across the entire corpus, showcasing its effectiveness in distinguishing relevant words for classification tasks.

Following that, we’ll delve into the powerful Word2Vec algorithm and its application in text classification. We’ll discuss how Word2Vec creates dense vector representations of words that capture semantic meaning and relationships, and how these embeddings can be used as features to improve classification performance. Furthermore, we’ll cover popular architectures such as continuous bag of words (CBOW) and skip-gram, providing a deeper understanding of their inner workings.

Lastly, we’ll explore the concept of topic modeling, a technique for discovering hidden thematic structures within a collection of documents. We’ll examine popular algorithms such as latent Dirichlet allocation (LDA) and describe how topic modeling can be applied to text classification, enabling the discovery of semantic relationships between documents and improving classification performance.

Throughout this chapter, we aim to provide a thorough understanding of the underlying concepts and techniques that are employed in text classification, equipping you with the knowledge and skills needed to successfully tackle real-world text classification problems.

The following topics will be covered in this chapter:

  • Types of text classification
  • Text classification based on N-grams
  • Text classification based on TF-IDF
  • Word2Vec and its application in text classification
  • Topic modeling
  • Reviewing our use case – ML system design for NLP classification in a Jupyter notebook

For this chapter, the following will be necessary:

  • Programming knowledge: Familiarity with Python programming is a must.
  • Local development environment: A local development environment setup with Python installed is required. An integrated development environment (IDE) such as PyCharm, Jupyter Notebook, or a simple text editor can be used. Note that we recommend a free Google Colab notebook, as it encapsulates all these requirements in a seamless web interface.
  • Ability to install libraries: You must have permission for the installation of the required Python libraries, such as NumPy, pandas, sentence-transformers, Note that the code we provide includes the required installations, so you won’t have to install them ahead of time. We simply stress that you should have permission to do so, which we expect you would.

Text classification has become a central capability in modern NLP because it offers a structured way to make sense of unstructured text at scale. Early approaches relied on handcrafted rules that were brittle and difficult to maintain as language evolved. As datasets grew and text sources diversified, statistical and ML techniques became essential, providing models that could learn patterns directly from data rather than depend on rigid rules. The field continued to advance through representation learning and distributed embeddings, which enabled models to capture nuance, context, and semantic meaning. These developments transformed text classification from a basic filtering mechanism into a dependable method for supporting decisions across a wide range of real-world environments.

Text classification methods can be categorized into three main types, that is, supervised learning, unsupervised learning, and semi-supervised learning:

  • Supervised learning: This type of text classification involves training a model on labeled data, where each data point is associated with a target label or category. The model then uses this labeled data to learn the patterns and relationships between the input text and the target labels. Examples of supervised tasks include sentiment analysis and spam detection. Algorithms commonly applied in supervised classification include naive Bayes, SVMs, and neural networks such as convolutional neural networks (CNNs) and recurrent neural networks (RNNs).
  • Unsupervised learning: This type of text classification involves clustering or grouping text documents into categories or topics without any prior knowledge of the categories or labels. Examples of unsupervised tasks include topic discovery and document clustering. Algorithms include K-means clustering, LDA, and hierarchical Dirichlet process (HDP).
  • Semi-supervised learning: This type of text classification combines both supervised and unsupervised learning approaches. It involves using a small amount of labeled data to train a model and then using the model to classify the remaining unlabeled data. The model then uses the unlabeled data to improve its classification performance. Semi-supervised learning is useful when labeled data is scarce or expensive to obtain. Examples of semi-supervised approaches include self-training, co-training, and label propagation.

Each of these text classification types has its strengths and weaknesses and is suitable for different types of applications. Understanding these types can help in choosing the appropriate approach for a given problem. In the following subsections, we’ll explain each of these methods in detail.

Supervised learning is a type of ML where an algorithm learns from labeled data to predict the label of new, unseen data.

In the context of text classification, supervised learning involves training a model on a labeled dataset, where each document or text sample is labeled with the corresponding category or class. The model then uses this training data to learn patterns and relationships between the text features and their associated labels:

  1. In a supervised text classification task, the first step is to obtain a labeled dataset, where each text sample is annotated with its corresponding category or class.

A labeled dataset is assumed to possess the highest level of reliability. Often, it is derived by having subject matter experts manually review the text and assign the appropriate class to each item. In other scenarios, there may be automated methods for deriving the labels. For instance, in cybersecurity, you may collect historical data and then assign labels, which may collect the outcome that followed each item, that is, whether the action was legitimate or not. Since such historical data exists in most domains, that too can serve as a reliable labeled set.

  1. The next step is to preprocess the text data to prepare it for modeling. This may include steps such as tokenization, stemming or lemmatization, removing stop words, and other text preprocessing techniques.
  2. After preprocessing, the text data is transformed into numerical features, often using techniques such as bag of words or TF-IDF encoding.
  3. Then, a supervised learning algorithm such as logistic regression, SVM, or a neural network is trained on the labeled dataset using these numerical features.

Once the model has been trained, it can be used to predict the category or class of new, unseen text data based on the learned patterns and relationships between the text features and their associated labels.

Supervised learning algorithms are commonly used for text classification tasks. Let’s look at some common supervised learning algorithms that are used for text classification.

Naive Bayes is a probabilistic algorithm that is commonly used for text classification. It is based on Bayes’ theorem, which states that the probability of a hypothesis (in this case, a document belonging to a particular class), given some observed evidence (in this case, the words in the document), is proportional to the probability of the evidence given the hypothesis times the prior probability of the hypothesis. Naive Bayes assumes that the features (words) are independent of each other given the class label, which is where the “naive” part of the name comes from.

Logistic regression is commonly used for binary classification and can be extended to multi-class classification (for example, multinomial logistic regression). It models the probability of the document belonging to a particular class using a logistic function, which maps any real-valued input to a value between 0 and 1.

SVM is a powerful classification algorithm that is used in a variety of applications, including text classification. SVM works by finding the hyperplane that best separates the data into different classes. In text classification, the features are typically the words in the document, and the hyperplane is used to divide the space of all possible documents into different regions corresponding to different classes.

All of these algorithms can be trained using labeled data, where the class labels are known for each document in the training set. Once trained, the model can be used to predict the class label of new, unlabeled documents. The performance of the model is typically evaluated using metrics such as accuracy, precision, recall, and F1 score.

Unsupervised learning is a type of ML where the data is not labeled and the algorithm is left to find patterns and structures on its own. In the context of text classification, unsupervised learning methods can be used when there is no labeled data available or when the goal is to discover hidden patterns in the text data.

Common unsupervised methods used in text classification include the following:

  • Clustering: Clustering algorithms group similar documents based on their content without prior knowledge of the topics or labels. They are useful for identifying themes within a large collection of documents and for grouping related text for further analysis.
  • LDA: LDA is a probabilistic generative model that treats each document as a mixture of topics. Each topic is represented as a probability distribution over words. This approach helps uncover the latent topics in a corpus even when the topics are not explicitly labeled.

Finally, word embeddings are a popular technique used to learn vector representations of words based on the contexts in which they appear. Although word embeddings are often introduced alongside unsupervised methods because they do not require human-labeled data, the learning process is more accurately described as self-supervised. The model creates its own prediction tasks from the text, which allows it to learn semantic relationships directly from raw data. Common word embedding models include Word2Vec and GloVe.

Word2Vec is a popular algorithm that’s used to generate word embeddings, which are vector representations of words in a high-dimensional space. The algorithm was developed by a team of researchers at Google, led by Tomas Mikolov, in 2013. The main idea behind Word2Vec is that words that appear in similar contexts tend to have similar meanings.

The algorithm takes in a large corpus of text as input and generates a vector representation for each word in the vocabulary. The vectors are typically high-dimensional (for example, 100 or 300 dimensions) and can be used to perform various NLP tasks, such as sentiment analysis, text classification, and machine translation.

Two main architectures are used in Word2Vec: CBOW and skip-gram. In the CBOW architecture, the algorithm tries to predict the target word given a window of context words. In the skip-gram architecture, the algorithm tries to predict the context words given a target word. The training objective is to maximize the likelihood of the target word or context words given the input.

Word2Vec has been widely adopted in the NLP community and has shown state-of-the-art performance on various benchmarks. It has also been used in many real-world applications, such as recommender systems, search engines, and chatbots.

Semi-supervised learning is an ML paradigm that sits between supervised and unsupervised learning. It utilizes a combination of labeled and unlabeled data for training, which is especially useful when the underlying models require labeled data, which is expensive or time-consuming. This approach allows the model to leverage the information in the unlabeled data to improve its performance on the classification task.

In the context of text classification, semi-supervised learning can be beneficial when we have a limited number of labeled documents but a large corpus of unlabeled documents. The goal is to improve the performance of the classifier by leveraging the information contained in the unlabeled data.

There are several common semi-supervised learning algorithms, including label propagation and co-training. We’ll discuss each of these in more detail next.

Label propagation is a graph-based semi-supervised learning algorithm. It builds a graph using both labeled and unlabeled data points, with each data point represented as a node and edges representing the similarity between nodes. The algorithm works by propagating the labels from the labeled nodes to the unlabeled nodes based on their similarity.

The key idea is that similar data points should have similar labels. The algorithm begins by assigning initial label probabilities to the unlabeled nodes, typically based on their similarity to labeled nodes. Then, an iterative process propagates these probabilities throughout the graph until convergence. The final label probabilities are used to classify the unlabeled data points.

Co-training is another semi-supervised learning technique that trains multiple classifiers on different views of the data. A view is a subset of features that are sufficient for the learning task and are conditionally independent given the class label. The basic idea is to use one classifier’s predictions to label some of the unlabeled data, and then use that newly labeled data to train the other classifier. This process is performed iteratively, with each classifier improving the other until a stopping criterion is met.

To apply semi-supervised learning in a specific domain, let’s consider a medical domain where we want to classify scientific articles into different categories, such as cardiology, neurology, and oncology. Suppose we have a small set of labeled articles and a large set of unlabeled articles.

A possible approach could be to use label propagation by creating a graph of articles where the nodes represent the articles and the edges represent the similarity between the articles. The similarity could be based on various factors, such as the words used, the topics covered, or the citation networks between the articles. After propagating the labels, we can classify the unlabeled articles based on the final label probabilities.

Alternatively, we could use co-training by splitting the features into two views, such as the abstract and the full text of the articles. We would train two classifiers, one for each view, and iteratively update the classifiers using the predictions made by the other classifier on the unlabeled data.

In both cases, the goal is to leverage the information in the unlabeled data to improve the performance of the classifier in the specific domain.

Sentence classification using a one-hot-encoding vector representation

Section titled “Sentence classification using a one-hot-encoding vector representation”

One-hot-encoded vector representation is a method of representing categorical data, such as words, as binary vectors. In the context of text classification, one-hot encoding can be used to represent text data as numerical input features for a classification model. Here’s a detailed explanation of text classification using one-hot-encoding vectors.

The first step is to preprocess the text data, as explained in the previous chapter. The main goal of preprocessing is to transform raw text into a more structured and consistent format that can be easily understood and processed by ML algorithms. Here are several reasons why text preprocessing is essential for one-hot-encoded vector classification:

  • Noise reduction: Raw text data often contains noise, such as typos, spelling errors, special characters, and formatting inconsistencies. Preprocessing helps to clean the text, reducing noise that may negatively impact the performance of the classification model.
  • Dimensionality reduction: One-hot-encoded vector representation has a high dimensionality as each unique word in the dataset corresponds to a separate feature. Preprocessing techniques, such as stop word removal, stemming, or lemmatization, can help reduce the size of the vocabulary, leading to a lower-dimensional feature space. This can improve the efficiency of the classification algorithm and reduce the risk of overfitting.
  • Consistent representation: Converting all text to lowercase and applying stemming or lemmatization ensures that words with the same meaning or root form are consistently represented in the one-hot-encoding vectors. This can help the classification model learn more meaningful patterns from the data as it will not treat different forms of the same word as separate features.
  • Semantic caution: Extremely aggressive stemming (e.g., Porter stemming) can merge semantically distinct words ( “universe” → “univers”, “university” → “univers”). When domain precision matters, consider lemmatization or a light stemmer and verify that crucial domain terms stay distinguishable.
  • Handling irrelevant information: Preprocessing can help remove irrelevant information, such as URLs, email addresses, or numbers, that may not contribute to the classification task. Removing such information can improve the model’s ability to focus on the meaningful words and patterns in the text.
  • Improving model performance: Preprocessed text data can lead to better performance of the classification model as the model will learn from a cleaner and more structured dataset. This can result in improved accuracy and generalization to new, unseen text data.

Once we preprocess the text, we can start extracting the words in the text. We call this task vocabulary construction.

Construct a vocabulary containing all unique words in the preprocessed text. Assign a unique index to each word in the vocabulary.

Vocabulary construction is an essential step in preparing text data for one-hot-encoded vector classification. The vocabulary is a set of all unique words (tokens) in the preprocessed text data. It serves as a basis for creating one-hot-encoded feature vectors for each document. Here’s a detailed explanation of the vocabulary construction process for one-hot-encoded vector classification:

  1. Create a set of unique words: After preprocessing the text data, gather all the words from all documents and create a set of unique words. This set will represent the vocabulary. The order of the words in the vocabulary does not matter, but it’s crucial to keep track of the indices assigned to each word as they will be used to create one-hot-encoded vectors later.

For example, consider that the following preprocessed dataset consists of two documents:

  • Document 1: “apple banana orange”
  • Document 2: “banana grape apple”

The vocabulary for this dataset would be {“apple”, “banana”, “orange”, “grape”}.

  1. Assign indices to the words: Once you have the set of unique words, assign a unique index to each word in the vocabulary. These indices will be used to create one-hot-encoded vectors for each document.

Using the preceding example, you might assign the following indices:

  • “apple”: 0
  • “banana”: 1
  • “orange”: 2
  • “grape”: 3

With the constructed vocabulary and assigned indices, you can now create one-hot-encoded vectors for each document in the dataset. One simple approach to creating a one-hot-encoded vector is to use bag of words. For each word in a document, find its corresponding index in the vocabulary and set the value at that index to 1 in the one-hot-encoded vector. If a word appears multiple times in the document, its corresponding value in the one-hot-encoded vector remains 1. All other values in the vector will be 0.

For example, using the vocabulary and indices mentioned previously, the one-hot-encoded vectors for the documents would be as follows:

  • Document 1: [1, 1, 1, 0] (apple, banana, and orange are present)
  • Document 2: [1, 1, 0, 1] (apple, banana, and grape are present)

Once we have the corresponding values for each document, we can create a feature matrix with one-hot-encoded vectors as rows, where each row represents a document and each column represents a word from the vocabulary. This matrix will be used as input for the text classification model. For example, in the previous example, the feature vectors for two documents are as follows:

AppleBananaOrangeGrape
Document 11110
Document 21101

Table 5.1 – Sample one-hot-encoded vector for two documents

Please note that with text preprocessing, it helps to have a smaller vocabulary, and it gives us better model performance. Besides that, if needed, we can perform feature selection methods (as explained previously in this book) on the extracted feature vectors to improve our model performance.

As a scalability tip, know that on large corpora, a full vocabulary can expand into hundreds of thousands (or millions) of columns, which may exceed RAM capacity. Two common mitigations are as follows:

  • Storing the matrix in a sparse format (e.g., scipy.sparse CSR/CSC) so only non-zero entries are kept
  • The hashing trick (a fixed-size “hashing vectorizer”) that maps tokens into a lower-dimensional space via a hash function instead of an explicit vocabulary

Both approaches allow bag-of-words and TF-IDF models to scale to large datasets while accommodating limited memory.

Now, consider a different perspective. While creating a one-hot-encoded vector from words is useful, sometimes, we need to consider the existence of two words beside each other. For example, “very good” and “not good” can have different meanings. To achieve this goal, we can use N-grams.

N-grams are a generalization of the bag-of-words model that takes into account the order of words by considering sequences of n consecutive words. An N-gram is a contiguous sequence of n items (typically words) from a given text. For example, in the sentence “The cat is on the mat,” the 2-grams (bigrams) would be “The cat,” “cat is,” “is on,” “on the,” and “the mat.”

Using N-grams can help capture local context and word relationships, which may improve the performance of the classifier. However, it also increases the dimensionality of the feature space, which can be computationally expensive.

We train an ML model, such as logistic regression, SVM, or neural networks, on the feature matrix to learn the relationship between the one-hot-encoded text features and the target labels. The model will learn to predict the class label based on the presence or absence of specific words in the document. Once we’ve decided on the training process, we need to perform the following tasks:

  • Model evaluation: Evaluate the performance of the model using appropriate evaluation metrics, such as accuracy, precision, recall, F1 score, or confusion matrix, and use techniques such as cross-validation to get a reliable estimate of the model’s performance on unseen data.
  • Model application: Apply the trained model to new, unseen text data. Preprocess and one-hot-encode the new text data using the same vocabulary and use the model to predict the class labels.

One limitation of one-hot-encoded vectors is that the feature space grows directly with the size of the vocabulary, which leads to very high-dimensional and sparse representations. Another limitation is that one-hot vectors do not capture word order, context, or semantic relationships between words, which we also noted earlier in the chapter. These factors can lead to weaker performance in more complex classification tasks. More advanced techniques, such as word embeddings (for example, Word2Vec or GloVe) or deep learning models (for example, CNNs or RNNs), provide richer and more compact representations that address these issues.

In summary, text classification using one-hot-encoded vectors involves preprocessing text data, constructing a vocabulary, representing text data as one-hot-encoded feature vectors, training an ML model on the feature vectors, and evaluating and applying the model to new text data. The one-hot-encoded vector representation is a simple but sometimes limited approach to text classification, and more advanced techniques may be necessary for complex tasks.

So far, we’ve learned about classifying documents using N-grams. However, this approach has a drawback. There are a considerable number of words that occur in the documents frequently and do not add value to our models. To improve the models, text classification using TF-IDF has been proposed.

A one-hot-encoded vector is a good approach to perform classification. However, one of its weaknesses is that it does not consider the importance of different words based on different documents. To solve this issue, using TF-IDF can be helpful.

TF-IDF is a numerical statistic that is used to measure the importance of a word in a document within a document collection. It helps reflect the relevance of words in a document, considering not only their frequency within the document but also their rarity across the entire document collection. The TF-IDF value of a word increases proportionally to its frequency in a document but is offset by the frequency of the word in the entire document collection.

Here’s a detailed explanation of the mathematical equations involved in calculating TF-IDF:

  • Term frequency (TF): The TF of a word, t, in a document, d, represents the number of times the word occurs in the document, normalized by the total number of words in the document. The TF can be calculated using the following equation:

The TF measures the importance of a word within a specific document.

  • Inverse document frequency (IDF): The IDF of a word, t, reflects the rarity of the word across the entire document collection. The IDF can be calculated using the following equation:

The logarithm is used to dampen the effect of the IDF component. If a word appears in many documents, its IDF value will be closer to 0, and if it appears in fewer documents, its IDF value will be higher.

  • TF-IDF computation: The TF-IDF value of a word, t, in a document, d, can be calculated by multiplying the TF of the word in the document by the IDF of the word across the document collection:

The resulting TF-IDF value represents the importance of a word in a document, taking into account both its frequency within the document and its rarity across the entire document collection. High TF-IDF values indicate words that are more significant in a particular document, whereas low TF-IDF values indicate words that are either common across all documents or rare within the specific document.

While the preceding formula is (where notes the total number of documents in the collection, and notes the number of documents containing word ‘t’), this formula has a risk of having a zero in the denominator. In practice, you will often see a smoothed version, for example, , or .

In the first smoothing, adding 1 avoids multiplying the TF component by zero when a term appears in every document and slightly dampens the influence of very rare words; the other is meant to accommodate for when the term doesn’t appear in any document in the current corpus, making be zero.

Let’s consider a simple example of classifying movie reviews into two categories: positive and negative. We have a small dataset with three movie reviews and their respective labels, as follows:

  • Document 1 (positive): “I loved the movie. The acting was great and the story was captivating”
  • Document 2 (negative): “The movie was boring. I did not like the story, and the acting was terrible”
  • Document 3 (positive): “An amazing movie with a wonderful story and brilliant acting”

Now, we will use TF-IDF to classify a new, unseen movie review:

  • Document 4 (unknown): “The story was interesting, and the acting was good”

Here are the steps that we need to perform to have the classifier predict the class of our document:

  1. Preprocess the text data: Tokenize, lowercase, remove stop words, and apply stemming or lemmatization to the words in all documents:
    • Document 1: “love movi act great stori captiv”
      • Document 2: “movi bore not like stori act terribl”
      • Document 3: “amaz movi wonder stori brilliant act”
      • Document 4: “stori interest act good”
  2. Create the vocabulary: Combine all unique words from the preprocessed documents:
    Vocabulary: {“love”, “movi”, “act”, “great”, “stori”, “captiv”, “bore”, “not”, “like”, “terribl”, “amaz”, “wonder”, “brilliant”, “interest”, “good”}
  3. Calculate the TF and IDF values: Compute the TF and IDF for each word in each document.

For example, for the word “stori” in document 4, we have the following:

  1. Compute the TF-IDF values: Calculate the TF-IDF values for each word in each document:

Repeat this process for all words in all documents and create a feature matrix with the TF-IDF values.

  1. Train a classifier: Split the dataset into a training set (documents 1 to 3) and a test set (document 4). Train a classifier, such as logistic regression or SVM, using the training set’s TF-IDF feature matrix and their corresponding labels (positive or negative).
  2. Predict the class label: Preprocess and compute the TF-IDF values for the new movie review (document 4) using the same vocabulary. Use the trained classifier to predict the class label for document 4 based on its TF-IDF feature vector.

For example, if the classifier predicts a positive label for document 4, the classification result would be as follows:

  • Document 4 (Predicted): “Positive”

By following these steps, you can use the TF-IDF representation to classify text documents based on the importance of words in the documents relative to the entire document collection.

In summary, the TF-IDF value is calculated using the mathematical equations for the TF and IDF. It serves as a measure of the importance of a word in a document relative to the entire document collection, considering both the frequency of the word within the document and its rarity across all documents.

While TF-IDF improves on one-hot encoding by weighting words based on their importance, it still represents each word independently and cannot capture deeper semantic relationships. To address these limitations, the next method we will explore uses learned vector representations that encode meaning and context.

One of the methods to perform text classification is to convert the words into embedding vectors so that you can use those vectors for classification. Word2Vec is a well-known method to perform this task.

Word2Vec is a group of neural network-based models that are used to create word embeddings, which are dense vector representations of words in a continuous vector space and are much smaller than the sparse high-dimensional vectors produced by TF-IDF. These embeddings capture the semantic meaning and relationships between words based on the context in which they appear in the text. Word2Vec has two main architectures. As mentioned previously, the two main architectures that were designed to learn word embeddings are CBOW and skip-gram. Both architectures are designed to learn word embeddings by predicting words based on their surrounding context:

  • CBOW: The CBOW architecture aims to predict the target word given its surrounding context words. It takes the average of the context word embeddings as input and predicts the target word. CBOW is faster to train and works well with smaller datasets but may be less accurate for infrequent words.

In the CBOW model, the objective is to maximize the average log probability of observing the target word given the context words:

Here, is the total number of words in the text, and (target | context) is the probability of observing the target word given the context words, which is calculated using the softmax function:

Here, is the output vector (word embedding) of the target word, is the average input vector (context word embedding) of the context words, and the sum in the denominator runs over all words in the vocabulary.

  • Skip-gram: The skip-gram architecture aims to predict the surrounding context words given the target word. It takes the target word embedding as input and predicts the context words. Skip-gram works well with larger datasets and can capture the meaning of infrequent words more accurately, but it may be slower to train compared to CBOW.

In the skip-gram model, the objective is to maximize the average log probability of observing the context words given the target word:

Here, is the total number of words in the text, and (context | target) is the probability of observing the context words given the target word, which is calculated using the softmax function:

Here, is the output vector (context word embedding) of the context word, is the input vector (word embedding) of the target word, and the sum in the denominator runs over all words in the vocabulary.

Practical optimization note: making Word2Vec trainable at scale

Section titled “Practical optimization note: making Word2Vec trainable at scale”

Computing the full softmax in the preceding two equations is (where is the set of all vectors) per training step, which becomes infeasible when the vocabulary contains hundreds of thousands of words. In practical Word2Vec implementations, the exact softmax calculation isn’t used; instead, one of two approximations is picked:

  • Negative sampling: For each true context pair, we sample random “noise” words and maximize a binary logistic objective that distinguishes genuine pairs from noise. Complexity drops to with.
  • Hierarchical softmax: Organize the vocabulary in a Huffman tree, predicting a word becomes a path traversal of length. This reduces the per-update cost from linear to logarithmic in vocabulary size.

Both tricks let Word2Vec process billions of tokens on commodity hardware while producing essentially the same embeddings.

The training process for both CBOW and skip-gram involves iterating through the text and updating the input and output weight matrices using stochastic gradient descent (SGD) and backpropagation to minimize the difference between the predicted words and the actual words. The learned input weight matrix contains the word embeddings for each word in the vocabulary.

GloVe and FastText: advancements in static word embeddings

Section titled “GloVe and FastText: advancements in static word embeddings”

While Word2Vec set the stage for learning dense vector representations of words based on their contextual usage, two important successors, GloVe and FastText, offered complementary innovations to address some of its limitations. These models, such as Word2Vec, produce static word embeddings, meaning each word has a single vector regardless of context. However, they differ in how they are trained and the types of patterns they emphasize.

GloVe: Global Vectors for Word Representation

Section titled “GloVe: Global Vectors for Word Representation”

GloVe (which stands for Global Vectors for Word Representation), developed by Stanford University, is a word embedding model that leverages global word co-occurrence statistics to learn embeddings. Unlike Word2Vec, which trains on local context windows, GloVe builds a co-occurrence matrix across the entire corpus and then factorizes it to generate word vectors. This allows it to capture both syntactic and semantic relationships more effectively.

At its core, GloVe minimizes the difference between the dot product of word vectors and the logarithm of the number of times the words co-occur. The optimization objective is as follows:

Here, we have the following:

  • : Word vectors for target and context words
  • : Bias terms
  • : Number of times word occurs in the context of word
  • : A weighting function to downscale very frequent co-occurrences

This design enables GloVe to represent linear substructures in vector space. Famous examples include the following:

vec(“king”) - vec(“man”) + vec(“woman”) ≈ vec(“queen”)

Here, vec() is a function that takes in a word and returns its vector.

FastText, developed by Facebook AI Research, builds upon Word2Vec’s skip-gram model by incorporating subword information. Rather than learning a single vector for each word, FastText represents a word as a bag of character n-grams (e.g., where becomes <wh, whe, her, ere, re>). The final embedding of a word is the sum of its subword embeddings.

This approach helps FastText to do the following:

  • Handle out-of-vocabulary (OOV) words by composing them from known subword units
  • Capture morphological structure, which improves performance in morphologically rich languages

For example, even if “neurodivergent” does not appear in the training corpus, FastText can still generate a meaningful embedding for it by composing subword units such as neuro, diverg, and ent.

FastText’s skip-gram objective is similar to Word2Vec’s but applied to subwords:

Here, we have the following:

  • is the context window size
  • is a context word
  • is the set of subword n-grams for the center word,
  • is the probability of predicting the context word given the subword representation of the center word

Having examined each model individually, the following table highlights their key differences and trade-offs:

FeatureWord2VecGloVeFastText
Training strategyLocal context predictionGlobal co-occurrence matrixLocal context + subwords
Handles OOV words✘✘✔ (via subwords)
Incorporates subword info✘✘✔
SpeedFastSlower (due to matrix factor)Comparable to Word2Vec
Captures global semanticsModerateStrongModerate
Robust to rare wordsModerateWeakStrong

Table 5.2 – Comparative summary: Word2Vec versus GloVe versus FastText

Where they fit in traditional ML pipelines

Section titled “Where they fit in traditional ML pipelines”

All three models, Word2Vec, GloVe, and FastText, produce dense, low-dimensional word vectors that can be averaged or pooled to represent documents. These document embeddings can then serve as features for traditional ML classifiers (e.g., logistic regression, SVM, or random forest).

While FastText’s subword awareness and GloVe’s semantic arithmetic offer improvements over Word2Vec in many tasks, the choice of model should be guided by the following:

  • The language and morphology of the corpus
  • The importance of handling rare or unseen words
  • The availability of pre-trained vectors (e.g., GloVe on Wikipedia + Gigaword, FastText on Common Crawl)

In Chapter 6, we will explore how these static embeddings compare to contextual embeddings derived from transformer-based models such as BERT, which produce dynamic vectors that depend on surrounding context.

Text classification using Word2Vec involves creating word embeddings using the Word2Vec algorithm and then training an ML model to classify text based on these embeddings. The following steps outline the process in detail, including the mathematical aspects:

  1. Text preprocessing: Clean and preprocess the text data by tokenizing, lowercasing, removing stop words, and stemming or lemmatizing the words.
  2. Train the Word2Vec model: Train a Word2Vec model (either CBOW or skip-gram) on the preprocessed text data to create word embeddings. The Word2Vec algorithm learns to predict a target word based on its context (CBOW) or predict the context words based on a target word (skip-gram). The training objective is to maximize the average log probability of observing the context words given the target word:

Here, T is the total number of words in the text, and is the probability of observing the context words given the target word, which is calculated using the softmax function:

Here, is the output vector (context word embedding) of the context word, is the input vector (word embedding) of the target word, and the sum in the denominator runs over all words in the vocabulary.

  1. Create document embeddings: For each document in the dataset, calculate the document embedding by averaging the word embeddings of the words in the document:

Here, is the number of words in the document, and the sum runs over all words in the document. Please note that based on our experience, this approach to text classification using Word2Vec is only useful when the document’s length is short. We’d like to stress that a plain mean is fast but can dilute information when documents are long or contain off-topic words. Common upgrades are available to accommodate that deficiency: TF-IDF weighted averaging, smooth inverse frequency (SIF) or uSIF re-weighting, max/concatenation pooling, and Doc2Vec/paragraph vector models that learn a dedicated vector per document. Thus, it may be useful to consider these when the baseline average underperforms. If you have longer documents or there are opposite words in the document, this approach won’t perform well. An alternative solution is to use Word2Vec and CNN together to fetch the word embeddings and then feed those embeddings as input to the CNN. Once the document embeddings are created, the classification process proceeds through a series of standard ML steps.

Once the document embeddings are created, the classification process proceeds through a series of standard ML steps:

  1. Model training: Use the document embeddings as features to train an ML model, such as logistic regression, SVM, or a neural network, for text classification. The model learns to predict the class label based on the document embeddings.
  2. Model evaluation: Evaluate the performance of the model using appropriate evaluation metrics, such as accuracy, precision, recall, F1 score, or confusion matrix, and use techniques such as cross-validation to get a reliable estimate of the model’s performance on unseen data.
  3. Model application: Apply the trained model to new, unseen text data. Preprocess and compute the document embeddings for the new text data using the same Word2Vec model and vocabulary, and use the model to predict the class labels.

In summary, text classification using Word2Vec involves creating word embeddings with the Word2Vec algorithm, averaging these embeddings to create document embeddings, and training an ML model to classify text based on these document embeddings. The Word2Vec algorithm learns word embeddings by maximizing the average log probability of observing context words given a target word, capturing the semantic relationships between words in the process.

As discussed in Chapter 3, feature selection plays a crucial role in text classification, especially when working with high-dimensional representations such as bag of words or TF-IDF. Techniques such as chi-squared filtering, mutual information, and -regularized models help reduce noise and improve generalization. Before evaluating your model, it’s often beneficial to perform such a selection, particularly in sparse feature spaces. Refer back to Chapter 3 for code examples and deeper explanations tailored to text features.

Evaluating the performance of text classification models is crucial to ensure that they meet the desired level of accuracy and generalizability. Several metrics and techniques are commonly used to evaluate text classification models, including accuracy, precision, recall, F1 score, and confusion matrix. Let’s discuss each of these in more detail:

  • Accuracy: Accuracy is the most straightforward metric for classification tasks. It measures the number of correctly classified records out of all classified records. It is defined as follows:

While accuracy is easy to understand, it may not be the best metric for imbalanced datasets, where the majority class can dominate the metric’s value.

  • Precision: Precision gauges the ratio of correctly identified positive instances to the total instances predicted as positive by the model. It is also referred to as positive predictive value (PPV). Precision proves valuable in scenarios where the expense associated with false positives is significant. Precision is defined as follows:

  • Recall: Recall, also recognized as sensitivity or the true positive rate (TPR), assesses the ratio of correctly identified positive instances among the total actual positive instances. Recall is useful when the cost of false negatives is high. Mathematically, it is defined as follows:

  • F1 score: The F1 score, derived as the harmonic mean of precision and recall, integrates both metrics into a unified value. It is an important metric in the context of imbalanced datasets as it considers both false positives and false negatives. Spanning from 0 to 1, with 1 representing the optimal outcome, the F1 score is mathematically expressed as follows:

When dealing with multi-class classification, we have F1 micro and F1 macro. F1 micro and F1 macro are two ways to compute the F1 score for multi-class or multi-label classification problems. They aggregate precision and recall differently, leading to different interpretations of the classifier’s performance. Let’s discuss each in more detail:

  • F1 macro: F1 macro computes the F1 score for each class independently and then takes the average of those values. This approach treats each class as equally important and does not consider the class imbalance. Mathematically, F1 macro is defined as follows:

Here, n is the number of classes, and is the F1 score for the i-th class.

F1 macro is particularly useful when you want to evaluate the performance of a classifier across all classes without giving more weight to the majority class. However, it may not be suitable when the class distribution is highly imbalanced as it can provide an overly optimistic estimate of the model’s performance.

  • F1 micro: F1 micro, on the other hand, aggregates the contributions of all classes to compute the F1 score. It does this by calculating the global precision and recall values across all classes and then computing the F1 score based on these global values. F1 micro takes class imbalance into account as it considers the number of instances in each class. Mathematically, F1 micro is defined as follows:

Here, global precision and global recall are calculated as follows:

F1 micro is useful when you want to evaluate the overall performance of a classifier considering the class distribution, especially when dealing with imbalanced datasets.

In summary, F1 macro and F1 micro are two ways to compute the F1 score for multi-class or multi-label classification problems. F1 macro treats each class as equally important, regardless of the class distribution, while F1 micro takes class imbalance into account by considering the number of instances in each class. The choice between F1 macro and F1 micro depends on the specific problem and whether class imbalance is an important factor to consider.

Beyond F1: metrics that shine on imbalanced datasets

Section titled “Beyond F1: metrics that shine on imbalanced datasets”

Although F-measure and its micro/macro variants are a good first line of defense, some tasks require metrics that explicitly discount class-imbalance or unequal error costs:

MetricWhat it measuresWhy it helps when classes are skewed
Receiver operating characteristic – area under the curve (ROC-AUC)Probability that a randomly chosen positive ranks above a randomly chosen negative as the decision threshold sweeps 0→1.Threshold-independent: reveals how well the model separates classes even if the minority class is tiny
Area under the precision recall curve (PR-AUC)Trade-off between precision and recall across thresholds.More sensitive than ROC-AUC when the positive class is rare (precision penalizes many FPs)
Cohen’sAgreement between predicted and true labels corrected for chance.Normalizes accuracy by expected random agreement; useful when the majority class dominates naive accuracy
Matthews correlation coefficient (MCC)Correlation between observed and predicted classes (-1 … 1). For binary:Takes every cell of the confusion matrix into account; gives a single, balanced score even under extreme skew

Table 5.3 – Metrics that suit scenarios with a class imbalance

The following are suggestions for when to employ each metric:

  • Compute PR-AUC in addition to ROC-AUC whenever the positive rate <10%
  • Use MCC or when you need a single threshold-dependent number that is robust to imbalance (for example, in model selection loops)
  • In scikit-learn, these metrics can be computed using built-in helpers, such as roc_auc_score, average_precision_score (PR-AUC), cohen_kappa_score, matthews_corrcoef

These metrics help ensure that you do not produce a model that looks great yet silently fails on the minority class.

A confusion matrix serves as a tabular representation, showcasing the count of true-positive, true-negative, false-positive, and false-negative predictions made by a classification model. This matrix offers a nuanced perspective on the model’s efficacy, enabling a thorough comprehension of both its strengths and weaknesses.

For a binary classification problem, the confusion matrix is arranged as follows:

Actual/Predicted(Predicted) Positive(Predicted) Negative
(Actual) PositiveTrue PositiveFalse Negative
(Actual) NegativeFalse PositiveTrue Negative

Table 5.4 – Confusion matrix, general view

For multi-class classification problems, the confusion matrix is extended to include the true and predicted counts for each class. The diagonal elements represent the correctly classified instances, while the off-diagonal elements represent misclassifications.

In summary, evaluating text classification models involves using various metrics and techniques, such as accuracy, precision, recall, F1 score, and the confusion matrix. Selecting the appropriate evaluation metrics depends on the specific problem, the dataset characteristics, and the trade-offs between false positives and false negatives. Evaluating a model using multiple metrics can provide a more comprehensive understanding of its performance and help guide further improvements.

Overfitting and underfitting in text classification

Section titled “Overfitting and underfitting in text classification”

Text classification models face the same general risks of overfitting and underfitting described in Chapter 3, but these effects often surface in ways that are specific to text data. High-dimensional and sparse feature spaces, limited labeled examples, and vocabulary imbalance can cause models to memorize idiosyncrasies of the training set rather than learn generalizable linguistic patterns. Conversely, overly simple feature representations, such as single-token counts or very small vocabularies, can prevent a model from capturing the structure of the text and lead to underfitting.

Common mitigation strategies remain effective in the text setting. These include regularization, cross-validation, careful control of vocabulary size, and the use of richer features such as N-grams, TF-IDF weighting, or embedding-based representations when simple counts are insufficient. When training data is limited, techniques such as data augmentation for text or semi-supervised learning can also improve generalization. For a full discussion of the underlying principles and methods for addressing overfitting and underfitting, see Chapter 3.

Cross-validation and experiment reproducibility

Section titled “Cross-validation and experiment reproducibility”

When building classification pipelines, it’s important to ensure not just high accuracy but also reliable, reproducible results. While Chapter 3 introduced the logic of stratified k-fold and time-series splits, let’s now integrate it into our text ML workflows.

In text classification tasks, it’s common to combine TF-IDF with stratified k-fold cross-validation to ensure balanced label distribution across folds. Here’s a concise pipeline using scikit-learn:

from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
# Load a binary subset of the 20 Newsgroups dataset
data = fetch_20newsgroups(
subset=’train’, categories=[‘sci.space’, ‘rec.autos’])
texts = data.data
labels = data.target
# Define pipeline: TF-IDF + Logistic Regression
clf = make_pipeline(
TfidfVectorizer(),
LogisticRegression(max_iter=1000)
)
# Use stratified 5-fold cross-validation
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(clf, texts, labels, cv=skf, scoring=’f1_macro’)
print(f”Mean F1 (macro): {scores.mean():.3f}”)

Here, texts is a list of documents (from data.data), and labels is a list of class labels (from data.target).

Also, a high F1 tells us that the classifier is achieving very high performance across both classes, and importantly, this metric reflects balanced performance, even if the dataset is not perfectly balanced.

Beyond performance, tracking each experiment is critical, especially as pipelines grow in complexity. Tools such as MLflow and Weights & Biases (W&B) let you log the following:

  • Model hyperparameters
  • Evaluation metrics
  • Artifacts (e.g., vectorizers, model weights)
  • Versioning for datasets and environments

For example, we can have the following with MLflow (run this code after the prior code, and make sure to install MLflow via pip first):

import mlflow
mlflow.set_experiment(‘text_classification’)
with mlflow.start_run() as run:
mlflow.log_param(‘vectorizer’, ‘TF-IDF’)
mlflow.log_param(‘model’, ‘LogisticRegression’)
mlflow.log_metric(‘f1_macro’, scores.mean())
run_id = run.info.run_id
print(mlflow.get_run(run_id).data)

This lightweight integration ensures reproducibility, supports collaborative development, and makes your pipeline audit-ready, whether in academia, production, or regulated environments.

Although both practices contribute to model reliability, they operate at different levels of the workflow, as summarized here:

AspectCross-ValidationExperiment Tracking
GoalEvaluate model generalizabilityEnsure reproducibility and traceability
What it doesSplits data to assess stability across foldsLogs metrics, parameters, artifacts, and code versions
Common toolscross_val_score, StratifiedKFold (scikit-learn)MLflow, Weights & Biases, Neptune, Sacred
OutputMetrics like mean accuracy, F1 across foldsDashboard of experiments with config, metrics, outputs
When to useAlways, especially on small or imbalanced datasetsRecommended for any project with iteration or collaboration
Who benefitsData scientists, ML engineers validating model qualityWhole ML team (incl. collaborators, reviewers, deployers)

Table 5.5 – Cross-validation versus experiment tracking

Evaluation pitfalls in text classification

Section titled “Evaluation pitfalls in text classification”

Even with well-chosen metrics, evaluation can mislead if the process is flawed. Here are common mistakes to avoid:

PitfallWhy it’s a problem
Data leakageFeatures or labels from the test set leak into training (e.g., via preprocessing)
Improper data shufflingShuffling before stratified splits can bias class distributions
Imbalanced metrics reportingReporting only accuracy on skewed data can hide poor performance on minority classes
Peeking at the test setRe-tuning models after seeing test performance makes the test set no longer valid
Training on pre-tokenized testPreprocessing steps such as TF-IDF fitted on the full corpus leak future information
Missing variance estimatesSingle-run metrics hide model instability—use cross-validation for more robust stats

Table 5.6 – Evaluation pitfalls in text classification

A good rule of thumb to keep in mind is to always preprocess within your training folds only, and treat the test set as truly unseen.

Hyperparameter tuning in text classification

Section titled “Hyperparameter tuning in text classification”

Hyperparameter tuning plays an important role in text classification because many design choices in text pipelines directly influence model performance. While Chapter 3 provides a full explanation of tuning methods such as grid search, random search, and Bayesian optimization, the key considerations in text classification often come from the feature space rather than the classifier alone. Parameters such as vocabulary size, the range of N-grams, TF-IDF weighting options, embedding dimensionality, and regularization strength all shape how well the model can represent linguistic structure.

In practice, tuning these text-specific hyperparameters usually has a larger impact on performance than adjusting the classifier architecture itself. Cross-validation remains the standard evaluation method, and the optimal configuration is the one that generalizes best to unseen text. For details on tuning strategies and search methods, see Chapter 3.

Applied considerations in text classification

Section titled “Applied considerations in text classification”

Real-world text classification introduces practical challenges that differ from those in general ML tasks. Many of these issues are discussed in depth in Chapter 3, but they manifest differently when working with text data because of vocabulary imbalance, noisy tokens, and the structure of linguistic inputs. In practice, these differences tend to appear in a small number of recurring areas:

  • Imbalanced classes: Text datasets often contain rare categories such as minority intents, infrequent topics, or edge-case sentiment labels. Class imbalance is intensified by vocabulary sparsity, which makes minority classes harder to represent. Techniques such as class weighting, controlled vocabulary selection, and text-specific augmentation help the model focus on low-frequency patterns. Chapter 3 covers general resampling and cost-sensitive methods.
  • Noise in text data: Misspellings, slang, OCR errors, emojis, and code-switching introduce noise that affects tokenization and feature extraction. Text classifiers often benefit from targeted cleaning steps such as normalization rules, subword tokenization, or context-aware replacement rather than the general preprocessing described in Chapter 3.
  • Choosing metrics for text tasks: Metric selection depends on linguistic goals. For example, intent classification may prioritize recall of rare intents, while sentiment analysis may prioritize precision for negative sentiment to avoid false alarms. Macro-averaged metrics are often preferred in multi-class text settings where class distributions differ. Chapter 3 covers the mathematical definitions of these metrics.

In practice, addressing these text-specific considerations improves robustness and aligns the model with application requirements without repeating the generic ML material covered earlier.

Topic modeling: a particular use case of unsupervised text classification

Section titled “Topic modeling: a particular use case of unsupervised text classification”

Topic modeling is an unsupervised ML technique that’s used to discover abstract topics or themes within a large collection of documents. It assumes that each document can be represented as a mixture of topics, and each topic is represented as a distribution over words. The goal of topic modeling is to find the underlying topics and their word distributions, as well as the topic proportions for each document.

There are several topic modeling algorithms, but one of the most popular and widely used is LDA. We will discuss LDA in detail, including its mathematical formulation.

LDA is a generative probabilistic model that assumes the following generative process for each document:

  1. Choose the number of words in the document.
  2. Choose a topic distribution () for the document from a Dirichlet distribution with parameter α.
  3. For each word in the document, do the following:
    1. Choose a topic () from the topic distribution () 2. Choose a word () from the word distribution of the chosen topic (), which is a distribution over words for that topic, drawn from a Dirichlet distribution with parameter

The generative process is a theoretical model used by LDA to reverse-engineer the original documents from presumed topics.

LDA aims to find the topic-word distributions () and document-topic distributions () that best explain the observed documents.

Mathematically, LDA can be described using the following notation:

  • : Number of documents.
  • : Number of words in a document.
  • : Number of topics.
  • : Dirichlet prior on document-topic distribution. It affects the sparsity of topics within documents.
  • : Dirichlet prior on topic-word distribution. It affects the sparsity of words within topics.
  • : Document-topic distributions (M × K matrix).
  • : Topic-word distributions (K × V matrix, where V is the vocabulary size).
  • : Topic assignments for each word in each document (M × N matrix).
  • : Observed words in the documents (M × N matrix).

The joint probability of the topic assignments () and words () in the documents, given the topic-word distributions () and document-topic distributions (), can be written as follows:

The objective of LDA is to maximize the likelihood of the observed words given the Dirichlet priors α and β:

However, computing the likelihood directly is intractable due to the integration over the latent variables and. Therefore, LDA uses approximate inference algorithms, such as Gibbs sampling or variational inference, to estimate the posterior distributions, and.

Once the posterior distributions have been estimated, we can obtain the document-topic distributions () and topic-word distributions (), which can be used to analyze the discovered topics and their word distributions, as well as the topic proportions for each document.

Let’s consider a simple example of topic modeling.

Suppose we have a collection of three documents:

  • Document 1: “I love playing football with my friends”
  • Document 2: “The football match was intense and exciting”
  • Document 3: “My new laptop has an amazing battery life and performance”

We want to discover two topics in this document collection. Here are the steps that we need to perform:

  1. Preprocessing: First, we need to preprocess the text data, which typically involves tokenization, stop word removal, and stemming/lemmatization (which was explained earlier in this chapter). In this example, we will skip these steps for simplicity and assume our documents are already preprocessed.
  2. Initialization: Choose the initial values for the Dirichlet priors, α and β. For example, we can set and (assuming a -dimensional vector with 0.1 for each word in the vocabulary).
  3. Random topic assignments: Randomly assign a topic (1 or 2) to each word in each document.
  4. Iterative inference (for example, Gibbs sampling or variational inference): Iteratively update the topic assignments and the topic-word and document-topic distributions ( and θ) until convergence or a fixed number of iterations. This process refines the assignments and distributions, ultimately revealing the underlying topic structure.
  5. Interpretation: After the algorithm converges or reaches the maximum number of iterations, we can interpret the discovered topics by looking at the most probable words for each topic and the most probable topics for each document.

For our example, LDA might discover the following topics:

  • Topic 1: {“football”, “playing”, “friends”, “match”, “intense”, “exciting”}
  • Topic 2: {“laptop”, “battery”, “life”, “performance”}

With these topics, the document-topic distribution (θ) might look like this:

  • = [0.9, 0.1] (Document 1 is 90% about topic 1 and 10% about topic 2)
  • = [0.8, 0.2] (Document 2 is 80% about topic 1 and 20% about topic 2)
  • = [0.1, 0.9] (Document 3 is 10% about topic 1 and 90% about topic 2)

In this example, topic 1 seems to be related to football and sports, while topic 2 seems to be related to technology and gadgets. The topic distributions for each document show that documents 1 and 2 are mostly about football, while document 3 is about technology.

Please note that this is a simplified example, and real-world data would require more sophisticated preprocessing and a larger number of iterations for convergence.

We are now ready to discuss the paradigm for putting together a complete project in a work or research setting.

BERTopic – a modern embedding-based topic modeling technique

Section titled “BERTopic – a modern embedding-based topic modeling technique”

While LDA has long been a standard technique in topic modeling, modern NLP pipelines are increasingly turning to BERTopic for improved flexibility, performance, and interpretability. BERTopic shifts from the probabilistic modeling paradigm to a vector-based and clustering-driven approach, enabling it to capture more nuanced semantic relationships between documents.

At its core, BERTopic operates through the following processes:

  • Embedding generation: Instead of relying on word co-occurrence statistics, BERTopic uses pretrained transformer-based models (e.g., BERT or Sentence-BERT) to convert documents into dense, contextualized vector representations. This allows semantically similar documents—even if they don’t share keywords—to be represented closely in embedding space.
  • Dimensionality reduction: To visualize and cluster high-dimensional embeddings efficiently, BERTopic applies a reduction technique such as Uniform Manifold Approximation and Projection (UMAP, as covered in Chapter 3). This step preserves the local neighborhood structure of the data.
  • Clustering: Using a clustering algorithm such as Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN), BERTopic groups similar documents together based on their vector proximity. Unlike LDA, which assumes a fixed number of topics, HDBSCAN can determine the number of clusters dynamically and ignore outliers.
  • Topic representation: Each cluster of documents is analyzed using class-based TF-IDF to extract representative keywords that define the topic. This makes the resulting topics both semantically rich and human-interpretable.

Let’s consider the same three-document example we saw with LDA:

  • Document 1: “I love playing football with my friends”
  • Document 2: “The football match was intense and exciting”
  • Document 3: “My new laptop has an amazing battery life and performance”

With BERTopic, note the following:

  • Document embeddings are generated using a Sentence-BERT model
  • UMAP reduces these embeddings to 2 or 5 dimensions
  • HDBSCAN identifies two clusters
  • TF-IDF scoring identifies keywords such as [“football”, “match”, “playing”] for topic 1 and [“laptop”, “battery”, “performance”] for topic 2

Like LDA, BERTopic groups documents 1 and 2 into a sports-related topic, and document 3 into a tech-related topic. However, because BERTopic uses dense contextual embeddings, it often performs better on short texts, colloquial language, and low-resource scenarios where traditional frequency-based models such as LDA struggle.

To better understand how this embedding-based approach differs from traditional probabilistic topic modeling, Table 5.7 contrasts LDA and BERTopic:

AspectLDABERTopic
Underlying principleProbabilistic generative modelEmbedding + clustering
RepresentationBag of words, sparse vectorsTransformer-based contextual embeddings
Dimensionality reductionNot usedUMAP
Clustering techniqueAssumes fixed K topicsDensity-based (e.g., HDBSCAN)
FlexibilityFixed topic countDynamic topic count, noise filtering
StrengthsSolid theory, interpretable mathHandles short texts, more semantic accuracy
DependenciesScikit-learn, GensimHugging Face, UMAP, HDBSCAN, BERTopic package

Table 5.7 – Comparing LDA and BERTopic

There are some points to consider:

  • Interpretability: BERTopic’s topics are grounded in modern semantic similarity but can still be expressed in keyword form using TF-IDF, making them suitable for business presentations
  • Performance: Though more computationally expensive than LDA, especially for large corpora, BERTopic benefits from GPU acceleration and modern embedding libraries
  • Customization: Users can plug in different embedding models (e.g., multilingual, domain-specific BERT) or clustering strategies, offering high flexibility

In summary, BERTopic is an ideal candidate for modern NLP projects that demand better handling of short documents, semantic closeness, and dynamic topic discovery. While LDA remains a valuable tool for understanding large corpora with sparse text, BERTopic represents the current state of the art in unsupervised topic modeling using dense representations.

Real-world ML system design for NLP text classification

Section titled “Real-world ML system design for NLP text classification”

This section walks through a complete text classification pipeline for a concrete case study, implemented in Python. Rather than reintroducing concepts already covered in earlier chapters, we will focus on how they come together in a realistic NLP project from end to end. Figure 5.1 shows the typical phases of an ML project.

Figure 5.1 – The paradigm of a typical ML project

Let’s break our case study down using the same structure that ML teams often follow in industry.

For our case study, suppose a company receives thousands of customer support emails every day and wants to route them automatically to the right team. The business objective can be phrased as follows:

We need to know, for each incoming email, which support queue should handle it and how urgent it is.

Next comes the technical objective.

Translating our business objective into a technical one, we define the task as follows:

“We will process the text of each email, transform it into numerical features, and train a classifier that predicts the target support queue for each message.”

This technical objective represents one possible design that satisfies the business need and may be refined as we learn more from the data. The next step is to outline a high-level plan for how the system will achieve this.

In our case study, the input data consists of raw email text and simple metadata such as submission time and product line. The output is a discrete label that represents the support queue. The tentative design is to read the email text, preprocess it, extract features such as TF-IDF vectors or Word2Vec-based embeddings, and feed those features into a supervised classifier.

When defining a potential solution approach, extra attention should be dedicated to identifying the best metric to focus on, also known as the objective function or error function. This is the metric by which the success of the solution will be evaluated. It is important to relate the metric to the original business or research objective.

For this email routing classifier, we will optimize macro-averaged F1 because each support queue is equally important, even when some receive fewer emails. In production, stakeholders may track metrics such as ticket resolution time and misrouting rate.

Now that we have a tentative plan, we can explore the data and evaluate the feasibility of the design.

Exploration has two goals: understanding the characteristics of the data and assessing whether the planned design is likely to succeed for our text classification task:

  • Data exploration: In our email routing case study, the raw text is far from clean. Many messages include long signature blocks, quoted reply chains, autofilled footers, emojis, inconsistent casing, and product-specific jargon. Some emails mix multiple languages or contain typos that affect tokenization. The purpose of data exploration is to identify these patterns early so we can decide which elements to clean, normalize, or retain. This ensures that the preprocessing and feature extraction steps support the downstream classifier rather than introducing noise.
  • Feasibility study: A feasibility study helps us estimate whether the input text contains enough signal to predict the support queue. For text data, a practical proxy is to measure the statistical dependency between terms and labels and inspect whether distinct patterns emerge for each class. In the code notebook presented later in this chapter, we compute a simple dependency score that highlights terms strongly associated with specific queues. If these patterns align with domain expectations, we gain initial confidence that a classifier can learn meaningful distinctions from the data.

With the feasibility study established, we can move on to implementing the ML solution.

Implementing the solution means turning the design into a reproducible pipeline. For our email routing case study, this includes loading the data, preprocessing the text, extracting features such as TF-IDF vectors or Word2Vec embeddings, training a classifier, and evaluating it on a held-out set. In the accompanying Jupyter notebook, we walk through each of these steps and highlight the decisions that matter most for a text classification workflow.

Even a simple text classifier requires experimenting with different preprocessing choices, vectorizers, and model hyperparameters. To keep these iterations organized, teams typically track each training run using an experiment tracking tool such as MLflow or W&B. For our case study, tracking lets us compare TF-IDF and Word2Vec models, review how changes to vocabulary size affect results, and ensure that we can reproduce the run that performs best. This turns the trial-and-error process of model development into a structured and auditable workflow.

We evaluate the classifier using the metric chosen earlier, macro-averaged F1, to ensure all support queues are treated equally. To obtain an unbiased estimate of performance, we apply the final model to a held-out test set that was not touched during model development. This avoids the common pitfall of repeatedly tuning the design based on test results, which would compromise our ability to predict real-world behavior once the classifier is deployed.

Once the model performs satisfactorily, the final step is deciding how it will be used in practice. For this email routing classifier, the output could be integrated into a customer support system where each incoming message is automatically tagged with the predicted queue. The model’s predictions may also be logged for monitoring, used to trigger escalation rules, or surfaced in an internal dashboard that visualizes queue volumes and patterns over time. The specific form of implementation depends on the business environment and downstream workflows.

The code for this case study is presented in a Jupyter notebook for clarity and narrative flow. In a production environment, the same logic would typically be refactored into modular Python files with clear interfaces and tests. A production-ready version would include unit tests for preprocessing and feature extraction, as well as data validation checks to catch schema changes or unexpected text anomalies. These practices ensure that the classifier can be deployed, monitored, and retrained reliably as the support system evolves.

With the overall design principles established, we can now turn to a concrete implementation of the case study. The following section walks through the full workflow in practice, showing how the concepts introduced earlier translate into code, decisions, and model results within a real text classification pipeline.

Reviewing our use case – ML system design for NLP classification in a Jupyter notebook

Section titled “Reviewing our use case – ML system design for NLP classification in a Jupyter notebook”

In this section, we will walk through a hands-on example. We will follow the steps we presented previously for articulating the problem, designing the solution, and evaluating the results. This section portrays the process that an ML developer goes through when working on a typical project in the industry. Refer to the following notebook: Ch5_Text_Classification_Traditional_ML.ipynb.

In this scenario, we are working for a financial news agency. Our objective is to publish news about companies and products in real time.

The CTO derives several technical objectives from the business objective. One objective is for the ML team: given a stream of financial tweets in real time, detect those tweets that discuss information about companies or products.

Let’s review the different parts of the pipeline, as shown in Figure 5.2:

Figure 5.2 – The structure of a typical ML pipeline

The phases of the pipeline in Figure 5.2 are explored in the following subsections.

In this part of the code, we set the key parameters. We choose to have them as a part of the code as this is instructional code made for presentation. In cases where the code is expected to go to production, it may be better to host the parameters in a separate .yaml file. That would also suit heavy iterations during the development phase as it will allow you to iterate over different code parameters without having to change the code, which is often desirable.

As for the choice of these values, it should be stressed that some of these values should be optimized to suit the optimization of the solution. We have chosen fixed measures here to simplify the process. For instance, the number of features to be used for classification is a fixed quantity here, but it should also be optimized to fit the training set.

This part loads the dataset. In our case, the loading function is simple. In other business cases, this part could be quite large as it may include a collection of SQL queries that are called. In such a case, it may be ideal to write a dedicated function in a separate .py file and source it via the imports section.

Here, we format the data in a way that suits our work. We also observe some of it for the first time. This allows us to get a feel of its nature and quality.

One key action we take here is to define the classes we care about.

As we discussed in Chapter 4, preprocessing is a key part of the pipeline. For instance, we may notice that many of the tweets have a URL, which we choose to remove.

At this point, we have observed the quality of the text and the distribution of the classes. This is where we explore any other characteristics of the data that may imply either its quality or its ability to indicate the desired class.

Next, we start processing the text. We seek to represent the text of each observation as a set of numerical features. The main reason for this is that traditional ML models are designed to accept numbers as input, not text. For instance, a common linear regression or logistic regression model is applied to numbers, not words, categories, or image pixels. Thus, we need to suggest a numeric representation for the text. This design constraint is lifted when working with language models such as BERT and GPT. We will see this in the coming chapters.

We partition the text into N-grams, where is a parameter of the code. is fixed in this code but should be optimized to best fit the training set.

Once the text has been partitioned into N-grams, they are modeled as numeric values. When a binary (that is, one-hot-encoding) method is chosen, the numerical feature that represents some N-gram gets a “1” when the observed text includes that N-gram, and “0” otherwise. See Figure 5.3 for an example. If a BOW approach is chosen, then the value of the feature is the number of times the N-gram appears in the observed text. Another common feature engineering method that isn’t implemented here is TF-IDF.

Here’s what we get by using unigrams only:

Input sentence: filing submitted

N-gram“report”“filing”“submitted”“product”“quarterly”The rest of the unigrams
Feature value01100(0s)

Figure 5.3 – Transforming an input text sentence into a numerical representation by partitioning to unigrams via one-hot encoding

The following figure shows what we get by using both unigrams and bigrams:

N-gram“report”“filing”“filing submitted”“report news”“submitted”The rest of the N-grams
Feature value01101(0s)

Figure 5.4 – Transforming an input text sentence into a numerical representation by partitioning with unigrams and bigrams via one-hot encoding

At this point in the code, the dataset hasn’t been partitioned into train and test sets, and the held-out set has not been excluded yet. This is because the binary and BOW feature engineering methods for any particular observation don’t depend on data outside of that underlying observation. With TF-IDF, this is different. Every feature value is calculated using the entire dataset for the document frequency. In order to avoid data leakage from our test set to our training set, we must partition the dataset and exclude the held-out set before fitting the TF-IDF vectorizer, so that the training features reflect only the distribution of the training data.

Now that our text has been represented as a feature, we can explore it numerically. We can look at its frequencies and statistics and get a sense of how it’s distributed.

This is the part where we must pause and carve out a held-out set, also known as a test set, but sometimes called the validation set. Since these terms are used differently in different sources, it is important to explain that what we refer to as a test set is a held-out set. A held-out set is a data subset that we dedicate to evaluating our solution’s performance. It is held out to simulate the results that we expect to get when the system is implemented in the real world and will encounter new data samples.

How do we know when to carve out the held-out set?

If we carve it out “too early,” such as right after loading the data, then we are guaranteed to keep it held out, but we may miss discrepancies in the data as it won’t take part in the preliminary exploration. If we carve it out “too late,” our design decisions might become biased because of it. For example, if we choose one ML model over another based on results that include the would-be held-out set, then our design becomes tailored to that set, preventing us from offering an objective evaluation of the model.

Then, we need to carry out the test set right before the first action that will feed into design decisions. In the next section, we’ll perform statistical analysis, which we can then feed into feature selection. Since that selection should be agnostic to the held-out set, we’ll exclude that set from this part onward.

Preliminary statistical analysis and feasibility study

Section titled “Preliminary statistical analysis and feasibility study”

This is the second part of the exploration phase we spoke about a few pages ago. The first part was data exploration, and we implemented that in the previous parts of the code. Now that we have the text represented as numerical features, we can perform the feasibility study.

We seek to measure the statistical dependence between the text inputs and the class values. Again, the motivation is to mimic the proxy that linear correlation provides with a regression problem. Rather than reintroducing the full mathematical derivation here, we provide a high-level idea and refer you to Appendix A for the complete formulation.

At a high level, we would like to evaluate whether any individual text feature shows a measurable relationship with the output class. If a feature is completely non-indicative of the class value, then in statistical terms, the feature and the class behave as if they were independent. Conversely, the larger the deviation from independence, the stronger the relationship between that feature and the class. Appendix A shows how we formalize this idea using conditional and marginal probabilities.

For our feasibility study, we compute this dependency measure for every feature-class pair and highlight the most indicative terms. We present the most indicative terms for class “0,” which is the class of tweets that do not indicate company or product information, and the most indicative terms for class “1,” which correspond to tweets containing such information.

This proves to us that there are indeed text terms that are indicative of the class value. This is a definite and clear success of the feasibility study. We are good to go, and we are expecting productive outcomes when implementing a classification model.

As a side note, keep in mind that as with most evaluations, what we’ve just mentioned is just one sufficient condition for the potential of the text to predict the class. If it had failed, it would not necessarily indicate that there is no feasibility. Just like when the linear correlation between and is near 0, this doesn’t mean that can’t infer; it just means that cannot infer via a linear model:

for every and

, belong to {0,1}

In the method that we’ve suggested, we make two key assumptions. First, we assume a particular feature design, meaning a fixed choice of for the N-gram partition and a defined quantitative encoding of each feature (e.g., binary, count-based, or TF-IDF). The second is that we perform the most simple evaluation of statistical dependency, a univariate statistical dependency. But it could be that only a higher order, such as multivariate, would have statistical dependence on the outcome class.

With a feasibility study of text classification, it’s ideal if the method is as simple as possible while covering as much of the “signal” it is hoping to uncover. The approach we designed in this example was derived after years of experience with different sets and various problem settings. We find that it hits the target very well.

With the feasibility study, we often kill two birds with one stone. As a feasibility study is successful, it not only helps us by confirming our plan, but it often hints toward the next steps that we should take. As we saw, some features are indicative of the class, and we learned which are the most significant. This allows us to reduce the feature space that the classification model will need to partition. We do that by keeping the most indicative features for each of the two classes. The number of features that we choose to keep would ideally be derived by computation constraints (for example, too many features would take too long to compute a model around), model capabilities (for example, too many features can’t be handled well by the model due to co-linearity), and optimization of the training results. In our code, we fixed this number to make things quick and simple.

It should be stressed that in many ML models, feature selection is an inherent part of the model design. For instance, with the least absolute shrinkage and selection operator (LASSO), the hyperparameter scaler of the norm component has an impact on which features get a zero coefficient, and thus get “thrown out.” It is possible and sometimes recommended to skip this part of the feature selection process, leave all features in, and let the model perform feature selection. It is advised to do so when all the models that are being evaluated and compared possess that characteristic.

Remember that at this point, we are only observing the train set. Now that we have decided which features to keep, we need to apply that selection to the test set as well.

With that, our data has been prepared for ML modeling.

To choose which model suits this problem best, we must train several models and see which one of them does best.

We should stress that we could do many things to try and identify the best model choice for a given problem. In our case, we only chose to evaluate a handful of models. Moreover, to make things simple and quick, we chose not to optimize the hyperparameters of each model in a comprehensive cross-validation approach. We simply fit each model to the training set with the default settings that its function comes with. Once we’ve identified the model we’d like to use, we optimize its hyperparameters for the train set via cross-validation.

By doing this, we identify the best model for the problem.

Here, we optimize the hyperparameters of the chosen model and fit it to our train set.

Generating the train results – design choices

Section titled “Generating the train results – design choices”

At this stage, we observe the results of the model for the first time. This result can be used to feed insight back into the design choice and the parameters chosen, such as the feature engineering method, the number of features left in the feature selection, and even the preprocessing scheme.

When feeding back insights from the results of the train set to the design of the solution, you are risking overfitting the train set. You’ll know whether you are by the gap between the results on the train set and the results on the test set.

While a gap is expected between these results in favor of the train results, a large gap should be treated as an alarm that the design isn’t optimal. In such cases, the design should be redone with systematic code-based parameters to ensure fair choices are made. It is possible to even carve out another semi-held-out set from the train set, often referred to as the validation set.

Generating the test results – presenting performance

Section titled “Generating the test results – presenting performance”

And that’s it! Now that the design has been optimized and we are confident that it suits our objective, we can apply it to our held-out set and observe the test results. These results are our most objective forecast of how well the system would do in the real world.

As mentioned previously, we should avoid letting these results impact our design choices.

In this chapter, we embarked on a comprehensive exploration of text classification, an indispensable aspect of NLP and ML. We delved into various types of text classification tasks, each presenting unique challenges and opportunities. This foundational understanding sets the stage for effectively tackling a broad range of applications, from sentiment analysis to spam detection.

We walked through the role of N-grams in capturing local context and word sequences within text, thereby enhancing the feature set used for classification tasks. We also illuminated the power of the TF-IDF method, the role of Word2Vec in text classification, and popular architectures such as CBOW and skip-gram, giving you a deep understanding of their mechanics.

Then, we introduced topic modeling and examined how popular algorithms such as LDA can be applied to text classification.

Lastly, we introduced a professional paradigm for leading an NLP-ML project in a business or research setting. We discussed the objectives and the project design aspect, and then dove into the system design. We implemented a real-world example in code and experimented with it.

In essence, this chapter aims to equip you with a holistic understanding of text classification and topic modeling by touching on the key concepts, methodologies, and techniques in the field. The knowledge and skills imparted will enable you to effectively approach and solve real-world text classification problems.

In the next chapter, we will introduce advanced methods for text classification. We will review deep learning methods such as language models, discuss their theory and design, and present a hands-on system design in code.

  1. Why do we need feature engineering for traditional text classification models?
  2. How do n-gram features differ between one-hot encoding and bag-of-words representations?
  3. What problem does TF-IDF solve compared to raw token counts, and how is it computed at a high level?
  4. Why must we split training and test data before fitting TF-IDF, and what risk are we avoiding?
  5. What are the two main Word2Vec architectures, and what is the intuition behind each one?
  6. Why is the naive softmax computationally expensive in Word2Vec, and which two approximations does the chapter highlight?
  7. How do GloVe and FastText extend the idea of static word embeddings?
  8. How does BERTopic differ from LDA in how it discovers topics?
  9. Which evaluation metrics does the chapter emphasize for text classification, and when are F1 micro and F1 macro useful?
  10. What additional metrics and workflow practices help when datasets are imbalanced and experimentation is iterative?
  • Zhu, X., & Ghahramani, Z. (2002). “Learning from labeled and unlabeled data with label propagation.” Technical Report, Carnegie Mellon.
  • Mikolov, T., Chen, K., Corrado, G., & Dean, J. (2013). Efficient Estimation of Word Representations in Vector Space. arXiv preprint arXiv:1301.3781.
  • Blei, D. M., Ng, A. Y., & Jordan, M. I. (2003). Latent Dirichlet Allocation. JMLR.
  • Salton, G. & Buckley, C. Term-Weighting Approaches in Automatic Text Retrieval. 1988.
  • Joachims, T. Text Categorization with Support Vector Machines. 1998.
  • Manning, C., Raghavan, P., Schütze, H. Introduction to Information Retrieval. 2008.
  • Mikolov, T. et al. “Efficient Estimation of Word Representations in Vector Space” (arXiv:1301.3781, 2013)
  • Pennington, J., Socher, R., Manning, C. “GloVe: Global Vectors for Word Representation” (EMNLP 2014).
  • Bojanowski, P. et al. “Enriching Word Vectors with Subword Information” (TACL 2017)
  • Arora, S., Liang, Y., & Ma, T. (2017). A Simple but Tough-to-Beat Baseline for Sentence Embeddings. ICLR.
  • Mikolov, T., Chen, K., Corrado, G., & Dean, J. (2013a). Efficient Estimation of Word Representations in Vector Space. arXiv:1301.3781.
  • Mikolov, T., Sutskever, I., Chen, K., Corrado, G., & Dean, J. (2013b). Distributed Representations of Words and Phrases and their Compositionality. NIPS.
  • Powers, D. M. W. (2011). Evaluation: From Precision, Recall and F-Measure to ROC, Informedness & Correlation. JoAI.
  • Bergstra, J. & Bengio, Y. (2012). Random Search for Hyper-Parameter Optimization. JMLR 13.
  • Snoek, J., Larochelle, H., & Adams, R. (2012). Practical Bayesian Optimization of Machine Learning Algorithms. NIPS.
  • Kohavi, R. (1995). A Study of Cross-Validation and Bootstrap for Accuracy Estimation and Model Selection. IJCAI.

You’re not the only one navigating fragmented tools, constant updates, and unclear best practices. Join a growing community of professionals exchanging insights that don’t make it into documentation.

Join our Discord at or scan the QR code below: A qr code on a white background AI-generated content may be incorrect.Follow us on Reddit at or scan the QR code below: A qr code on a white background AI-generated content may be incorrect.