Data Preprocessing for Machine Learning — Lecture 2
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- 1.4 Features, Attributes, Predictors, and Dimensions — covered in Lecture 1
- 1.4.2 High-Dimensional Data — covered in Lecture 1
- 1.7 Dimensionality Reduction (Preview) — covered in Lecture 1
Data Preprocessing for Machine Learning — Enriched Lecture Notes
2.1 Entities, Entity Sets, and Attributes
This is the central tension of data preprocessing: the numbers look fine, but their meaning determines everything. Let's build the vocabulary to describe what each column really is.
An entity is a real-world object — a person, a car, a transaction, a flower. A collection of entities is called an entity set. Each characteristic or property of an entity is an attribute.
Synonyms you must know (they all mean the same thing):
- For a data object: record, point, case, sample, entity, instance, vector, observation, pattern, event
- For an attribute: feature, dimension, characteristic, variable, field
One row = one data object. One column = one attribute. A collection of rows = a dataset.
2.2 Types of Attributes
2.2.1 The Four-Level Hierarchy
The answer unlocks the entire classification system. Here's the mental model.
| Type | Operations | Meaning | Examples |
|---|---|---|---|
| Nominal | , | Values are names only; no order | Hair color, ZIP code, ID numbers, jersey numbers |
| Ordinal | , , , | Values have order but unknown magnitude between them | Shirt size (S/M/L), grades (A/B/C), military rank, satisfaction surveys |
| Interval | , , , , , | Differences are meaningful; no true zero | Temperature in °C or °F, calendar year, CGPA, credit score |
| Ratio | , , , , , , , | Both differences and ratios are meaningful; true zero exists | Height, weight, age, temperature in Kelvin, counts, percentage |
Nominal and ordinal are collectively called categorical (or qualitative). Interval and ratio are collectively called numerical (or quantitative).
- Numbers don't mean numeric. Employee ID 1001 and 1002 — you can subtract them and get 1, but that 1 means nothing. The numbers are labels, not quantities. Always ask: "Does the number represent a count or measurement, or is it just a name written in digits?"
- The temperature trap. Celsius and Fahrenheit are interval, NOT ratio. 40°C is NOT "twice as hot" as 20°C. Kelvin is ratio. This is the most common exam trick question.
- CGPA and credit scores are interval, not ratio. A CGPA of 8 does not mean double the quality of a CGPA of 4. The zero is not a true zero of quality.
- Ordinal vs. interval for shoe size. Shoe size is tricky. If magnitude differences between sizes are standardized (e.g., each full size = ⅓ inch), it could be interval. If not, it's ordinal. The professor flagged this as ambiguous — state your assumption.
2.2.2 Nominal Attributes — The "Names Only" Type
A nominal attribute has values that are symbols or names. "Nominal" comes from the Latin nomen (name). Each value is a category, a code, or a state. Nominal attributes are also called categorical attributes.
Examples: hair color (black, brown, blonde, red, gray), marital status (single, married, divorced, widowed), occupation, ZIP code, ID numbers, jersey numbers.
The textbook (Tan, Steinbach & Kumar) makes this point vividly: "While it is reasonable to talk about the average age of an employee, it makes no sense to talk about the average employee ID". Both age and ID can be stored as integers — but their meaning is completely different.
Nominal: Favorite candy bar, Jersey numbers, Gender (binary symmetric), Course ID. Each is a name or label with no inherent order.
2.2.3 Ordinal Attributes — Order Without Magnitude
An ordinal attribute has values with a meaningful order or ranking, but the magnitude between successive values is unknown.
Examples include drink size (small, medium, large), shirt size (XS, S, M, L, XL), and grades (A, A−, B). Also satisfaction surveys (0 = very dissatisfied to 4 = very satisfied), professional ranks, and military ranks.
- Q: Is grade a categorical attribute?
- A: Grades are ordinal, not nominal. Grades have an inherent order (A > B > C) but the magnitude difference between them is not known. If grades are relative to other students (curved), they remain ordinal — the ranking exists but the gap between A and B is not a fixed quantity.
2.2.4 Interval Attributes — Equal Gaps, No True Zero
An interval-scaled attribute is measured on a scale of equal-size units. Values have order, can be positive/zero/negative, and allow you to quantify differences. But there is no true zero — you cannot say one value is a multiple of another.
Examples: calendar year, temperature in °C or °F, marks, CGPA, credit score.
2.2.5 Ratio Attributes — The Full Arithmetic
A ratio-scaled attribute has an inherent zero point. Zero means the absence of that quantity. You can say one value is a multiple of another.
Examples include length (20 cm is twice 10 cm), weight (80 kg is double 40 kg), and number of children (4 is double 2, zero means no children). Also temperature in Kelvin (40 K is double 20 K), exam percentage (50% is double 25%), and age.
2.2.6 Discrete vs. Continuous
A discrete attribute has a finite or countably infinite set of values. A continuous attribute can take any real-number value between its minimum and maximum.
- Discrete: hair color, ZIP codes, ID numbers, number of children
- Continuous: temperature, height, weight, percentage (74.5% is possible)
2.2.7 Binary Attributes — Symmetric and Asymmetric
A binary attribute is a nominal attribute with exactly two categories (0 or 1).
- Binary symmetric: Both states carry equal weight. Either can be coded as 0 or 1. Example: gender (male/female).
- Binary asymmetric: One state is more important (usually the rarer one), coded as 1. Example: HIV test result — positive = 1 (rare, important), negative = 0.
2.3 Important Characteristics of Data
2.3.1 Dimensionality
2.3.2 Sparsity
2.3.3 Resolution
- Temporal resolution: data collected hourly vs. yearly
- Spatial resolution: a map showing individual buildings vs. entire regions
- Value resolution (measurement precision): 100 vs. 100.00 — more decimal places = finer gradation
Higher resolution enables discovery of more patterns, but requires more capable systems.
2.3.4 Size
2.4 Types of Data
2.4.1 Record Data (Relational, Transactional, Document, Data Matrix)
- Relational data: Standard structured format in relational databases. Each row is a record; each column is an attribute.
- Transactional data: Each record is a set of items (a "market basket"). Used for association analysis and market basket analysis — finding which items are frequently bought together. Example: a retail bill — customer X bought items A, B, C for price Y on date Z.
- Document data: Each document is a vector of term frequencies. Used for TF-IDF calculation and cosine similarity. Example: Document 1 = {trend: 5, data: 10, story: 4, mining: 8}.
- Data matrix: All attributes are numeric — the dataset is an matrix suitable for linear algebra operations.
- Sparse data matrix: A data matrix where most entries are zero (document-term matrices, transaction data).
2.4.2 Graph-Based Data
Data represented as nodes (entities) and edges (relationships). Examples: social networks (Jack and Mary are friends → an edge connects them), the World Wide Web (pages linked by hyperlinks), chemical compounds (atoms connected by bonds). Graph databases like Neo4j store this data.
2.4.3 Ordered Data (Temporal, Sequence, Time Series, Spatial, Clickstream)
- Sequential/Temporal data: Records have timestamps. Example: retail transactions with purchase times — enables patterns like "candy sales peak before Halloween."
- Time series data: A set of data points indexed in time order at regular intervals. Example: stock market charts, monthly profit percentages.
- Sequence data: Order matters, but no timestamps. Example: genomic data (DNA sequences — A, T, G, C), text (word order in a sentence).
- Spatial data: Data with geographic components — latitude, longitude, state, country.
- Clickstream data: The order of user clicks through a website. Example path: Home → Product → Checkout → Thank You.
- Q: Is stock market data time series or sequence?
- A: Stock market data is normally considered time series. In sequence data, there is a fixed, defined sequence considered ideal behavior, and you check for repeated occurrence. Stock market data does not have a fixed predefined sequence in that sense.
2.5 Data Quality
Good data must be: correct, usable, complete, trustable, and consistent. The textbook (Tan, Steinbach & Kumar) identifies four major data quality issues: (1) measurement and data collection errors, (2) noise and artifacts, (3) outliers, and (4) missing, inconsistent, and duplicate data.
2.5.1 Common Data Quality Problems — A Concrete Example
Consider a loan prediction dataset:
| Transaction ID | Refund | Marital Status | Taxable Income | Cheat (target) |
|---|---|---|---|---|
| 1 | Yes | Single | 125K | No |
| 2 | No | Married | 100K | No |
| 3 | No | Single | 70K | No |
| 4 | Yes | Married | 120K | No |
| 5 | No | Divorced | 95K | Yes |
| 6 | No | Married | 60K | No |
| 7 | Yes | Divorced | 220K | No |
| 8 | No | Single | 85K | Yes |
| 9 | No | Married | 75K | No |
| 9 | No | Single | 90K | Yes |
| 10 | No | — | 10,000K | — |
Problems visible:
- Missing values: Marital status missing for record 10; target label missing for record 10.
- Outliers: Record 7 shows taxable income of 220K (others: 60K–125K). Record 10 shows 10,000K — extreme outlier.
- Duplicate/inconsistent: Two records for Transaction ID 9 — one says "Married," the other says "Single."
2.5.2 Noise
The textbook defines noise as "the random component of a measurement error" — it may involve distortion of a value or addition of spurious objects. Signal processing techniques can sometimes reduce noise, but the best approach is robust algorithms that tolerate it.
2.5.3 Outliers
An outlier is data that does not fit with the rest — but it is NOT necessarily an error. Example: analyzing income of 1,000 people — one is Bill Gates. His income is much higher, but he is a valid data point from the same population. He is an outlier, not noise.
2.5.4 Missing Values
| Attribute Type | Replacement Strategy |
|---|---|
| Numerical (interval/ratio) | Mean of the column |
| Categorical (nominal) | Mode of the column |
| Ordinal | Median of the column |
- Is the missing value in the target label column? → Delete the record. You cannot impute what you're trying to predict.
- Are many columns missing for one record? (e.g., 10 out of 15) → Delete the record. Even imputed, it adds little value.
- Is only one column missing? → Impute using mean/median/mode based on attribute type.
- Do you have abundant data? (10,000+ records) → Consider deleting instead of imputing.
- Replace with 0 or a default value
- Replace with the last known value (carry forward)
- Interpolate using splines: fit a curve through known data points, read the missing value from the curve. A spline is a mathematical function that creates a smooth curve passing through a set of points.
- Use nearest neighbors: find similar records and use their values
2.5.5 Duplicate Data
Duplicate data represents loss of information, not additional information. If two records exist for the same entity with conflicting values, you lose the true information. Either fix with the domain expert or delete both records.
The textbook notes that deduplication is often necessary when the same real-world entity appears multiple times under slightly different names (e.g., "J. Smith" and "John Smith").
2.5.6 Inconsistent Data
Examples: birthday format DD-MM-YY in one record, MON-DD-YYYY in another; age = 42 but birthday = 3/7/2010; ratings as 1/2/3 in some records and A/B/C in others. Fix by checking with the domain expert for the correct format.
2.5.7 Wrong Data, Fake Data, Biased Data
- Wrong/fake data: Intentionally incorrect (e.g., everyone's birthday = January 1). No automated method detects this without domain knowledge.
- Biased data: Purposefully unrepresentative. Example: survey data only from people who responded — sampling bias.
2.6 Data Preprocessing Overview
Data preprocessing involves two major phases:
- Data Engineering: Converting raw data into prepared (clean) data — aggregation, cleansing, instance selection, partitioning.
- Feature Engineering: Tuning prepared data to create features expected by the ML model — may involve combining features to create new ones.
The workflow: Raw data → Data Engineering → Prepared data → Feature Engineering → ML-ready features.
2.7 Data Aggregation
- Smaller datasets → less memory, faster processing
- High-level view instead of low-level — change of scope/scale
- Aggregated quantities (averages, totals) have less variability than individual objects — more stable behavior
2.8 Data Cleaning Techniques
2.8.1 Handling Noisy Data
For values that are errors (e.g., salary = −10):
- Delete the record (last resort — data is precious)
- Replace with the measure of central tendency (mean/median/mode)
2.8.2 Handling Outliers — The IQR Method
The method is simpler than it sounds. Here's the one-sentence version first.
Given a numerical column with 12 sorted values.
Step 1: Sort the values in ascending order. This step is worth marks — missing it loses all marks for the question. Step 2: Find Q2 (the median). With 12 values (even count), average the 6th and 7th values.From the worked example:
- Sorted data (positions 1–12): 6th = 12, 7th = 13
Step 7: Calculate outlier boundaries:
Step 8: Any value below 5.75 or above 19.75 is an outlier.
Sorted data: [6, 8, 10, 11, 11, 12, 13, 14, 14, 15, 18, 22]
- Q2: (12 + 13)/2 = 12.5
- Q1: (10 + 11)/2 = 10.5
- Q3: (15 + 18)/2 = 16.5
- IQR: 16.5 − 10.5 = 6.0
- Lower bound: 10.5 − 1.5 × 6.0 = 1.5
- Upper bound: 16.5 + 1.5 × 6.0 = 25.5
No outliers in this data — all values are within [1.5, 25.5]. Sense-check: The range is 6 to 22, which fits comfortably within the bounds.
- ~68% of data within
- ~95% of data within
- ~99.7% of data within
Values beyond are considered outliers. The box plot bounds and approximate this same concept. For a normal distribution, the IQR ≈ 1.35σ, so 1.5 × IQR ≈ 2σ — close to the 95% boundary.
Alternative method: Directly use . Calculate mean and standard deviation, flag anything outside .- Q: When calculating the mean for outlier detection, do you include the outliers?
- A: In the basic method, yes — consider the entire data. However, if you suspect outliers, use a trimmed mean: trim a percentage (e.g., 1%) from both ends, then calculate the mean from the remaining data. The textbook defines the trimmed mean formally: specify a percentage p between 0 and 100, throw out the top and bottom (p/2)% of data, compute the mean normally. The median is a trimmed mean with p = 100%.
- Forgetting to sort. The IQR calculation starts with sorting. Unsorted data → wrong quartiles → wrong bounds → zero marks.
- Confusing Q1/Q3 calculation for even vs. odd n. For even n, average the two middle values. For odd n, take the single middle value.
- Using IQR on categorical data. IQR only makes sense for numerical (interval/ratio) attributes.
- Automatically deleting all outliers. Outliers may be the most interesting data points (fraud detection, anomaly detection). Always investigate before deleting.
2.9 Sampling and Training/Testing Data
2.9.1 Representative Sampling
The training data must be a representative sample of the population — it should have approximately the same properties (mean, standard deviation, distribution shape) as the original data. A non-representative sample produces incorrect results regardless of sample size.
Visual intuition: Original data has 8,000 points with visible dense and sparse regions. A good sample of 2,000 points preserves that structure. A bad sample of 50 points loses the shape entirely.2.9.2 Simple Random Sampling
- Sampling with replacement: After selecting an item, put it back. Every item always has the same probability of being selected. For 7 items: always .
- Sampling without replacement: After selecting, keep it out. Probabilities change: first draw , second , third .
- Without replacement — when each sample must be unique (e.g., selecting 100 students from 1,000 for a project).
- With replacement — when repetition is allowed (e.g., bootstrapping to estimate model uncertainty, or when the dataset is too small and you need many different training subsets).
2.9.3 Stratified Sampling
- Simplest version: Equal number from each group. 4 groups, need 40 people → 10 from each.
- Proper version: Proportional to group percentage. Population: 48.7% male, 51.3% female. To select 1,000: 487 males, 513 females.
Stratified sampling is the most commonly used method because it guarantees representation of every subgroup.
2.9.4 Handling Imbalanced Data
An imbalanced dataset has one class heavily underrepresented. Example: HIV test results — 95 negative, 5 positive out of 100. The rare class (positive) is what you want to analyze, but it's severely underrepresented. Many classifiers fail on imbalanced data.
Strategies:- Undersample the majority class — reduce majority-class records.
- Oversample the minority class — create synthetic data for the rare class.
2.10 Normalization and Standardization
2.10.1 Min-Max Normalization
Use when you know the upper and lower bounds of the data.
Formula — to normalize a value to a new range :
The fraction maps to . Then multiply by the desired range width and add the new minimum to shift.
Sense-check: 73,000 is roughly 71% of the way from 12,000 to 98,000. The normalized value 0.7093 confirms this.
2.10.2 Z-Score Normalization (Standardization)
Use when you do NOT know the min and max, but you know (or can compute) the mean and standard deviation . The result has mean = 0 and standard deviation = 1.
The textbook notes that the mean and standard deviation are strongly affected by outliers. A robust alternative replaces the mean with the median and the standard deviation with the absolute standard deviation: where is either the mean or median.
2.10.3 Decimal Scaling
The simplest method. Divide by a power of 10 to shift the decimal point:
Where is chosen so that the largest absolute value becomes less than 1. Example: values in thousands (3000, 6000) → use : , .
- Normalizing before handling outliers. Outliers distort min, max, mean, and standard deviation. Always detect and handle outliers first.
- Applying min-max to data with unknown future bounds. If new data might arrive with values outside the original [min, max], min-max normalization breaks. Use z-score instead.
- Forgetting to use the SAME parameters on test data. Normalize test data using the min/max or mean/std from the TRAINING data, not from the test data itself. Otherwise, you leak information.
- Normalizing binary/categorical columns. Only normalize numerical (interval/ratio) columns. Normalizing a 0/1 binary column is meaningless.
2.11 The Iris Dataset — Full Walkthrough
2.11.1 Dataset Overview
The Iris dataset (Fisher, 1936) is the most famous dataset in machine learning. Contents:
- 3 species: Iris setosa, Iris versicolor, Iris virginica
- 50 records per species (150 total)
- 4 features: sepal length, sepal width, petal length, petal width (all in cm)
- 1 target label: species
- 3 duplicate records exist
2.11.2 Python Operations
- `iris.shape` → returns (rows, columns)
- `iris.head()` → first 5 rows
- `iris.info()` → attribute types (float64 for numerical, object for categorical)
- `iris.describe()` → the five-point summary plus mean and standard deviation for all numerical columns
2.11.3 The Five-Point Summary
For any numerical column, the five-point summary is (in order): min, Q1, Q2 (median), Q3, max. Along with mean and standard deviation, this is what `describe()` returns. The five-point summary must be memorized and recallable instantly for the exam.
2.11.4 Duplicate Handling
Check duplicates with `duplicated()`, drop with `drop_duplicates()`. In Iris, duplicates are exact (no inconsistency), so dropping the second occurrence is straightforward.
2.11.5 Outlier Detection with Box Plots
Using Seaborn's `boxplot` for each attribute:
- Sepal length shows outliers (black dots outside whiskers)
- Whiskers represent the 1.5 × IQR bounds
- Decision to keep or remove outliers depends on domain expertise
2.12 The Automobile Dataset — Full Walkthrough
2.12.1 Dataset Description
Source: UCI Machine Learning Repository. Columns: symboling, normalized-losses, make, fuel-type, number-of-doors, body-style, drive-wheels, engine-location, wheel-base, length, width, height, curb-weight, engine-type, num-of-cylinders, engine-size, fuel-system, bore, stroke, compression-ratio, horsepower, peak-rpm, city-mpg, highway-mpg, price (target).
2.12.2 Cleaning Steps (Procedural Spine)
Here is the exact sequence of operations, in order:
- Add headers — Raw data had no column headers; provided in a separate file.
- Identify missing values — Many "?" characters throughout.
- Replace "?" with NaN — Convert all "?" to proper NaN so Python recognizes them as missing.
- Impute numerical columns with mean: `normalized-losses`, `bore`, `stroke`, `horsepower`, `peak-rpm`.
- Impute categorical column with mode: `number-of-doors` → majority of cars have 4 doors.
- Handle missing target label: `price` had missing values → drop those entire records.
- Data type conversions — Convert columns to appropriate types.
- Create derived attribute — Convert `city-mpg` (miles per gallon) to liters per 100 km.
- Q: For number-of-doors, why use mode instead of deleting the 2 missing records out of 10,000?
- A: With only 2 missing out of 10,000, it is better to impute. Find the majority — most cars have 4 doors — and replace with that value (the mode). Deleting would lose the other 15+ columns of valid data in those 2 rows.
2.13 Exam Guidance Summary
- Five-point summary (min, Q1, Q2, Q3, max) — recall instantly.
- IQR calculation — expect a numerical question. SORT FIRST. Missing the sorting step = zero marks.
- Attribute type identification — given a dataset, classify each column as nominal, ordinal, interval, or ratio, and as discrete or continuous.
- Box plot interpretation — know what the box, whiskers, median line, and outlier dots represent.
- Normalization formulas — min-max, z-score, and decimal scaling.
- Missing value strategies by attribute type — mean for numerical, median for ordinal, mode for categorical.
Beyond the theory, the lab component is equally important.
2.14 Key Industry Applications and Tools
- Relational databases — store structured relational data
- Graph databases (Neo4j) — store web and social network data
- TF-IDF and cosine similarity — used for document data and text mining
- Association analysis / Market basket analysis — used on transactional data (retail billing)
- SMOTE and ADASYN — techniques for handling imbalanced data in classification problems
- UCI Machine Learning Repository — source of benchmark datasets (Iris, Automobile)
- Python libraries: pandas (data manipulation), matplotlib/seaborn (visualization), scikit-learn (ML algorithms)
- Bootstrapping — sampling with replacement technique used to estimate model uncertainty
- Credit card fraud detection and intrusion detection — domains where outlier detection IS the goal
- Pre-election opinion polls — real-world example of sampling (and sampling bias)
- Great Expectations, dbt, Apache Griffin — data quality automation tools in industry
- John Tukey's Exploratory Data Analysis (EDA) — the philosophical foundation of data exploration and visualization
- Batch Normalization (Ioffe & Szegedy, 2015) — deep learning layer that internalizes the normalization concept
ML Lecture 2 notes · Data Preprocessing for Machine Learning — Lecture 2
Summary
Comprehensive lecture on data preprocessing for machine learning. Covers the four-level attribute type hierarchy (nominal, ordinal, interval, ratio), discrete vs continuous attributes, binary attribute types, data characteristics (dimensionality, sparsity, resolution, size), data types (record, graph, ordered), data quality issues (noise, outliers, missing values, duplicates), the IQR method for outlier detection, sampling strategies (simple random, stratified, SMOTE/ADASYN for imbalance), normalization techniques (min-max, z-score, decimal scaling), and full walkthroughs of the Iris and Automobile datasets.
Learning Objectives
Sections Breakdown
Hook: You sit down to analyze a medical dataset. One column is labeled "Field 1". You build a model. It predicts perfectly. Then the statistician tells you: "Field 1 is just the patient ID number — we sorted the records by the target variable before assigning IDs". Your perfect model is meaningless. Knowing what each column actually is matters more than any algorithm.
2.2.1 The Four-Level Hierarchy Hook: Why can you say "Alice is twice as tall as Bob" but not "Monday is twice as hot as Tuesday"? The answer lies in the measurement scale — and there are exactly four levels, each adding one new mathematical power.
2.3.1 Dimensionality Hook: A dataset with 3 columns fits on a screen. A dataset with 10,000 columns — like a document-term matrix where every word in the English language is a column — breaks most algorithms. This is the curse of dimensionality, and it is one of the hardest problems in ML.
2.4.1 Record Data (Relational, Transactional, Document, Data Matrix) Record data is the most common form — data stored in rows and columns. Relational data: Standard structured format in relational databases. Each row is a record; each column is an attribute. Transactional data: Each record is a set of items (a "market basket"). Used for association analysis and market basket analysis — finding which items are frequently bought together. Example: a retail bill — customer X bought items A, B, C for price Y on date Z. Document data: Each document is a vector of term frequencies. Used for TF-IDF calculation and cosine similarity. Example: Document 1 = {trend: 5, data: 10, story: 4, mining: 8}. Data matrix: All attributes are numeric — the dataset is an \( m \times n \) matrix suitable for linear algebra operations. Sparse data matrix: A data matrix where most entries are zero (document-term matrices, transaction data).
Hook: "Garbage in, garbage out". The most sophisticated deep learning model trained on dirty data produces sophisticated garbage. Data quality is not glamorous, but it is the single highest-leverage activity in any ML project.
Data preprocessing involves two major phases: Data Engineering: Converting raw data into prepared (clean) data — aggregation, cleansing, instance selection, partitioning. Feature Engineering: Tuning prepared data to create features expected by the ML model — may involve combining features to create new ones.
Data aggregation combines granular data into coarser summaries. Example: daily sales → monthly sales by summing (or averaging) numerical columns. The standard operation is GROUP BY (as in SQL). Motivations (from the textbook):
2.8.1 Handling Noisy Data For values that are errors (e.g., salary = −10): Delete the record (last resort — data is precious) Replace with the measure of central tendency (mean/median/mode) 2.8.2 8.2 Handling Outliers — The IQR Method
2.9.1 Representative Sampling Hook: Pre-election polls don't ask every voter — they sample. When polls are wrong, it's almost always because the sample wasn't representative, not because the sample was too small. The same principle governs ML: a small but representative training set beats a large but biased one every time.
Hook: A dataset has "number of pregnancies" (0–10) and "glucose level" (0–200). A distance-based model like k-NN sees glucose differences of 50 as 5× more important than pregnancy differences of 10 — not because glucose matters more, but because its numbers are bigger. Normalization fixes this invisible bias.
2.11.1 Dataset Overview The Iris dataset (Fisher, 1936) is the most famous dataset in machine learning. Contents: 3 species: Iris setosa, Iris versicolor, Iris virginica 50 records per species (150 total) 4 features: sepal length, sepal width, petal length, petal width (all in cm) 1 target label: species 3 duplicate records exist
2.12.1 Dataset Description Source: UCI Machine Learning Repository. Columns: symboling, normalized-losses, make, fuel-type, number-of-doors, body-style, drive-wheels, engine-location, wheel-base, length, width, height, curb-weight, engine-type, num-of-cylinders, engine-size, fuel-system, bore, stroke, compression-ratio, horsepower, peak-rpm, city-mpg, highway-mpg, price (target).
Exam note: Questions from data preprocessing WILL appear on the mid-semester exam. The sample question papers already shared contain questions from these topics. Must-memorize items: Five-point summary (min, Q1, Q2, Q3, max) — recall instantly. IQR calculation — expect a numerical question. SORT FIRST. Missing the sorting step = zero marks. Attribute type identification — given a dataset, classify each column as nominal, ordinal, interval, or ratio, and as discrete or continuous. Box plot interpretation — know what the box, whiskers, median line, and outlier dots represent. Normalization formulas — min-max, z-score, and decimal scaling. Missing value strategies by attribute type — mean for numerical, median for ordinal, mode for categorical.
Relational databases — store structured relational data Graph databases (Neo4j) — store web and social network data TF-IDF and cosine similarity — used for document data and text mining Association analysis / Market basket analysis — used on transactional data (retail billing)
Exam Revision Notes
Why attribute types matter. The attribute type is the most important factor deciding which ML model you can use, which visualization to apply, and which measure of central tendency (mean, median, mode) to use for replacing missing values. Get the type wrong, and every downstream decision is wrong.
Confusing attribute names (columns) with data objects (rows), or assuming data objects are always independent.
Why is it important to know an attribute's meaning before applying a machine learning algorithm?
Recap: Attribute types form a four-level hierarchy: Nominal → Ordinal → Interval → Ratio. Each level adds one new mathematical operation. Identifying the correct type is the first decision in any ML pipeline. Bridge: Now we zoom in on the two most commonly confused types — nominal and ordinal — and their critical nuances.
Scope / Assumption: The four-level hierarchy is cumulative — ratio attributes have all the properties of interval, ordinal, and nominal. But the reverse is NOT true: an operation valid for ratio attributes (like computing a geometric mean) is NOT valid for interval attributes.
Classify the following attributes: Celsius temperature, credit score, ZIP code, and age.
Recap: Dimensionality, sparsity, resolution, and size are the four high-level characteristics that determine which algorithms will work and how to preprocess. Bridge: These characteristics manifest differently across the major types of data — relational, transactional, document, graph, spatial, temporal, and sequence data.
Assuming that higher resolution data is always better, ignoring the extra computation and storage requirements.
How does the curse of dimensionality affect distance-based machine learning algorithms?
Recap: Data comes in many forms — record, graph, and ordered. The type of data determines which preprocessing techniques and algorithms apply. Bridge: No matter the data type, one universal truth holds: real data is messy. Next, we confront data quality head-on.
Confusing stock market data (time series) with genomic sequences (sequence data).
Give an example of a sparse data matrix and explain why sparsity is computationally advantageous.
Recap: Data quality problems — noise, outliers, missing values, duplicates, inconsistencies, and bias — are universal. The first step is always detection; the second is correction using the strategies above. Bridge: With quality problems identified, we now turn to the systematic preprocessing pipeline that transforms raw data into ML-ready features.
Key distinction — Noise vs. Outliers: Noise is garbage — remove it. Outliers are valid data that behave differently — decide whether to include or exclude based on domain knowledge.
When should you delete a record with missing values rather than imputing them?
Data preprocessing involves two major phases: (1) Data Engineering (converting raw data into prepared clean data via aggregation, cleansing, instance selection, partitioning) and (2) Feature Engineering (tuning prepared data to create features expected by the ML model).
Confusing Data Engineering (cleansing/aggregation) with Feature Engineering (tuning features for a specific ML model).
What is the difference between data engineering and feature engineering in the preprocessing workflow?
Data aggregation combines granular data into coarser summaries (e.g., daily to monthly sales). Key motivations include smaller dataset size (less memory/faster processing), changing the scope/scale to a high-level view, and reducing variability (aggregated quantities are more stable than individual objects), though it can lose interesting details.
Assuming aggregation is always beneficial, ignoring the disadvantage that it causes potential loss of interesting low-level details/variability.
What are the three main motivations for data aggregation, and what is its primary disadvantage?
Recap: The IQR method: sort → find Q1, Q2, Q3 → IQR = Q3 − Q1 → bounds = Q1 − 1.5×IQR and Q3 + 1.5×IQR. Values outside bounds are outliers. Bridge: Outlier detection is part of cleaning. Next, we address how to split cleaned data into training and testing sets — and why the split must be representative.
Assumptions & Scope: The IQR method assumes a roughly symmetric distribution. The 1.5× multiplier is a convention, no...
What are the outlier bounds in the IQR method if Q1 = 10.5 and Q3 = 16.5?
Recap: Sampling must be representative. Stratified sampling is the gold standard. For imbalanced data, SMOTE and ADASYN create synthetic minority samples. Bridge: With clean, sampled data in hand, the final preprocessing step is normalization — bringing all numerical columns to the same scale.
Using simple random sampling on heavily imbalanced datasets without stratification, which may completely omit the minority class.
What is the difference between simple random sampling with and without replacement, and when is SMOTE used?
Recap: Three normalization methods — min-max (known bounds), z-score (known mean/std), decimal scaling (simplest). Always handle outliers first. Always use training-data parameters on test data. Bridge: Theory meets practice. We now walk through two real datasets — Iris and Automobile — applying every concept from this lecture.
Scope: Min-max normalization is sensitive to outliers. A single extreme value stretches the range, compressing all ot...
Why must you use the mean and standard deviation from the training data, rather than the test data, when normalizing test data?
The Iris dataset contains 150 records across 3 species (Setosa, Versicolor, Virginica) with 4 numerical features. Essential Python operations include shape, head(), info(), and describe() (which provides the five-point summary: min, Q1, Q2/median, Q3, max). Exact duplicates are dropped.
Forgetting to write interpretations below every visualization in Python assignments, which is required to earn full marks.
What are the 4 features and 3 classes of the Iris dataset, and what Python command is used to generate its five-point summary?
The preprocessing pipeline for the Automobile dataset consists of: adding headers, replacing '?' with NaN, imputing missing values (mean for numerical like horsepower, mode for categorical like number-of-doors), dropping records with missing price target, converting types, and creating derived attributes.
Imputing missing target labels (price) instead of dropping the entire record, or deleting records with missing features when the missingness is extremely rare.
What is the correct sequence of cleaning steps for handling missing values and wrong data types in the Automobile dataset walkthrough?
Exam note: Questions from data preprocessing WILL appear on the mid-semester exam. The sample question papers already shared contain questions from these topics.
Forgetting to sort the dataset in ascending order before finding quartiles for IQR, leading to incorrect calculations and zero marks.
What are the key formulas and missing value strategies that you must memorize for the mid-semester exam?
Data preprocessing relies on standard tools and concepts including: Relational and Graph (Neo4j) databases; TF-IDF and Cosine Similarity for text; Market Basket Analysis for transactions; SMOTE/ADASYN for class imbalance; Pandas, Matplotlib, Seaborn, and Scikit-learn in Python; Bootstrapping for sampling; EDA (Tukey) for visual exploration; and industrial data quality tools like Great Expectations, dbt, and Apache Griffin.
Failing to use automated data quality tools (like Great Expectations or dbt) or ignoring class imbalance (requiring SMOTE/ADASYN) when training classifiers on skewed industrial datasets.
Which Python libraries and data quality automation tools are standard in the industry for data preprocessing and analysis?
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.