Unleashing Machine Learning Potential in NLP
local graph
Chapter 3 — Unleashing Machine Learning Potential in NLP
Section titled “Chapter 3 — Unleashing Machine Learning Potential in NLP”In this chapter, we will delve into the fundamentals of machine learning and preprocessing techniques that are essential for natural language processing (NLP) tasks. Machine learning is a powerful tool for building models that can learn from data, and NLP is one of the most exciting and challenging applications of machine learning.
By the end of this chapter, you will have gained an understanding of data exploration, preprocessing, and data splitting, know how to deal with imbalanced data techniques, and learned about some of the common ML models required for successful machine learning, particularly in the context of NLP.
The following topics will be covered in this chapter:
- Data exploration
- Common machine learning models
- Ensemble models
- Neural networks and transformers
- Splitting data
- Hyperparameter tuning
- Model underfitting and overfitting
- Handling imbalanced data
- Dealing with correlated data and features
Technical requirements
Section titled “Technical requirements”Prior knowledge of programming languages, particularly Python, is assumed in this chapter and subsequent chapters of this book. It is also expected that you have already gone through previous chapters to become acquainted with the necessary linear algebra and statistics concepts that will be discussed in detail.
Data exploration
Section titled “Data exploration”When working in a learning environment, datasets are often well-known and preprocessed, such as Kaggle datasets. However, in real-world business environments, one important early task is to define the dataset based on all relevant sources, to explore the gathered data, and to find the best method for preprocessing it. That task is the foundation for evaluating and ultimately deciding on the machine learning and natural language models that will be applied. Both of these tasks are to be guided by the underlying problem that we are trying to solve. Therefore, our process relies on a thorough understanding of the business problem at hand.
In NLP, the data can be quite complex, as it often includes text and speech data that can be unstructured and difficult to analyze. This complexity makes preprocessing an essential step in preparing the data for machine learning models. The first step of any NLP or machine learning solution starts with exploring the data to learn more about it, which helps us decide on our path to tackling the problem.
Once the data has been preprocessed, the next step is to explore it to gain a better understanding of its characteristics and structure. Data exploration is an iterative process that involves visualizing and analyzing the data, looking for patterns and relationships, and identifying potential issues or outliers. This process can help us determine which features are most important for our machine learning models and identify any potential biases or data quality issues.
To streamline data and enhance analysis through machine learning models, preprocessing methods such as tokenization, stemming, and lemmatization can be employed. In this chapter, we will provide an overview of general preprocessing techniques for machine learning problems. In the following chapter, we will delve into preprocessing techniques specific to text processing. It is important to note that employing effective preprocessing techniques can significantly enhance the performance and accuracy of machine learning models, making them more robust and reliable.
Finally, once the data has been preprocessed and explored, we can start building our machine learning models. There is no single magical solution that works for all machine learning problems, so it’s important to carefully consider which models are best suited for the data and the problem at hand. Different types of NLP models exist, encompassing rule-based, statistical, and deep learning models. Each model type possesses unique strengths and weaknesses, underscoring the importance of selecting the most fitting one for the specific problem and dataset at hand.
We will now explore the core methods for data exploration and preparation.
Data visualization
Section titled “Data visualization”Data visualization is a crucial component of machine learning as it allows us to understand and explore complex datasets more easily. It involves creating visual representations of data using charts, graphs, and other types of visual aids. By visually presenting data, we can discern patterns, trends, and relationships that might not be readily evident when examining the raw data alone.
For NLP tasks, data visualization can help us gain insights into the linguistic patterns and structures in text data. For example, we can create word clouds to visualize the frequency of words in a corpus or use heatmaps to display the co-occurrence of words or phrases. We can also use scatter plots and line graphs to visualize changes in sentiment or topic over time.
One common type of visualization for machine learning is the scatter plot, which is used to display the relationship between two variables. By plotting the values of two variables on the X and Y axes, we can identify any patterns or trends that exist between them. Scatter plots are particularly useful for identifying clusters or groups of data points that share similar characteristics.
Another type of visualization that’s frequently employed in machine learning is the histogram, a tool that illustrates the distribution of a single variable. By grouping data into bins and portraying the frequency of data points in each bin, we can pinpoint the range of values that predominate in the dataset. Histograms prove useful for detecting outliers or anomalies, and they aid in recognizing areas where the data may exhibit skewness or bias.
Let us go beyond the basic visualizations and highlight more complicated and useful algorithms. Machine learning practitioners often use more advanced techniques, such as dimensionality reduction and network visualizations. Dimensionality reduction techniques, such as principal component analysis (PCA) and t-distributed stochastic neighbor embedding (t-SNE), are commonly used to visualize or explore data more easily. The virtue of dimensionality reduction for visualization is in the fact that it allows us to portray high-dimensional data (i.e., in 4 dimensions and more) on a 2D or 3D grid. Network visualizations, on the other hand, are used to display complex relationships between entities, such as the co-occurrence of words or the connections between social media users. Figure 3.1 shows how useful these techniques really are:

Figure 3.1 – Dimensionality reduction methods. Top: PCA, bottom: t-SNE
We use the classic Digits benchmark, where each handwritten numeral is captured as an 8 × 8 grayscale image and flattened into a 64-feature vector, yielding a high-dimensional dataset of 10 classes (digits 0–9).
The dataset can be obtained by calling: from sklearn.datasets import load_digits
In the top plot, PCA compresses the 64-dimensional pixel data into two axes that capture maximum global variance, revealing broad structure but only partial class separation (some digits overlap). The bottom plot uses t-SNE, which preserves local neighborhoods rather than global variance. Here, the same digits form tight, well-separated clusters, making the underlying category structure visually obvious. Together, the two projections demonstrate how different dimensionality-reduction methods offer complementary insights during exploration of data visualization.
Data cleaning
Section titled “Data cleaning”Data cleaning, sometimes called data cleansing or data scrubbing, involves recognizing and rectifying or eliminating inconsistencies and inaccuracies within a dataset. This crucial phase in data preparation for machine learning significantly influences the accuracy and performance of a model, relying on the quality of the data used for training. Numerous prevalent techniques are employed in data cleaning. Let’s take a closer look.
Handling missing values
Section titled “Handling missing values”Missing data is a common problem that occurs in many machine learning projects. Dealing with missing data is important because machine learning models cannot handle missing data and will either produce errors or provide inaccurate results.
There are several methods for dealing with missing data in machine learning projects:
- Dropping rows: Addressing missing data can involve a straightforward approach of discarding rows that contain missing values. Nevertheless, exercising caution is paramount when employing this method, as excessive row removal may result in the loss of valuable data, impacting the overall accuracy of the model. We usually use this method when we have relatively few rows in our dataset that have missing values. In this case, removing those few rows can be a good, easy approach to training our model, while the final performance will not be affected significantly.
- Dropping columns: Another approach is to drop the columns that contain missing values. This method can be effective if the missing values are concentrated in a few columns and if those columns are not important for the analysis. However, when that isn’t the case, dropping important columns can lead to a loss of valuable information. It is better to perform an analysis to evaluate the correlation of the values in these columns with the target class or value before dropping these columns.
- Mean/median/mode imputation: Mean, median, and mode imputation entail substituting missing values with the mean, median, or mode derived from the non-missing values within the corresponding column. This method is easy to implement and can be effective when the missing values are few and randomly distributed. However, it can also introduce bias and affect the variability of the data.
- Regression imputation: Regression imputation involves predicting the missing values based on the values of other variables in the dataset. This method can be effective when the missing values are statistically related to other variables in the dataset, but it requires a regression model to be generated for each variable to be imputed.
- Multiple imputation: Multiple imputation encompasses generating multiple imputed datasets through statistical models, followed by amalgamating the outcomes to produce a conclusive dataset. This approach proves efficacious, particularly when dealing with non-randomly distributed missing values and a substantial number of gaps in the dataset.
- K-nearest neighbor imputation: K-nearest neighbor imputation entails identifying the k-nearest data points to the missing value and utilizing their values to impute the absent value. This method can be effective when the missing values are clustered together in the dataset. In this approach, we can find the most similar records in the dataset to the record that has the missing value, and then use the sample mean of the values of those records for that specific record as the missing value.
In essence, selecting a method to handle missing data hinges on factors such as the nature and extent of the missing data, analysis objectives, and resource availability. It is crucial to thoughtfully assess the pros and cons of each method and opt for the most suitable approach tailored to the specific project.
Removing duplicates
Section titled “Removing duplicates”Eliminating duplicates is a prevalent preprocessing measure that’s employed to cleanse datasets by detecting and removing identical records. The occurrence of duplicate records may be attributed to factors such as data entry errors, system glitches, or data merging processes. The presence of duplicates can skew models and yield inaccurate insights. Hence, it is imperative to recognize and eliminate duplicate records to uphold the accuracy and dependability of the dataset.
There are different methods for removing duplicates in a dataset. The most common method is to compare all the rows of the dataset to identify duplicate records. If two or more rows have the same values in all the columns, they are considered duplicates. In some cases, it may be necessary to compare only a subset of columns if certain columns are more prone to duplicates.
Another method is to use a unique identifier column to identify duplicates. A unique identifier column is a column that contains unique values for each record, such as an ID number or a combination of unique columns. By comparing the unique identifier column, it is possible to identify and remove duplicate records from the dataset.
After identifying the duplicate records, the next step is to decide which records to keep and which ones to remove. One approach is to keep the first occurrence of a duplicate record and remove all subsequent occurrences. Another approach is to keep the record with the most complete information, or the record with the most recent timestamp.
It’s crucial to recognize that the removal of duplicates might lead to a reduction in dataset size, potentially affecting the performance of machine learning models. Consequently, assessing the impact of duplicate removal on both the dataset and the machine learning model is essential. In some cases, it may be necessary to keep duplicate records if they contain important information that cannot be obtained from other records.
Standardizing and transforming data
Section titled “Standardizing and transforming data”Standardizing and transforming data is a critical step in preparing data for machine learning tasks. This process involves scaling and normalizing the numerical features of the dataset to make them easier to interpret and compare. The main objective of standardizing and transforming data is to enhance the accuracy and performance of a machine learning model by mitigating the influence of features with diverse scales and ranges. A widely used method for standardizing data is referred to as “standardization” or “Z-score normalization.” This technique involves transforming each feature such that it has a mean of zero and a standard deviation of one. The formula for standardization is shown in the following equation:

Here, x represents the feature, denotes the mean of the feature, indicates the standard deviation of the feature, and represents the new value assigned to the feature. By standardizing the data in this way, the range of each feature is adjusted to be centered around zero, which makes it easier to compare features and prevents features with large values from dominating the analysis.
Another technique for transforming data is “min-max scaling.” This method rescales the data to a consistent range of values, commonly ranging between 0 and 1. The formula for min-max scaling is shown here:

