Skip to main content
Machine Learning

Data Preprocessing for Machine Learning — Lecture 2

📅 Published: 2026-06-27
🎓 Level: postgraduate
👥 Audience: Graduate students in computer science and related fields studying machine learning

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

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.

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.

Intuition + Analogy: Think of a spreadsheet of student records. Each row is one student — that is a data object. Each column — name, age, GPA, ID number — is an attribute. The whole spreadsheet is the entity set. Just as you wouldn't add two phone numbers together or divide one ZIP code by another, you can't treat every column the same way. Some columns are names, some are counts, some are measurements. The type of each column decides everything you can legally do with it.
Formal definitions:

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.

Why attribute types matter: The type of each attribute is the single most important factor deciding (a) which ML model you can use, (b) which visualization to apply, and (c) which measure of central tendency (mean, median, mode) to use for replacing missing values. Get the type wrong, and every downstream decision is wrong.
Real-World & Domain Connection: In any data science project, the first hour is spent not on modeling but on understanding what each column means. The UCI Machine Learning Repository — the source of the Iris and Automobile datasets used in this course — always ships a `.names` file alongside the data precisely because attribute types are not self-evident from raw numbers. Professional data scientists call this "data profiling" and it is step zero of every project.

2.2 Types of Attributes

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.

The answer unlocks the entire classification system. Here's the mental model.

Intuition + Analogy: Imagine four levels of a video game. At Level 1 (Nominal), you can only tell if two things are the same or different — like sorting laundry by color. At Level 2 (Ordinal), you unlock ordering — you can rank movies from best to worst, but you can't say how much better. At Level 3 (Interval), you unlock addition and subtraction — you can say Monday is 5°C warmer than Tuesday. At Level 4 (Ratio), you unlock multiplication and division — you can say this rope is twice as long as that one. Each level inherits all the powers of the levels below it.
The four attribute types, defined by the mathematical operations they support:
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).

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. Always use the lowest level that accurately describes the attribute. If you're unsure between interval and ratio, default to interval — it's safer to under-claim than over-claim.
Visual Intuition: Picture a thermometer with three scales side by side. Fahrenheit and Celsius have arbitrary zero points (0°F is not "no temperature") — these are interval. Kelvin has its zero at absolute zero (−273.15°C), where molecular motion stops — this is ratio. The formula connecting them: . The shift by a constant is exactly what distinguishes interval from ratio.
Pitfalls:

  1. 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?"
  2. 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.
  3. 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.
  4. 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.
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.

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.

Critical nuance — numbers used qualitatively: If you encode nominal values with numbers (black = 0, brown = 1, blonde = 2), the attribute remains nominal. The numbers are qualitative labels, not quantities. You cannot add "black" to "brown" — 0 + 1 makes no sense. You cannot divide one employee ID by another. The only requirement for ID numbers is uniqueness; no mathematical operation carries meaning.

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.

Worked Example — Spot the nominal: Given these columns: Favorite candy bar, Weight of luggage, Year of birth, Shirt size, Military rank, Number of children, Jersey numbers, Shoe size, Age, Gender, Course ID, Percentage, Grade.

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.

Measure of central tendency for ordinal attributes: Use the median or mode, never the mean. The mean requires addition and division — both meaningless when you don't know the gap between "satisfied" and "very satisfied."
Student Q&A — Several students asked about grades:

  • 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.

Worked Example: Temperature in °C: 20°C and 15°C differ by 5°C. Temperature can be negative: −15°C and 0°C differ by 15°C. But 40°C is NOT "twice as hot" as 20°C — because 0°C is not "no temperature". Convert to Kelvin: 20°C = 293.15 K, 40°C = 313.15 K. The ratio is 313.15/293.15 ≈ 1.07, not 2. Sense-check: If 40°C were truly twice 20°C, then doubling 20°C should feel twice as hot — it doesn't.

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.

