Chapter 2: Getting started with baselines: Data preprocessing
This introduction explains the purpose of NLP baselines, the limitations of keyword rules, and how to run the book’s notebooks with attention to dependencies.
After this chapter you will be able to
- Baselines for transfer learning. Explain why the book establishes baselines for email spam and movie-review sentiment classification before comparing transfer learning approaches.
- Supervised Spam Dataset. Describe the spam-classification task and how the two email sources serve as proxies for its labels.
- Enron corpus inspection. Describe how the Enron corpus is loaded and inspected before preprocessing.
- Email body and headers. Explain why and how the section separates email bodies from headers for spam classification.
- Fraudulent Corpus Loading. Describe how the fraudulent email text file is loaded into a DataFrame and why it needs different handling from the Enron CSV.
- Class Sampling and Dataset Assembly. Explain how the spam and nonspam datasets are sampled and combined, including the reason for the chosen class proportions.
- Word Tokenization and Limits. Explain how the emails are tokenized and why limits are set on tokens and their lengths.
- Text Normalization and Stop Words. Describe how punctuation, case, and stop words are handled and why these steps are used.
- Bag-of-words email representation. Explain how the email bag-of-words DataFrame represents each email and why infrequent tokens are excluded.
- Unison shuffling of emails. Explain why the vectorized emails are shuffled with their labels before splitting.
- Training and test split. Describe the email dataset's training and testing split and explain its evaluation purpose.
- Sentiment-sensitive stop word handling. Explain why movie review preprocessing requires care with stop words and how it differs from email preprocessing.
- Review preparation and representation. Trace the review preparation sequence from extracted files to a bag-of-words dataset and state the remaining data split.
- Sample class balance. Explain why the sampled reviews' label distribution is checked before modeling.
- Generalized linear model structure. Describe the roles of X, Y, β, the expected value, and the link function in the generalized linear model.
- Logistic Regression Probability Model. Explain how logistic regression relates input variables to a categorical output using the logistic function.
- Classifier Training and Evaluation. Describe how the section fits and evaluates a logistic regression classifier for the email and IMDB examples, and state what the comparison suggests.
- Classification Metric Definitions. Distinguish accuracy, precision, recall, and F1-score using the definitions given in the section.
- Metric Choice and Balance. Justify the section's use of accuracy for its examples and describe when precision, recall, and F1 can be useful.
- SVM kernel decision boundaries. Explain how SVMs use kernel methods to find decision boundaries and what changes when the kernel is linear.
- SVM baseline performance comparison. Describe how the SVM performed on the two example datasets relative to logistic regression, including the training-time observation.
Section by section
Introduction
This introduction explains the purpose of NLP baselines, the limitations of keyword rules, and how to run the book’s notebooks with attention to dependencies.
- Baselines for transfer learning: Explain why the book establishes baselines for email spam and movie-review sentiment classification before comparing transfer learning approaches.
Why it matters: A baseline gives you a reference point for judging whether a more sophisticated approach improves a task. - Keyword rule limitations: Describe how a keyword-matching rule could classify text and why the section treats such rules as limited.
Why it matters: Simple rules can be a starting point, but their limitations motivate looking beyond fixed keyword matches. - Notebook dependency reproducibility: Describe the recommended way to run the Kaggle notebooks and how the frozen dependency list should be treated for local installation.
Why it matters: Following the notebook and dependency guidance helps avoid preventable version-related problems.
Key terms: baselines, transfer learning, spam classification, sentiment classification, rule-based methods, keyword-matching, Kaggle notebooks, Copy and Edit Kernel, frozen dependency requirement list
2.1 Preprocessing email spam classification example data
Introduces a supervised spam-classification example built from two email sources and explains why the dataset is assembled rather than taken ready-labeled.
- Supervised Spam Dataset: Describe the spam-classification task and how the two email sources serve as proxies for its labels.
Why it matters: The sources and labels define what the example classifier is being trained to distinguish. - Dataset Curation Rationale: Explain why the example builds a dataset from existing email sources instead of using a ready-labeled dataset.
Why it matters: The example illustrates that preparing a usable dataset is often part of real-world machine learning work.
Key terms: supervised classification, Enron email corpus, 419 fraudulent emails, spam, data collection, preprocessing, built and curated
2.1.1 Loading and visualizing the Enron corpus
This section loads and inspects the Enron email corpus, then separates message bodies from headers for content-based spam classification.
- Enron corpus inspection: Describe how the Enron corpus is loaded and inspected before preprocessing.
Why it matters: Inspecting both the dataset and an individual email helps you understand what needs preprocessing. - Email body and headers: Explain why and how the section separates email bodies from headers for spam classification.
Why it matters: Separating the body lets the example classify messages using content even when identifying header information is unavailable.
Key terms: Enron corpus, Pandas, DataFrame, filepath, message column, header, email body, email package, de-identified
2.1.2 Loading and visualizing the fraudulent email corpus
This section loads fraudulent emails and combines them with Enron emails into a balanced, preprocessed spam-classification dataset.
- Fraudulent Corpus Loading: Describe how the fraudulent email text file is loaded into a DataFrame and why it needs different handling from the Enron CSV.
Why it matters: The file’s encoding and layout determine how its emails can be separated and processed. - Class Sampling and Dataset Assembly: Explain how the spam and nonspam datasets are sampled and combined, including the reason for the chosen class proportions.
Why it matters: Sampling choices affect what the classifier learns, and the combined array prepares the examples for later processing. - Word Tokenization and Limits: Explain how the emails are tokenized and why limits are set on tokens and their lengths.
Why it matters: Tokenization determines the text units used downstream, while limits control the cost of unusually long inputs. - Text Normalization and Stop Words: Describe how punctuation, case, and stop words are handled and why these steps are used.
Why it matters: These steps reduce differences and common words that the example treats as unhelpful for classification.
Key terms: 419 fraudulent email corpus, Latin-1, From r, Pandas DataFrame, class imbalance, 50/50 split, NumPy array, spam, nonspam, tokenization
2.1.3 Converting the email text into numbers
This section converts emails into bag-of-words vectors, shuffles them with their labels, and splits them for classifier training and evaluation.
- Bag-of-words email representation: Explain how the email bag-of-words DataFrame represents each email and why infrequent tokens are excluded.
Why it matters: This representation turns email text into numeric features that classifiers can use. - Unison shuffling of emails: Explain why the vectorized emails are shuffled with their labels before splitting.
Why it matters: Shuffling helps prevent the original class ordering from distorting the training and test sets. - Training and test split: Describe the email dataset's training and testing split and explain its evaluation purpose.
Why it matters: Holding out data gives the classifier an evaluation on examples it did not train on.
Key terms: bag-of-words model, word tokens, frequency counts, used_tokens, sparse DataFrame, shuffle, classes, labels, unison, training set
2.2 Preprocessing movie sentiment classification example data
This section prepares IMDB movie reviews for sentiment classification, emphasizing sentiment-sensitive preprocessing, class balance, and a numerical representation.
- IMDB sentiment classification dataset: Describe the IMDB review dataset and how its sentiment labels were derived.
Why it matters: The dataset and its labels define the classification problem the baseline models will address. - Sentiment-sensitive stop word handling: Explain why movie review preprocessing requires care with stop words and how it differs from email preprocessing.
Why it matters: Removing a seemingly unimportant word can change the sentiment expressed by a review. - Review preparation and representation: Trace the review preparation sequence from extracted files to a bag-of-words dataset and state the remaining data split.
Why it matters: This sequence turns raw reviews into data that can be used to build and evaluate classifiers. - Sample class balance: Explain why the sampled reviews' label distribution is checked before modeling.
Why it matters: Checking class proportions helps ensure the sample's label distribution is appropriate for the intended use.
Key terms: IMDB, sentiment analysis, positive, negative, stop words, header extraction, sentiment, tokenizing, NumPy array, bag-of-words
2.3 Generalized linear models
This section introduces linearity and the generalized linear model framework used for classification.
- Linear model properties: Explain how a linear model responds to combined inputs and why that property is useful.
Why it matters: Linearity provides the starting point for understanding the relaxed definition used here. - Generalized linear model structure: Describe the roles of X, Y, β, the expected value, and the link function in the generalized linear model.
Why it matters: This framework connects the inputs and trained parameters to the classifier's expected response.
Key terms: linear models, addition, multiplication, generalized linear model, independent variables, responses, expected value, link function, parameters
2.3.1 Logistic regression
This section introduces logistic regression, applies it to two classification examples, and explains how to evaluate the results.
- Logistic Regression Probability Model: Explain how logistic regression relates input variables to a categorical output using the logistic function.
Why it matters: This explains what the classifier models and the role of the logistic curve. - Classifier Training and Evaluation: Describe how the section fits and evaluates a logistic regression classifier for the email and IMDB examples, and state what the comparison suggests.
Why it matters: Held-out evaluation provides the basis for comparing the two example classifiers. - Classification Metric Definitions: Distinguish accuracy, precision, recall, and F1-score using the definitions given in the section.
Why it matters: These definitions distinguish different ways to measure classifier performance. - Metric Choice and Balance: Justify the section's use of accuracy for its examples and describe when precision, recall, and F1 can be useful.
Why it matters: The choice of metric should reflect the dataset and the kinds of errors that matter.
Key terms: logistic regression, logistic function, categorical output, probability, scikit-learn, hold out, test/validation sets, spam classification, IMDB, accuracy
2.3.2 Support vector machines (SVMs)
This section introduces SVMs as kernel methods and compares their baseline performance with logistic regression on email and movie-review classification.
- SVM kernel decision boundaries: Explain how SVMs use kernel methods to find decision boundaries and what changes when the kernel is linear.
Why it matters: This connects SVM decision boundaries to the role of kernels and identifies the linear-kernel special case. - SVM baseline performance comparison: Describe how the SVM performed on the two example datasets relative to logistic regression, including the training-time observation.
Why it matters: The comparison shows that baseline performance and training time can vary across tasks and models.
Key terms: SVM, kernel method, hyperplane, kernel trick, linear kernel, SVM classifier, logistic regression, accuracy score, training time, IMDB
2.4 Summary
Where this is used later
- Neural network models (chapter 3) · Applies neural models in the continuation of the baseline exercise.
- (chapter intro) (chapter 3) · The email spam classification data.
- Embeddings from Language Models (ELMo) (chapter 3) · The email text preprocessing produced token lists used by the traditional models.
- Random forests (RFs) (chapter 3) · The movie sentiment classification example data
- Bidirectional Encoder Representations from Transformers (BERT) (chapter 3) · The movie sentiment data has been preprocessed.
- (chapter intro) (chapter 4) · Logistic regression as a classification method.
- Optimizing performance (chapter 3) · Performance optimization builds on having a baseline to evaluate.
- Decision-tree-based models (chapter 3) · Provides SVM baseline results for comparison with decision-tree-based methods on the two problems.
Concepts explained in this chapter
- preprocessingData preprocessing is the preparation and transformation of raw data into a form suitable for analysis or machine learning.
- generalized linear modelA statistical model in which a function links a linear combination of independent variables to the expected value of an output variable.
- transfer learningTransfer learning is a machine-learning paradigm in which knowledge acquired from one task or domain is adapted to another task or domain.
- bag-of-words modelA bag-of-words model represents text by its words and their counts or weights while disregarding word order.
- accuracyAccuracy is the proportion of evaluated samples whose predicted labels match their actual labels.
- logistic regressionA statistical classification method that models class probabilities using a logistic function of input features.
- support vector machineA supervised learning method that determines a separating boundary by maximizing its margin from the closest training points.
- stop wordA word commonly filtered from text during processing because it is often considered less informative than other words.
- tokenizationThe process of dividing text into units such as words, subwords, or characters.
- sigmoidA sigmoid function maps real-valued inputs to values between zero and one, with an S-shaped curve.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
