Lecture 4 - Data Preprocessing
DES431 - Big Data Analytics and Machine Learning
Lecture 4: Data Preprocessing
Asst.Prof.Dr. Apichon Witayangkurn (apichon@siit.tu.ac.th)
Roadmap
- Tasks in Data Preprocessing
- Validation
- Verification
- Cleaning
- Filter
- Integration
- Transformation
- Reduction
- Discretization
- Hierarchy Generation
- Know Your Data (KYD)
Principle Tasks in Data Preprocessing
Related
- Data Validation
- Validation ensures the validity of input data as expected.
- Data Verification
- Verification is the process of checking the typed data against some other 'business' rules.
- Data Cleaning
- Fill in missing values, smooth noisy data, identify or remove outliers, and resolve inconsistencies.
- Data filtering/sorting
- Filter or select only interested data.
- Sort or order data by some key or criteria.
- Data Integration
- Combine, Merge, Integrate multiple files, databases, datasets.
- Data Transformation
- Normalization and aggregation.
- Data Reduction
- Obtains reduced representation in volume but produces the same or similar analytical results.
- Data Discretization and Concept Hierarchy Generation
- Part of data reduction but with particular importance, especially for numerical data.
Think of preprocessing like preparing ingredients before cooking — you wash (clean), measure (transform), combine (integrate), and trim excess (reduce) before the meal (analysis/model) can actually be made.
Data Validation (in data processing)
A process to automatically check data, ensuring input is as expected and sensible for the computer. Typical checks:
- Presence Check
- Checks that data exists and is complete. Data file must have 8 columns.
- Type Check
- Check that an input value is of a particular type. Ex. age is numeric.
- Length Check
- Address data must not be longer than 100 characters.
- Range Check
- Data must be in a particular range such as month value [1-12].
- Format Check
- Date value must be "DD-MM-YYYY" format. Email must be XX@YY.ZZ.
Data Verification (in data processing)
Verification is the process of checking the typed data against some other 'business' rules.
- Verify email address is correct by sending email and waiting for response.
- It is a process wherein different types of data are checked for accuracy or existence.
- Check if User ID exists in the system.
- Verify Product ID and data.
- Check Credit card information and verify purchase.
Validation asks "is this data shaped correctly?" (e.g., is this a valid email format?), while Verification asks "is this data actually true/real?" (e.g., does this email account actually exist?).
Data Cleaning
- Importance
- Data cleaning is the number one problem in data processing.
- Data cleaning tasks
- Fill in missing values (imputation, deletion)
- Identify outliers and smooth out noisy data
- Correct inconsistent data
- Resolve redundancy caused by data integration
[Image: Map of flight/travel paths converging on Thailand — illustrative graphic, no extractable data]
Data Cleaning: Missing Data
- Data is not always available
- E.g., many tuples have no recorded values for several attributes, such as customer income in sales data.
- Missing data may be due to:
- Equipment malfunction
- Inconsistent with other recorded data and thus deleted
- Data not entered due to misunderstanding
- Certain data may not be considered important at the time of entry
- Not registered history or changes of the data
- Missing data may need to be inferred.
Data Cleaning: Identify Missing Data
- Summary statistics, Visualization
[Image: RapidMiner-style attribute statistics table showing "Missing data(Age): 263" highlighted, along with a histogram of Age distribution — used to visually identify missing values per column]
Data Cleaning: How to Handle Missing Data?
- Ignore the tuple
- Usually done when class label is missing (assuming the tasks in classification)
- Not effective when the percentage of missing values per attribute varies considerably.
- Listwise Deletion: Remove entire rows with missing values.
- Pairwise Deletion: Use available data for each analysis.
- Fill in the missing value manually
- Time consuming + infeasible (large data)?
[Image: Table comparing "Listwise deletion (Complete case analysis)" vs "Pairwise deletion (Available case analysis)" — Listwise deletes entire rows with any missing value; Pairwise keeps rows but only uses available fields per analysis]
Listwise deletion is like throwing away an entire exam paper because one question was left blank. Pairwise deletion is like still grading every question the student did answer, and just skipping the blank one.
- Fill in it automatically (Imputation Methods)
- A global constant: e.g., "unknown", a new class?!
- Mean/Median/Mode Imputation: Replace with central tendency (Average income)
- The attribute mean for all samples belonging to the same class: smarter
- Forward/Backward Fill: Use adjacent values (time series)
- K-Nearest Neighbors (KNN): Use similar data points.
- Regression Imputation: Predict missing values using other features.
- The most probable value: inference-based such as Bayesian formula or decision tree
df.na.fill(0) # Fill missing values
df.dropna() # Drop rows with nulls
df.fillna(df.mean()) # Mean imputation
df.dropna() # Listwise deletionForward/Backward Fill
- Forward filling: propagate the last known value forward to fill gaps.
- Backward filling: propagate the next known value backward to fill gaps.
# Forward Fill
df_ffill = df.fillna(method='ffill')
# Backward Fill
df_bfill = df.fillna(method='bfill')[Image: Table example — a price time series with NaN values for "apple" and "mango" on certain dates; forward fill copies the last valid price down to fill the NaNs]
Forward fill is like assuming "if I don't know today's price, it's probably still the same as yesterday's."
Python Example (KNNImputer from Scikit-learn)
from sklearn.impute import KNNImputer
import pandas as pd
# Sample data
data = {
'Age': [25, 30, 22, None, 28],
'Salary': [50000, 60000, None, 52000, 58000]
}
df = pd.DataFrame(data)
# Apply KNN imputation
imputer = KNNImputer(n_neighbors=2)
df_imputed = pd.DataFrame(imputer.fit_transform(df), columns=df.columns)
print(df_imputed)Python Example (Using an imputer within a Pipeline)
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
# 1. Define the imputation step
imputer_step = ('imputer', SimpleImputer(strategy='mean'))
# Alternative: ('imputer', KNNImputer(n_neighbors=2))
# 2. Define the model step
model_step = ('classifier', LogisticRegression())
# 3. Create the pipeline
pipeline = Pipeline(steps=[imputer_step, model_step])Data Cleaning: Noisy Data
- Types of Noisy Data
- Outliers – Data points that deviate significantly from others.
- Random errors – Mistakes in data entry or measurement.
- Inconsistent formatting – Mixed units, typos, or irregular values.
- Irrelevant features – Features that add noise but no value.
- Other data problems which require data cleaning
- Duplicate records
- Incomplete data
- Inconsistent data
Data Cleaning: How to Handle Noisy Data?
Data Smoothing
- Moving average: Smooth time-series data.
- Exponential smoothing: Weighted averages with decay.
- Bin smoothing: Group data into bins and average.
[Image: Line chart comparing Original_Value against Moving Averages MA_3, MA_5, MA_7 over time — showing MA(3) captures short-term trends, MA(5) is smoother/less sensitive to quick changes, MA(7) is even smoother, good for long-term patterns]
A moving average is like judging how well a student is doing based on their last 3, 5, or 7 quiz scores instead of just one — the more scores you average, the smoother (but less reactive) the trend line becomes.
Binning Method
- Equal-width (distance) partitioning
- Divides the range into intervals of equal size: uniform grid.
- If and are the lowest and highest values of the attribute, the width of intervals will be:
- The most straightforward.
- But outliers may dominate presentation.
- Equal-depth (frequency) partitioning
- Divides the range into intervals, each containing approximately the same number of samples.
- Good data scaling.
- Managing categorical attributes can be tricky.
Example — Data: 0, 4, 12, 16, 16, 18, 24, 26, 28
- Equal width:
- Bin 1: 0, 4 → [-,10)
- Bin 2: 12, 16, 16, 18 → [10,20)
- Bin 3: 24, 26, 28 → [20,+)
- Equal frequency:
- Bin 1: 0, 4, 12 → [-,14)
- Bin 2: 16, 16, 18 → [14,21)
- Bin 3: 24, 26, 28 → [21,+)
[Image: Bar charts comparing "Equal width" bin counts (2, 4, 3) vs "Equal frequency" bin counts (3, 3, 3) for the same dataset above]
Binning Methods for Data Smoothing (bin means example)
Sorted data for price (in dollars): 4, 8, 9, 15, 21, 21, 24, 25, 26, 28, 29, 34
- Partition into equal-frequency (equi-depth) bins:
- Bin 1: 4, 8, 9, 15
- Bin 2: 21, 21, 24, 25
- Bin 3: 26, 28, 29, 34
- Smoothing by bin means:
- Bin 1: 9, 9, 9, 9
- Bin 2: 23, 23, 23, 23
- Bin 3: 29, 29, 29, 29
Binning smooths data the way rounding grades into letter grades (A/B/C) smooths out small differences between 88 and 91 — both just become "A".
Outlier Detection and Removal
- Statistical methods: Z-score, IQR (Interquartile Range)
- Machine learning: Regression, DBSCAN
- Visualization: Boxplots, scatter plots
[Image: Left — a scatter plot with a regression line y = x + 1, showing an outlier point Y1 far from its predicted value Y1'. Right — a scatter plot showing clusters of points (via ML/clustering) with a couple of clear outlier points sitting outside all clusters]
Noise Filtering
- Clustering: Remove small or irrelevant clusters.
- Signal processing: Apply filters (e.g., low-pass filters for time-series).
- Different outliers
- Valid: CEO's salary
- Noisy: One's age = 200, widely deviated points
[Image: Left — a noisy signal overlaid with a smooth filtered sine-wave signal (low-pass filtering example). Right — a scatter plot with one clear noisy outlier point far above a smooth increasing trend]
Filtering noise is like turning down radio static so you can hear the actual song underneath.
Principle Tasks in Data Preprocessing (Revisit)
- Data Validation
- Data Verification
- Data Cleaning
- Data Filtering/Sorting
- Filter or select only interested data.
- Sort or order data by some key or criteria.
- Data Integration
- Data Transformation
- Data Reduction
- Data Discretization and Concept Hierarchy Generation
Data Filtering/Sorting
- Filtering = narrowing the window based on criteria
- Show only interested data column.
- Remove unnecessary data.
- Display only data with ID=5 or only data of today.
- Sorting = alphabetizing (type?)
- On a single column
- On multiple columns
- Sort the least important column first, progressing to the most important
- Sort the most important column last
- Prioritizing your sorts (Year, month, week)
Data Integration
Related
- Combines data from multiple sources into a coherent store
- Schema integration: e.g., A.cust-id = B.cust-#
- Integrate metadata from different sources
- Entity identification problem
- Identify real world entities from multiple data sources, e.g., Bill Clinton = William Clinton
- Detecting and resolving data value conflicts
- For the same real-world entity, attribute values from different sources are different
- Possible reasons: different representations, different scales, e.g., metric vs. British units
Handling Redundancy in Data Integration
- Redundant data occur often when integration of multiple databases
- Object identification: The same attribute or object may have different names in different databases.
- Derivable data: One attribute may be a "derived" attribute in another table, e.g., annual revenue.
- Redundant attributes
- It may be able to be detected by correlation analysis.
- Careful integration of the data from multiple sources
- It may help reduce/avoid redundancies and inconsistencies and improve mining speed and quality.
Data integration is like merging two contact lists on your phone — "Bill Clinton" and "William Clinton" might be the same person (entity identification), and you might have his phone number listed in two different formats (data value conflict) that need reconciling.
Data Transformation
- Aggregation: summarization
- Log transformation: Reduces skewness.
- Normalization/Standardization: scaled to fall within a small, specified range
- Min-max normalization
- Z-score normalization
- Attribute/feature construction
- New attributes constructed from the given ones
Skewed Data
It refers to a situation where the distribution of data is not symmetrical. This can affect the performance of analytics models and algorithms, especially those that assume a normal (Gaussian) distribution.
- (if a positive skew) → The mean > median > mode
- (if normal distribution) → The mean = median = mode
- (if a negative skew) → The mean < median < mode
[Image: Three histograms labeled Negative Skew, No Skew, Positive Skew, plus three bell-curve diagrams below them showing the relative positions of Mean, Median, and Mode for each skew direction]
Skew is like a class's test scores where most people did well but a few failed badly (negative skew, pulling the mean down) versus most people doing poorly with a few high scorers (positive skew, pulling the mean up).
Why Skewed Data Matters
- Model Bias: Many machine learning algorithms (e.g., linear regression, logistic regression) assume normally distributed data. Skewness can lead to biased predictions.
- Outlier Sensitivity: Skewed data often contains outliers that can distort statistical measures like mean and standard deviation.
- Feature Engineering: Skewed features may need transformation (e.g., log, square root) to improve model performance.
- Sampling Issues: In distributed systems (like Hadoop or Spark), skewed data can cause data processing bottlenecks if one node gets a disproportionately large chunk of data.
Data Transformation (Log)
- Log transformation: Reduces skewness.
[Image: Two histograms — "Original data set" (heavily right-skewed, most values near 0) versus "Log-transformed data set" (much more symmetric/bell-shaped after taking the log)]
Data Transformation: Normalization
- Min-max normalization: to
- Ex. Let income range 98,000 normalized to [0.0, 1.0].
- Then $73,000 is mapped to:
- Z-score normalization (: mean, : standard deviation):
Z-score is very common for data normalization.
- Ex. Let , . Then:
Min-max normalization is like re-grading a test out of 100 points based on the class's actual lowest and highest scores, so everyone falls between 0 and 1. Z-score normalization instead tells you "how many standard deviations above/below average" a score is — like saying someone scored 1.2 standard deviations above the class mean.
Normalization in Python (Scalers)
- StandardScaler (from sklearn.preprocessing)
- Scales features to have zero mean and unit variance.
- Limitation: Assumes data is normally distributed. If the data is skewed, the scaling might not be effective or could distort the feature distribution.
- MinMaxScaler
- Scales data to a fixed range, usually [0, 1].
- Limitation: Sensitive to outliers, which are common in skewed data.
- RobustScaler
- Uses median and interquartile range (IQR) for scaling.
- Advantage: More robust to outliers and skewed data.
from sklearn.preprocessing import StandardScaler
import numpy as np
# Simulate skewed data
data = np.random.exponential(scale=2.0, size=(1000, 1))
# Log transform to reduce skewness
log_data = np.log1p(data)
# Apply StandardScaler
scaler = StandardScaler()
scaled_data = scaler.fit_transform(log_data)Data Reduction
- Data reduction
- Refers to techniques used to reduce the volume or dimensionality of data while preserving its essential characteristics.
- Why data reduction?
- Data is too big to work with, Reduce storage and memory requirements.
- Improve efficiency of data processing and model training.
- Enhance model performance by removing noise or irrelevant features.
- Make data more interpretable.
[Image: Funnel graphic showing many scattered colorful dots being funneled down into fewer dots — representing reducing data volume]
Data Reduction Strategies
- Dimensionality reduction, e.g., remove unimportant attributes
- Wavelet transforms
- Principal Components Analysis (PCA)
- Feature subset selection, feature creation
- Aggregation and clustering (some simply call it: Data Reduction)
- Regression and Linear Models
- Histograms (Represent data using bins), clustering (centroid)
- Sampling (Select a representative subset of the data).
- Data compression
- Encoding mechanism used to reduce data size. (image/audio formats)
Data Reduction Strategies — Feature Selection
- Feature selection (i.e., attribute subset selection)
- Select a minimum set of attributes (features) that is sufficient for the task.
- Best/worst attributes are determined using test of statistical significance.
- Information gain (building decision tree for classification).
- Reduce # of patterns in the patterns, easier to understand.
[Image: "Table 2. Feature Selection (Rank, Score)" — lists features like Rank in cluster, No. of stay point (%), Night time (%), No. of day (%), Day time (%), Maximum stay, Average stay, Minimum stay, each with a Rank (1-8) and a Score (0.60 down to 0.13)]
Attribute Subset Selection
- Redundant attributes
- Duplicate much or all of the information contained in one or more other attributes.
- E.g., purchase price of a product and the amount of sales tax paid.
- Irrelevant attributes
- Contain no information that is useful for the data mining task at hand.
- E.g., students' ID is often irrelevant to the task of predicting students' GPA.
Histogram Analysis
- Divide data into buckets and store average (sum) for each bucket.
- Partitioning rules:
- Equal-width: equal bucket range
- Equal-frequency (or equal-depth)
[Image: A histogram/bar chart of some value distribution across buckets ranging from 10,000 to 90,000+ on the x-axis, with counts up to ~38 on the y-axis]
Clustering (as Data Reduction)
- Partition data set into clusters based on similarity.
- Store cluster representation only
- e.g., centroid and diameter
- Can be very effective if data is clustered but not if data is "spread"
- Can have hierarchical clustering and be stored in multi-dimensional index tree structures
- There are many choices of clustering definitions and clustering algorithms
- Store cluster representation only
[Image: "Clustering of life pattern" — 12 small line-chart panels labeled cluster_0 through cluster_15, each showing a distinct daily activity pattern (over hours 1-23) with a percentage share label, e.g. cluster_7: 21.36%, cluster_1: 17.11%, cluster_10: 1.29%, etc. — representing "Life Patterns Extraction from User Active Periods"]
Clustering as data reduction is like summarizing a whole city's daily traffic patterns into just a handful of "typical day" templates (morning rush, night owl, etc.) instead of storing every single person's movement.
Sampling
- Obtaining a small sample to represent the whole data set .
- Allow a mining algorithm to run in complexity that is potentially sub-linear to the size of the data.
- Key principle: Choose a representative subset of the data.
- Simple random sampling may have very poor performance in the presence of skew.
- Develop adaptive sampling methods.
- e.g., stratified sampling.
[Image: A simple diagram — a large green circle full of stick figures labeled "SAMPLING" with an arrow pointing to a smaller blue circle containing fewer stick figures, illustrating drawing a sample from a population]
Types of Sampling
- Simple random sampling
- There is an equal probability of selecting any item.
- Sampling without replacement: Once an object is selected, it is removed from the population.
- Sampling with replacement: A selected object is not removed from the population.
- Stratified sampling
- Partition the data set, and draw samples from each partition (proportionally, i.e., approximately the same percentage of the data).
- Used in conjunction with skewed data.
[Image: "Sampling: With or without Replacement" — diagram titled "Raw Data" (visual not fully described in source)]
Stratified Sampling
[Image: "Stratified sampling" diagram from simplypsychology.org — shows a POPULATION of people divided into 4 colored strata (smaller population groups), with a random sample drawn from each group forming the final SAMPLE. Source: https://www.simplypsychology.org/stratified-random-sampling.html]
Stratified sampling is like making sure your survey sample includes students from every year (freshman, sophomore, junior, senior) in the same proportion as the actual school population, rather than randomly picking students and risking missing an entire year group.
Data Discretization
- Discretization: Divide the range of a continuous attribute into intervals.
- Interval labels can then be used to replace actual data values.
- Reduce data size by discretization.
- Supervised vs. unsupervised.
- Split (top-down) vs. merge (bottom-up).
- Discretization can be performed recursively on an attribute.
- Prepare for further analysis, e.g., classification.
[Image: Diagram showing a smooth continuous curve labeled "CONTINUOUS VALUE" being transformed via "DISCRETIZATION" into a stepped/blocky curve labeled "DISCRETE VALUE"]
Coding For Continuous Data: Encode/Decode
- Encoding Information
- Processing turns data into information.
- Sometimes you might want to turn information into data – i.e. to store it – this is called encoding.
- How do you code information to make it easy to re-process, without losing its meaning?
- Coding categorizes information and can replace long, descriptive strings with a few letters or numbers.
- Decode
- A reverse process of encoding to reveal original information.
Example: Severity encoding
| Severity | Encode |
|---|---|
| Critical | 3 |
| Major | 2 |
| Minor | 1 |
| Info | 0 |
(Decode reverses this: 3 → Critical, 2 → Major, 1 → Minor, 0 → Info)
Encode/Decode — Advantages & Disadvantages
- Coding Advantages
- It is quicker to enter into the computer.
- It requires less disc space to store, and less memory to process.
- It can make processing easier – or possible – as there will be fewer responses.
- It improves the consistency of the data as spelling mistakes are less likely.
- Validation is easier to apply.
- Coding Disadvantages
- Information is coarsened by forcing it all into categories – there might not be a category that matches what you want to record – e.g. hair color.
- The same can be true of rounding numbers – the intervals or numbers of categories is called the granularity– this needs to be chosen carefully to maintain the quality of the information.
Encoding is like using abbreviations "NY" for "New York" — faster to write and less error-prone, but you lose nuance (a "reddish-brown" hair color has to be forced into just "brown" or "red").
Encode/Decode — Latitude/Longitude Precision Example
[Image: "Degree precision versus length" table — shows how many decimal places of lat/long precision correspond to real-world distance and what scale that identifies, e.g.: 0 decimal places = 1.0° = country/large region ≈111.32km; 4 decimal places = 0.0001° = individual street/land parcel ≈11.132m; 8 decimal places = 0.00000001° = specialized surveying (e.g. tectonic plate mapping) ≈1.1132mm]
This shows a real trade-off in granularity: storing GPS coordinates with fewer decimal places saves storage space but can only identify a general area (like a country); more decimal places let you pinpoint individual trees or even sub-millimeter surveying work, but cost more storage.
Concept Hierarchy Generation
- Concept hierarchy organizes concepts (i.e., attribute values) hierarchically.
- Usually associated with each dimension in a data warehouse.
- Concept hierarchy formation
- Recursively reduce the data by collecting and replacing low level concepts (such as numeric values for age) by higher level concepts (such as youth, adult, or senior).
[Image: Two hierarchy diagrams — Left: Address → ZipNo → City → Country. Right: Day → Week/Month → Quarter → Year (Week and Month both feed up into Year)]
A concept hierarchy is like an org chart for data values — "Bangkok" rolls up into "Thailand", just like "Week 3" rolls up into "Q1" and then into "Year 2026".
Hierarchy Generation for Nominal Data
- Specification of a partial/total ordering of attributes explicitly at the schema level by users or experts.
- street < city < state < country
- Specification of a hierarchy for a set of values by explicit data grouping.
- {Urbana, Champaign, Chicago} < Illinois
- Specification of only a partial set of attributes.
- E.g., only street < city, not others
- Automatic generation of hierarchies (or attribute levels) by the analysis of the number of distinct values.
- E.g., for a set of attributes: {street, city, state, country}
Automatic Concept Hierarchy Generation
Some hierarchies can be automatically generated based on the analysis of the number of distinct values per attribute in the data set.
- The attribute with the most distinct values is placed at the lowest level of the hierarchy.
- Exceptions, e.g., weekday, month, quarter, year.
Example hierarchy (by distinct value count):
- country → 15 distinct values
- province_or_state → 365 distinct values
- city → 3567 distinct values
- street → 674,339 distinct values
(street has the most distinct values, so it sits at the lowest/most granular level; country has the fewest, so it sits at the top)
[Image: "Automatic Concept Hierarchy Generation" — a real map example showing Prefecture (e.g., Saitama, Tokyo, Yamanashi, Kanagawa), zooming into City-level ward numbers (e.g., 13101–13121 within Tokyo), and further into a Grid overlay, given a lat/lon point of 139.702777, 35.694152]
This is like Google Maps auto-detecting that a GPS coordinate belongs to a specific grid cell, which belongs to a city ward, which belongs to a prefecture, which belongs to a country — built automatically from how many unique values exist at each level.
Roadmap (Recap)
- Tasks in Data Preprocessing
- Validation
- Verification
- Cleaning
- Filter
- Integration
- Transformation
- Reduction
- Discretization
- Hierarchy Generation
- Know Your Data (KYD)
Know Your Data (KYD)
Process of deeply understanding the structure, quality, and characteristics of your dataset before applying any models or transformations. It's a critical step in data preprocessing and exploratory data analysis (EDA).
- Helps identify data quality issues (missing values, outliers, duplicates).
- Reveals patterns, trends, and distributions.
- Guides feature selection and model choice.
- Prevents misleading results due to incorrect assumptions.
Key Activities in "Know Your Data"
- Data Overview
- Number of rows and columns
- Data types (numerical, categorical, datetime, text)
- Sample records (e.g.,
df.head()in pandas)
- Summary Statistics
- Mean, median, mode
- Standard deviation, variance
- Min, max, range
- Skewness
- Missing Values
- Count and percentage of missing values per column
- Patterns of missingness
- Unique Values & Cardinality
- Number of unique values per column
- Useful for identifying categorical vs. continuous features
- Outliers
- Use box plots, z-scores, or IQR to detect extreme values
- Correlations
- Pearson/Spearman correlation for numerical features
- Chi-square for categorical features
- Visualizations
- Histograms, box plots, scatter plots, heatmaps
- Help reveal distributions, relationships, and anomalies
Example of Customer Dataset (Walkthrough)
- Data Overview
- 200 customers, each with:
- Age: 18–69
- Annual Income: Normally distributed around $50,000
- Spending Score: 1–99
- Gender: Male or Female
- No missing values.
- 200 customers, each with:
- Summary Statistics
- Income has a wide range: 97,805
- Spending scores are evenly distributed
- Outlier Detection
- Annual Income has 2 outliers (extremely high or low values)
[Image: Sample data table — CustomerID, Age, AnnualIncome, SpendingScore, Gender for 10 customers, e.g. CustomerID 1: Age 56, AnnualIncome 51905, SpendingScore 75, Gender Female]
Feature Distributions
[Image: Two histograms side by side — "Age Distribution" (fairly spread across 18-69, peak around 40-45) and "Annual Income Distribution" (roughly bell-shaped/normal, peak around 40,000-60,000)]
Correlation Matrix
- Weak correlations overall.
- Slight negative correlation between Age ↔ SpendingScore: -0.15
- Very weak correlation between Income ↔ SpendingScore: -0.07
[Image: 4x4 correlation heatmap matrix for CustomerID, Age, AnnualIncome, SpendingScore — diagonal values are 1; notable off-diagonal values include Age-SpendingScore = -0.147, AnnualIncome-SpendingScore = -0.075, Age-AnnualIncome = 0.099]
Customer Segmentation Example
- Customer segmentation using KMeans clustering on the synthetic dataset. The clustering was based on three features: Age, Annual Income, and Spending Score.
- Each color represents a different cluster, helping identify distinct customer groups (e.g., high spenders with high income, budget-conscious younger customers, etc.).
Cluster Distribution:
- Cluster 0: 62 customers
- Cluster 1: 42 customers
- Cluster 2: 45 customers
- Cluster 3: 51 customers
[Image: 3D scatter plot with axes Age, AnnualIncome, SpendingScore — points colored by cluster (0-3) via a yellow-to-purple color scale, showing 4 distinct customer segments in 3D space]
This customer segmentation example ties the whole lecture together — cleaning (no missing values here), KYD (summary stats, distributions, correlations), and reduction/discretization (clustering into just 4 customer "types" instead of analyzing 200 individuals one by one).
Summary
- Tasks in Data Preprocessing
- Validation
- Verification
- Cleaning
- Filter
- Integration
- Transformation
- Reduction
- Discretization
- Hierarchy Generation