Pitfall — The temperature trap, restated: Temperature in °C and °F are interval. Temperature in Kelvin is ratio. The formula: . The subtraction of a constant is the hallmark of an interval scale. If you can change the zero point by adding/subtracting a constant without destroying meaning, it's interval, not ratio.

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)
Age — discrete or continuous? Some literature treats age as continuous because it can be expressed as real numbers: 30 years, 5 months, 6 days, these many hours, these many seconds. The professor noted this ambiguity. ID numbers — discrete or continuous? Discrete. Between 1001 and 1002 there are infinitely many real numbers, but an ID cannot logically take values like 1001.1.

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.
Recap: The attribute type hierarchy — nominal, ordinal, interval, ratio — plus discrete/continuous and binary symmetric/asymmetric — forms the complete classification system. Bridge: With attribute types mastered, we now zoom out to the broader characteristics of entire datasets.
Real-World & Domain Connection: The four-level measurement scale was formalized by psychologist S. Smith Stevens in 1946. It remains the standard taxonomy in statistics, data mining, and machine learning. Every major ML library (scikit-learn, pandas) relies on this distinction: `pandas` infers `dtype` from data, but it cannot tell you whether column "ID" is nominal or ratio — that requires human judgment. The `sklearn.preprocessing` module has different transformers for different attribute types: `OneHotEncoder` for nominal, `OrdinalEncoder` for ordinal, `StandardScaler` for numerical.

2.3 Important Characteristics of Data

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.
Dimensionality is the number of attributes (features) in the dataset. Each attribute is one dimension. High-dimensional data brings the curse of dimensionality: as dimensions increase, data becomes increasingly sparse, distances between points become less meaningful, and many algorithms degrade in performance.

2.3.2 Sparsity

Sparsity means most values are zero; only the non-zero values carry information. Example: a document-term matrix for 100 documents — only 2 contain the word "sports". Most entries are 0. Sparse data is an advantage for storage and computation because only non-zero entries need to be stored and processed.

2.3.3 Resolution

Resolution is the level of detail or granularity. Patterns depend on scale.

  • 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

Size is the number of records (rows). Shape is rows × columns (e.g., 10,000 × 50).
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.

2.4 Types of Data

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 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.
Student Q&A:

  • 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.
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.

2.5 Data Quality

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.
Intuition + Analogy: Imagine building a house. Data quality is the foundation. You can have the best architects (algorithms) and the finest materials (compute power), but if the foundation is cracked (dirty data), the house collapses. Data preprocessing is pouring the concrete.

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

Noise is extraneous, unwanted values — modifications of the original value. Example: a column expecting numerical income contains "pizza," "ABC," or dollar symbols. Noise is garbage. Once identified, eliminate it entirely.

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.

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. Outliers can be the goal: In credit card fraud detection and intrusion detection, identifying the outlier IS the goal. Outliers are very useful in these contexts.

2.5.4 Missing Values

Strategies for handling missing values by attribute type:
Attribute Type Replacement Strategy
Numerical (interval/ratio) Mean of the column
Categorical (nominal) Mode of the column
Ordinal Median of the column
Advanced strategy — class-conditional imputation: Look at the target label of the row with the missing value. Find all rows with the same target label, then compute the mean (or mode/median) using only those rows. Example: if taxable income is missing for a row where target = "yes," compute the mean taxable income of all rows where target = "yes". This preserves the relationship between features and target.
Missing value decision flow:

  1. Is the missing value in the target label column? → Delete the record. You cannot impute what you're trying to predict.
  2. Are many columns missing for one record? (e.g., 10 out of 15) → Delete the record. Even imputed, it adds little value.
  3. Is only one column missing? → Impute using mean/median/mode based on attribute type.
  4. Do you have abundant data? (10,000+ records) → Consider deleting instead of imputing.
Other imputation strategies from the textbook:

  • 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.
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.
Real-World & Domain Connection: The textbook's opening anecdote (Section 2.1) about the medical researcher who forgot to mention that Field 1 was an ID number sorted by the target variable is not fiction — it's a composite of real disasters. In industry, data quality issues consume 60-80% of a data scientist's time. Tools like Great Expectations, dbt, and Apache Griffin exist solely to automate data quality checks.

2.6 Data Preprocessing Overview

Data preprocessing involves two major phases:

  1. Data Engineering: Converting raw data into prepared (clean) data — aggregation, cleansing, instance selection, partitioning.
  2. 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

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):

  1. Smaller datasets → less memory, faster processing
  2. High-level view instead of low-level — change of scope/scale
  3. Aggregated quantities (averages, totals) have less variability than individual objects — more stable behavior
Disadvantage: Potential loss of interesting details. Aggregating over months loses which day of the week has highest sales.

2.8 Data Cleaning Techniques

2.8.1 Handling Noisy Data

For values that are errors (e.g., salary = −10):

  1. Delete the record (last resort — data is precious)
  2. Replace with the measure of central tendency (mean/median/mode)

2.8.2 Handling Outliers — The IQR Method

Hook: You have a column of 12 numbers. Which ones are "too far" from the pack? The IQR method gives a precise, mathematical answer — and it's the most commonly tested numerical question on the exam.