In this equation, represents the feature, signifies the minimum value of the feature, and denotes the maximum value of the feature. Min-max scaling proves beneficial when the precise distribution of the data is not crucial, but there is a need to standardize the data for meaningful comparisons across different features.
Transforming data can also involve changing the distribution of the data. A frequently applied transformation is log transformation, which is employed to alleviate the influence of outliers and skewness within the data. This transformation involves taking the logarithm of the feature values, which can help to normalize the distribution and reduce the influence of extreme values.
Overall, standardizing and transforming data constitutes a pivotal stage in the data preprocessing workflow for machine learning endeavors. Through scaling and normalizing features, we can enhance the accuracy and performance of the machine learning model, rendering the data more interpretable and conducive to meaningful comparisons.
Handling outliers
Section titled “Handling outliers”Outliers are data points that markedly deviate from the rest of the observations in a dataset. Their occurrence may stem from factors such as measurement errors, data corruption, or authentic extreme values. The presence of outliers can wield a substantial influence on the outcomes of machine learning models, introducing distortion to the data and disrupting the relationships between variables. Therefore, handling outliers is an important step in preprocessing data for machine learning.
There are several methods for handling outliers:
- Removing outliers: One straightforward approach involves eliminating observations identified as outliers from the dataset, which means eliminating the rows that hold the outlier values. Nevertheless, exercising caution is paramount when adopting this method, as excessive removal of observations may result in the loss of valuable information and potentially introduce bias to the analysis results.
- Transforming data: Applying mathematical functions such as logarithms or square roots to transform the data can mitigate the influence of outliers. For instance, taking the logarithm of a variable can alleviate the impact of extreme values, given the slower rate of increase in the logarithmic scale compared to the original values.
- Winsorizing: Winsorizing is a technique that caps outliers by replacing any value below a chosen lower percentile (e.g., 1%) with that percentile’s value and any value above an upper percentile (e.g., 99%) with that percentile’s value. This preserves sample size while limiting the influence of extreme observations and keeping the overall distribution shape.
- Imputing values: Imputation involves replacing missing or extreme values with estimated values derived from the remaining observations in the dataset. For instance, substituting extreme values with the median or mean of the remaining observations is a common imputation technique.
- Using robust statistical methods: Robust statistical methods exhibit lower sensitivity to outliers, leading to more accurate results even in the presence of such extreme values. For instance, opting for the median instead of the mean can effectively diminish the influence of outliers on the final results.
It’s crucial to emphasize that selecting an outlier-handling method should be tailored to the unique characteristics of the data and the specific problem at hand. Generally, employing a combination of methods is advisable to address outliers comprehensively, and assessing the impact of each method on the results is essential. Moreover, documenting the steps taken to manage outliers is important for reproducibility and to provide clarity on the decision-making process.
The next step in our preparation of the data for machine learning modeling is to design it to best serve our problem. We call that step feature engineering.
Feature engineering
Section titled “Feature engineering”Feature engineering is the process of transforming, selecting, and extracting features from raw (or preprocessed) data to improve the performance of machine learning models. Features are the individual measurable properties or characteristics of the data that can be used to make predictions or classifications. We should stress that while classic feature selection and scaling remain vital, today’s NLP pipelines increasingly draw their features directly from large, self-supervised language models, thus ridding us of the need to design text features.
One common technique in feature engineering is feature extraction, which involves transforming the data into a new set of features that may be more useful for the model.
Another technique in feature engineering is feature selection, which involves selecting a subset of relevant features from the dataset to improve the model’s accuracy and reduce its complexity. This can be done through statistical methods such as correlation analysis or feature importance ranking using decision trees or random forests.
The primary distinction between feature extraction and feature selection lies in their approaches: While feature extraction algorithms reconfigure and transform the data into a new feature space, feature selection methods retain a subset of the original (or extracted) features without modifying them. It is interesting to note that feature engineering can also be done through various techniques such as dimensionality reduction, PCA, or t-SNE, which we showcased above for data visualization.
Let us review some of the common methods for feature engineering. As we do so, we will notice calculations and algorithms that are common to both data exploration and feature engineering. The rationale in this commonality is that in both stages, we seek to identify the “signal” that the data is encapsulating. In data exploration, we seek to vet the data by identifying whether the data is related to the problem we are trying to solve, while in feature engineering, we are seeking to set the data in a manner that best correlates with the outcome we are trying to model.
Feature scaling
Section titled “Feature scaling”Feature scaling is an important technique in feature engineering that involves scaling the values of features to the same range, typically between 0 and 1 or -1 and 1. We touched on it earlier in the context of data exploration, and we now note it as a feature engineering method as well.
Here are several simple, common methods for feature scaling:
| Technique | Typical Use Case / Strength | Formula | Key Notes |
|---|---|---|---|
| Min-Max Scaling (Normalization) | Features on heterogeneous scales. Preserves relative distances. | Output range is 0–1. Sensitive to outliers. | |
| Standardization (Z-Score) | Centering + unit variance for many ML algos. Less outlier-sensitive than min-max. | Produces mean ≈ 0, std ≈ 1. Still affected by extreme outliers. | |
| Robust Scaling | Data with heavy-tailed or skewed distributions. | and are 3 rd and 1 st quartiles, resp. Guards against outliers. | |
| Power / Box-Cox Transform | Stabilizing variance, making distributions more Gaussian. | chosen via maximum-likelihood. Applies to x where x>0 only. |
Table 3.1 – Common methods for feature scaling
These are some of the most common methods for feature scaling in machine learning. The choice of method depends on the distribution of the data, the machine learning algorithm being used, and the specific requirements of the problem.
Now, let’s review several techniques in feature extraction. Feature extraction is a method that involves creating new features by combining or transforming existing ones. This can be done through techniques such as polynomial expansion, logarithmic transformation, or interaction terms.
Polynomial expansion
Section titled “Polynomial expansion”Polynomial expansion creates additional features by raising existing variables to powers and multiplying them together, thus allowing linear models to capture non-linear patterns.
A single feature can be expanded with,, and so on. Two features and yield interaction terms such as (). Tools such as scikit-learn ’s PolynomialFeatures automate this to a user-defined degree.
When creating interaction terms, it is important to consider which features to combine and how to combine them. Here are some common techniques:
- Domain knowledge: Use domain knowledge or expert intuition to identify which features are likely to interact and how they might interact.
- Pairwise combinations: Create interaction terms by pairwise combining all pairs of features in the dataset. This can be computationally expensive, but it can help identify potential interaction effects.
- PCA: Use PCA to identify the most important combinations of features, and create interaction terms based on these combinations.
Here’s an example:
In a housing-price dataset, a straight-line model
where are to be learned,
may under-fit. We know marginal price gains tend to diminish as homes get bigger. Adding size² yields
So, the curve can rise linearly for small homes and plateau for mansions, matching empirical trends without switching to a more complex learner. We’ll stress that is expected to be positive and is expected to be negative, allowing for the curve to plateau.
Polynomial terms boost expressiveness but also balloon dimensionality, which can overfit and obscure interpretation. Keep degrees low (often ≤ 3) and pair expansion with regularization techniques such as Ridge and LASSO, or apply feature selection to retain only the most informative terms.
High-degree expansions were once popular but proved brittle and computationally costly; modern practice limits the degree or opts for kernels/neural nets when richer non-linearity is needed.
Logarithmic transformation
Section titled “Logarithmic transformation”Logarithmic transformation is a common feature engineering technique that’s used in data preprocessing. The goal of logarithmic transformation is to make data less skewed and more symmetric by applying a logarithmic function to the features. This technique can be particularly useful for features that are skewed, such as those with a long tail of high values.
The logarithmic transformation is defined as an equation taking the natural logarithm of the data:
Here, is the transformed data and is the original data. The logarithmic function maps the original data to a new space, where the relationship between the values is preserved but the scale is compressed. The logarithmic transformation is particularly useful for features with large ranges or that are distributed exponentially, such as the prices of products or the incomes of individuals.
One of the benefits of the logarithmic transformation is that it can help normalize data and make it more suitable for certain machine learning algorithms that assume normally distributed data. Additionally, logarithmic transformation can reduce the impact of outliers on the data, which can help improve the performance of some models.
It’s important to note that logarithmic transformation is not appropriate for all types of data. For example, if the data includes zero or negative values, the logarithmic transformation cannot be applied directly. In these cases, a modified logarithmic transformation, such as adding a constant before taking the logarithm, may be used. Overall, logarithmic transformation is a useful technique for feature engineering that can help improve the performance of machine learning models, especially when dealing with skewed or exponentially distributed data.
Self-supervised representations as features
Section titled “Self-supervised representations as features”Machine learning pipelines no longer start from scratch when turning raw text into numbers. Modern language models, trained with self-supervised objectives, act as universal feature factories that distil syntactic and semantic cues into dense vectors ready for any downstream learner.
Self-supervised learning relies on predictive training objectives, including the following:
- Masked-Language Modeling (MLM): Models such as BERT hide a fraction of tokens and predict them from context, forcing the network to internalize word order and meaning. We will dive deeper into this concept later in the book.
- Contrastive objectives: Sentence encoders such as SimCSE, E5, or Instructor create pairs of semantically similar/dissimilar sentences and train the model to pull true pairs closer while pushing unpaired sentences apart, yielding high-quality sentence-level embeddings.
These objectives produce fixed-length vectors, with one vector representing a token, sentence, or document. These numerical vectors plug straight into traditional models (e.g., logistic regression, SVMs, and gradient-boosted trees), exactly as TF-IDF vectors do, but with far richer information.
Here’s an example of pulling embedding representation from Hugging Face:
from transformers import AutoTokenizer, AutoModelimport torchtokenizer = AutoTokenizer.from_pretrained( “sentence-transformers/all-mpnet-base-v2”)model = AutoModel.from_pretrained( “sentence-transformers/all-mpnet-base-v2”)model.eval()def embed(texts): inputs = tokenizer( texts, padding=True, truncation=True, return_tensors=”pt”) with torch.no_grad(): reps = model(**inputs).last_hidden_state.mean(1) return repsprint(embed(“flower”))When you print the embedding for the word “flower”, you will see the rich numerical representation it brings. Note, however, that using this method to embed a single word is just for demonstration purposes. Since the semantic context of the words is important, we will embed whole sentences, meaning we will embed all the words simultaneously.
Word embeddings are known to capture similarities between the words they represent. To visualize these relations, see this notebook: https://github.com/LiorGazit/Word_Vector_Functionalities/blob/master/playing_with_vector_embeddings.ipynb.
In summary, feature extraction is a critical step in the machine learning pipeline as it can significantly impact the performance and interpretability of the resulting models. Effective feature engineering requires domain knowledge, creativity, and an iterative process of testing and refining different techniques until the optimal set of features is identified.
Now that we have established a set of features, we can further refine it by applying smart selection techniques.
Feature selection
Section titled “Feature selection”Feature selection involves choosing the most pertinent features from a dataset for constructing a machine learning model. The objective is to decrease the number of features without substantially compromising the model’s accuracy, resulting in enhanced performance, quicker training, and a more straightforward interpretation of the model.
Many approaches to feature selection exist. Let’s review some of the best and most practical ones we recommend.
Filter methods
Section titled “Filter methods”These techniques employ statistical methods to rank features according to their correlation with the target variable. Common methods encompass chi-squared, mutual information, and correlation coefficients. Features are subsequently chosen based on a predefined threshold.
Chi-squared
Section titled “Chi-squared”The chi-squared test is a widely employed statistical method in machine learning for feature selection that’s particularly effective for categorical variables. This test gauges the dependence between two random variables, providing a P-value that signifies the likelihood of obtaining a result as extreme as or more extreme than the actual observations.
In hypothesis testing, the chi-squared test assesses whether the collected data aligns with the expected data. A small chi-squared test statistic indicates a robust match, while a large statistic implies a weak match. A P-value less than or equal to 0.05 leads to the rejection of the null hypothesis, considering it highly improbable. Conversely, a P-value greater than 0.05 results in accepting or “failing to reject” the null hypothesis. When the P-value hovers around 0.05, further scrutiny of the hypothesis is warranted.
In feature selection, the chi-squared test evaluates the relationship between each feature and the target variable in the dataset. It determines significance based on whether a statistically significant difference exists between the observed and expected frequencies of the feature, assuming independence between the feature and target. Features with a high chi-squared score exhibit a stronger dependence on the target variable, making them more informative for classification or regression tasks. The formula for calculating chi-squared is presented in the following equation:

In this equation, represents the observed value and
represents the expected value. The computation involves finding the difference between the observed frequency and the expected frequency, squaring the result, and then dividing by the expected frequency. The summation of these values across all categories of the feature yields the overall chi-squared statistic for that feature.
The degrees of freedom for the test rely on the number of categories in the feature and the number of categories in the target variable.
An exemplary application of chi-squared feature selection lies in text classification, particularly in scenarios where the presence or absence of specific words in a document serves as features. The chi-squared test helps identify words strongly associated with a particular class or category of documents, subsequently enabling their use as features in a machine learning model. In categorical data, especially where the relationship between features and the target variable is non-linear, chi-squared proves to be a valuable method for feature selection. However, its suitability diminishes for continuous or highly correlated features, where alternative feature selection methods may be more fitting.
Here is simple code that portrays how this method can be used to reduce feature dimensionality. For this example, we use a dataset with nearly 20,000 features.
from sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.feature_selection import SelectKBest, chi2from sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import make_pipelinefrom sklearn.model_selection import cross_val_score# Load a text-classification dataset:train = fetch_20newsgroups( subset=”train”, categories=[“sci.space”, “rec.autos”])# Number of χ²-selected features to keep:k_values = [‘all’, 2000, 200, 20, 2]# Build a pipeline: TF-IDF -> χ² filter -> classifier:for k in k_values: clf = make_pipeline( TfidfVectorizer(stop_words=”english”), SelectKBest(score_func=chi2, k=k), LogisticRegression(max_iter=1000) ) scores = cross_val_score(clf, train.data, train.target, cv=5, scoring=”accuracy”) print(f”Mean CV accuracy with top {k:>4} χ² features: {100*scores.mean():.0f}%”)The output is as follows:
Mean CV accuracy with top all χ² features: 99%Mean CV accuracy with top 2000 χ² features: 98%Mean CV accuracy with top 200 χ² features: 95%Mean CV accuracy with top 20 χ² features: 88%Mean CV accuracy with top 2 χ² features: 76%Mutual information
Section titled “Mutual information”Mutual information acts as a metric to gauge the interdependence of two random variables. In the context of feature selection, it quantifies the information a feature provides about the target variable. The core methodology entails calculating the mutual information between each feature and the target variable, ultimately selecting features with the highest mutual information scores.
Mathematically, the mutual information between two discrete random variables, X and Y, can be defined as follows:

In the given equation, represents the joint probability mass function of and, while and denote the marginal probability mass functions of and, respectively.
In the context of feature selection, mutual information calculation involves treating the feature as and the target variable as. By computing the mutual information score for each feature, we can then select features with the highest scores.
To estimate the probability mass functions needed for calculating mutual information, histogram-based methods can be employed. This involves dividing the range of each variable into a fixed number of bins and estimating the probability mass functions based on the frequencies of observations in each bin. Alternatively, kernel density estimation can be utilized to estimate the probability density functions, and mutual information can then be computed based on the estimated densities.
In practical applications, mutual information is often employed alongside other feature selection methods, such as chi-squared or correlation-based methods, to enhance the overall performance of the feature selection process.
Correlation coefficients
Section titled “Correlation coefficients”Correlation coefficients serve as indicators of the strength and direction of the linear relationship between two variables. In the realm of feature selection, these coefficients prove useful in identifying features highly correlated with the target variable, thus serving as potentially valuable predictors.
The prevalent correlation coefficient employed for feature selection is the Pearson correlation coefficient, also referred to as Pearson’s r. Pearson’s r measures the linear relationship between two continuous variables, ranging from -1 (indicating a perfect negative correlation) to 1 (indicating a perfect positive correlation), with 0 denoting no correlation. Its calculation involves dividing the covariance between the two variables by the product of their standard deviations, as depicted in the following equation:

In the given equation, and represent the two variables of interest, denotes the covariance function, and represents the standard deviation function.
Utilizing Pearson’s for feature selection involves computing the correlation between each feature and the target variable. Features with the highest absolute correlation coefficients are then selected. A high absolute correlation coefficient signifies a strong correlation with the target variable, whether positive or negative. The interpretation of Pearson correlation values and their degree of correlation is outlined here:
| Pearson Correlation Value | Degree of Correlation |
|---|---|
| ± 1 | Perfect |
| ± 0.50 - ± 1 | High degree |
| ± 0.30 - ± 0.49 | Moderate degree |
| < +0.29 | Low degree |
| 0 | No correlation |
Table 3.2 – Pearson correlation values and their degree of correlation
Keep in mind a few limitations about Pearson’s r. It is only appropriate for identifying linear relationships between variables. If the relationship is nonlinear, or some variables are categorical, other correlation coefficients such as Spearman’s or Kendall’s may be more appropriate. Pearson’s r must be used with caution when dealing with very small samples, as it may be unstable. And finally, it is important to be mindful when interpreting correlation coefficients that high correlation does not necessarily imply causation.
Wrapper methods
Section titled “Wrapper methods”These techniques delve into subsets of features through iterative model training and testing. Widely known methods include forward selection, backward elimination, and recursive feature elimination. While computationally demanding, these methods have the potential to significantly enhance model accuracy.
A concrete illustration of a wrapper method is recursive feature elimination (RFE). Functioning as a backward elimination approach, RFE systematically removes the least important feature until a predetermined number of features remain. During each iteration, a machine learning model is trained on the existing features, and the least important feature is pruned. This sequential process persists until the specified number of features is attained. The feature importance score can be extracted using diverse methods, including coefficient values from linear models or feature importance scores derived from decision trees. RFE is a computationally expensive method, but it can be useful when the number of features is very large, and there is a need to reduce the feature space. An alternative approach is to have feature selection during the training process, something that’s done via embedding methods.
Embedded methods
Section titled “Embedded methods”These methods select features during the training process of the model. Popular methods include LASSO and ridge regression, decision trees, and random forests.
LASSO, an acronym for Least Absolute Shrinkage and Selection Operator, serves as a linear regression technique that’s commonly employed for feature selection in machine learning. Its mechanism involves introducing a penalty term to the standard regression loss function. This penalty encourages the model to reduce the coefficients of less important features to zero, effectively eliminating them from the model.
The LASSO method proves especially valuable when grappling with high-dimensional data, where the number of features far exceeds the number of samples. In such scenarios, discerning the most crucial features for predicting the target variable can be challenging. LASSO comes to the fore by automatically identifying the most relevant features while simultaneously shrinking the coefficients of others.
The LASSO method works by finding the solution for the following optimization problem, which is a minimization problem:

In the given equation, vector represents the target variable, denotes the feature matrix, signifies the vector of regression coefficients, is a hyperparameter dictating the intensity of the penalty term, and stands for the norm of the coefficients (that is, the sum of their absolute values).
The inclusion of the penalty term in the objective function prompts the model to precisely zero out certain coefficients, essentially eliminating the associated features from the model. The degree of penalty strength is governed by the hyperparameter, which can be fine-tuned through the use of cross-validation.
LASSO has several advantages over other feature selection methods, such as its ability to handle correlated features and its ability to perform feature selection and regression simultaneously. However, LASSO has some limitations, such as its tendency to select only one feature from a group of correlated features, and its performance may deteriorate if the number of features is much larger than the number of samples.
Consider the application of LASSO for feature selection in predicting house prices. Imagine a dataset encompassing details about houses – such as the number of bedrooms, lot size, construction year, and so on – alongside their respective sale prices. Employing LASSO, we can pinpoint the most crucial features to predict the sale price while concurrently fitting a linear regression model to the dataset. The outcome is a model that’s ready to forecast the sale price of a new house based on its features.
Ridge regression
Section titled “Ridge regression”Ridge regression, a linear regression method applicable to feature selection, closely resembles ordinary least squares regression but introduces a penalty term to the cost function to counter overfitting.
In ridge regression, the cost function undergoes modification with the inclusion of a penalty term directly proportional to the square of the coefficients’ magnitude. This penalty term is regulated by a hyperparameter, often denoted as or dictating the regularization strength. When is set to zero, ridge regression reverts to ordinary least squares regression.
The penalty term’s impact manifests in shrinking the coefficients’ magnitude toward zero. This proves beneficial in mitigating overfitting, discouraging the model from excessively relying on any single feature. In effect, the penalty term acts as a form of feature selection by reducing the importance of less relevant features.
The equation for the ridge regression loss function is as follows:

Here, we have the following:
- is the number of samples in the training set.
- is the column vector of target values of size N.
- is the design matrix of input features.
- is the vector of regression coefficients to be estimated.
- is the regularization parameter that controls the strength of the penalty term. It is a hyperparameter that needs to be tuned.
The first term in the loss function measures the mean squared error between the predicted values and the true values. The second term is the penalty term that shrinks the coefficients toward zero. The ridge regression algorithm finds the values of the regression coefficients that minimize this loss function. By tuning the regularization parameter,, we can control the bias-variance trade-off of the model, with higher alpha values leading to more regularization and less overfitting.
Ridge regression can be used for feature selection by examining the magnitudes of the coefficients produced by the model. Features with coefficients that are close to zero or smaller are considered less important and can be dropped from the model. The value of can be tuned using cross-validation to find the optimal balance between model complexity and accuracy.
One of the main advantages of ridge regression is its ability to handle multicollinearity, which occurs when there are strong correlations between the independent variables. In such cases, ordinary least squares regression can produce unstable and unreliable coefficient estimates, but ridge regression can help stabilize the estimates and improve the overall performance of the model.
Choosing LASSO or ridge regression
Section titled “Choosing LASSO or ridge regression”Ridge regression and LASSO are both regularization techniques that are used in linear regression to prevent overfitting of the model by penalizing the model’s coefficients. While both methods seek to prevent overfitting, they differ in their approach to how the coefficients are penalized.
Ridge regression adds a penalty term to the sum of squared errors (SSE) that is proportional to the square of the magnitude of the coefficients. The penalty term is controlled by a regularization parameter (), which determines the amount of shrinkage applied to the coefficients. This penalty term shrinks the values of the coefficients toward zero but does not set them exactly to zero. Therefore, ridge regression can be used to reduce the impact of irrelevant features in a model, but it will not eliminate them completely.
On the other hand, LASSO also adds a penalty term to the SSE, but the penalty term is proportional to the absolute value of the coefficients. Like ridge, LASSO also has a regularization parameter () that determines the amount of shrinkage applied to the coefficients. However, LASSO has a unique property of setting some of the coefficients exactly to zero when the regularization parameter is sufficiently high. Therefore, LASSO can be used for feature selection as it can eliminate irrelevant features and set their corresponding coefficients to zero.
In general, if the dataset has many features and a small number of them are expected to be important, LASSO regression is a better choice as it will set the coefficients of irrelevant features to zero, leading to a simpler and more interpretable model. On the other hand, if most of the features in the dataset are expected to be relevant, ridge regression is a better choice as it will shrink the coefficients toward zero but not set them exactly to zero, preserving all the features in the model.
However, it is important to note that the optimal choice between ridge and LASSO depends on the specific problem and dataset, and it is often recommended to try both and compare their performance using cross-validation techniques.
Dimensionality reduction techniques
Section titled “Dimensionality reduction techniques”These methods transform the features into a lower-dimensional space while retaining as much information as possible. Popular methods include PCA, linear discriminant analysis (LDA), and t - SNE.
PCA is a widely used technique in machine learning for reducing the dimensionality of large datasets while retaining most of the important information. The basic idea of PCA is to transform a set of correlated variables into a set of uncorrelated variables known as principal components.
The goal of PCA is to identify the directions of maximum variance in the data and project the data in these directions, reducing the dimensionality of the data. The principal components are sorted in order of the amount of variance they explain, with the first principal component explaining the most variance in the data.
The PCA algorithm involves the following steps:
- Standardize the data: PCA requires the data to be standardized – that is, each feature must have zero mean and unit variance.
- Compute the covariance matrix: The covariance matrix is a square matrix that measures the linear relationships between pairs of features in the data.
- Compute the eigenvectors and eigenvalues of the covariance matrix: The eigenvectors represent the primary directions of the highest variance within the dataset, while the eigenvalues quantify the extent of variance elucidated by each eigenvector.
- Select the number of principal components: The number of principal components to retain can be determined by analyzing the eigenvalues and selecting the top k eigenvectors that explain the most variance.
- Project the data onto the selected principal components: The original data is projected onto the selected principal components, resulting in a lower-dimensional representation of the data.
PCA can be used for feature selection by selecting the top k principal components that explain the most variance in the data. This can be useful for reducing the dimensionality of high-dimensional datasets and improving the performance of machine learning models. However, it’s important to note that PCA may not always lead to improved performance, especially if the data is already low-dimensional or if the features are not highly correlated. It’s also important to consider the interpretability of the selected principal components, as they may not always correspond to meaningful features in the data.
LDA is a dimensionality reduction technique that’s used for feature selection in machine learning. It is often used in classification tasks to reduce the number of features by transforming them into a lower-dimensional space while retaining as much class-discriminatory information as possible.
In LDA, the goal is to find a linear combination of the original features that maximizes the separation between classes. The input to LDA is a dataset of labeled examples, where each example is a feature vector with a corresponding class label. The output of LDA is a set of linear combinations of the original features, which can be used as new features in a machine learning model.
To perform LDA, the first step is to compute the mean and covariance matrix of each class. The overall mean and covariance matrix are then calculated from the class means and covariance matrices. The goal is to project the data onto a lower-dimensional space while still retaining the class information. This is achieved by finding the eigenvectors and eigenvalues of the matrix defined, sorting them in descending order of the eigenvalues, and selecting the top k eigenvectors that correspond to the k largest eigenvalues. The selected eigenvectors form the basis for the new feature space.
The LDA algorithm can be summarized in the following steps:
- Compute the mean vector of each class.
- Compute the covariance matrix of each class.
- Compute the overall mean vector and overall covariance matrix.
- Compute the between-class scatter matrix.
- Compute the within-class scatter matrix.
- Compute the eigenvectors and eigenvalues of the matrix calculated by the following equation:
Here, is the within-class scatter matrix and is the between-class scatter matrix.
- Select the top eigenvectors with the highest eigenvalues as the new feature space.
A scatter matrix quantifies how data points are distributed around a mean. In LDA, the within-class scatter matrix measures how samples spread around their class means, while the between-class scatter matrix measures how far the class means are from the overall mean. Together, they capture class compactness versus class separability.
LDA is particularly useful when the number of features is large and the number of examples is small. It can be used in a variety of applications, including image recognition, speech recognition, and NLP. However, it assumes that the classes are normally distributed and that the class covariance matrices are equal, which may not always be the case in practice.
t-SNE is the dimensionality reduction technique that we presented for visualizing high-dimensional data in a low-dimensional space. It is a good opportunity to expand on t-SNE in the context of feature selection.
It was developed by Laurens van der Maaten and Geoffrey Hinton in 2008. The basic idea behind t-SNE is to preserve the pairwise similarities of data points in a low-dimensional space, as opposed to preserving the distances between them. In other words, it tries to retain the local structure of the data while discarding the global structure. This can be useful in situations where the high-dimensional data is difficult to visualize, but there may be meaningful patterns and relationships among the data points.
t-SNE starts by calculating the pairwise similarity between each pair of data points in the high-dimensional space. The similarity is usually measured using a Gaussian kernel, which gives higher weights to nearby points and lower weights to distant points. The similarity matrix is then converted into a probability distribution using a softmax function. This distribution is used to create a low-dimensional space, typically 2D or 3D.
In the low-dimensional space, t-SNE again calculates the pairwise similarities between each pair of data points, but this time using a Student’s t-distribution instead of a Gaussian distribution. The t-distribution has heavier tails than the Gaussian distribution, which helps to better preserve the local structure of the data. t-SNE then adjusts the position of the points in the low-dimensional space to minimize the difference between the pairwise similarities in the high-dimensional space and the pairwise similarities in the low-dimensional space.
t-SNE is a powerful technique for visualizing high-dimensional data by reducing it to a low-dimensional space. However, it is not typically used for feature selection as its primary purpose is to create visualizations of complex datasets.
Instead, t-SNE can be used to help identify clusters of data points that share similar features, which may be useful in identifying groups of features that are important for a particular task. For example, suppose you have a dataset of customer demographics and purchase history, and you want to identify groups of customers that are similar based on their purchasing behavior. You could use t-SNE to reduce the high-dimensional feature space to two dimensions, and then plot the resulting data points on a scatter plot. By examining the plot, you might be able to identify clusters of customers with similar purchasing behavior, which could then inform your feature selection process. Here’s a sample t-SNE for the MNIST dataset:

A colorful dots on a white background Description automatically generated
Figure 3.2 – t-SNE on the MNIST dataset
To view the preceding figure in color, access the free PDF version of this book and other associated benefits. Instructions are available in the Free benefits with your book section in the Preface.
It’s worth noting that t-SNE is primarily a visualization tool and should not be used as the sole method for feature selection. Instead, it can be used in conjunction with other techniques, such as LDA or PCA, to gain a more complete understanding of the underlying structure of your data.
The choice of feature selection method depends on the nature of the data, the size of the dataset, the complexity of the model, and the computational resources available. It is important to carefully evaluate the performance of the model after feature selection to ensure that important information has not been lost. Another important process is feature engineering, which is about transforming or selecting features for machine learning models.
Common machine learning models
Section titled “Common machine learning models”Here, we will explain some of the most common machine learning models, as well as their advantages and disadvantages. Possessing this skill will help you pick the best model for the problem and be able to improve the implemented model.
Linear regression
Section titled “Linear regression”Linear regression is a type of supervised learning algorithm that’s used to model the relationship between a dependent variable and one or more independent variables. It assumes a linear relationship between the input features and the output. The goal of linear regression is to find the best-fit line that predicts the value of the dependent variable based on the independent variables.
The equation for a simple linear regression with one independent variable (also called a simple linear equation) is as follows:
Here, we have the following:
- is the dependent variable (the variable we want to predict)
- is the independent variable (the input variable)
- is the slope of the line (how much changes when changes)
- is the y-intercept (where the line intercepts the axis when )
The goal of linear regression is to find the values of m and b that minimize the difference between the predicted values and the actual values of the dependent variable. This difference is typically measured using a cost function, such as mean squared error or mean absolute error.
Multiple linear regression is an extension of simple linear regression, where there are multiple independent variables. The equation for multiple linear regression is shown here:
Here, we have the following:
- is the dependent variable
- are the independent variables
is the y-intercept (when all the independent variables are equal to 0)- are the coefficients (how much y changes when each independent variable changes)
Similar to simple linear regression, the goal of multiple linear regression is to find the values of that minimize the difference between the predicted values and the actual values of the dependent variable.
The advantages of linear regression are as follows:
- It’s simple and easy to understand
- It can be used to model a wide range of relationships between the dependent and independent variables
- It’s computationally efficient, making it fast and suitable for large datasets
- It provides interpretable results, allowing for the analysis of the impact of each independent variable on the dependent variable
The disadvantages of linear regression are as follows:
- It assumes a linear relationship between the input features and the output, which may not always be the case in real-world data
- It may not capture complex non-linear relationships between the input features and the output
- It’s sensitive to outliers and influential observations, which can affect the accuracy of the model
- It assumes that the errors are normally distributed with constant variance, which may not always hold true in practice
Logistic regression
Section titled “Logistic regression”Logistic regression is a popular machine learning algorithm that’s used for classification problems. Unlike linear regression, which is used for predicting continuous values, logistic regression is used for predicting discrete outcomes, typically binary outcomes (0 or 1).
The goal of logistic regression is to estimate the probability of a certain outcome based on one or more input variables. The output of logistic regression is a probability score, which can be converted into a binary class label by applying a threshold value. The threshold value can be adjusted to balance between precision and recall based on the specific requirements of the problem.
The logistic regression model assumes that the relationship between the input variables and the output variable is linear in the logit (log odds) space. The logit function is defined as follows:
Here, p is the probability of the positive outcome (that is, the probability of the event occurring).
The logistic regression model can be represented mathematically as follows:
Here, are the coefficients of the model, are the input variables, and is the logit function of the probability of a positive outcome.
The logistic regression model is trained using a dataset of labeled examples, where each example consists of a set of input variables and a binary label indicating whether the positive outcome occurred or not. The coefficients of the model are estimated using maximum likelihood estimation, which seeks to find the values of the coefficients that maximize the likelihood of the observed data.
The advantages of logistic regression are as follows:
- Interpretable: The coefficients of the model can be interpreted as the change in the log odds of the positive outcome associated with a unit change in the corresponding input variable, making it easy to understand the impact of each input variable on the predicted probability of the positive outcome
- Computationally efficient: Logistic regression is a simple algorithm that can be trained quickly on large datasets
- Works well with small datasets: Logistic regression can be effective even with a small number of observations, provided that the input variables are relevant to the prediction task
The disadvantages of logistic regression are as follows:
- Assumes linearity: Logistic regression assumes a linear relationship between the input variables and the logit of the probability of the positive outcome, which may not always be the case in real-world datasets
- May suffer from overfitting: If the number of input variables is large compared to the number of observations, the model may suffer from overfitting, leading to poor generalization performance on new data
- Not suitable for non-linear problems: Logistic regression is a linear algorithm and is not suitable for problems where the relationship between the input variables and the output variable is non-linear
Decision trees
Section titled “Decision trees”Decision trees are a type of supervised learning algorithm used for classification and regression analysis. A decision tree consists of a series of nodes that represent decision points, each of which has one or more branches that lead to other decision points or a final prediction.
In a classification problem, each leaf node of the tree represents a class label, while in a regression problem, each leaf node represents a numerical value. The process of building a decision tree involves choosing a sequence of attributes that best splits the data into subsets that are more homogeneous concerning the target variable. This process is typically repeated recursively for each subset until a stopping criterion is met, such as a minimum number of instances in each subset or a maximum depth of the tree.
The equations for decision trees involve calculating the information gain (or another splitting criterion, such as Gini impurity or entropy) for each potential split at each decision point. The attribute with the highest information gain is selected as the split criterion for that node. The conceptual formula for information gain is shown here:

Here, entropy is a measure of the impurity or randomness of a system. In the context of decision trees, entropy is used to measure the impurity of a node in the tree.
The entropy of a node is calculated as follows:

Here, c is the number of classes and is the proportion of the samples that belong to class i in the node.
The entropy of a node ranges from 0 to 1, with 0 indicating a pure node (that is, all samples belong to the same class) and 1 indicating a node that is evenly split between all classes.
In a decision tree, the entropy of a node is used to determine the splitting criterion for the tree. The idea is to split the node into two or more child nodes such that the entropy of the child nodes is lower than the entropy of the parent node. The split with the lowest entropy is chosen as the best split.
The choice of splitting criterion depends on the specific tree-building algorithm:
- ID3 selects the attribute that maximizes information gain (entropy reduction)
- C4.5 extends ID3 and chooses the split with the highest gain ratio, an entropy-based measure that normalizes for attribute cardinality
- CART (Classification and Regression Trees) uses Gini impurity for classification and variance reduction for regression
Throughout this section, we describe CART, relating impurity to the Gini criterion.
The advantage of using entropy as a splitting criterion is that it can handle both binary and multi-class classification problems. It is also relatively computationally efficient compared to other splitting criteria. However, one disadvantage of using entropy is that it tends to create biased trees in favor of attributes with many categories.
Here are some of the advantages of decision trees:
- Easy to understand and interpret, even for non-experts
- Can handle both categorical and numerical data
- Can handle missing data and outliers
- Can be used for feature selection
- Can be combined with other models in ensemble methods, such as random forests
Here are some of the disadvantages of decision trees:
- Can be prone to overfitting, especially if the tree is too deep or complex
- Can be sensitive to small changes in the data or the way the tree is built
- Can be biased toward features with many categories or high cardinality
- Can have problems with rare events or imbalanced datasets
Support vector machines (SVMs)
Section titled “Support vector machines (SVMs)”SVMs are considered robust supervised learning algorithms that can perform both classification and regression tasks. They excel in scenarios with intricate decision boundaries, surpassing the limitations of linear models. At their core, SVMs aim to identify a hyperplane within a multi-dimensional space that maximally segregates the classes. This hyperplane is positioned to maximize the distance between itself and the closest points from each class, known as support vectors. Here’s how SVMs work for a binary classification problem. Given a set of training data,, where is a d-dimensional feature vector and is the binary class label (+1 or -1), the goal of an SVM is to find a hyperplane that separates the two classes with the largest margin. The margin is defined as the distance between the hyperplane and the closest data points from each class:

Figure 3.3 – SVM margins
To view the preceding figure in color, access the free PDF version of this book and other associated benefits. Instructions are available in the Free benefits with your book section in the Preface.
The hyperplane is defined by a weight vector,, and a bias term,, such that for any new data point,, the predicted class label,, is given by the following equation:
+b)
Here, is the sign function, which returns +1 if the argument is positive and -1 otherwise.
The objective function of an SVM is to minimize the classification error subject to the constraint that the margin is maximized. This can be formulated as an optimization problem:
Here, is the squared Euclidean norm of the weight vector,. The constraints ensure that all data points are correctly classified and that the margin is maximized.
Here are some of the advantages of SVMs:
- Effective in high-dimensional spaces, which is useful when the number of features is large.
- Can be used for both classification and regression tasks.
- Work well with both linearly separable and non-linearly separable data.
- More robust to outliers than purely distance-based linear models, because SVMs allow a controlled number of margin violations. A regularization parameter C determines how strictly the model enforces separation between classes, balancing margin width against tolerance for misclassified or noisy points.
- Have a regularization parameter that allows you to control overfitting.
Here are some of the disadvantages of SVMs:
- Can be sensitive to the choice of kernel function, which can greatly affect the performance of the model
- Computationally intensive for large datasets
- It can be difficult to interpret the results of an SVM model
- Require careful tuning of parameters to achieve good performance
Ensemble models
Section titled “Ensemble models”Ensemble modeling is a technique in machine learning that combines the predictions of multiple models to improve overall performance. The idea behind ensemble models is that multiple models can be better than a single model, as different models may capture different patterns in the data.
There are several types of ensemble models, all of which we’ll cover in the following sections.
Bagging
Section titled “Bagging”Bootstrap aggregating, also known as bagging, is an ensemble method that combines multiple independent models trained on different subsets of the training data to reduce variance and improve model generalization.
The bagging algorithm can be summarized as follows:
- Given a training dataset of size, create bootstrap samples of size (that is, sample instances with replacement times).
- Train a base model (for example, a decision tree) on each bootstrap sample independently.
- Aggregate the predictions of all base models to obtain the ensemble prediction. This can be done by either taking the majority vote (in the case of classification) or the average (in the case of regression).
The bagging algorithm is particularly effective when the base models are unstable (that is, have high variance), such as decision trees, and when the training dataset is small.
The equation for aggregating the predictions of the base models depends on the type of problem (classification or regression). For classification, the ensemble prediction is obtained by taking the majority vote:

Here, is the predicted class of the base model for the instance and is the indicator function (equal to 1 if is true, and 0 otherwise).
For regression, the ensemble prediction is obtained by taking the average score:

Here, is the predicted value of the base model.
The advantages of bagging are as follows:
- Improved model generalization by reducing variance and overfitting
- Ability to handle high-dimensional datasets with complex relationships
- Can be used with a variety of base models
The disadvantages of bagging are as follows:
- Increased model complexity and computation time due to the use of multiple base models
- It can sometimes lead to overfitting if the base models are too complex or the dataset is too small
- It does not work well when the base models are highly correlated or biased
Boosting
Section titled “Boosting”Boosting is another popular ensemble learning technique that aims to improve the performance of weak classifiers by combining them into a stronger classifier. Unlike bagging, boosting focuses on iteratively improving the accuracy of the classifier by adjusting the weights of the training examples. The basic idea behind boosting is to learn from the mistakes of the previous weak classifiers and to put more emphasis on the examples that were incorrectly classified in the previous iteration.
There are several boosting algorithms, but one of the most popular ones is AdaBoost (short for adaptive boosting). The AdaBoost algorithm works as follows:
- First, it initializes the weights of the training examples to be equal.
- Then, it trains a weak classifier on the training set.
- Next, it computes the weighted error rate of the weak classifier.
- After, it computes the importance of the weak classifier based on its weighted error rate.
- Then, it increases the weights of the examples that were misclassified by the weak classifier.
- Once it’s done that, it normalizes the weights of the examples so that they sum up to one.
- It repeats Steps 2 to 6 for a predetermined number of iterations or until the desired accuracy is achieved.
- Finally, it combines the weak classifiers into a strong classifier by assigning weights to them based on their importance.
The final classifier is a weighted combination of the weak classifiers. The importance of each weak classifier is determined by its weighted error rate, which is computed as an equation:

Here, is the index of the weak classifier, is the number of training examples, is the weight of the training example, is the true label of the training example, is the prediction of the weak classifier for the training example, and is an indicator function that returns 1 if the prediction of the weak classifier is incorrect and 0 otherwise.
The importance of the weak classifier is computed by the following equation:

The weights of the examples are updated based on their importance:

The final classifier is then obtained by combining the weak classifiers:

Here,
is the total number of weak classifiers,
is the prediction of the
weak classifier, and sign() is a function that returns +1 if its argument is positive and -1 otherwise.
Let’s look at some of the advantages of boosting:
- Boosting can improve the accuracy of weak classifiers and can lead to a significant improvement in performance
- Boosting is relatively easy to implement and can be applied to a wide range of classification problems
- Boosting can handle noisy data and reduce the risk of overfitting
Here are some of the disadvantages of boosting:
- Boosting can be sensitive to outliers and can overfit to noisy data
- Boosting can be computationally expensive, especially when dealing with large datasets
- Boosting can be difficult to interpret as it involves combining multiple weak classifiers
Stacking
Section titled “Stacking”Stacking is another popular ensemble learning technique that combines the predictions of multiple base models by training a higher-level model on their predictions. The idea behind stacking is to leverage the strengths of different base models to achieve better predictive performance.
Here’s how stacking works:
- Divide the training data into two parts: the first part is used to train the base models, while the second part is used to create a new dataset of predictions from the base models.
- Train multiple base models on the first part of the training data.
- Use the trained base models to make predictions on the second part of the training data to create a new dataset of predictions.
- Train a higher-level model (also known as a metamodel or blender) on the new dataset of predictions.
- Use the trained higher-level model to make predictions on the test data.
The higher-level model is typically a simple model such as a linear regression, logistic regression, or a decision tree. The idea is to use the predictions of the base models as input features for the higher-level model. This way, the higher-level model learns to combine the predictions of the base models to make more accurate predictions.
Random forest – a common ensemble model
Section titled “Random forest – a common ensemble model”Random forest is an ensemble learning method that’s versatile and can perform classification and regression tasks. It operates by generating multiple decision trees during training, predicting the target class for classification based on the majority of the trees, and the predicted value based on the mean prediction by trees for regression tasks. The algorithm for constructing a random forest can be summarized in the following steps:
- Bootstrap sampling: Randomly select a subset of the data with replacement to create a new dataset that’s the same size as the original dataset.
- Feature selection: Randomly select a subset of the features (columns) for each split when building a decision tree. This helps to create diversity in the trees and reduce overfitting.
- Tree building: Construct a decision tree for each bootstrap sample and feature subset. The decision tree is constructed recursively by splitting the data based on the selected features until a stopping criterion is met (for example, maximum depth or minimum number of samples in a leaf node).
- Ensemble learning: Combine the predictions of all decision trees to make a final prediction. For classification, the class that receives the most votes from the decision trees is the final prediction. For regression, the average of the predictions from all decision trees is the final prediction.
The random forest algorithm can be expressed mathematically as follows.
Given a dataset,
, with samples and
features, we create
decision trees by applying the preceding steps. Each decision tree is constructed using a bootstrap sample of the data,
, with size
and a subset of the features,
, with size
. For each split in the decision tree, we randomly select
features from
and choose the best feature to split the data based on an impurity measure (for example, Gini index or entropy). The decision tree is built until a stopping criterion is met (for example, the maximum depth or minimum number of samples in a leaf node).
The final prediction,
, for a new sample,, is obtained by aggregating the predictions from all decision trees.
For classification,
is the class that receives the most votes from all decision trees:

Here,
is the prediction of the
decision tree for the
sample, and is the indicator function that returns 1 if the condition is true and 0 otherwise.
For regression,
is the average of the predictions from all decision trees:

Here, is the prediction of the
decision tree for the new sample,.
In summary, random forest is a powerful machine learning algorithm that can handle high-dimensional and noisy datasets. It works by constructing multiple decision trees using bootstrap samples of the data and feature subsets, and then aggregating the predictions of all decision trees to make a final prediction. The algorithm is scalable, easy to use, and provides a measure of feature importance, making it a popular choice for many machine learning applications.
The advantages of random forests are as follows:
- Robustness: Random forest is a very robust algorithm that can handle a variety of input data types, including numerical, categorical, and ordinal data
- Feature selection: Random forest can rank the importance of features, allowing users to identify the most important features for classification or regression tasks
- Overfitting: Random forest has a built-in mechanism for reducing overfitting, called bagging (discussed in more detail in the Ensemble models section), which helps to generalize well on new data
- Scalability: Random forest can handle large datasets with a high number of features, making it a good choice for big data applications
- Outliers: Random forest is robust to the presence of outliers as it is based on decision trees, which can handle outliers effectively
The disadvantages of random forests are as follows:
- Interpretability: Random forest models can be difficult to interpret as they are based on an ensemble of decision trees
- Training time: The training time of a random forest can be longer than that of other simpler algorithms, especially when the number of trees in the ensemble is large
- Memory usage: Random forest requires more memory than some other algorithms, as it has to store the decision trees in memory
- Bias: Random forest can suffer from bias if the data is imbalanced or if the target variable has a high cardinality
- Overfitting: Although random forest is designed to prevent overfitting, it is still possible to overfit the model if the hyperparameters are not properly tuned
Overall, random forest is a powerful machine learning algorithm that has many advantages, but it is important to carefully consider its limitations before applying it to a particular problem.
Gradient boosting
Section titled “Gradient boosting”Gradient boosting is another ensemble model that can be used for classification and regression tasks. It works by getting a weak classifier (such as a simple tree), and in each step tries to improve this weak classifier to build a better model. The main idea here is that the model tries to focus on its mistakes in each step and improve itself by fitting the model by correcting the errors made in previous trees.
During each iteration, the algorithm computes the negative gradient of the loss function concerning the predicted values, followed by fitting a decision tree to these negative gradient values. The predictions of the new tree are then combined with the predictions of the previous trees, using a learning rate parameter that controls the contribution of each tree to the final prediction.
The overall prediction of the gradient boosting model is obtained by summing up the predictions of all the trees, which are weighted by their respective learning rates.
Let’s take a look at the equation for the gradient boosting algorithm.
First, we initialize the model with a constant value:

Here,
is a constant, is the true label of the
sample, is the number of samples, and
is the loss function, which is used to measure the error between the predicted and true labels.
At each iteration,, the algorithm fits a decision tree to the negative gradient values of the loss function concerning the predicted values,
. The decision tree predicts the negative gradient values, which are then used to update the predictions of the model via the following equation:

Here,
is the prediction of the model at the previous iteration, is the learning rate, and
is the prediction of the decision tree at the current iteration.
The final prediction of the model is obtained by combining the predictions of all the trees:

Here,
is the total number of trees in the model and
and
are the learning rate and prediction of the
tree, respectively.
Let’s look at some of the advantages of gradient boosting:
- High prediction accuracy
- Handles both regression and classification problems
- Can handle missing data and outliers
- Can be used with various loss functions
- Can handle high-dimensional data
Now, let’s look at some of the disadvantages:
- Sensitive to overfitting, especially when the number of trees is large
- Computationally expensive and time-consuming to train, especially for large datasets
- Requires careful tuning of hyperparameters, such as the number of trees, the learning rate, and the maximum depth of the trees
With that, we have reviewed the ensemble models that can help us improve our model performance.
Neural networks and transformers
Section titled “Neural networks and transformers”Up to this point, the chapter has focused on classical machine learning models that rely on manually designed features and relatively simple decision boundaries. This section introduces neural networks and transformers, which extend those ideas by learning hierarchical and contextual representations directly from data. These models are especially important for NLP because they can capture non-linear patterns, long-range dependencies, and semantic structure that traditional models struggle to represent. The goal of this section is not to replace earlier techniques, but to explain how modern deep learning models build on the same training, evaluation, and optimization principles while enabling the large-scale language systems that the rest of this book will explore.
We will introduce some of the core concepts around neural networks and transformers to support our discussion of machine learning modeling for natural language processing. In Chapter 6, we will dive deeper into neural network design and introduce further concepts such as recurrent neural networks (RNNs), convolutional neural networks (CNNs), and the attention mechanism.
Neural networks
Section titled “Neural networks”Neural networks draw inspiration from the structure and functioning of the human brain. They represent a category of machine learning models that are proficient in various tasks such as classification, regression, and more. Comprising multiple layers of interconnected nodes known as neurons, these networks adeptly process and manipulate data. The output of each layer is fed into the next layer, creating a hierarchy of feature representations. The input to the first layer is the raw data, and the output of the final layer is the prediction. A simple neural network for detecting the gender of a person based on their height and weight is shown in Figure 3.4:

A diagram of a triangle with blue circles and black lines Description automatically generated
Figure 3.4 – Simple neural network
The operation of a single neuron in a neural network can be represented by the following equation:

Here, are the input values, are the weights of the connections between the neurons, is the bias term, and is the activation function. The activation function applies a non-linear transformation to the weighted sum of the inputs and bias term.
Training a neural network involves adjusting the weights and biases of the neurons to minimize a loss function. This is typically done using an optimization algorithm such as stochastic gradient descent.
The advantages of neural networks include their ability to learn complex non-linear relationships between input and output data, their ability to automatically extract meaningful features from raw data, and their scalability to large datasets.
The disadvantages of neural networks include their high computational and memory requirements, their sensitivity to hyperparameter tuning, and the difficulty of interpreting their internal representations.
Transformers
Section titled “Transformers”Transformers are a type of neural network architecture that is particularly well-suited to sequential data such as text or speech. They were introduced in the context of NLP and have since been applied to a wide range of tasks.
The core component of a transformer is the self-attention mechanism, which allows the model to attend to different parts of the input sequence when computing the output. The self-attention mechanism computes similarity scores between each query vector and a set of key vectors using a dot product. These scores are normalized into attention weights, which are then used to form a weighted combination of the corresponding value vectors to produce the output. The resulting attention weights are used to weight the values, which are then combined to produce the output.
The mechanics of self-attention are built around three components: queries, keys, values. These operations can be represented by the following equations:



Here,
is the input sequence and
,
, and
are learned projection matrices that turn tokens into queries, keys, and values, respectively.
is the key dimension. A separate matrix,
,later projects the attention output back to the model’s hidden size.
Intuitively, each token’s query asks “Which other tokens matter?”, keys provide the answers, and values supply the information to be combined.
Positional encodings
Section titled “Positional encodings”Because self-attention is permutation-invariant, transformers add positional encodings to each token embedding:
- Sinusoidal: fixed sines/cosines of varying wavelengths
- Learned: additional embeddings trained jointly with the model
Without these signals, the model cannot distinguish “dog bites man” from “man bites dog.”
The following table compares the function of encoder and decoder blocks:
| Component | Main flow | Cross-attention? | Typical use |
|---|---|---|---|
| Encoder block | Self-attention → feed-forward → residual + norm | No | Represent source text (e.g., BERT) |
| Decoder block | Masked self-attention → cross-attention to encoder → feed-forward → residual + norm | Yes | Generate targets autoregressively (e.g., GPT, T5 decoder) |
Table 3.3 – Reviewing the encoder and decoder blocks
Why the Transformer matters for NLP
Section titled “Why the Transformer matters for NLP”This mechanism captures long-range dependencies by enabling tokens to directly reference any other position in the sequence, instead of relying on information being passed sequentially from one step to the next.
It allows parallel training/inference across sequence positions, yielding dramatic speed-ups over designs that were state of the art, such as RNNs.
It forms the backbone of today’s best pre-trained language models, which later chapters delve into.
The disadvantages of transformers include their high computational and memory requirements, sensitivity to hyper-parameter tuning, and the absence of an explicit “arrow of time” bias; they do not inherently model monotonic temporal order, so extra positional or causal masking tricks are needed for certain sequential tasks.
Now that we have explored the most common machine learning models, we will start to walk through the practical steps for designing the solution. The next step would be to understand how to properly partition the data in a way that serves our purposes of evaluation and validation of the results that we will eventually deliver.
Splitting data
Section titled “Splitting data”When developing a machine learning model, it’s important to split the data into training, validation, and test sets. This is called data splitting. This is done to evaluate the performance of the model on new, unseen data and to prevent overfitting.
The most common method for splitting the data is the train-test split, which splits the data into two sets: the training set, which is used to train the model, and the test set, which is used to evaluate the performance of the model. The data is randomly divided into two sets, with a typical split being 80% of the data for training and 20% for testing. The model will be trained using the majority of the data (training data) and then tested on the remaining data (test set). Using this approach, we can ensure that the model’s performance is based on new, unseen data.
Most of the time in machine learning model development, we have a set of hyperparameters for our model that we like to tune (we will explain hyperparameter tuning in the next subsection). In this case, we like to make sure that the performance that we get on the test set is reliable and not just by chance, based on a set of hyperparameters. In this case, based on the size of our training data, we can divide the data into 60%, 20%, and 20% (or 70%, 15%, and 15%) for training, validation, and testing. We train the model on the training data and select the set of hyperparameters that gives us the best performance on the validation set. We then report the actual model performance on the test set, which has not been seen or used before during model training or hyperparameter selection.
A more advanced method for splitting the data, especially when the size of our training data is limited, is k-fold cross-validation. In this method, the data is split into k equally sized “folds,” and the model is trained and tested K times, with each fold being used as the test set once and the remaining folds used as the training set. The results of each fold are then averaged to get an overall measure of the model’s performance. K-fold cross-validation is useful for small datasets where the train-test split may result in a large variance in performance evaluation. In this case, we report the average, minimum, and maximum performance of the model on each of the K folds, as shown here

Figure 3.5 – K-fold cross-validation
Another variant of k-fold cross-validation is stratified k-fold cross-validation, which ensures that the distribution of the target variable is consistent across all folds. This is useful when dealing with imbalanced datasets, where the number of instances of one class is much smaller than the others.
Time series data requires special attention when splitting. In this case, we typically use a method called time series cross-validation, which preserves the temporal order of the data. In this method, the data is split into multiple segments, with each segment representing a fixed time interval. The model is then trained on the past data and tested on the future data. This helps to evaluate the performance of the model in real-world scenarios. You can see an example of how to split the data in a time series problem in Figure 3.6:

Figure 3.6 – Time series data splitting
In all cases, it’s important to ensure that the split is done randomly but with the same random seed each time to ensure the reproducibility of the results. It’s also important to ensure that the split is representative of the underlying data – that is, the distribution of the target variable should be consistent across all sets. Once we have split the data into different subsets for training and testing our model, we can try to find the best set of hyperparameters for our model. This process is called hyperparameter tuning and will be explained next.
Hyperparameter tuning
Section titled “Hyperparameter tuning”Hyperparameter tuning is an important step in the machine learning process that involves selecting the best set of hyperparameters for a given model. Hyperparameters are values that are set before the training process begins and can have a significant impact on the model’s performance. Examples of hyperparameters include learning rate, regularization strength, number of hidden layers in a neural network, and many others.
The process of hyperparameter tuning involves selecting the best combination of hyperparameters that results in the optimal performance of the model. This is typically done by searching through a predefined set of hyperparameters and evaluating their performance on a validation set.
There are several methods for hyperparameter tuning, including grid search, random search, and Bayesian optimization. Grid search involves creating a grid of all possible hyperparameter combinations and evaluating each one on a validation set to determine the optimal set of hyperparameters. Random search, on the other hand, randomly samples hyperparameters from a predefined distribution and evaluates their performance on a validation set.
Random search and grid search are methods that are used to search the search space, entirely or randomly, without considering previous hyperparameter results. Thus, these methods are inefficient. An alternative Bayesian optimization method has been proposed that iteratively computes the posterior distribution of the function and considers past evaluations to find the best hyperparameters. Using this approach, we can find the best set of hyperparameters with fewer iterations.
Bayesian optimization utilizes past evaluations to probabilistically map hyperparameters to objective function scores, as demonstrated in the following equation:

Here are the steps Bayesian optimization undertakes:
- It develops a surrogate probabilistic model for the objective function.
- It identifies the optimal hyperparameters based on the surrogate.
- It utilizes these hyperparameters in the actual objective function.
- It updates the surrogate model to integrate the latest results.
- It reiterates Steps 2 to 4 until it reaches the maximum iteration count or time limit.
Sequential model-based optimization (SMBO) methods are a formalization of Bayesian optimization, with trials run one after another, trying better hyperparameters each time and updating a probability model (surrogate). SMBO methods differ in Steps 3 and 4 – specifically, how they build a surrogate of the objective function and the criteria used to select the next hyperparameters. These variants include Gaussian processes, random forest regressions, and tree-structured Parzen estimators, among others.
In low-dimensional problems with numerical hyperparameters, Bayesian optimization is considered the best available hyperparameter optimization method. However, it is restricted to problems of moderate dimensions.
In addition to these methods, there are also several libraries available that automate the process of hyperparameter tuning. Examples of these libraries include scikit-learn’s GridSearchCV and RandomizedSearchCV, Keras Tuner, and Optuna. These libraries allow for efficient hyperparameter tuning and can significantly improve the performance of machine learning models.
Hyperparameter optimization in machine learning can be a complex and time-consuming process. Two primary complexity challenges arise in the search process: the trial execution time and the complexity of the search space, including the number of evaluated hyperparameter combinations. In deep learning, these challenges are especially pertinent due to the extensive search space and the utilization of large training sets.
To address these issues and reduce the search space, some standard techniques may be used. For example, reducing the size of the training dataset based on statistical sampling or applying feature selection techniques can help reduce the execution time of each trial. Additionally, identifying the most important hyperparameters for optimization and using additional objective functions beyond just accuracy, such as the number of operations or optimization time, can help reduce the complexity of the search space.
By combining accuracy with visualization through a deconvolution network, researchers have achieved superior results. However, it’s important to note that these techniques are not exhaustive, and the best approach may depend on the specific problem at hand.
Another common approach for improving model performance is to use multiple models in parallel in the form of ensemble models, which we elaborated on earlier in this chapter.
These last two sections have highlighted the value of properly setting the data to subsets that serve the modeling process and the value of hyperparameter tuning. Next, we will explain model underfitting and overfitting, which happen during the training process.
Model underfitting and overfitting
Section titled “Model underfitting and overfitting”In machine learning, the ultimate goal is to build a model that can generalize well on unseen data. However, sometimes, a model can fail to achieve this goal due to either underfitting or overfitting.
Underfitting occurs when a model is too simple to capture the underlying patterns in the data. In other words, the model can’t learn the relationship between the features and the target variable properly. This can result in poor performance on both the training and testing data. For example, in Figure 3.7, we can see that the model is underfitted, and it cannot present the data very well. This is not what we like in machine learning models, as we usually like to see a precise model, as shown here:

Figure 3.7 – The machine learning model underfitting on the training data
Underfitting happens when the model is not trained well, or the model complexity is not enough to catch the underlying pattern in the data. To solve this problem, we can use more complex models, and continue the training process:

Figure 3.8 – Optimal fitting of the machine learning model on the training data
Optimal fitting happens when the model captures the pattern in the data pretty well but does not overfit every single sample. This helps the model work better on unseen data.
On the other hand, overfitting occurs when a model is too complex and fits the training data too closely, which can lead to poor generalization on new, unseen data, as shown in Figure 3.9:

Figure 3.9 – Overfitting the model on the training data
This happens when the model learns the noise or random fluctuations in the training data, rather than the underlying patterns. In other words, the model becomes too specialized for the training data and does not perform well on the testing data. Observe that the model is overfitted, and the model tried to predict every single sample very precisely. The problem with this model is that it does not learn the general pattern, and learns the pattern of each individual sample, which makes it work poorly when facing new, unseen records.
A useful way to understand the trade-off between underfitting and overfitting is through the bias-variance trade-off. Bias refers to the difference between the predicted values of the model and the actual values in the training data. A high bias means that the model is not complex enough to capture the underlying patterns in the data and underfits the data as can be seen Figure 3.10. An underfit model has poor performance on both the training and testing data:

Figure 3.10 – High bias
Variance, on the other hand, refers to the sensitivity of the model to small fluctuations in the training data. A high variance means that the model is overly complex and overfits the data, which leads to poor generalization performance on new data. An overfit model has good performance on the training data but poor performance on the testing data:

Figure 3.11 – High variance
To strike a balance between bias and variance, we need to choose a model that is neither too simple nor too complex. As mentioned previously, this is often referred to as the bias-variance trade-off. A model with a high bias and low variance can be improved by increasing the complexity of the model, while a model with a high variance and low bias can be improved by decreasing the complexity of the model:

Figure 3.12 – Just right (not high bias, not high variance)
There are several methods to reduce bias and variance in a model. One common approach is regularization, which adds a penalty term to the loss function to control the complexity of the model. Another approach is to use ensembles, which combine multiple models to improve the overall performance by reducing the variance. Cross-validation can also be used to evaluate the model’s performance and tune its hyperparameters to find the optimal balance between bias and variance.
Overall, understanding bias and variance is crucial in machine learning as it helps us to choose an appropriate model and identify the sources of error in the model.
In practice, underfitting corresponds to high bias and low variance, while overfitting corresponds to low bias and high variance. Understanding where a model falls along this spectrum helps guide corrective actions, such as adjusting model complexity, regularization strength, or training strategy.
Once we identify whether a model is underfitting or overfitting, we can apply targeted techniques to correct its behavior and improve generalization.
To overcome underfitting, we can try increasing the complexity of the model, adding more features, or using a more sophisticated algorithm. To prevent overfitting, several methods can be used:
- Cross-validation: Assessing the performance of machine learning models is essential. Cross-validation serves as a method for assessing the effectiveness of a machine learning model. It entails training the model on one portion of the data and testing it on another. By employing distinct subsets for training and evaluation, cross-validation mitigates the risk of overfitting. Further elaboration on this technique will be provided in the subsequent section on data splitting.
- Regularization: Regularization is a technique that’s used to add a penalty term to the loss function during training, which helps to reduce the complexity of the model and prevent overfitting. There are different types of regularization, including L1 regularization (LASSO), L2 regularization (ridge), and elastic net regularization.
- Early stopping: Early stopping is a technique that’s used to stop the training process when the performance of the model on the validation data starts to degrade. This helps to prevent overfitting by stopping the model from continuing to learn from the training data when it has already reached its maximum performance. This technique is usually used in iterative algorithms such as deep learning methods, where the model is being trained for multiple iterations (epochs). To use early stopping, we usually train the model while evaluating the model’s performance on the training and validation subsets. The model’s performance usually improves on the training set with more training, but since the model has not seen the validation set, the validation error usually decreases initially and, at some point, starts increasing again. This point is where the model starts overfitting. By visualizing the training and validation error of the model during training, we can identify and stop the model at this point:

Figure 3.13 – Early stopping
- Dropout: Dropout is a technique in deep learning models that is used to randomly drop out some neurons during training, which helps to prevent the model from relying too heavily on a small subset of features or neurons and overfitting the training data. By dropping the weight of neurons in the model during the process, we make the model learn the general pattern and prevent it from memorizing the training data (overfitting).
- Data augmentation: Data augmentation artificially expands the training dataset by creating modified versions of existing examples, helping the model learn more robust patterns and reduce overfitting. In computer vision, this often involves transformations such as rotation, scaling, or flipping images. In NLP, augmentation may include techniques such as paraphrasing, synonym replacement, back-translation, or controlled noise injection. For tabular data, augmentation can involve resampling strategies or synthetic data generation. Across domains, the goal is to expose the model to meaningful variation without altering the underlying label semantics.
- Ensemble methods: Ensemble methods are techniques that are used to combine multiple models to improve their performance and prevent overfitting. This can be done by using techniques such as bagging, boosting, or stacking.
By using these techniques, it is possible to prevent overfitting and build models that generalize well to new, unseen data. In practice, it is important to monitor both the training and testing performance of the model and make adjustments accordingly to achieve the best possible generalization performance. Beyond model complexity and training strategy, generalization can also be strongly affected by the structure of the dataset itself, particularly when class distributions are highly skewed. This brings us to the challenge of handling imbalanced data.
Handling imbalanced data
Section titled “Handling imbalanced data”In most real-world problems, our data is imbalanced, which means that the distribution of records from different classes (such as patients with and without cancer) is different. Handling imbalanced datasets is an important task in machine learning as it is common to have datasets with uneven class distribution. In such cases, the minority class is often under-represented, which can cause poor model performance and biased predictions. The reason behind this is that machine learning methods try to optimize their objective function to minimize the error in the training set. Now, let’s say that we have 99% of the data from the positive class and 1% from the negative class. In this case, if the model predicts all records as positive, the error will be 1%; however, this model is not useful for us. That’s why, if we have an imbalanced dataset, we need to use various methods to handle imbalanced data. In general, we can have three categories of methods to handle imbalanced datasets:
- Resampling: Resampling methods involve modifying the original dataset to create a balanced distribution. This can be achieved by either oversampling the minority class (creating more samples of the minority class) or undersampling the majority class (removing samples from the majority class).
- Oversampling tackles imbalance by adding information to the minority class so that both classes contribute equally during training. The simplest approach is random oversampling, which duplicates minority instances until class counts align. This preserves every original example but risks overfitting. More sophisticated methods create synthetic points instead of straight duplicates.
- SMOTE interpolates between a minority instance and its nearest minority neighbors, generating new samples that lie along the line segments connecting them and thus thickening the minority region of feature space. More on SMOTE will follow. - ADASYN extends SMOTE by generating more synthetic points where the class boundary is harder to learn, adapting to local density and giving extra focus to difficult areas. - Cluster-based oversampling first groups minority examples, then synthesizes points around each cluster centroid to reduce noise in very sparse regions. These techniques enlarge the training set, which can improve recall for rare classes but may lengthen training time and, in extreme cases, lead to models that memorize artifacts of the synthetic data.
- Undersampling takes the opposite route: it reduces the majority class so that its prevalence no longer dominates the loss function. A straightforward tactic is random undersampling, which discards majority instances at random until a balance is reached. This is fast but can throw away valuable information. To prune more intelligently, Tomek links identify borderline pairs – one majority, one minority – that are each other’s nearest neighbors. Removing the majority element of each pair cleans the decision boundary without cutting deep into the core of the class. Cluster-centroid undersampling goes further: it groups majority points into clusters and replaces each cluster with its centroid, preserving the overall geometric structure while reducing the record count. Because undersampling shortens the training time and curbs storage needs, it is appealing when data is abundant, but it must be applied carefully to avoid losing patterns essential for accurate classification.
- Oversampling tackles imbalance by adding information to the minority class so that both classes contribute equally during training. The simplest approach is random oversampling, which duplicates minority instances until class counts align. This preserves every original example but risks overfitting. More sophisticated methods create synthetic points instead of straight duplicates.
- Model-level reweighting and batching: Instead of changing the dataset, we can change how the model learns from it by assigning higher loss weights to minority-class errors (cost-sensitive learning) or by using sampling strategies that ensure each mini-batch contains a more balanced mix of classes during training.
- Text-specific augmentation: When the minority class contains too few documents for robust learning, we can create synthetic text rather than numeric feature vectors. Two lightweight, label-preserving techniques work well in NLP pipelines:
- Back-translation: Translate a minority sentence into a pivot language (e.g., English → French) and immediately translate it back. The round-trip paraphrase keeps meaning while altering surface form, providing fresh training examples without manual writing.
- Contextual word replacement: Mask one or more tokens in the sentence and let a pre-trained language model such as BERT predict plausible substitutes. The filled-in sentence is then stored as an additional sample.
- Back-translation: Translate a minority sentence into a pivot language (e.g., English → French) and immediately translate it back. The round-trip paraphrase keeps meaning while altering surface form, providing fresh training examples without manual writing.
Both methods expand the dataset without changing class labels, but they must be monitored for semantic drift: aggressive paraphrasing can flip sentiment, topic, or named-entity references and thus silently corrupt the target label.
Synthetic Minority Oversampling Technique (SMOTE) generates new minority-class points by interpolating between an existing sample and one of its k -nearest minority neighbors.
SMOTE algorithm:
- Pick a minority instance.
- Select one of its k -nearest minority neighbors.
- Draw a random scalar, between 0 and 1 and create the following:

- Repeat until the desired number of synthetic samples is reached.
Numeric example

The new sample is as follows:

Iterating this procedure for each of the 100 original minority points would raise the class total to 200, matching a 900-sample majority class.
Strengths
- Directly increases minority representation without discarding majority data
- Often boosts recall when class separation is clear
- Combines readily with undersampling (e.g., Tomek links) for cleaner boundaries
Limitations
- Can introduce noisy or unrealistic points, risking overfitting
- May inflate the influence of borderline minority samples, distorting the decision surface
- Computational costs grow with dataset size and choice of k
The NearMiss algorithm
Section titled “The NearMiss algorithm”NearMiss undersampling balances classes by retaining only those majority examples that sit closest to the minority class in feature space. All variants follow the same template, compute pairwise distances, rank majority points, and keep a fixed quota, yet differ in how they define “closest”:
- NearMiss-1 keeps majority samples with the smallest average distance to the k -nearest minority neighbors
- NearMiss-2 instead uses distance to the k farthest minority neighbors, preserving points that are globally closest to the minority cloud
- NearMiss-3 selects, for each minority sample, the N majority points farthest from it, then chooses among those whose overall distances remain relatively small
By trimming the majority set along these data-driven edges, NearMiss widens the separation between classes while discarding as little useful information as possible.
Cost-sensitive learning
Section titled “Cost-sensitive learning”Cost-sensitive learning is a method that’s used to train machine learning models on imbalanced datasets. Cost-sensitive learning involves assigning misclassification costs to the model that differ based on the class being predicted, which can help the model focus more on correctly classifying the minority class.
Let’s assume we have a binary classification problem with two classes, positive and negative. In cost-sensitive learning, we assign different costs to different types of errors. For example, we may assign a higher cost to misclassifying a positive example as negative because in an imbalanced dataset, the positive class is the minority class, and misclassifying positive examples can have a greater impact on the performance of the model.
We can assign costs in the form of a confusion matrix:
| Predicted Positive | Predicted Negative | |
|---|---|---|
| Actual Positive | TP_cost | FN_cost |
| Actual Negative | FP_cost | TN_cost |
Table 3.4 – Confusion matrix costs
Here, TP_cost, FN_cost, FP_cost, and TN_cost are the costs associated with true positives, false negatives, false positives, and true negatives, respectively.
To incorporate the cost matrix into the training process, we can modify the standard loss function that the model optimizes during training. One common cost-sensitive loss function is the weighted cross-entropy loss, which is defined as follows:

Here, is the true label (either 0 or 1),
is the predicted probability of the positive class, and
and
are weights that are assigned to the positive and negative classes, respectively.
The weights,
and
can be determined by the costs assigned in the confusion matrix. For example, if we assign a higher cost to false negatives (that is, misclassifying a positive example as negative), we may set
to a higher value than
.
Cost-sensitive learning can also be used with other types of models, such as decision trees and SVMs. The concept of assigning costs to different types of errors can be applied in various ways to improve the performance of a model on imbalanced datasets. However, it’s important to carefully select the appropriate cost matrix and loss function based on the specific characteristics of the dataset and the problem being solved.
- Ensemble techniques: Ensemble techniques combine multiple models to improve predictive performance. In imbalanced datasets, an ensemble of models can be trained on different subsets of the dataset, ensuring that each model is trained on both the minority and majority classes. Examples of ensemble techniques for imbalanced datasets include bagging and boosting.
- Anomaly detection: Anomaly detection techniques can be used to identify the minority class as an anomaly in the dataset. These techniques aim to identify rare events that are significantly different from the majority class. The identified samples can then be used to train the model on the minority class.
For neural classifiers, focal loss dynamically down-weights well-classified examples, focusing the gradient on hard minority samples. To achieve that, the standard cross-entropy term is multiplied by
, 
To conclude our discussion of unbalanced data, we find that choosing among resampling, augmentation, or loss-reweighting depends on data volume, text domain, and compute budget. The following table summarizes the trade-offs:
| Strategy | When it shines | Typical data volume | Compute footprint | Key strengths | Common caveats |
|---|---|---|---|---|---|
| Oversampling (SMOTE, ADASYN, cluster-based) | Minority class < 20% and features are continuous or embedding-based | Small → medium | Moderate (extra samples enlarge training set) | Improves recall without discarding majority data | Risk of overfitting to synthetic points, longer training times |
| Undersampling (Tomek links, NearMiss, cluster centroids) | Majority class is huge, storage or latency constraints | Medium → very large | Low (dataset shrinks) | Fast to train, removes redundancy | Possible loss of informative majority patterns |
| Text-specific augmentation (back-translation, contextual synonym swap) | Language data, limited labelled text (< 10k docs) and label-stable paraphrases | Small → medium | Moderate–high (requires LM inference / MT) | Produces natural paraphrases, keeps label semantics | Semantic drift, depends on quality of language models |
| Cost-sensitive or noise-robust losses (class weights, focal loss) | Neural classifiers with moderate imbalance (up to ~1:100), often with sampling | Any | Low (no data size change) | Simple to implement, no synthetic data needed | Requires tuning weight/focal γ, may still underperform when minority is extremely rare |
| Hybrid pipelines (e.g., SMOTE + Tomek, oversample + cost weight) | Severe imbalance or noisy boundaries | Any | Moderate | Combines benefits, cleans boundary and re-weights errors | Added complexity, more hyper-parameters |
Table 3.5 – Trade-offs when dealing with imbalanced data
Dealing with correlated data and features
Section titled “Dealing with correlated data and features”Correlations arise in two very different ways: temporal dependency in time-stamped observations and multicollinearity among high-dimensional text features. Treating them separately helps avoid data-leakage pitfalls and improves model generalization.
Temporal correlation
Section titled “Temporal correlation”Time-series samples violate the i.i.d. assumption that underpins most ML algorithms. Random shuffling or k-fold CV therefore inflates test accuracy. Practical remedies include the following:
- Time-series cross-validation: Split the sequence into expanding windows (train on up-to-t, validate on
). This mimics production where tomorrow is predicted from yesterday, not vice versa. - Lag and difference features: Creating
and
, along with rolling means or windowed sums computed over previous time steps, converts serial dependence into explanatory variables that a regression can absorb. - Specialized models: Classical ARIMA/SARIMA, or neural LSTMs and temporal convolutional networks capture seasonality and long-range memory directly.
- Pre-processing for stationarity: Differencing, detrending, or z-normalizing each series removes global trends that can otherwise dominate.
- Dimensionality reduction for panel data: When thousands of correlated sensors are recorded over time, PCA or autoencoders compress them before a temporal model is applied.
These steps preserve order dependence while preventing information from the “future” from contaminating the training set.
Correlated text features
Section titled “Correlated text features”Sparse bag-of-words or dense embeddings often contain highly redundant columns. Left untreated, multicollinearity can inflate variance in linear models and slow tree algorithms.
- Dimensionality reduction
Applying PCA to a TF-IDF matrix uncovers latent topic axes and cuts sparsity, t-SNE, or UMAP project embeddings to 2-D for quick sanity-check plots. Figure 3.14 shows a 2-D UMAP of 10 K news headlines colored by K-means clusters.

Figure 3.14 – Visualizing dimensionality reduction using UMAP
To view the preceding figure in color, access the free PDF version of this book and other associated benefits. Instructions are available in the Free benefits with your book section in the Preface.
- Regularization strategies
L2 (Ridge) shrinks correlated coefficients toward zero uniformly, stabilizing estimates.
L1 (LASSO) drives many coefficients exactly to zero, yielding a sparse interpretable subset.
Tree-based ensembles implicitly handle correlation via feature subsampling and split selection, but linear pipelines should always add an L1/L2 penalty.
- Feature agglomeration
The sklearn.cluster.FeatureAgglomeration function groups highly correlated n-grams or embedding dimensions, replacing each group with its centroid. This retains cluster-level semantics while slashing width and mitigating noise.
Combining temporal-aware validation with multicollinearity controls ensures models generalize both across time and across redundant feature sets.
Summary
Section titled “Summary”In this chapter, we learned about various concepts related to machine learning, starting with data exploration and preprocessing techniques. We then explored various machine learning models, such as logistic regression, decision trees, support vector machines, and random forests, along with their strengths and weaknesses. We also discussed the importance of splitting data into training and test sets, as well as techniques for handling imbalanced datasets.
The chapter also covered the concepts of model bias, variance, underfitting, and overfitting, and how to diagnose and address these issues. We also explored ensemble methods such as bagging, boosting, and stacking, which can improve model performance by combining the predictions of multiple models.
Finally, we learned about the limitations and challenges of machine learning, including the need for large amounts of high-quality data, the risk of bias and unfairness, and the difficulty of interpreting complex models. Despite these challenges, machine learning offers powerful tools for solving a wide range of problems and has the potential to transform many industries and fields.
In the next chapter, we will discuss text preprocessing, which is required for text to be used by machine learning models.
Questions
Section titled “Questions”- Why does the chapter emphasize data exploration before modeling in NLP projects?
- What is the practical risk of keeping duplicate records in a training dataset?
- When would you standardize features, and what does Z-score normalization do?
- How does the chapter define underfitting and overfitting using bias and variance?
- Name three techniques the chapter recommends to reduce overfitting.
- Why do we split data into training, validation, and test sets rather than only training and test sets?
- What is k-fold cross-validation, and when is stratified k-fold especially useful?
- What is the difference between grid search, random search, and Bayesian optimization for hyperparameter tuning?
- What are three strategies for handling imbalanced classification, and what is one trade-off of SMOTE?
- Why are transformers particularly important for NLP compared with many classical models?
References
Section titled “References”- Géron, A. Hands-On Machine Learning with Scikit-Learn, Keras & TensorFlow – practical coverage of data prep and model selection.
- Jurafsky & Martin, Speech and Language Processing (ch. 2–4) for tokenization, stemming, and corpus exploration best practices.
- Van der Walt, S. et al., “The NumPy Array: A Structure for Efficient Numerical Computation,” Computing in Science & Engineering, 2011.
- Wickham, H., ggplot2: Elegant Graphics for Data Analysis, Springer, 2016.
- Little, R. J. A. & Rubin, D. B., Statistical Analysis with Missing Data, Wiley, 2019.
- Guyon, I. & Elisseeff, A., “An Introduction to Variable and Feature Selection,” JMLR, 2003.
- Pedregosa et al., Scikit-learn documentation – sections on
feature_selection,RFE, andLassoCV. - Van der Maaten, L. & Hinton, G., “Visualizing data using t-SNE,” JMLR, 2008.
- Devlin, J. et al., “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding,” 2019.
- Vaswani, A. et al., “Attention Is All You Need,” NeurIPS, 2017.
- Bishop, C. M., Pattern Recognition and Machine Learning, 2006
- Breiman, L., “Bagging Predictors,” Machine Learning, 1996.
- Shahriari, B., Swersky, K., Wang, Z., Adams, R.P., de Freitas, N.: Taking the human out of the loop: A review of Bayesian optimization. Proceedings of the IEEE 104(1), 148–175 (2016). DOI 10.1109/JPROC.2015.2494218.
Join our Discord and Reddit Space
Section titled “Join our Discord and Reddit Space”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. |
|---|
A qr code on a white background AI-generated content may be incorrect.
A qr code on a white background AI-generated content may be incorrect.