The method is simpler than it sounds. Here's the one-sentence version first.

Intuition + Analogy: Imagine sorting your class by height. The middle person is the median (Q2). Now look at the shorter half — the middle of that group is Q1. The taller half's middle is Q3. The spread between Q1 and Q3 — the IQR — captures where the "normal" heights live. Anyone shorter than Q1 − 1.5×IQR or taller than Q3 + 1.5×IQR is unusually short or tall. That's the IQR method in one sentence.
Step-by-step IQR calculation:

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 3: Divide into lower half (positions 1–6) and upper half (positions 7–12). Step 4: Find Q1 (median of lower half). Middle two of lower 6: 11 and 11.

Step 5: Find Q3 (median of upper half). Middle two of upper 6: 14 and 15.

Step 6: Calculate IQR:

Step 7: Calculate outlier boundaries:

Step 8: Any value below 5.75 or above 19.75 is an outlier.
Worked Example — Full IQR calculation:

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.

Assumptions & Scope: The IQR method assumes a roughly symmetric distribution. The 1.5× multiplier is a convention, not a law of nature — for very large datasets, 3× is sometimes used. The method flags potential outliers; domain knowledge makes the final call. The IQR method does NOT assume normality — it's non-parametric.
Visual Intuition — The Box Plot: The box spans Q1 to Q3. The line inside the box is the median (Q2). The whiskers extend to the minimum and maximum values within the bounds (Q1 − 1.5×IQR to Q3 + 1.5×IQR). Points outside the whiskers are plotted as individual dots — these are the outliers. The box plot compresses the entire five-point summary plus outlier detection into a single compact graphic.
The Empirical Rule Connection: The IQR method is derived from the empirical rule (68-95-99.7 rule) for normal distributions:

  • ~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 .
Student Q&A:

  • 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%.
Pitfalls:

  1. Forgetting to sort. The IQR calculation starts with sorting. Unsorted data → wrong quartiles → wrong bounds → zero marks.
  2. 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.
  3. Using IQR on categorical data. IQR only makes sense for numerical (interval/ratio) attributes.
  4. Automatically deleting all outliers. Outliers may be the most interesting data points (fraud detection, anomaly detection). Always investigate before deleting.
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.
Real-World & Domain Connection: The box plot was invented by statistician John Tukey in the 1970s as part of Exploratory Data Analysis (EDA). Tukey's philosophy — "look at your data before you model it" — remains the first commandment of data science. The IQR method is built into every statistical package: `df.describe()` in pandas gives the five-point summary; `sns.boxplot()` in seaborn draws the box plot; `plt.boxplot()` in matplotlib does the same.

2.9 Sampling and Training/Testing Data

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.

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 .
When to use which:

  • 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

Stratified sampling ensures each group (stratum) in the population is proportionally represented.

  • 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:

  1. Undersample the majority class — reduce majority-class records.
  2. Oversample the minority class — create synthetic data for the rare class.
SMOTE (Synthetic Minority Oversampling Technique): Creates synthetic examples of the minority class by interpolating between existing minority samples. ADASYN (Adaptive Synthetic Sampling): Built on SMOTE, adaptively generates more synthetic samples in regions where the minority class is hardest to learn.
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.
Real-World & Domain Connection: Sampling theory originated in agricultural experiments (R.A. Fisher, 1920s) and political polling (George Gallup, 1930s). Today, it's essential for big data: when you have billions of rows, you don't train on all of them — you sample. Progressive sampling (start small, increase until accuracy plateaus) is used in production ML pipelines at companies like Google and Meta.

2.10 Normalization and Standardization

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.
Intuition + Analogy: Imagine comparing prices in dollars, euros, and yen. You can't add $10 + €10 + ¥10 — the units differ. Normalization is like converting all currencies to dollars first. Every column gets the same "currency," so comparisons become fair.

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.

Worked Example: Income data: min = 12,000, max = 98,000. Normalize 73,000 to [0, 1]:

Sense-check: 73,000 is roughly 71% of the way from 12,000 to 98,000. The normalized value 0.7093 confirms this.
Scope: Min-max normalization is sensitive to outliers. A single extreme value stretches the range, compressing all other values into a tiny interval. Always handle outliers BEFORE min-max normalization.

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 : , .

Pitfalls:

  1. Normalizing before handling outliers. Outliers distort min, max, mean, and standard deviation. Always detect and handle outliers first.
  2. 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.
  3. 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.
  4. Normalizing binary/categorical columns. Only normalize numerical (interval/ratio) columns. Normalizing a 0/1 binary column is meaningless.
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.
Real-World & Domain Connection: Normalization is not optional for distance-based models (k-NN, SVM, k-means clustering, neural networks). Tree-based models (decision trees, random forests, XGBoost) are scale-invariant and don't need it. In deep learning, batch normalization (Ioffe & Szegedy, 2015) internalizes this idea as a trainable layer — one of the most important innovations of the last decade.

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
Important practice: Whenever you plot a visualization in Python, immediately write your interpretation below it. Without interpretation, assignments will not earn full marks.

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)

Purpose: Transform raw automobile data (with "?" markers, missing values, wrong types) into a clean, ML-ready dataset. Inputs: Raw CSV with no headers, "?" as missing value marker, mixed data types. Outputs: Clean DataFrame with proper types, no missing values (except dropped target-missing rows), and a derived feature.

Here is the exact sequence of operations, in order:

Steps:

  1. Add headers — Raw data had no column headers; provided in a separate file.
  2. Identify missing values — Many "?" characters throughout.
  3. Replace "?" with NaN — Convert all "?" to proper NaN so Python recognizes them as missing.
  4. Impute numerical columns with mean: `normalized-losses`, `bore`, `stroke`, `horsepower`, `peak-rpm`.
  5. Impute categorical column with mode: `number-of-doors` → majority of cars have 4 doors.
  6. Handle missing target label: `price` had missing values → drop those entire records.
  7. Data type conversions — Convert columns to appropriate types.
  8. Create derived attribute — Convert `city-mpg` (miles per gallon) to liters per 100 km.
Trace — Imputing number-of-doors: Out of 10,000 records, only 2 are missing the number-of-doors. Find the mode: most cars have 4 doors. Replace both missing values with "four." Rationale: With only 2 missing out of 10,000, imputation is better than deletion — you preserve 9,998 complete records' worth of information in the other columns.
Student Q&A:

  • 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

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.

Beyond the theory, the lab component is equally important.

Exam note — Python lab work: Lab sheets are available in the virtual lab. Practice the Iris and Automobile notebook workflows. Always write interpretations below every visualization in Python assignments — without interpretation, assignments will not earn full marks.

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

Machine Learning· postgraduate· 2026-06-27

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

1Classify attributes as nominal, ordinal, interval, or ratio and justify each classification
2Identify data quality problems: noise, outliers, missing values, duplicates, inconsistencies
3Apply the IQR method to detect outliers with correct step-by-step calculation
4Choose appropriate missing value imputation strategies by attribute type
5Differentiate sampling strategies: simple random (with/without replacement), stratified
6Apply min-max, z-score, and decimal scaling normalization to numerical features
7Execute a complete data preprocessing pipeline on real datasets (Iris, Automobile)

Sections Breakdown

12.1 Entities, Entity Sets, and Attributes

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.

22.2 Types of Attributes

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.

32.3 Important Characteristics of Data

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.

42.4 Types of Data

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).

52.5 Data Quality

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.

62.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.

72.7 Data Aggregation

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):

82.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 8.2 Handling Outliers — The IQR Method

92.9 Sampling and Training/Testing Data

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.

102.10 Normalization and Standardization

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.

112.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

122.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).

132.13 Exam Guidance Summary

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.

142.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)

Graduate students in computer science and related fields studying machine learning

Exam Revision Notes

Key Topics· Must Knows· Formulas· Quick Checks
12.1 Entities, Entity Sets, and Attributes
Must Know

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.

Key Formula
Common Pitfall

Confusing attribute names (columns) with data objects (rows), or assuming data objects are always independent.

Quick Check

Why is it important to know an attribute's meaning before applying a machine learning algorithm?

Connections:2.2 Types of Attributes2.3 Important Characteristics of Data2.4 Types of Data
22.2 Types of Attributes
Must Know

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.

Key Formula
Common Pitfall

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.

Quick Check

Classify the following attributes: Celsius temperature, credit score, ZIP code, and age.

Connections:2.1 Entities, Entity Sets, and Attributes2.3 Important Characteristics of Data2.4 Types of Data
32.3 Important Characteristics of Data
Must Know

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.

Key Formula
Common Pitfall

Assuming that higher resolution data is always better, ignoring the extra computation and storage requirements.

Quick Check

How does the curse of dimensionality affect distance-based machine learning algorithms?

Connections:2.1 Entities, Entity Sets, and Attributes2.2 Types of Attributes2.4 Types of Data
42.4 Types of Data
Must Know

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.

Key Formula
Common Pitfall

Confusing stock market data (time series) with genomic sequences (sequence data).

Quick Check

Give an example of a sparse data matrix and explain why sparsity is computationally advantageous.

Connections:2.1 Entities, Entity Sets, and Attributes2.2 Types of Attributes2.3 Important Characteristics of Data
52.5 Data Quality
Must Know

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 Formula
Common Pitfall

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.

Quick Check

When should you delete a record with missing values rather than imputing them?

Connections:2.1 Entities, Entity Sets, and Attributes2.2 Types of Attributes2.3 Important Characteristics of Data
62.6 Data Preprocessing Overview
Must Know

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).

Key Formula
Common Pitfall

Confusing Data Engineering (cleansing/aggregation) with Feature Engineering (tuning features for a specific ML model).

Quick Check

What is the difference between data engineering and feature engineering in the preprocessing workflow?

Connections:2.5 Data Quality2.7 Data Aggregation2.8 Data Cleaning Techniques
72.7 Data Aggregation
Must Know

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.

Key Formula
Common Pitfall

Assuming aggregation is always beneficial, ignoring the disadvantage that it causes potential loss of interesting low-level details/variability.

Quick Check

What are the three main motivations for data aggregation, and what is its primary disadvantage?

Connections:2.3 Important Characteristics of Data2.6 Data Preprocessing Overview2.8 Data Cleaning Techniques
82.8 Data Cleaning Techniques
Must Know

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.

Key Formula
Common Pitfall

Assumptions & Scope: The IQR method assumes a roughly symmetric distribution. The 1.5× multiplier is a convention, no...

Quick Check

What are the outlier bounds in the IQR method if Q1 = 10.5 and Q3 = 16.5?

Connections:2.5 Data Quality2.9 Sampling and Training/Testing Data2.10 Normalization and Standardization
92.9 Sampling and Training/Testing Data
Must Know

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.

Key Formula
Common Pitfall

Using simple random sampling on heavily imbalanced datasets without stratification, which may completely omit the minority class.

Quick Check

What is the difference between simple random sampling with and without replacement, and when is SMOTE used?

Connections:2.5 Data Quality2.8 Data Cleaning Techniques2.10 Normalization and Standardization
102.10 Normalization and Standardization
Must Know

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.

Key Formula
Common Pitfall

Scope: Min-max normalization is sensitive to outliers. A single extreme value stretches the range, compressing all ot...

Quick Check

Why must you use the mean and standard deviation from the training data, rather than the test data, when normalizing test data?

Connections:2.8 Data Cleaning Techniques2.9 Sampling and Training/Testing Data2.11 The Iris Dataset — Full Walkthrough
112.11 The Iris Dataset — Full Walkthrough
Must Know

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.

Key Formula
Common Pitfall

Forgetting to write interpretations below every visualization in Python assignments, which is required to earn full marks.

Quick Check

What are the 4 features and 3 classes of the Iris dataset, and what Python command is used to generate its five-point summary?

Connections:2.2 Types of Attributes2.8 Data Cleaning Techniques2.12 The Automobile Dataset — Full Walkthrough
122.12 The Automobile Dataset — Full Walkthrough
Must Know

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.

Key Formula
Common Pitfall

Imputing missing target labels (price) instead of dropping the entire record, or deleting records with missing features when the missingness is extremely rare.

Quick Check

What is the correct sequence of cleaning steps for handling missing values and wrong data types in the Automobile dataset walkthrough?

Connections:2.5 Data Quality2.8 Data Cleaning Techniques2.11 The Iris Dataset — Full Walkthrough
132.13 Exam Guidance Summary
Must Know

Exam note: Questions from data preprocessing WILL appear on the mid-semester exam. The sample question papers already shared contain questions from these topics.

Key Formula
Common Pitfall

Forgetting to sort the dataset in ascending order before finding quartiles for IQR, leading to incorrect calculations and zero marks.

Quick Check

What are the key formulas and missing value strategies that you must memorize for the mid-semester exam?

Connections:2.2 Types of Attributes2.8 Data Cleaning Techniques2.10 Normalization and Standardization
142.14 Key Industry Applications and Tools
Must Know

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.

Key Formula
Common Pitfall

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.

Quick Check

Which Python libraries and data quality automation tools are standard in the industry for data preprocessing and analysis?

Connections:2.4 Types of Data2.5 Data Quality2.9 Sampling and Training/Testing Data

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.