Data Mining Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to Data Mining
Module 2
Data Preprocessing and Mining Frequent Patterns
Module 3
Classification
Module 4
Cluster Analysis: Basic Concepts and Methods
Module 5
Time-Series, Spatial, Web, and Text Mining
Read Module Notes Online
Module I: Introduction to Data Mining
Chapter 1: Foundations of Data Mining and Knowledge Discovery in Databases (KDD)
1.1 Data, Information, Knowledge, and the Need for Data Mining
Modern enterprises, scientific observatories, healthcare networks, and e-commerce platforms generate vast volumes of digital records every second through point-of-sale terminals, web server logs, banking gateways, genomic sequencers, and Internet of Things (IoT) sensors. On its own, raw data consists of unprocessed facts, measurements, or discrete symbols—such as individual invoice line items, temperature readings, or customer click timestamps—that carry minimal decision value in isolation. When raw data is filtered, aggregated, and contextualized, it becomes information, answering concrete operational questions such as total monthly revenue by region. At a higher cognitive tier, knowledge represents generalized, actionable patterns, rules, and predictive models extracted from large-scale information repositories—such as recognizing that customers who purchase a laptop and a wireless mouse within a single transaction exhibit a high probability of purchasing an external hard drive within thirty days.
The explosive growth of terabyte- and petabyte-scale databases has created a widening gap between our capacity to collect and store data and our ability to comprehend it manually. Traditional SQL queries and basic spreadsheet summaries can retrieve explicit records and compute simple totals, but they cannot automatically uncover hidden correlations, non-linear customer segments, or subtle fraud signatures buried across hundreds of attributes. Data Mining—formally defined as the non-trivial extraction of implicit, previously unknown, and potentially useful patterns or knowledge from large amounts of data—bridges this gap by combining techniques from database systems, statistics, machine learning, pattern recognition, and high-performance computing.
1.2 The Knowledge Discovery in Databases (KDD) Process
Data mining is not an isolated algorithmic step; rather, it serves as the core analytical engine inside a broader, iterative lifecycle known as Knowledge Discovery in Databases (KDD). Each stage transforms raw operational records closer to validated, deployable domain knowledge, with feedback loops allowing analysts to refine earlier choices whenever discovered patterns prove trivial or noisy.
| KDD Stage | Primary Objective | Core Operations Performed | Output Artifact |
|---|---|---|---|
| 1. Data Cleaning | Eliminate errors and inconsistencies | Impute missing values, smooth sensor noise, resolve conflicting codes, remove duplicate tuples. | Clean operational tables |
| 2. Data Integration | Unify heterogeneous sources | Merge relational databases, flat files, and logs; resolve schema naming and unit mismatches. | Unified enterprise repository |
| 3. Data Selection | Retrieve task-relevant records | Filter rows by time window, geography, or cohort; project relevant target attributes. | Task-specific analytical dataset |
| 4. Data Transformation | Convert data into mining-ready form | Apply normalization, aggregation, attribute construction, and concept-hierarchy discretization. | Normalized feature matrix |
| 5. Data Mining | Extract candidate patterns | Execute association, classification, clustering, regression, or anomaly detection algorithms. | Candidate models and rule sets |
| 6. Pattern Evaluation | Assess novelty and usefulness | Filter patterns using interestingness metrics (support, confidence, lift, cross-validation accuracy). | Validated, actionable knowledge |
| 7. Knowledge Presentation | Communicate insights to stakeholders | Render dashboards, decision trees, association graphs, and executive summaries. | Interactive reports and deployed rules |
1.3 Types of Data Repositories and Data Warehouse / OLAP Basics
Data mining algorithms must adapt to diverse storage architectures beyond conventional flat tables. Relational databases organize entities into normalized tables linked by primary and foreign keys, queried via SQL. Transactional databases record time-stamped market-basket events where each tuple contains a transaction identifier and a variable-length list of purchased items. Temporal and time-series databases capture ordered sequences of measurements indexed by time, such as stock ticks or electrocardiogram waveforms, while spatial and spatio-temporal databases store geometric coordinates, polygons, and satellite rasters. Modern pipelines also mine text databases, multimedia repositories (images, audio, video), World Wide Web hyperlink graphs, and high-velocity data streams that require single-pass processing.
A cornerstone repository for enterprise data mining is the Data Warehouse—a subject-oriented, integrated, time-variant, and non-volatile collection of data built to support management decision-making. Unlike OLTP (Online Transaction Processing) systems optimized for rapid concurrent inserts and updates, a data warehouse supports OLAP (Online Analytical Processing) workloads that aggregate historical records across multiple dimensions. Modern data warehouses follow a Three-Tier Architecture: the Bottom Tier comprises the warehouse database server and ETL (Extract, Transform, Load) pipelines that clean and reconcile operational sources; the Middle Tier hosts the OLAP server—implemented as ROLAP (Relational OLAP using extended SQL), MOLAP (Multidimensional OLAP using sparse array cubes), or HOLAP (Hybrid OLAP); and the Top Tier provides front-end query, reporting, visualization, and data mining client tools.
Data warehouses are commonly modeled using a Star Schema (a central fact table linked to denormalized dimension tables), a Snowflake Schema (normalized dimension hierarchies that reduce storage redundancy at the cost of extra joins), or a Fact Constellation (Galaxy Schema) (multiple fact tables sharing conformed dimensions). Analysts explore multidimensional Data Cubes using five core OLAP operations: Roll-up (aggregating upward along a concept hierarchy, such as city → state → country), Drill-down (navigating from summary to finer detail, such as quarter → month → day), Slice (fixing one dimension—e.g., Year = 2025—to extract a 2D sub-cube), Dice (selecting value ranges across two or more dimensions—e.g., Location IN {Kochi, Trivandrum} AND Quarter IN {Q1, Q2}), and Pivot (Rotate) (reorienting dimensional axes to alter the cross-tabulated view).
| Comparison Dimension | OLTP (Operational Systems) | OLAP (Data Warehousing) | Data Mining (KDD Engine) |
|---|---|---|---|
| Primary Purpose | Day-to-day transaction recording | Multidimensional summary & reporting | Automated hidden pattern discovery |
| Data Orientation | Application-oriented, current state | Subject-oriented, historical (5–10 years) | Task-oriented, integrated feature sets |
| Query Profile | Short, atomic reads/writes (indexed) | Complex aggregations (group-by, cube) | Iterative scans, optimization, induction |
| Schema Design | Normalized (3NF) ER tables | Star, Snowflake, or Fact Constellation | Denormalized feature matrices / graphs |
| Output Artifact | Updated operational records | Cross-tabs, KPI dashboards, slice/dice | Decision trees, clusters, association rules |
1.4 Data Mining Functionalities
Data mining tasks are broadly divided into descriptive functionalities (characterizing general properties of existing data) and predictive functionalities (inducing models to forecast unknown or future values).
| Functionality | Learning Paradigm | Core Purpose | Representative Example |
|---|---|---|---|
| Concept / Class Description | Descriptive | Summarizes target class traits (characterization) or contrasts a target class against opposing classes (discrimination). | Comparing spending profiles of high-value vs. occasional retail buyers. |
| Frequent Pattern & Association Mining | Descriptive | Discovers itemsets, subsequences, or substructures that co-occur frequently across transactions. | Identifying that 72% of customers buying bread and butter also buy milk. |
| Classification | Predictive (Supervised) | Learns a model from labeled training tuples to assign unseen records to discrete categorical classes. | Classifying loan applicants as Low Risk or High Risk. |
| Regression / Prediction | Predictive (Supervised) | Models continuous numerical functions to estimate missing or future numeric quantities. | Forecasting quarterly regional sales revenue in rupees. |
| Cluster Analysis | Descriptive (Unsupervised) | Groups unlabeled objects so intra-cluster similarity is maximized and inter-cluster similarity is minimized. | Segmenting telecom subscribers into behavioral usage tiers. |
| Outlier (Anomaly) Analysis | Descriptive / Predictive | Identifies data objects that deviate sharply from the expected distribution or normal behavioral baseline. | Detecting stolen credit-card transactions in real time. |
| Evolution Analysis | Descriptive / Predictive | Models regularities, trends, periodicity, and structural shifts for objects whose behavior changes over time. | Tracking seasonal retail demand shifts across five-year cycles. |
1.5 Application Domains and Major Issues in Data Mining
Data mining delivers measurable value across nearly every data-intensive sector. In retail and e-commerce, market basket analysis optimizes shelf placement, cross-selling bundles, and personalized product recommendations. In banking and finance, credit scoring, anti-money-laundering detection, and algorithmic risk modeling rely on classification and anomaly detection. In healthcare and bioinformatics, predictive models assist in early disease screening, patient readmission risk stratification, and gene-expression clustering. Telecommunications providers deploy churn prediction to retain subscribers, while cybersecurity systems monitor network packet streams to flag intrusion signatures.
Despite its maturity, data mining faces significant technical and societal challenges grouped into five major issue categories: (1) Mining Methodology Issues—developing algorithms capable of handling noisy, incomplete, or uncertain data, incorporating domain constraints, and evaluating pattern interestingness; (2) User Interaction Issues—designing interactive mining interfaces, ad-hoc query languages, and visual explanations so domain experts can guide discovery; (3) Efficiency and Scalability Issues—ensuring algorithms scale linearly or sub-linearly on distributed, multi-terabyte datasets; (4) Diversity of Data Types—handling complex graphs, unstructured text, spatial rasters, and high-speed streams; and (5) Societal Impacts, Privacy, and Security—preventing unauthorized re-identification of sensitive personal records, mitigating algorithmic bias, and complying with data protection regulations.
1.6 Data Mining in Relation to Statistics, Machine Learning, and Databases
Data mining sits at the intersection of three foundational disciplines, inheriting specialized strengths from each while addressing distinct operational constraints. Classical Statistics focuses on hypothesis testing, confidence intervals, and parametric probability distributions derived from relatively small, carefully sampled datasets; data mining adapts statistical measures (chi-square tests, regression, variance analysis) to massive, observational, secondary datasets that were not collected under controlled experimental designs. Machine Learning provides the core inductive algorithms—decision trees, Bayesian networks, support vector machines, and neural architectures—for learning predictive functions from experience; data mining embeds these algorithms inside disk-resident, database-aware workflows that prioritize interpretability and scalability. Database Management Systems (DBMS) contribute ACID transactions, B+-tree indexing, query optimization, and parallel storage engines; data mining extends relational algebra with pattern-discovery primitives capable of scanning billions of tuples efficiently.
| Discipline | Primary Focus | Typical Data Scale | Key Contribution to KDD |
|---|---|---|---|
| Statistics | Inference, estimation, hypothesis testing | Small to medium samples | Significance testing, correlation, variance, outliers |
| Machine Learning | Adaptive generalization & prediction | Medium to large feature vectors | Classification, clustering, regularization, validation |
| Database Systems | Storage, indexing, query optimization | Terabyte/petabyte repositories | Data warehouses, OLAP cubes, scalable I/O access |
| Visualization | Human-in-the-loop visual perception | Aggregated or projected views | Histograms, scatter matrices, dendrograms, heatmaps |
Chapter 2: Attribute Types and Statistical Descriptions of Data
2.1 Taxonomy of Attribute Types
Datasets consist of data objects (also called records, tuples, samples, or instances) described by a set of attributes (features, dimensions, or variables). Choosing valid statistical summaries, distance formulas, and mining algorithms depends directly on the mathematical scale of each attribute.
| Attribute Type | Mathematical Properties | Permissible Operations | Concrete Examples |
|---|---|---|---|
| Nominal | Unordered categorical symbols representing distinct names or states. | Equality (=, ≠), Mode, Chi-square frequency counts. | Blood group (A, B, AB, O), City, Marital status. |
| Binary (Symmetric / Asymmetric) | Special nominal case with exactly two states (0/1 or True/False). | Equality, Mode; Jaccard coefficient for asymmetric positives. | Gender (symmetric), HIV test positive/negative (asymmetric). |
| Ordinal | Categories possessing a meaningful rank order, but unknown intervals between ranks. | Equality, Ordering (<, >), Median, Percentiles, Rank correlation. | Grades (A, B, C, D), Satisfaction (Low, Medium, High). |
| Numeric: Interval-Scaled | Equal-sized measurement units with an arbitrary zero point (no true absence). | Addition, Subtraction, Mean, Standard Deviation (no true ratios). | Temperature in Celsius or Fahrenheit, Calendar year. |
| Numeric: Ratio-Scaled | Equal-sized units with an inherent, absolute zero point representing total absence. | All arithmetic operations including multiplication and ratios (×, ÷). | Age, Salary, Weight in kg, Transaction count, Kelvin temperature. |
Attributes are also categorized by domain cardinality into discrete versus continuous attributes. A discrete attribute has a finite or countably infinite set of values—such as zip codes, number of children, or integer word counts—which can often be represented as integers or nominal labels. A continuous attribute takes real-valued measurements within an interval—such as height, voltage, or serum cholesterol—typically represented as floating-point numbers with finite precision.
2.2 Measuring Central Tendency and Dispersion
Basic statistical descriptions summarize the overall distribution of numeric and categorical attributes prior to model building, revealing skewness, typical baselines, and potential anomalies.
- x̄: Arithmetic mean of the N observed values x1, x2, …, xN.
- x̄w: Weighted arithmetic mean where each observation xi carries weight wi.
- s: Sample standard deviation measuring average spread around the mean (s2 is sample variance).
While the mean is sensitive to extreme outliers, a trimmed mean (computed after discarding the top and bottom p% of sorted values) improves robustness. The median is the middle value of a sorted dataset (or the average of the two middle values for even N), making it ideal for skewed income or housing price distributions. For grouped frequency intervals, the median is interpolated within the median class. The mode is the most frequently occurring value; distributions may be unimodal, bimodal, or multimodal. In moderately skewed unimodal distributions, the three measures satisfy the empirical relationship: Mean − Mode ≈ 3(Mean − Median). Dispersion is further summarized by the Range (Max − Min), Quartiles (Q1 at 25%, Q2 at 50%, Q3 at 75%), the Interquartile Range (IQR = Q3 − Q1), and the Five-Number Summary (Min, Q1, Median, Q3, Max) visualized via a Boxplot, where points beyond Q1 − 1.5×IQR or Q3 + 1.5×IQR are flagged as candidate outliers.
Worked Numerical Example (Central Tendency & Dispersion): Consider 9 sorted daily server response times (in milliseconds): [12, 15, 15, 18, 20, 22, 24, 26, 46]. Here, N = 9. The Mean is (12 + 15 + 15 + 18 + 20 + 22 + 24 + 26 + 46) / 9 = 198 / 9 = 22.0 ms. The Median is the 5th value = 20 ms. The Mode is 15 ms (appears twice). For quartiles, Q1 is the median of the lower half [12, 15, 15, 18] = (15 + 15)/2 = 15 ms, and Q3 is the median of the upper half [22, 24, 26, 46] = (24 + 26)/2 = 25 ms. Thus, IQR = 25 − 15 = 10 ms. The upper outlier fence is Q3 + 1.5 × IQR = 25 + 15 = 40 ms, so the reading 46 ms is flagged as a statistical outlier.
2.3 Graphic Displays and Data Visualization
Visualizing distributions exposes structural patterns, multimodality, gaps, and anomalies that summary statistics alone obscure. Histograms partition numeric ranges into equal-width buckets and plot bar heights proportional to frequency, highlighting peaks, skewness, and bin sparsity. Quantile plots graph each sorted value x(i) against its cumulative fraction fi = (i − 0.5)/N, enabling direct visual reading of median, quartiles, and tail steepness. Quantile-Quantile (Q-Q) plots graph the quantiles of one univariate distribution against the corresponding quantiles of a second distribution (or a theoretical normal distribution); points falling along a straight 45-degree diagonal indicate identical distributional shapes, whereas systematic S-curves or upward bends expose skewness or heavy tails.
Scatter plots display pairs of numeric attributes on Cartesian axes to reveal linear, quadratic, or clustered relationships, enhanced by Loess curves (local weighted polynomial regression smoothing) to trace non-linear trends without assuming a global parametric formula. When datasets exceed three dimensions, specialized high-dimensional visualization families are employed:
| Visualization Family | Encoding Mechanism | Representative Techniques | Analytical Strength |
|---|---|---|---|
| Pixel-Oriented | Maps each attribute value to a colored pixel arranged in sub-windows. | Spiral, Recursive Pattern, Circle Segments | Displays millions of records simultaneously without overlap. |
| Geometric Projection | Projects multi-dimensional space onto 2D parallel or orthogonal axes. | Scatter-plot Matrices, Parallel Coordinates | Reveals multi-attribute correlations and cluster separations. |
| Icon-Based | Maps attribute values to geometric features of visual icons/glyphs. | Chernoff Faces, Stick Figures, Star Glyphs | Leverages human pre-attentive recognition of facial/shape symmetry. |
| Hierarchical | Partitions screen space recursively according to attribute hierarchies. | Treemaps, Dimensional Stacking, Cone Trees | Visualizes nested part-to-whole proportions and tree depth. |
Worked Numerical Example (Sample Variance & Standard Deviation): Consider 5 monthly transaction counts: [10, 12, 16, 18, 24]. The mean is x̄ = (10 + 12 + 16 + 18 + 24)/5 = 80/5 = 16. Computing squared deviations from 16: (10 − 16)2 = 36, (12 − 16)2 = 16, (16 − 16)2 = 0, (18 − 16)2 = 4, and (24 − 16)2 = 64. The sum of squared deviations is 36 + 16 + 0 + 4 + 64 = 120. Dividing by N − 1 = 4 gives sample variance s2 = 120 / 4 = 30.0, and sample standard deviation s = √30 ≈ 5.48. Note that standard deviation shares the exact measurement unit of the original attribute, whereas variance is expressed in squared units.
2.4 Grouped Data Median Interpolation and Distributional Skewness
When large datasets are summarized into grouped frequency intervals (bins), the exact median is estimated via linear interpolation within the median class (the first interval whose cumulative frequency reaches or exceeds N/2):
- L1: Lower boundary of the median class interval.
- N: Total number of observations across all intervals.
- (∑ freq)l: Cumulative frequency of all intervals strictly below L1.
- freqmedian, w: Frequency and width of the median class interval.
Worked Numerical Example (Grouped Median): Suppose 100 customer ages are binned into intervals: [10–20): 15, [20–30): 30, [30–40): 35, [40–50): 20. Here N/2 = 50. Cumulative frequencies are 15, 45, 80, 100, so the median class is [30–40) with L1 = 30, (∑ freq)l = 45, freqmedian = 35, and width w = 10. Interpolating: Median = 30 + ((50 − 45) / 35) × 10 = 30 + (5/35) × 10 = 30 + 1.43 = 31.43 years. Assessing skewness compares Mean, Median, and Mode: in a positively (right) skewed distribution (such as household income), Mean > Median > Mode; in a negatively (left) skewed distribution (such as easy exam scores), Mean < Median < Mode; and in a symmetric distribution, Mean = Median = Mode.
Chapter 3: Measuring Data Similarity, Dissimilarity, and Practical WEKA Workflows
3.1 Data Matrix, Dissimilarity Matrix, and Proximity Measures
Clustering, nearest-neighbor classification, and outlier detection rely on quantifying how alike (similarity) or different (dissimilarity/distance) two data objects are. A dataset of n objects and p attributes is stored in an n × p Data Matrix (two-mode matrix), whereas pairwise distances between all objects form a symmetric n × n Dissimilarity Matrix (one-mode matrix) with zeros along the main diagonal.
For nominal attributes with M distinct states, the dissimilarity between objects i and j is computed by simple matching: , where p is the total number of nominal attributes and m is the number of matching states. For asymmetric binary attributes (where state 1, such as disease presence or item purchase, is far more informative than joint absence 0-0), the Jaccard Coefficient ignores joint absences: and , where q counts (1,1) matches, r counts (1,0), and s counts (0,1). For symmetric binary attributes, joint (0,0) matches t are included via the Simple Matching Coefficient.
For numeric attributes, the general Minkowski Distance unifies the most widely used geometric metrics:
- dh(i, j): Minkowski distance of order h ≥ 1 between p-dimensional objects i and j. When h = 1, it yields Manhattan (L1) distance; when h = 2, Euclidean (L2) distance; as h → ∞, Supremum (L∞) distance maxk|xik − xjk|.
- cos(x, y): Cosine similarity measuring the angle between sparse non-negative vectors (such as TF-IDF document vectors), ranging from 0 (orthogonal) to 1 (identical direction).
For ordinal attributes with Mf ordered states (1, …, Mf), each rank rif is first mapped onto [0, 1] via , after which Euclidean or Manhattan distance is applied. When records contain mixed attribute types, Gower's Dissimilarity aggregates normalized per-attribute dissimilarities weighted by indicator flags that omit missing-value pairs.
Worked Numerical Example (Euclidean, Manhattan, and Cosine): Let Object A = (2, 4, 0) and Object B = (5, 0, 0). The Manhattan distance is |2 − 5| + |4 − 0| + |0 − 0| = 3 + 4 + 0 = 7. The Euclidean distance is √((2 − 5)2 + (4 − 0)2 + 02) = √(9 + 16) = √25 = 5.0. The Supremum distance is max(3, 4, 0) = 4. The dot product A · B = (2)(5) + (4)(0) + (0)(0) = 10, ||A|| = √(4 + 16) = √20 ≈ 4.472, and ||B|| = √25 = 5, so Cosine Similarity = 10 / (4.472 × 5) = 0.447.
Worked Numerical Example (Asymmetric Binary Jaccard vs. Symmetric SMC): Suppose two retail customers are profiled over 6 binary product flags (1 = purchased, 0 = not purchased): Customer A = (1, 1, 0, 0, 1, 0) and Customer B = (1, 0, 0, 1, 1, 0). Counting pairwise outcomes: q (both 1) = 2 (positions 1, 5); r (A=1, B=0) = 1 (position 2); s (A=0, B=1) = 1 (position 4); t (both 0) = 2 (positions 3, 6). Using the Jaccard Coefficient (ignoring joint absences t): simJaccard = q / (q + r + s) = 2 / (2 + 1 + 1) = 0.50, and Jaccard Dissimilarity = 1 − 0.50 = 0.50. Using the Simple Matching Coefficient (SMC) (appropriate only for symmetric binary attributes like gender or yes/no survey toggles): SMC = (q + t) / (q + r + s + t) = (2 + 2) / 6 = 0.667.
Worked Numerical Example (Mixed-Type Gower Dissimilarity): Consider two patients described by three attributes: Test_Result (Nominal: {Pos, Neg}), Severity (Ordinal: {Mild=1, Mod=2, Sev=3}), and Age (Numeric, range R = 60 − 20 = 40). Patient 1 = (Pos, Mild[1], 24) and Patient 2 = (Pos, Sev[3], 44). Per-attribute dissimilarities: (1) Nominal Test_Result: matches, so d(1) = 0; (2) Ordinal Severity: normalized ranks z1 = (1−1)/(3−1) = 0, z2 = (3−1)/(3−1) = 1, so d(2) = |0 − 1| = 1.0; (3) Numeric Age: d(3) = |24 − 44| / 40 = 20/40 = 0.50. With all three attributes valid (δ = 1), overall mixed dissimilarity d(1, 2) = (0 + 1.0 + 0.50) / 3 = 0.50.
3.2 Practical Lab Workflows Using WEKA (ARFF Creation & Attribute Exploration)
In laboratory sessions, the WEKA (Waikato Environment for Knowledge Analysis) workbench provides an accessible graphical and programmatic interface for data mining. Datasets are natively stored in ARFF (Attribute-Relation File Format), an ASCII text structure comprising a @relation header, @attribute declarations specifying nominal sets or numeric/real types, and a @data section listing comma-separated instances (with ? denoting a missing value).
To execute Practical Exercises 1, 2, and 3 in WEKA Explorer: (1) Open WEKA GUI Chooser → Explorer → Preprocess tab → click Open file to load the saved .arff table (or use WEKA's built-in ArffViewer under Tools to create and edit rows directly); (2) Inspect the Attributes panel on the left: WEKA labels nominal/categorical columns as Nominal (displaying category frequency counts) and continuous columns as Numeric (real-valued); (3) Click any numeric attribute in the list to inspect the Selected attribute summary panel on the right, which reports Minimum, Maximum, Mean, and StdDev alongside a color-coded class distribution histogram. Because WEKA reports Mean and StdDev directly, students compute the Median (middle sorted observation via ArffViewer sort) and Mode (highest-count nominal category or modal numeric bin) to complete Exercise 3.
@relation student_mining
@attribute student_id nominal {S01, S02, S03, S04, S05, S06}
@attribute attendance_pct numeric
@attribute lab_score real
@attribute study_tier {Low, Medium, High}
@attribute result {Pass, Fail}
@data
S01, 92, 85.5, High, Pass
S02, 78, 70.0, Medium, Pass
S03, 55, 42.0, Low, Fail
S04, 88, 79.5, High, Pass
S05, 64, 51.0, Medium, Pass
S06, 48, 35.0, Low, FailChapter 4: OLAP Cube Operations and Distance Metric Selection Guide
4.1 Worked Example of Multidimensional OLAP Cube Operations
Consider a retail Data Warehouse tracking quarterly electronics sales (in lakhs of rupees) across three dimensions: Time (Q1, Q2, Q3, Q4 → Year), Location (Kochi, Kozhikode, Trivandrum → Kerala → India), and Item (Laptop, Tablet, Phone → Electronics). Starting from the base cuboid (Time, Location, Item), each OLAP operation transforms the analytical view systematically:
| OLAP Operation | Dimensional Transformation | Resulting Analytical View | Business Question Answered |
|---|---|---|---|
| Roll-Up | Climbs hierarchy: City → State (Kerala) | Aggregates Kochi + Kozhikode + Trivandrum totals | What is total Kerala sales per quarter? |
| Drill-Down | Descends hierarchy: Quarter → Month | Splits Q1 into Jan, Feb, Mar figures | Which month drove Q1 laptop growth? |
| Slice | Fixes Time = "Q4" | 2D table of Location × Item for Q4 only | How did cities perform across products in Q4? |
| Dice | Filters Time IN {Q1, Q2} AND Item IN {Laptop, Phone} | Reduced 3D sub-cube of 2 quarters × 2 items | Compare first-half Laptop vs Phone demand. |
| Pivot | Swaps Location (rows) and Item (columns) | Rotated cross-tabulated summary grid | Reformat report for regional managers. |
4.2 Choosing the Right Proximity Measure by Data Domain
Selecting an inappropriate distance metric distorts downstream clustering and nearest-neighbor classification. Analysts match proximity metrics to attribute scale, sparsity, and outlier sensitivity using the reference matrix below:
| Data Domain / Attribute Scale | Recommended Proximity Measure | Key Mathematical Property |
|---|---|---|
| Dense Continuous Numeric | Euclidean (L2) or Manhattan (L1) | Manhattan resists isolated extreme coordinate spikes better than Euclidean. |
| Sparse Text / TF-IDF Vectors | Cosine Similarity | Invariant to document length; ignores shared zero entries. |
| Asymmetric Binary Baskets | Jaccard Coefficient | Ignores joint absences (0–0) when evaluating co-purchased items. |
| Symmetric Binary Surveys | Simple Matching Coefficient (SMC) | Weights (1–1) and (0–0) matches equally. |
| Mixed Enterprise Tables | Gower's Combined Dissimilarity | Normalizes nominal, ordinal, binary, and numeric columns onto [0, 1]. |
Module II: Data Preprocessing and Mining Frequent Patterns
Chapter 4: Data Preprocessing Techniques
4.1 Why Preprocess Data? Data Quality Dimensions
Real-world enterprise databases are rarely ready for immediate algorithmic modeling. Operational data is routinely incomplete (lacking attribute values or containing only aggregate summaries), noisy (corrupted by sensor jitter, transcription typos, or transmission glitches), and inconsistent (exhibiting conflicting department codes, mixed date formats, or impossible values such as a negative age). Feeding flawed inputs into a learner triggers the "garbage-in, garbage-out" phenomenon, degrading accuracy and generating spurious rules. High-grade analytical datasets satisfy six core quality dimensions: Accuracy (closeness to true real-world values), Completeness (absence of missing records or attributes), Consistency (uniform schemas and integrity constraints across tables), Timeliness (up-to-date freshness), Believability (trustworthiness to domain users), and Interpretability (clear, unambiguous semantics).
4.2 Data Cleaning: Missing Values and Noisy Data
Data Cleaning fills in missing values, smooths noisy readings, identifies or removes outliers, and resolves structural inconsistencies. When a record contains a missing value (represented as ? in WEKA ARFF files or null in SQL), analysts select among six standard remediation strategies depending on data volume and missingness mechanism:
| Missing Value Strategy | Mechanism | Strengths | Limitations |
|---|---|---|---|
| Ignore the Tuple | Discard records missing the class label or multiple attributes. | Simple; introduces no synthetic bias if missingness is rare. | Wastes data; severe information loss when many tuples have gaps. |
| Fill Manually | Domain expert inspects source documents and enters true value. | Highest accuracy for small, critical datasets. | Slow, expensive, and infeasible for large repositories. |
| Global Constant | Replace missing entries with a constant such as "Unknown" or −999. | Preserves missingness as an explicit state. | Algorithms may mistakenly treat the constant as a meaningful cluster. |
| Attribute Mean / Median | Substitute the global mean (symmetric) or median (skewed) of that column. | Fast, preserves sample size, easy to automate (WEKA ReplaceMissingValues). |
Reduces variance and ignores correlations with other features. |
| Class-Conditional Mean | Substitute the mean or median computed strictly within the same class label. | More accurate than global mean when classes differ sharply. | Requires labeled training data; unusable for unlabeled test inputs. |
| Most Probable Value | Predict missing entry via linear regression, Bayesian inference, or decision trees. | Leverages inter-attribute relationships to maximize fidelity. | Computationally heavier; may overfit existing feature correlations. |
To handle noisy data (random error or variance in a measured variable), three primary smoothing techniques are applied. Binning sorts values and partitions them into neighborhoods—either equal-width bins (constant interval size) or equal-frequency bins (equal count per bin)—and then smooths each bin by replacing values with the bin mean, bin median, or closest bin boundary. Regression fits a linear or multiple regression function to the data so noisy deviations from the fitted trend line are damped. Outlier Analysis uses clustering or statistical fences to isolate anomalous points that fall outside valid clusters.
Worked Numerical Example (Binning Smoothing): Suppose sorted price readings are [4, 8, 15, 21, 21, 24, 25, 28, 34]. Partitioning into 3 equal-frequency bins (size 3 each) gives Bin 1: [4, 8, 15], Bin 2: [21, 21, 24], Bin 3: [25, 28, 34]. Smoothing by bin means replaces each bin with its average: Bin 1 → [9, 9, 9], Bin 2 → [22, 22, 22], Bin 3 → [29, 29, 29]. Smoothing by bin boundaries replaces interior points with the nearest endpoint: Bin 1 → [4, 4, 15] (since 8 is closer to 4 than 15), Bin 2 → [21, 21, 24], Bin 3 → [25, 25, 34].
4.3 Data Integration, Reduction, Transformation, and Discretization
Data Integration merges records from multiple databases into a coherent store. Key challenges include the entity identification problem (matching cust_id in one schema to client_no in another), tuple duplication, data value conflicts (such as currency in INR versus USD or metric versus imperial units), and redundancy. Redundant attributes are detected using statistical correlation tests: for nominal attributes, the Chi-Square (χ2) test compares observed joint frequencies Oij against expected independence counts Eij = (row_totali × col_totalj) / N; for numeric attributes, Pearson's correlation coefficient (r) and Covariance measure linear dependence.
- χ2: Chi-square statistic across c columns and r rows; large χ2 exceeding the critical threshold at (r−1)(c−1) degrees of freedom rejects independence, confirming attribute correlation.
- Cov(A, B): Sample covariance indicating joint directional movement (+ for positive, − for negative).
- rA,B: Scale-free Pearson correlation coefficient (−1 ≤ r ≤ +1), where |r| near 1 signals strong linear redundancy.
Worked Numerical Example (Chi-Square Correlation Test): Suppose 1,000 students are surveyed on Device (Laptop vs. Tablet) and Stream (BCA vs. BCom). Observed counts: (BCA, Laptop) = 450, (BCA, Tablet) = 50 (row total = 500); (BCom, Laptop) = 350, (BCom, Tablet) = 150 (row total = 500). Column totals: Laptop = 800, Tablet = 200. Expected counts under independence: E11 = (500 × 800)/1000 = 400; E12 = (500 × 200)/1000 = 100; E21 = 400; E22 = 100. Computing χ2 = (450−400)2/400 + (50−100)2/100 + (350−400)2/400 + (150−100)2/100 = 6.25 + 25.0 + 6.25 + 25.0 = 62.5. With df = (2−1)(2−1) = 1, the 0.001 critical value is 10.828; since 62.5 > 10.828, Device and Stream are strongly correlated.
- x′: Min-Max normalized value mapping raw x from [minA, maxA] linearly into [new_min, new_max] (typically [0, 1]).
- z: Z-score standardized value expressing how many standard deviations sA an observation lies from the mean Ā.
- xdec: Decimal-scaled value where j is the smallest integer satisfying max(|xdec|) < 1.
Worked Numerical Example (Data Normalization): Given five salary values (in thousands): [20, 40, 60, 80, 100]. Here min = 20, max = 100, mean Ā = 60, and sample standard deviation s = 31.62. For x = 80: (1) Min-Max to [0, 1]: (80 − 20)/(100 − 20) = 60/80 = 0.75; (2) Z-Score: (80 − 60)/31.62 = +0.632; (3) Decimal Scaling: max(|x|) = 100, so j = 3 (103 = 1000) gives 80/1000 = 0.08.
Data Reduction produces a compressed representation that yields nearly identical analytical outcomes at a fraction of the computational cost. Dimensionality reduction removes irrelevant or redundant features using Principal Components Analysis (PCA)—which mean-centers the data, computes the covariance matrix, extracts orthogonal eigenvectors (principal components) ordered by descending eigenvalues, and projects records onto the top k components—or Discrete Wavelet Transforms (DWT), and attribute subset selection (stepwise forward selection, backward elimination, combined stepwise, or decision-tree attribute ranking). Numerosity reduction replaces large record volumes with compact parametric models (linear/log-linear regression) or non-parametric summaries (histograms, clustering centroids, data cube aggregation, or sampling). Common sampling designs include SRSWOR (Simple Random Sample Without Replacement), SRSWR (With Replacement), Cluster Sampling (sampling natural groups/pages), and Stratified Sampling (sampling proportionally within each class stratum to preserve rare minority classes).
Data Transformation and Discretization prepare numeric ranges for algorithms requiring categorical inputs or uniform scales. Discretization converts continuous attributes into ordered interval labels (e.g., Age → Youth, Middle-Aged, Senior) using unsupervised binning/histogram analysis or supervised Entropy-based splitting and ChiMerge (recursively merging adjacent intervals with the lowest χ2 statistic until class distributions differ significantly), and constructs multi-level concept hierarchies for nominal attributes via schema ordering or explicit value grouping.
4.4 Missingness Mechanisms, Sampling Designs, and Data Reduction Summary
Selecting an appropriate data cleaning strategy requires understanding why values are missing. Statisticians classify missingness into three mechanisms: MCAR (Missing Completely At Random), where missingness is independent of both observed and unobserved values (e.g., accidental packet drop); MAR (Missing At Random), where missingness depends on other observed attributes (e.g., younger respondents skipping an income field); and MNAR (Missing Not At Random), where missingness depends on the unobserved value itself (e.g., high earners concealing salary). Under MCAR, tuple deletion introduces no bias; under MAR, regression or model-based imputation preserves statistical validity; under MNAR, domain-specific indicator flags are essential.
| Reduction / Sampling Technique | Category | Operational Mechanism | Best Use Case |
|---|---|---|---|
| Principal Components Analysis (PCA) | Dimensionality Reduction | Projects features onto orthogonal eigenvectors ordered by variance. | Correlated continuous numeric matrices. |
| Discrete Wavelet Transform (DWT) | Dimensionality Reduction | Applies hierarchical Haar/Daubechies filters, keeping top coefficients. | Time-series, signals, and spatial rasters. |
| Stepwise Subset Selection | Dimensionality Reduction | Greedily adds (forward) or drops (backward) attributes via p-value/gain. | Removing redundant or irrelevant columns. |
| SRSWOR / SRSWR | Numerosity (Sampling) | Uniform random draw without (SRSWOR) or with (SRSWR) replacement. | Balanced large datasets needing fast prototyping. |
| Stratified Sampling | Numerosity (Sampling) | Samples proportionally within each class stratum. | Imbalanced datasets (fraud, rare diseases). |
| Data Cube Aggregation | Numerosity Reduction | Pre-aggregates granular records to higher concept hierarchy levels. | OLAP reporting and executive dashboards. |
Chapter 5: Mining Frequent Patterns, Associations, and Market Basket Analysis
5.1 Basic Concepts: Support, Confidence, and Association Rules
Frequent Pattern Mining discovers itemsets, subsequences, or substructures that appear together in a dataset with frequency above a user-specified threshold. Its classic motivation is Market Basket Analysis, where supermarkets examine point-of-sale receipts to understand which products customers buy together, informing store layout, bundle pricing, and targeted coupons.
Let I = {i1, i2, …, im} be the universe of items and D be a transactional database of N transactions, where each transaction T ⊆ I carries a unique identifier TID. An association rule is an implication of the form A ⇒ B, where A ⊂ I, B ⊂ I, A ≠ ∅, B ≠ ∅, and A ∩ B = ∅. Rule quality is governed by two primary interestingness measures:
- Support(A ⇒ B): Joint probability that a transaction in D contains both itemset A and itemset B.
- Confidence(A ⇒ B): Conditional probability that a transaction containing A also contains B.
- Strong Rule: A rule satisfying both Support ≥ min_sup and Confidence ≥ min_conf.
An itemset containing k items is called a k-itemset. An itemset whose support meets or exceeds min_sup is a frequent itemset. Because a frequent k-itemset generates 2k − 2 non-empty subsets, mining large datasets requires compact lossless or summary representations: a closed frequent itemset X has no immediate superset Y ⊃ X with the exact same support count (lossless: every frequent itemset and its exact support can be reconstructed), whereas a maximal frequent itemset X has no frequent superset at all (compact boundary, though exact subset supports are not retained). For example, if {a, b, c} has support 3 and {a, b, c, d} has support 2 (with min_sup = 2), then {a, b, c, d} is both maximal and closed, while {a, b, c} is closed (since its superset has lower support 2 ≠ 3) but not maximal.
Beyond single-level market baskets, modern systems mine multilevel association rules (across concept hierarchies such as Dairy → Milk → Skim Milk using uniform or reduced minimum support at deeper levels), multidimensional association rules (combining multiple predicates such as age(X, "20..29") ∧ income(X, "High") ⇒ buys(X, "Laptop")), and constraint-based association rules incorporating user-specified anti-monotonic, monotonic, succinct, or convertible constraints to prune the search space early.
Chapter 6: Frequent Itemset Mining Methods — Apriori, FP-Growth, and WEKA Lab
6.1 The Apriori Algorithm and the Downward Closure Property
Proposed by Agrawal and Srikant, the Apriori Algorithm discovers all frequent itemsets using an iterative level-wise breadth-first search: frequent 1-itemsets L1 are used to find frequent 2-itemsets L2, which in turn generate L3, and so on. Its efficiency rests on the Apriori Property (Downward Closure): every non-empty subset of a frequent itemset must also be frequent. Equivalently, if any subset of a candidate k-itemset is infrequent, the entire k-itemset cannot be frequent and can be pruned immediately without scanning the database.
Each iteration k ≥ 2 executes two phases: (1) Join Step—generate candidate set Ck by self-joining Lk−1 on matching first k − 2 items; and (2) Prune Step—remove any candidate in Ck that possesses an infrequent (k − 1)-subset before counting remaining candidates against the transaction database D to obtain Lk.
Worked Numerical Example (Apriori Step-by-Step): Consider a 5-transaction database D with min_sup = 60% (minimum support count = 3 transactions) and min_conf = 75%:
| TID | Purchased Items | Frequent 1-Itemsets (L1, count ≥ 3) | Frequent 2-Itemsets (L2, count ≥ 3) | Frequent 3-Itemsets (L3) |
|---|---|---|---|---|
| T100 | {Milk, Bread, Butter} | {Milk}: 4 | {Milk, Bread}: 3 | {Milk, Bread, Butter}: 2 (Pruned) |
| T200 | {Milk, Bread, Eggs} | {Bread}: 4 | {Milk, Butter}: 3 | No frequent 3-itemsets remain. |
| T300 | {Milk, Butter, Jam} | {Butter}: 4 | {Bread, Butter}: 3 | — |
| T400 | {Bread, Butter} | {Eggs}: 1 (Pruned) | — | — |
| T500 | {Milk, Bread, Butter} | {Jam}: 1 (Pruned) | — | — |
From L2, every itemset has support count 3/5 = 60%. Generating association rules from {Milk, Bread} (count 3): Milk ⇒ Bread has Confidence = 3 / count(Milk) = 3/4 = 75% (Strong Rule); Bread ⇒ Milk has Confidence = 3/4 = 75% (Strong Rule). Similarly, Milk ⇒ Butter and Butter ⇒ Milk both achieve 75% confidence. Despite its clarity, Apriori suffers from two bottlenecks on dense datasets: generating massive candidate sets Ck and performing repeated full-database scans.
To improve Apriori efficiency, five optimizations are used: Hash-based itemset counting (hashing 2-itemsets into buckets to prune low-count candidates early), Transaction reduction (dropping transactions that contain no frequent k-itemsets), Partitioning (finding local frequent itemsets in memory-sized partitions in two scans), Sampling (mining a random subset at a lowered support threshold), and Dynamic Itemset Counting (DIC).
6.2 FP-Growth Algorithm and Correlation Analysis (Lift)
The FP-Growth (Frequent Pattern Growth) algorithm eliminates candidate generation entirely by compressing the database into a compact prefix-tree structure called an FP-Tree in just two database scans. In Scan 1, frequent 1-itemsets are counted, infrequent items are discarded, and surviving items are sorted in descending support order into an F-list. In Scan 2, each transaction's frequent items are reordered to match the F-list and inserted as a path from the null root of the FP-tree; transactions sharing common prefixes merge along the same tree nodes, incrementing path support counters while maintaining a Header Table with horizontal node-links connecting identical items across branches.
Mining proceeds recursively bottom-up from the least frequent item in the Header Table: (1) follow its node-links to collect all prefix paths ending at that item—forming its Conditional Pattern Base; (2) construct a smaller Conditional FP-Tree from those prefix paths (pruning items falling below min_sup); and (3) recursively mine the conditional tree and concatenate the suffix item to output all frequent patterns without ever generating candidate Ck sets. Using our 5-transaction example (F-list: Milk:4, Bread:4, Butter:4), T100 (Milk, Bread, Butter) and T500 (Milk, Bread, Butter) share a single branch root → Milk(2) → Bread(2) → Butter(2); T200 adds Milk(3) → Bread(3); T300 branches at Milk(4) → Butter(1); and T400 creates Bread(1) → Butter(1). Following the Butter links yields prefix paths {Milk, Bread: 2}, {Milk: 1}, and {Bread: 1}, immediately revealing {Milk, Butter}: 3 and {Bread, Butter}: 3.
Furthermore, support and confidence alone can produce misleading rules when the consequent item is inherently very popular. Consider a beverage survey of 1,000 customers: 600 buy Coffee, 750 buy Tea, and 400 buy both. The rule Coffee ⇒ Tea has Support = 400/1000 = 40% and Confidence = 400/600 = 66.7%—appearing strong! However, 75% of all customers buy Tea regardless of Coffee, so Coffee buyers actually buy Tea less often than the baseline population. To expose such misleading rules, analysts compute correlation measures such as Lift and All-Confidence:
- Lift > 1: A and B are positively correlated (co-occur more often than random chance).
- Lift = 1: A and B are statistically independent.
- Lift < 1: A and B are negatively correlated (for Coffee ⇒ Tea, Lift = 0.40 / (0.60 × 0.75) = 0.889 < 1, exposing negative correlation).
- AllConf(A, B): Null-invariant measure (unaffected by huge numbers of transactions containing neither A nor B).
6.3 Practical WEKA Preprocessing and Apriori Workflows (Exercises 4, 5, and 6)
In WEKA, Practical Exercises 4, 5, and 6 are executed cleanly through Explorer filters and the Associate panel. For missing-value cleaning (Exercise 5), open the dataset in Preprocess, click Choose under Filter → filters → unsupervised → attribute → ReplaceMissingValues, and click Apply; WEKA replaces every ? in numeric columns with the attribute mean and in nominal columns with the mode. For general preprocessing (Exercise 4), apply Normalize (scaling to [0, 1]), Standardize (Z-score), or Discretize (binning continuous columns into nominal intervals—mandatory before running Apriori). Under the Associate tab, select Apriori, configure lowerBoundMinSupport = 0.2 and minMetric = 0.75 (Confidence), and click Start to inspect ranked strong rules.
6.4 Apriori vs. FP-Growth Comparison and Rule Generation Walkthrough
Once frequent itemsets L are discovered, association rules are generated by iterating over every frequent itemset l ∈ L with |l| ≥ 2 and testing every non-empty proper subset s ⊂ l for the rule s ⇒ (l − s). A rule is retained if support_count(l) / support_count(s) ≥ min_conf. For example, suppose frequent 3-itemset l = {I1, I2, I5} has support count 2 out of 9 transactions (22.2%), and subset counts are: {I1, I2}: 4, {I1, I5}: 2, {I2, I5}: 2, {I1}: 6, {I2}: 7, {I5}: 2. With min_conf = 70%, testing all 23 − 2 = 6 candidate rules yields: (1) {I1, I2} ⇒ I5 (Conf = 2/4 = 50%, Rejected); (2) {I1, I5} ⇒ I2 (Conf = 2/2 = 100%, Accepted); (3) {I2, I5} ⇒ I1 (Conf = 2/2 = 100%, Accepted); (4) I1 ⇒ {I2, I5} (Conf = 2/6 = 33.3%, Rejected); (5) I2 ⇒ {I1, I5} (Conf = 2/7 = 28.6%, Rejected); and (6) I5 ⇒ {I1, I2} (Conf = 2/2 = 100%, Accepted). Notice how anti-monotonicity also speeds rule generation: if {I1, I2} ⇒ I5 fails confidence, then any rule with a smaller antecedent subset of {I1, I2} (such as I1 ⇒ {I2, I5}) is guaranteed to fail confidence too.
| Architectural Feature | Apriori Algorithm | FP-Growth Algorithm |
|---|---|---|
| Search Strategy | Breadth-first, level-wise candidate generation & test. | Depth-first, divide-and-conquer pattern growth. |
| Database Scans | k + 1 full scans (where k is max frequent itemset size). | Exactly 2 scans (F-list count + FP-Tree insertion). |
| Candidate Sets Ck | Explicitly generates huge C2, C3 candidate sets. | Zero candidate generation (compressed prefix tree). |
| Memory Bottleneck | Large candidate hash trees in RAM on dense datasets. | FP-Tree fits compactly unless data is extremely sparse. |
| Runtime Scaling | Degrades sharply when min_sup is low or patterns are long. | Typically 10×–100× faster on dense transactional logs. |
# 1. Impute missing values & discretize numeric attributes (Exercises 4 & 5) java weka.filters.unsupervised.attribute.ReplaceMissingValues \ -i raw_data.arff -o clean_data.arff java weka.filters.unsupervised.attribute.Discretize \ -B 4 -i clean_data.arff -o nominal_data.arff # 2. Run Apriori with min_sup = 0.2 and min_conf = 0.75 (Exercise 6) java weka.associations.Apriori \ -N 10 -T 0 -C 0.75 -D 0.05 -U 1.0 -M 0.2 -t nominal_data.arff
Chapter 7: End-to-End Preprocessing Case Study and Apriori Optimizations
7.1 Integrated Data Preprocessing Pipeline Case Study
To observe how cleaning, integration, normalization, and discretization interact sequentially, consider a raw 6-record retail customer table containing a missing Age entry, an impossible negative Spend typo, and disparate attribute scales:
| Customer ID | Raw Age | Cleaned Age (Mean Imputed) | Raw Annual Spend (INR) | Min-Max Spend [0, 1] | Discretized Spend Tier |
|---|---|---|---|---|---|
| C01 | 22 | 22.0 | 12,000 | 0.00 | Low |
| C02 | Missing value | 32.4 | 24,000 | 0.25 | Low |
| C03 | 28 | 28.0 | 36,000 | 0.50 | Medium |
| C04 | 36 | 36.0 | 48,000 | 0.75 | High |
| C05 | 44 | 44.0 | 60,000 | 1.00 | High |
| C06 | 32 | 32.0 | −500 (Corrected → 36,000) | 0.50 | Medium |
First, the domain integrity constraint (Spend ≥ 0) flags −500 for C06 as an impossible noisy entry, which is corrected via median/mean imputation to 36,000. Second, the missing Age for C02 is imputed using the arithmetic mean of the five valid ages: (22 + 28 + 36 + 44 + 32) / 5 = 32.4. Third, Min-Max normalization maps Annual Spend from [12,000, 60,000] onto [0.0, 1.0] via (x − 12,000) / 48,000 so distance-based learners are not dominated by rupee magnitudes over age. Finally, equal-width discretization partitions spend into Low [12k–28k), Medium [28k–44k), and High [44k–60k] categories ready for Apriori association rule mining.
7.2 Apriori Scalability Optimizations and Constraint-Based Mining
In production databases spanning millions of transactions, standard level-wise Apriori can be accelerated substantially through five algorithmic refinements without sacrificing exactness or recall:
| Optimization Technique | Core Algorithmic Mechanism | Performance Benefit |
|---|---|---|
| Hash-Based Technique | Hashes candidate 2-itemsets into buckets during Scan 1; prunes buckets below min_sup. | Dramatically shrinks C2—the largest bottleneck in Apriori. |
| Transaction Reduction | Drops any transaction T that contains no frequent k-itemsets from subsequent scans. | Shrinks effective database size N on each pass k → k + 1. |
| Partitioning (Savasere et al.) | Splits D into p memory-fit partitions; finds local frequent sets (Scan 1), verifies global counts (Scan 2). | Guarantees at most 2 full disk scans for all frequent itemsets. |
| Sampling | Mines a random sample S ⊂ D at a slightly lowered support threshold; verifies against D. | Trades minor completeness risk for sub-second interactive speed. |
| Dynamic Itemset Counting (DIC) | Adds new candidate itemsets dynamically at fixed checkpoints within a single scan. | Overlaps counting of different k-lengths, reducing total scans. |
When analysts specify domain constraints—such as sum(I.price) ≤ 5000 or avg(I.price) ≥ 1000—modern pattern miners classify them as anti-monotonic (if a set violates the constraint, all supersets violate it too, enabling immediate pruning inside Apriori), monotonic (once satisfied, all supersets satisfy it), succinct (itemsets satisfying the constraint can be enumerated directly via a formula), or convertible (becoming anti-monotonic once items are sorted by price).
Chapter 8: Null-Invariant Correlation Measures and Concept Hierarchy Generation
8.1 Null-Invariant Interestingness Measures for Imbalanced Transactions
In massive retail databases containing tens of thousands of distinct SKUs, any two products A and B are absent together from the vast majority of shopping baskets (creating a huge null-transaction count f00). Traditional measures such as Lift and Chi-Square (χ2) depend heavily on f00 and can become unstable as the database grows. To evaluate association strength reliably without distortion from null transactions, analysts use null-invariant measures—chiefly Kulczynski, Cosine (IS), and Imbalance Ratio (IR):
- Kulc(A, B): Average of conditional probabilities P(A | B) and P(B | A), ranging from 0 to 1 (0.5 is neutral).
- Cosine(A, B): Geometric mean of P(A | B) and P(B | A), completely independent of null transactions f00.
- IR(A, B): Imbalance Ratio measuring skewness between support(A) and support(B) (0 = perfectly balanced, 1 = skewed).
Worked Numerical Example (Null-Invariant Comparison): Suppose 10,000 baskets record Milk (M) and Cereal (C): both M and C = 1,000; M without C = 100; C without M = 100; neither = 8,800. Here P(M ∪ C) = 0.10, P(M) = 0.11, P(C) = 0.11. Kulc(M, C) = 0.5 × (1000/1100 + 1000/1100) = 0.909; Cosine(M, C) = 0.10 / √(0.11 × 0.11) = 0.909; IR(M, C) = |1100 − 1100| / (1100 + 1100 − 1000) = 0.0 (perfectly balanced strong positive correlation). Notice that if 100,000 unrelated transactions are added to the database, Kulc, Cosine, and IR remain unchanged at 0.909 and 0.0, whereas Lift would artificially inflate tenfold.
8.2 Concept Hierarchy Generation for Nominal and Numeric Attributes
Discretization and multilevel pattern mining depend on structured Concept Hierarchies that map low-level attribute values to higher-level concepts. For nominal attributes, hierarchies are constructed through four mechanisms: (1) Specification of a partial ordering at schema level (e.g., street < city < district < state < country); (2) Explicit data grouping of small categories (e.g., {Kochi, Kozhikode} → Kerala); (3) Specification of a set of attributes without explicit ordering (where the system infers hierarchy depth by counting distinct values—country has fewest distinct values, street has the most); and (4) Specification of only a partial set of attributes. For numeric attributes, hierarchies are generated automatically by recursive equal-width binning, histogram segmentation, or 3-4-5 segmentation rules that partition ranges into human-readable intervals.
8.3 Multilevel Support Strategies and Closed/Maximal Lattice Summary
When mining association rules across multiple concept hierarchy levels, using a single uniform minimum support threshold across all levels is simple but problematic: high-level items (e.g., Beverages) easily pass a 5% threshold, whereas specific items (e.g., Organic Green Tea) fall below 5% and are missed; conversely, lowering uniform support to 0.5% floods Level 1 with trivial rules. Consequently, practical systems apply reduced minimum support at deeper levels (e.g., 5% at Level 1, 2% at Level 2, 0.5% at Level 3) or group-based support tailored to item frequency. Similarly, selecting between All Frequent, Closed, and Maximal itemsets trades compactness against exact support retention:
| Representation | Formal Definition | Support Information Retained? | Relative Set Size |
|---|---|---|---|
| All Frequent Itemsets | Every itemset X with support(X) ≥ min_sup | Yes (exact support stored for all) | Largest (exponential in pattern length) |
| Closed Frequent Itemsets | Frequent X with no superset Y ⊃ X having support(Y) = support(X) | Yes (lossless—all subset supports recoverable) | Medium (10×–100× smaller on dense data) |
| Maximal Frequent Itemsets | Frequent X with no frequent superset Y ⊃ X | No (only membership known, not exact count) | Smallest (compact boundary set) |
Module III: Classification
Chapter 7: General Approach to Classification and Prediction
7.1 Supervised Learning, Classification vs. Prediction, and Model Evaluation
Classification is a two-step supervised learning process that assigns unseen data objects to discrete, predefined categorical class labels. In the Learning (Training) Step, a classification algorithm analyzes a training set of tuples whose class labels are already known, inducing a mathematical or logical model (such as a decision tree, conditional probability table, or rule set) expressed as y = f(X). In the Classification (Testing) Step, the learned model predicts class labels for an independent test set whose true labels are withheld during prediction and revealed afterward to estimate generalization accuracy—ensuring the model has not merely memorized training noise (overfitting).
While classification predicts discrete unordered labels (e.g., Spam vs. Ham, Approve vs. Reject), prediction (regression) models continuous-valued functions to forecast numeric outcomes (e.g., house price in lakhs or customer lifetime value). Comparing candidate classifiers requires balancing five criteria: Predictive Accuracy (correctness on unseen tuples), Speed (training and inference latency), Robustness (resilience to noise and missing values), Scalability (efficiency on disk-resident big data), and Interpretability (human understandability of learned rules).
Evaluating classifier quality goes beyond raw accuracy, especially on imbalanced datasets (such as 1% fraud detection). Outcomes are tabulated in a Confusion Matrix counting True Positives (TP), True Negatives (TN), False Positives (FP), and False Negatives (FN):
- TP / TN: Correctly predicted positive and negative instances, respectively.
- FP / FN: Type I error (false alarm) and Type II error (missed positive), respectively.
- F1-Score: Harmonic mean balancing Precision (exactness) and Recall (completeness/sensitivity).
Reliable estimation uses Holdout (typically 70% train / 30% test), Random Subsampling (repeating holdout k times and averaging accuracy), Stratified k-Fold Cross-Validation (partitioning data into k equal folds preserving class ratios, training on k − 1 folds and testing on the remaining fold across k rounds—standard k = 10), Leave-One-Out (LOOCV) (where k = N for tiny datasets), or .632 Bootstrap sampling (sampling N tuples with replacement). Receiver Operating Characteristic (ROC) curves plot True Positive Rate (Recall) against False Positive Rate (1 − Specificity) across decision thresholds, summarized by Area Under the Curve (AUC, where 1.0 is perfect discrimination and 0.5 is random guessing).
Worked Numerical Example (Confusion Matrix & Evaluation Metrics): Suppose a fraud-detection classifier evaluates 200 test transactions and produces: TP = 36 (fraud caught), FN = 4 (fraud missed), FP = 10 (legitimate flagged as fraud), TN = 150 (legitimate cleared). Total predictions = 36 + 4 + 10 + 150 = 200. Computing metrics: Accuracy = (36 + 150) / 200 = 186 / 200 = 93.0%; Error Rate = (4 + 10) / 200 = 7.0%; Precision = 36 / (36 + 10) = 36 / 46 = 78.3%; Recall (Sensitivity) = 36 / (36 + 4) = 36 / 40 = 90.0%; Specificity = 150 / (150 + 10) = 150 / 160 = 93.75%; and F1-Score = (2 × 0.783 × 0.900) / (0.783 + 0.900) = 1.4094 / 1.683 = 0.837.
| Classifier Family | Learning Paradigm | Interpretability | Key Strength & Limitation |
|---|---|---|---|
| Decision Trees (ID3/C4.5/CART) | Eager (Divide & Conquer) | High (visual flowchart rules) | Fast, handles mixed types; prone to overfitting without pruning. |
| Naïve Bayes | Eager (Probabilistic) | Moderate (feature likelihoods) | Extremely fast, handles high dimensions; assumes feature independence. |
| K-Nearest Neighbour (KNN) | Lazy (Instance-based) | Moderate (example-based) | Zero training cost, non-linear boundaries; slow inference, sensitive to scale. |
| Rule-Based (RIPPER/CN2) | Eager (Sequential Covering) | Very High (IF-THEN rules) | Compact modular rules; greedy search may miss global interactions. |
Chapter 8: Decision Tree Induction (ID3, C4.5, and CART)
8.1 Tree Architecture and Attribute Selection Measures
A Decision Tree is a flowchart-like hierarchical classifier where each internal node tests an attribute, each branch represents an outcome of the test, and each leaf node holds a predicted class label. Decision tree induction algorithms (Hunt's algorithm, ID3, C4.5, and CART) construct trees top-down in a greedy, recursive divide-and-conquer manner without backtracking. At each node, the algorithm selects the attribute that best separates the training tuples into pure, homogeneous class partitions using an Attribute Selection Measure (ASM).
- Info(D): Shannon entropy (expected information in bits) needed to classify a tuple in dataset D across m classes with probabilities pi.
- InfoA(D): Weighted average entropy after partitioning D into v subsets D1, …, Dv using attribute A.
- Gain(A): Information Gain—reduction in entropy achieved by branching on attribute A; the attribute maximizing Gain(A) is chosen.
Because Information Gain is biased toward attributes with many distinct values (such as a unique Customer_ID), C4.5 normalizes Gain(A) by to compute Gain Ratio = Gain(A) / SplitInfoA(D). Meanwhile, CART (Classification and Regression Trees) constructs strictly binary trees using the Gini Index: , selecting the binary split that minimizes weighted impurity GiniA(D) (maximizing ΔGini(A)).
Worked Numerical Example (ID3 Information Gain): Suppose a training dataset D of 10 loan applications has 6 Approved (Yes) and 4 Rejected (No) records. Parent entropy is Info(D) = −(6/10)log2(6/10) − (4/10)log2(4/10) = −0.6(−0.737) − 0.4(−1.322) = 0.971 bits. Consider splitting on attribute Credit_Rating with two values: Good (6 tuples: 5 Yes, 1 No) and Fair (4 tuples: 1 Yes, 3 No). Here, Info(DGood) = −(5/6)log2(5/6) − (1/6)log2(1/6) = 0.650 bits, and Info(DFair) = −(1/4)log2(1/4) − (3/4)log2(3/4) = 0.811 bits. The expected entropy after splitting is InfoCredit(D) = (6/10)(0.650) + (4/10)(0.811) = 0.390 + 0.324 = 0.714 bits. Therefore, Gain(Credit_Rating) = 0.971 − 0.714 = 0.257 bits. Computing Gain for all candidate attributes identifies the optimal root split.
Worked Numerical Example (C4.5 Gain Ratio & CART Gini Index): Continuing the 10-tuple loan dataset (6 Yes, 4 No) split on Credit_Rating (6 Good: 5 Yes, 1 No; 4 Fair: 1 Yes, 3 No). For C4.5 Gain Ratio, SplitInfoCredit(D) = −(6/10)log2(6/10) − (4/10)log2(4/10) = 0.971 bits, yielding GainRatio(Credit_Rating) = 0.257 / 0.971 = 0.265. For CART Gini Index, parent impurity is Gini(D) = 1 − ((6/10)2 + (4/10)2) = 1 − (0.36 + 0.16) = 0.480. After splitting: Gini(DGood) = 1 − ((5/6)2 + (1/6)2) = 1 − (26/36) = 0.278; Gini(DFair) = 1 − ((1/4)2 + (3/4)2) = 1 − (10/16) = 0.375. Weighted impurity is GiniCredit(D) = (6/10)(0.278) + (4/10)(0.375) = 0.167 + 0.150 = 0.317, giving impurity reduction ΔGini = 0.480 − 0.317 = 0.163. For continuous attributes (such as Income), C4.5 sorts distinct values and evaluates binary split thresholds at midpoints (vi + vi+1)/2.
8.2 Tree Pruning and Overfitting Prevention
Unconstrained decision trees grow deep branches that fit isolated outliers and noise, harming test-set accuracy (overfitting). Pre-pruning halts tree growth early if information gain, Gini reduction, or node sample count falls below a threshold, though selecting an overly strict threshold risks underfitting. Post-pruning grows a full tree first and then removes unreliable subtrees bottom-up—replacing them with leaf nodes labeled by the majority class—using Cost-Complexity Pruning (balancing training error against tree leaf count via complexity parameter α) or Pessimistic Error Pruning (adding a continuity correction to node error rates without requiring a separate validation set). For massive disk-resident datasets, scalable induction algorithms such as SLIQ, SPRINT, RainForest (maintaining compact Attribute-Value-Class AVC-sets in memory), and BOAT build trees without holding all records in RAM.
| Attribute Selection Measure | Algorithm | Splitting Criterion | Key Bias & Remedy |
|---|---|---|---|
| Information Gain | ID3 | Maximizes entropy reduction Gain(A) | Biased toward multi-valued attributes (e.g., IDs). |
| Gain Ratio | C4.5 | Maximizes Gain(A) / SplitInfoA(D) | Corrects multi-value bias; prefers unbalanced splits if SplitInfo is tiny. |
| Gini Index | CART | Minimizes weighted binary impurity GiniA(D) | Biased toward multi-valued attributes; favors equal-sized binary splits. |
8.3 Handling Continuous Attributes, Missing Values, and Bias-Variance Tradeoff
Decision tree induction handles continuous numeric attributes (such as Income or Age) by sorting distinct observed values in ascending order and evaluating candidate binary split points at adjacent midpoints (ai + ai+1)/2 whenever the class label changes. During classification of a tuple with a missing attribute value, C4.5 routes the instance fractionally down all outgoing branches weighted by the observed training frequencies of each branch and aggregates the resulting leaf class probabilities. Understanding classifier generalization also requires balancing the Bias-Variance Tradeoff: overly simple models (such as heavily pruned 1-level stumps) exhibit high bias and miss true non-linear patterns (underfitting), whereas overly deep unpruned trees exhibit high variance and memorize random training noise (overfitting), achieving near-zero training error while failing on unseen test records.
Chapter 9: Bayesian Classification, K-Nearest Neighbours, and Rule-Based Methods
9.1 Naïve Bayesian Classification and Laplace Smoothing
Bayesian Classifiers are statistical models grounded in Bayes' Theorem, predicting class membership probabilities for an unseen feature vector X = (x1, x2, …, xn). Because estimating full joint likelihoods P(X | Ci) across high-dimensional spaces is computationally intractable, the Naïve Bayesian Classifier introduces the class-conditional independence assumption: given class label Ci, all attributes are assumed conditionally independent of one another.
- P(Ci | X): Posterior probability that tuple X belongs to class Ci; the class maximizing P(X | Ci)P(Ci) is predicted.
- P(Ci): Prior probability of class Ci estimated from training class frequencies.
- P(xk | Ci): Conditional likelihood of attribute value xk given class Ci (modeled via frequency counts for nominal attributes or Gaussian probability density for continuous attributes).
If an attribute value xk never appears alongside class Ci in the training set, its conditional likelihood P(xk | Ci) = 0 would wipe out the entire product! Laplacian Correction (Laplace Smoothing) prevents this zero-probability collapse by adding 1 to every numerator count and adding v (the number of distinct values for that attribute) to the denominator: . For continuous numeric attributes (such as Income or Age), Naïve Bayes models class-conditional likelihoods using the Gaussian Probability Density Function parameterized by class mean μCi and standard deviation σCi:
- μCi, σCi: Sample mean and standard deviation of continuous attribute xk computed strictly across training tuples belonging to class Ci.
Worked Numerical Example (Gaussian Naïve Bayes for Continuous Attributes): Suppose for class Pass, exam scores have mean μ = 75 and standard deviation σ = 10; for class Fail, mean μ = 45 and σ = 10. A student scores x = 68. Evaluating the Gaussian density: for Pass, P(68 | Pass) = (1 / (√(2π) × 10)) × exp(−(68 − 75)2 / (2 × 100)) = 0.03989 × exp(−0.245) = 0.03989 × 0.7827 = 0.0312. For Fail, P(68 | Fail) = 0.03989 × exp(−(68 − 45)2 / 200) = 0.03989 × exp(−2.645) = 0.03989 × 0.0710 = 0.0028. Even with equal priors, the posterior odds favor Pass by more than 11-to-1.
Worked Numerical Example (Naïve Bayes): Using the same 10 loan applications (6 Yes, 4 No), prior probabilities are P(Yes) = 0.6 and P(No) = 0.4. Suppose for Income = High, 4 of 6 Approved and 1 of 4 Rejected have High income: P(High | Yes) = 4/6 = 0.667, P(High | No) = 1/4 = 0.25. For Credit = Good, P(Good | Yes) = 5/6 = 0.833, P(Good | No) = 1/4 = 0.25. For a new applicant X = (Income=High, Credit=Good): Likelihood(Yes) = 0.667 × 0.833 × 0.6 = 0.333; Likelihood(No) = 0.25 × 0.25 × 0.4 = 0.025. Since 0.333 > 0.025, Naïve Bayes predicts Approved (Yes) with normalized posterior 0.333 / (0.333 + 0.025) = 93.0%.
9.2 K-Nearest Neighbour (KNN) Classification
Unlike decision trees or Naïve Bayes—which are eager learners that construct an explicit global model before seeing test data—K-Nearest Neighbour (KNN) is a lazy learner (instance-based learner) that simply stores training tuples and defers computation until a test tuple X arrives. Given a query X, KNN computes the distance (typically Euclidean or Manhattan after Min-Max/Z-score normalization so large-scale attributes do not dominate) to all stored training records, selects the k closest neighbours, and assigns the majority class (or distance-weighted vote wi = 1 / d(X, Xi)2 so closer neighbours exert stronger influence). Choosing k too small (e.g., k = 1) makes predictions sensitive to noise, whereas choosing k too large blurs local class boundaries; odd values of k avoid ties in binary classification. In very high dimensions, KNN suffers from the curse of dimensionality as pairwise distances converge, and large training stores use spatial indexing (KD-Trees or Ball-Trees) to accelerate neighbour lookup.
Worked Numerical Example (KNN Classification): Consider 4 normalized training points (x1, x2, Class): P1 = (0.2, 0.3, Fail), P2 = (0.4, 0.5, Fail), P3 = (0.7, 0.8, Pass), P4 = (0.8, 0.6, Pass). Classify query Q = (0.6, 0.7) using k = 3 and Euclidean distance: d(Q, P1) = √(0.42 + 0.42) = 0.566; d(Q, P2) = √(0.22 + 0.22) = 0.283; d(Q, P3) = √(0.12 + 0.12) = 0.141; d(Q, P4) = √(0.22 + 0.12) = 0.224. The 3 nearest neighbours are P3 (0.141, Pass), P4 (0.224, Pass), and P2 (0.283, Fail). By 2-to-1 majority vote, Q is classified as Pass.
9.3 Rule-Based Classification and WEKA Classification Labs (Exercises 7 & 8)
Rule-Based Classifiers represent knowledge as human-readable IF condition THEN conclusion rules. Each rule R is evaluated by its Coverage (ncovers / |D|, fraction of tuples satisfying the antecedent) and Accuracy (ncorrect / ncovers, fraction of covered tuples matching the consequent class). Rules can be extracted directly by tracing every root-to-leaf path in a decision tree—producing mutually exclusive and exhaustive rules—or learned directly from data using Sequential Covering algorithms (such as RIPPER, CN2, and FOIL) that learn one rule at a time via FOIL information gain, prune redundant conjuncts, remove covered positive tuples, and iterate. When multiple rules fire simultaneously for a test tuple, conflict resolution applies either size ordering (highest-specificity rule with most antecedent tests wins), class-based ordering, or rule-based ordering (ordered priority list with a default fallback rule).
Worked Numerical Example (Rule Coverage, Accuracy & Tree-to-Rule Extraction): Suppose a pruned loan decision tree yields the root-to-leaf rule R1: IF (Credit_Rating = Good) AND (Income = High) THEN Loan = Approved. Across a dataset D of 100 applicants, 30 applicants satisfy both conditions (ncovers = 30), and of those 30, 27 are genuinely Approved (ncorrect = 27). Thus, Coverage(R1) = 30 / 100 = 30%, and Accuracy(R1) = 27 / 30 = 90%. In Sequential Covering (RIPPER), once R1 is accepted, those 27 covered positive tuples are removed from the working training set before searching for R2, ensuring subsequent rules focus exclusively on remaining uncovered positive cases. To further boost generalization and reduce variance on complex classification boundaries, modern workflows also combine multiple base learners via Ensemble Methods—such as Bagging / Random Forests (training parallel trees on bootstrap samples and random feature subsets) and Boosting (AdaBoost) (sequentially reweighting misclassified tuples).
| Evaluation / Validation Protocol | Partitioning Mechanism | Bias & Variance Profile | Recommended Scenario |
|---|---|---|---|
| Holdout Method | Single random split (e.g., 70% train / 30% test). | High variance if dataset is small. | Very large datasets (> 100,000 tuples). |
| Stratified k-Fold CV | k equal class-balanced folds; k−1 train, 1 test (k rounds). | Low bias, low variance (standard k = 10). | Medium datasets and imbalanced classes. |
| Leave-One-Out (LOOCV) | Special case k = N (N−1 train, 1 test). | Nearly zero bias, high computational cost. | Tiny clinical or laboratory datasets. |
| .632 Bootstrap | Samples N tuples with replacement; out-of-bag (~36.8%) tests. | Optimistic bias corrected by 0.632/0.368 weighting. | Small datasets needing tight error bounds. |
In WEKA (Practical Exercises 7 & 8), open the clean dataset under Preprocess, switch to the Classify tab, choose trees → J48 (WEKA's C4.5 implementation) or bayes → NaiveBayes, select Cross-validation Folds = 10, and click Start. WEKA outputs overall accuracy, Kappa statistic, per-class Precision/Recall/F-Measure, ROC Area, and the full Confusion Matrix; right-clicking the J48 result entry and selecting Visualize tree renders the pruned decision tree.
# Exercise 7: Decision Tree Induction (J48 / C4.5) with 10-fold CV java weka.classifiers.trees.J48 \ -C 0.25 -M 2 -t loan_data.arff # Exercise 8: Naive Bayes Classification with 10-fold Cross-Validation java weka.classifiers.bayes.NaiveBayes \ -t loan_data.arff
Chapter 10: Complete Decision Tree Case Study, SVM Overview, and Ensemble Methods
10.1 Full Multi-Attribute Root Split Selection (14-Tuple Electronics Dataset)
To illustrate full top-down tree induction across competing candidate attributes, consider the classic 14-tuple AllElectronics customer dataset predicting buys_computer (9 Yes, 5 No). Parent dataset entropy is Info(D) = −(9/14)log2(9/14) − (5/14)log2(5/14) = 0.940 bits. Evaluating the four candidate attributes yields the exact root-selection table below:
| Candidate Attribute | Partitioned Subsets (Yes, No) | Expected Entropy InfoA(D) | Information Gain Gain(A) | Root Selection Decision |
|---|---|---|---|---|
| Age | Youth (2,3), Middle (4,0), Senior (3,2) | (5/14)(0.971) + (4/14)(0) + (5/14)(0.971) = 0.694 | 0.940 − 0.694 = 0.246 bits | Selected as Root Node (Highest Gain) |
| Income | High (2,2), Medium (4,2), Low (3,1) | (4/14)(1.000) + (6/14)(0.918) + (4/14)(0.811) = 0.911 | 0.940 − 0.911 = 0.029 bits | Deferred to deeper branches |
| Student | Yes (6,1), No (3,4) | (7/14)(0.592) + (7/14)(0.985) = 0.789 | 0.940 − 0.789 = 0.151 bits | Used under Age = Youth branch |
| Credit_Rating | Fair (6,2), Excellent (3,3) | (8/14)(0.811) + (6/14)(1.000) = 0.892 | 0.940 − 0.892 = 0.048 bits | Used under Age = Senior branch |
Because Age = Middle-Aged contains 4 Yes and 0 No tuples (entropy = 0.000), that branch immediately terminates in a pure leaf node Yes. The remaining branches (Age = Youth and Age = Senior) recurse on the remaining attributes, splitting on Student and Credit_Rating respectively to form a compact 5-leaf decision tree.
10.2 Support Vector Machines (SVM) and Ensemble Classification Methods
Beyond trees, Bayes, KNN, and rules, modern data mining employs Support Vector Machines (SVM) and Ensemble Learning to achieve state-of-the-art generalization on complex, high-dimensional datasets. An SVM finds the Maximum Marginal Hyperplane (MMH) separating two classes with the widest possible geometric margin between the closest boundary training points (called support vectors). When classes are not linearly separable in input space, SVMs apply the Kernel Trick (using Polynomial or Radial Basis Function RBF kernels) to map vectors implicitly into a higher-dimensional feature space where a linear separator exists.
Ensemble Methods combine predictions from multiple diverse base classifiers to outperform any single constituent model:
| Ensemble Strategy | Training Mechanism | Aggregation Rule | Primary Error Reduction |
|---|---|---|---|
| Bagging (Bootstrap Aggregating) | Trains k independent models on bootstrap samples drawn with replacement. | Uniform majority vote (or average). | Reduces Variance (stabilizes unstable trees). |
| Random Forest | Bagging + random subset of m ≈ √p features tested at each tree split. | Majority vote across decorrelated trees. | Reduces Variance & prevents dominant-feature correlation. |
| Boosting (AdaBoost) | Trains models sequentially; increases weights on previously misclassified tuples. | Accuracy-weighted majority vote. | Reduces Bias (focuses on hard boundary cases). |
Chapter 11: Regression Prediction, Multiclass Strategies, and Imbalanced Data
11.1 Linear Regression and Logistic Regression for Prediction
While classification predicts discrete categorical labels, numeric prediction estimates continuous real-valued outputs using Linear Regression, which models a dependent target Y as a linear function of predictor X (simple regression: $) or multiple predictors (multiple regression). Parameters w0 (intercept) and w1 (slope) are fitted via the Method of Least Squares minimizing the sum of squared residuals:
- w1, w0: Estimated slope and y-intercept minimizing squared error ∑(yi − ŷi)2.
- P(Y = 1 | X): Logistic Regression sigmoid output mapping any real linear combination into a calibrated probability in (0, 1).
Worked Numerical Example (Simple Linear Regression): Consider 4 students' study hours (X) and exam scores (Y): (2, 50), (4, 60), (6, 70), (8, 80). Means are x̄ = 5.0 and ȳ = 65.0. Numerator ∑(xi − 5)(yi − 65) = (−3)(−15) + (−1)(−5) + (1)(5) + (3)(15) = 45 + 5 + 5 + 45 = 100. Denominator ∑(xi − 5)2 = 9 + 1 + 1 + 9 = 20. Thus w1 = 100 / 20 = 5.0, and w0 = 65 − 5(5) = 40.0, giving predictive equation Y = 40 + 5X. For a student studying 7 hours, predicted score is 40 + 5(7) = 75.0.
11.2 Multiclass Classification and Handling Imbalanced Datasets
When a classification task involves m > 2 classes (e.g., Low, Medium, High risk), binary algorithms such as SVMs or logistic regression generalize via two decomposition schemes: One-vs-All (OvA / One-vs-Rest), which trains m binary classifiers (each separating class Ci from all other classes combined) and picks the highest confidence score; and One-vs-One (OvO), which trains m(m − 1)/2 pairwise classifiers and assigns the class winning the most pairwise votes.
In real-world fraud, medical, and intrusion datasets, the positive class often represents fewer than 1–5% of records (class imbalance). A naive classifier predicting the majority class everywhere achieves 99% accuracy while missing 100% of positive cases! Analysts remediate class imbalance through four strategies: (1) Random Oversampling (duplicating minority tuples); (2) SMOTE (Synthetic Minority Over-sampling Technique) (interpolating synthetic minority instances along line segments connecting k-nearest minority neighbors); (3) Random Undersampling (subsampling the majority class); and (4) Cost-Sensitive Learning (assigning a higher misclassification penalty to False Negatives than False Positives inside the loss matrix and decision threshold).
| Imbalance Strategy | Mechanism | Primary Advantage | Key Risk |
|---|---|---|---|
| Random Oversampling | Replicates existing minority class records. | Retains all majority information. | Increases overfitting on duplicated minority points. |
| SMOTE | Synthesizes new minority points between k neighbors. | Broadens minority decision region smoothly. | May generate noisy points across overlapping boundaries. |
| Random Undersampling | Discards random majority class tuples. | Dramatically speeds up training on huge data. | May discard informative majority boundary records. |
| Cost-Sensitive Matrix | Weights FN penalty ≫ FP penalty during induction. | Directly optimizes business/clinical risk cost. | Requires domain experts to specify relative error costs. |
11.3 Interpreting WEKA Classifier Outputs (Kappa Statistic & Error Metrics)
When running J48 or NaiveBayes in WEKA under 10-fold cross-validation, the summary panel reports several diagnostic statistics alongside overall accuracy. The Kappa Statistic (κ) measures agreement between predicted and true labels adjusted for random chance agreement: , where po is observed accuracy and pe is expected random-chance accuracy from row and column marginals (κ > 0.75 indicates excellent agreement, 0.40–0.75 fair-to-good, and 0 no better than chance). WEKA also reports Mean Absolute Error (MAE) and Root Mean Squared Error (RMSE) over predicted class probabilities, TP Rate (Recall), FP Rate, F-Measure, MCC (Matthews Correlation Coefficient), and ROC Area (AUC) per class, enabling rigorous side-by-side model selection.
Worked Numerical Example (Kappa Statistic): Suppose a binary confusion matrix on 100 test tuples has TP = 45, TN = 35, FP = 10, FN = 10. Observed accuracy is po = (45 + 35)/100 = 0.80. Actual totals: Pos = 55, Neg = 45; Predicted totals: Pos = 55, Neg = 45. Chance agreement is pe = (55/100)(55/100) + (45/100)(45/100) = 0.3025 + 0.2025 = 0.505. Therefore, κ = (0.80 − 0.505) / (1 − 0.505) = 0.295 / 0.495 = 0.596 (moderate-to-substantial agreement beyond chance).
11.4 Neural Network Classifiers (Backpropagation) and Model Deployment
For complex non-linear boundaries in vision, speech, and tabular fraud detection, Multilayer Perceptron (MLP) Neural Networks connect an input layer of normalized features through one or more hidden layers of weighted neurons with non-linear activation functions (such as Sigmoid or ReLU) to an output layer predicting class probabilities. Training proceeds via Backpropagation: (1) feed each training tuple forward to compute predicted output ŷ; (2) measure prediction error against true label y; and (3) propagate error gradients backward from the output layer to hidden layers using the chain rule, updating connection weights wij ← wij − η(∂E/∂wij) via stochastic gradient descent with learning rate η. Once validated and deployed to production, classifiers require continuous monitoring for concept drift—gradual shifts in underlying feature or class distributions over time that necessitate periodic retraining.
11.5 Practical Classifier Selection Matrix
When designing a production classification pipeline, practitioners select an algorithm by matching dataset dimensionality, sample size, feature types, and interpretability requirements:
| Problem Profile | Top Classifier Choice | Primary Reason |
|---|---|---|
| Audit / Regulatory Explainability | J48 (C4.5) or RIPPER Rules | Produces transparent human-readable IF-THEN rules. |
| High-Dimensional Text / Spam | Naïve Bayes / Linear SVM | Scales linearly with thousands of sparse TF-IDF terms. |
| Non-Linear Tabular Accuracy | Random Forest / Gradient Boosting | Captures complex feature interactions with low variance. |
| Low-Latency Edge / Streaming | Naïve Bayes / Hoeffding Tree | Constant-time O(p) inference and incremental updates. |
Module IV: Cluster Analysis: Basic Concepts and Methods
Chapter 10: Cluster Analysis Foundations and Taxonomy of Methods
10.1 Definition, Characteristics, and Requirements of Cluster Analysis
Cluster Analysis is an unsupervised learning methodology that partitions a collection of unlabeled data objects into meaningful groups called clusters such that objects within the same cluster exhibit high intra-cluster similarity while objects in different clusters exhibit low inter-cluster similarity. Unlike classification, clustering requires no pre-assigned class labels; instead, it discovers natural groupings directly from attribute proximity. Clustering serves both as a standalone exploratory tool (e.g., customer segmentation, gene co-expression discovery) and as a preprocessing step for summarization, compression, and outlier detection.
To operate effectively on real-world repositories, a clustering algorithm must satisfy nine key requirements: (1) Scalability to millions of records; (2) Ability to deal with diverse attribute types (numeric, binary, nominal, ordinal, mixed); (3) Discovery of clusters with arbitrary shapes (not merely spherical balls); (4) Minimal domain knowledge for input parameters (avoiding brittle sensitivity to user-guessed thresholds); (5) Robustness to noise and outliers; (6) Insensitivity to the input order of records; (7) Capability to handle high-dimensional spaces; (8) Support for user-specified domain constraints; and (9) Interpretability and usability of resulting clusters.
10.2 Types of Data and Overview of Basic Clustering Methods
Cluster analysis accommodates interval-scaled, binary (symmetric/asymmetric), nominal, ordinal, ratio-scaled, and mixed-type variables organized in an n × p data matrix or n × n dissimilarity matrix. Because interval-scaled attributes measured in different units (e.g., salary in rupees vs. age in years) would distort Euclidean distances, clustering pipelines standardize values using Mean Absolute Deviation (sf), which is more robust to outliers than standard deviation: and . For ratio-scaled variables that grow exponentially (such as bacterial counts or web traffic), a logarithmic transformation converts multiplicative growth into additive intervals before standardization. Modern clustering algorithms fall into four major paradigms:
| Clustering Paradigm | Core Mechanism | Cluster Shapes | Representative Algorithms |
|---|---|---|---|
| Partitioning Methods | Divides n objects into k partitions optimizing an objective criterion (e.g., SSE) via iterative relocation. | Convex / Spherical | K-Means, K-Medoids (PAM), CLARA, CLARANS |
| Hierarchical Methods | Builds a nested tree of clusters (dendrogram) either bottom-up (agglomerative) or top-down (divisive). | Nested / Arbitrary (linkage-dependent) | AGNES, DIANA, BIRCH, Chameleon |
| Density-Based Methods | Grows clusters wherever object density exceeds a threshold within a neighborhood radius, separating sparse noise. | Arbitrary (non-convex, elongated) | DBSCAN, OPTICS, DENCLUE |
| Grid-Based Methods | Quantizes the object space into a finite number of multi-resolution rectangular cells and clusters dense cells. | Axis-aligned / Subspace | STING, CLIQUE |
Chapter 11: Partitioning, Hierarchical, Density-Based, and Grid-Based Algorithms
11.1 K-Means and K-Medoids (PAM)
K-Means is the most widely deployed centroid-based partitioning algorithm. Given a user-specified number of clusters k, K-Means randomly selects k initial centroids and alternates between two steps until convergence: (1) Assignment Step—assign every data point x to the cluster whose centroid μi minimizes Euclidean distance; and (2) Update Step—recompute each centroid as the arithmetic mean of all points currently assigned to that cluster. K-Means minimizes the within-cluster Sum of Squared Errors (SSE):
- Ci, μi: The i-th cluster and its arithmetic mean centroid in K-Means.
- oi: The actual representative data object (medoid) of cluster Ci in K-Medoids (PAM).
- EPAM: Total absolute-error cost summed across all non-medoid objects p and their nearest medoid oi.
Worked Numerical Example (K-Means 1D Clustering): Consider points {2, 4, 10, 12, 3, 20, 30, 11, 25} with k = 2 and initial centroids μ1 = 2, μ2 = 20. Iteration 1 Assignment: Points closer to 2 are C1 = {2, 4, 10, 3, 11} (since |11 − 2| = 9 ≤ |11 − 20| = 9), and points closer to 20 are C2 = {12, 20, 30, 25}. Update: New centroids become μ1 = (2+4+10+3+11)/5 = 6.0 and μ2 = (12+20+30+25)/4 = 21.75. Iteration 2 Assignment: Midpoint is (6 + 21.75)/2 = 13.875, so C1 = {2, 4, 10, 12, 3, 11} and C2 = {20, 30, 25}. Update: μ1 = 42/6 = 7.0 and μ2 = 75/3 = 25.0. Iteration 3: Midpoint is 16.0; cluster memberships do not change, so K-Means converges cleanly.
While K-Means runs in O(tkn) time, it is sensitive to initial centroid placement (mitigated by K-Means++, which chooses subsequent initial centroids with probability proportional to squared distance D(x)2 from existing centroids), vulnerable to outliers that skew the mean, limited to numeric attributes, and unable to capture non-convex shapes. K-Medoids (PAM — Partitioning Around Medoids) overcomes outlier sensitivity by selecting actual dataset objects (medoids) rather than virtual means and iteratively testing swaps between a current medoid oj and a non-medoid orandom whenever total absolute-error cost EPAM decreases. To scale PAM (which costs O(k(n−k)2) per iteration) to large datasets, CLARA (Clustering LARge Applications) runs PAM on multiple fixed-size random samples, while CLARANS performs randomized graph search restricting the number of examined neighbor swaps.
Worked Numerical Example (K-Medoids vs. K-Means Robustness): Consider 1D points {1, 2, 3, 9, 10, 100} partitioned into k = 2 clusters. In K-Means, if the second cluster contains {9, 10, 100}, its mean centroid shifts dramatically to (9 + 10 + 100)/3 = 39.67—far from the dense core {9, 10}. In K-Medoids (PAM), choosing medoid o2 = 10 gives cluster cost |9 − 10| + |10 − 10| + |100 − 10| = 1 + 0 + 90 = 91; swapping to o2 = 9 gives |10 − 9| + |100 − 9| = 92 (worse), and swapping to o2 = 100 gives |9 − 100| + |10 − 100| = 181 (much worse). Thus PAM keeps the medoid anchored at 10, completely resisting the outlier 100.
11.2 Hierarchical, Density-Based (DBSCAN), and Grid-Based Clustering
Hierarchical Clustering constructs a multi-level tree called a dendrogram, allowing analysts to cut the tree at any height without committing to a fixed k upfront. Agglomerative (bottom-up, AGNES) starts with each object as a singleton cluster and repeatedly merges the two closest clusters until one root remains; Divisive (top-down, DIANA) starts with one all-encompassing cluster and recursively splits the most heterogeneous cluster. Inter-cluster distance is governed by linkage criteria: Single-Linkage (minimum pairwise distance—captures elongated shapes but suffers from chaining), Complete-Linkage (maximum pairwise distance—produces compact spheres), Average-Linkage (mean pairwise distance), and Ward's Method (minimizing SSE increase). BIRCH summarizes dense regions into compact Clustering Feature tuples CF = (N, LS, SS) inside a height-balanced CF-Tree, while Chameleon uses a k-nearest-neighbor graph partitioned by hMetis and merged via relative interconnectivity and relative closeness.
Worked Numerical Example (Agglomerative Linkage): Suppose Cluster A = {1, 3} and Cluster B = {6, 10}. Pairwise distances are |1−6|=5, |1−10|=9, |3−6|=3, |3−10|=7. Under Single-Linkage, dmin(A, B) = min(5, 9, 3, 7) = 3.0. Under Complete-Linkage, dmax(A, B) = max(5, 9, 3, 7) = 9.0. Under Average-Linkage, davg(A, B) = (5 + 9 + 3 + 7)/4 = 6.0.
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) discovers arbitrarily shaped clusters and isolates outliers using two parameters: neighborhood radius ϵ and minimum points MinPts. A point p is a core point if its ϵ-neighborhood Nϵ(p) contains at least MinPts objects; a border point lies within ϵ of a core point but has fewer than MinPts neighbors itself; any point that is neither core nor border is classified as noise. Clusters grow by linking core points that are density-reachable or density-connected. OPTICS eliminates DBSCAN's sensitivity to a single global ϵ by ordering points into a reachability plot that reveals nested density clusters, while DENCLUE models point density via smooth Gaussian kernel influence functions. Grid-based methods like STING store statistical summaries (count, mean, min, max) in hierarchical grid cells for O(K) query speed, while CLIQUE combines grid and density ideas for high-dimensional subspace clustering.
Worked Numerical Example (DBSCAN Point Classification): Consider 5 points on a line: A=1, B=2, C=3, D=5, E=10, with ϵ = 1.5 and MinPts = 3 (including the point itself). Neighborhood counts within distance 1.5: N(A) = {1, 2} (size 2); N(B) = {1, 2, 3} (size 3 ≥ MinPts → Core Point); N(C) = {2, 3} (size 2); N(D) = {5} (size 1); N(E) = {10} (size 1). Since A and C lie within ϵ = 1.5 of core point B, both A and C are Border Points belonging to Cluster 1 = {A, B, C}. Meanwhile, D and E have fewer than 3 neighbors and are not within ϵ of any core point, so both D and E are flagged as Noise (Outliers).
| Algorithm | Time Complexity | Requires k? | Handles Outliers & Arbitrary Shapes? |
|---|---|---|---|
| K-Means | O(t · k · n) | Yes | No (spherical clusters; sensitive to outliers). |
| K-Medoids (PAM) | O(k(n − k)2) | Yes | Resists outliers; still prefers convex shapes. |
| AGNES (Hierarchical) | O(n2) to O(n3) | No (cut dendrogram) | Single-linkage captures non-convex; sensitive to chaining. |
| BIRCH | O(n) | Optional | Spherical micro-clusters via CF-Tree; scales to big data. |
| DBSCAN | O(n log n) with index | No (ϵ, MinPts) | Yes—discovers arbitrary shapes & isolates noise. |
| STING / CLIQUE | O(K) grid cells | No (grid resolution) | Fast spatial queries (STING); high-D subspaces (CLIQUE). |
Chapter 12: Cluster Validation, Outlier Detection, and WEKA Clustering Labs
12.1 Cluster Validation Metrics (Silhouette Coefficient & Purity)
Evaluating unsupervised clusters relies on internal validation (measuring compactness and separation without ground-truth labels) and external validation (comparing clusters against known reference labels via Purity or Rand Index). The most widely used internal metric is the Silhouette Coefficient for each object i:
- a(i): Average distance from object i to all other objects in the same cluster (cohesion; smaller is better).
- b(i): Minimum average distance from object i to all objects in any other cluster (separation; larger is better).
- s(i) ∈ [−1, +1]: Values near +1 indicate well-clustered objects; near 0 indicates boundary overlap; negative values indicate misassignment.
Worked Numerical Example (Silhouette Coefficient): If point x1 has average intra-cluster distance a(x1) = 1.5 and nearest-neighbor cluster distance b(x1) = 6.0, then s(x1) = (6.0 − 1.5) / max(1.5, 6.0) = 4.5 / 6.0 = +0.75, confirming strong cluster assignment. Before clustering, analysts may also compute the Hopkins Statistic to verify clustering tendency (distinguishing true clusters from uniform random noise).
12.2 Outlier Categories and Detection Methodologies
An outlier is a data object that deviates markedly from the remaining population, raising suspicion that it was generated by a different mechanism (such as credit card fraud, network intrusion, or faulty sensor hardware) rather than random variation. Outliers fall into three categories: Global (Point) Outliers (individual records far from the entire dataset), Contextual (Conditional) Outliers (values anomalous only within a specific context, such as 32°C in winter), and Collective Outliers (a group of individually normal events whose joint sequence is anomalous, such as repeated failed logins).
Four major outlier detection approaches are practiced: (1) Statistical / Distribution-Based—flagging points beyond μ ± 3σ (Z-score), outside [Q1 − 1.5×IQR, Q3 + 1.5×IQR], or via Grubb's test; (2) Proximity-Based—distance-based methods DB(p, D) (flagging points with fewer than fraction p of neighbors within radius D) and density-based LOF (Local Outlier Factor), which compares a point's local reachability density lrd(o) against its k-nearest neighbors' densities; (3) Clustering-Based—identifying points that do not belong to any dense cluster (DBSCAN noise), lie far from their assigned K-Means centroid, or form tiny isolated clusters; and (4) Classification-Based—training one-class Support Vector Machines around normal behavior.
- Nk(o): Set of k-nearest neighbors of object o.
- lrdk(o): Local reachability density of o (inverse of average reachability distance to its k neighbors).
- LOFk(o) ≈ 1: Object o has similar density to its neighbors (normal point); LOFk(o) ≫ 1 indicates o sits in a much sparser region than its neighbors (local outlier).
| Outlier Detection Method | Underlying Assumption | Strengths | Weaknesses |
|---|---|---|---|
| Parametric (Z-Score / Gaussian) | Data follows known normal distribution. | Mathematically fast O(n); zero tuning if Gaussian. | Fails on multimodal, skewed, or high-D data. |
| Non-Parametric (IQR / Histogram) | Normal points lie inside dense interquartile core. | Distribution-free; resists extreme skew. | Univariate only unless multivariate bins used. |
| Distance-Based DB(p, D) | Outliers lack close neighbors within radius D. | Works in arbitrary metric spaces. | Struggles when clusters have varying densities. |
| Density-Based (LOF) | Outliers have lower local density than neighbors. | Detects local anomalies near dense & sparse clusters. | O(n2) pairwise distance cost without spatial index. |
| Clustering-Based | Normal objects belong to large, tight clusters. | Discovers clusters & outliers simultaneously. | Sensitive to clustering parameter choices (k, ϵ). |
12.3 Practical WEKA Clustering & Outlier Workflows (Exercises 9 & 10)
In WEKA (Practical Exercises 9 & 10), load the normalized dataset under Preprocess, switch to the Cluster tab, and choose SimpleKMeans (configuring numClusters = 3 and EuclideanDistance), HierarchicalClusterer (inspecting dendrograms under Single/Complete linkage), or MakeDensityBasedClusterer. Click Ignore attributes if a class label is present, then click Start to inspect cluster centroids and Within-Cluster Sum of Squared Errors (SSE). To detect outliers (Exercise 10), apply the InterquartileRange filter under Preprocess—which appends binary Outlier and ExtremeValue flags—or inspect distance-to-centroid residuals.
# Exercise 9: K-Means Clustering (k = 3) java weka.clusterers.SimpleKMeans \ -N 3 -A "weka.core.EuclideanDistance" -t customer_data.arff # Exercise 10: Statistical Outlier Detection via InterquartileRange Filter java weka.filters.unsupervised.attribute.InterquartileRange \ -R first-last -O 3.0 -E 6.0 -i customer_data.arff -o outliers.arff
Chapter 13: 2D K-Means Trace, Hierarchical Matrix Merge, and Subspace Clustering
13.1 Complete 2D K-Means Worked Example (Two-Iteration SSE Trace)
To trace centroid movement and Sum of Squared Errors (SSE) convergence in two dimensions, consider 6 customer coordinate points (Annual_Income_Lakh, Spending_Score): P1(1, 1), P2(1.5, 2), P3(3, 4), P4(5, 7), P5(3.5, 5), P6(4.5, 5) with k = 2 and initial centroids μ1 = P1(1, 1) and μ2 = P4(5, 7):
| Point (x, y) | Dist to μ1(1, 1) | Dist to μ2(5, 7) | Iter 1 Cluster | Dist to New μ1(1.25, 1.5) | Dist to New μ2(4.0, 5.25) | Iter 2 Cluster |
|---|---|---|---|---|---|---|
| P1(1.0, 1.0) | 0.00 | 7.21 | C1 | 0.56 | 5.20 | C1 |
| P2(1.5, 2.0) | 1.12 | 6.10 | C1 | 0.56 | 4.10 | C1 |
| P3(3.0, 4.0) | 3.61 | 3.61 | C2 (tie-break) | 3.05 | 1.60 | C2 |
| P4(5.0, 7.0) | 7.21 | 0.00 | C2 | 6.66 | 2.02 | C2 |
| P5(3.5, 5.0) | 4.72 | 2.50 | C2 | 4.16 | 0.56 | C2 |
| P6(4.5, 5.0) | 5.32 | 2.06 | C2 | 4.78 | 0.56 | C2 |
After Iteration 1, C1 = {P1, P2} yields updated centroid μ1 = ((1+1.5)/2, (1+2)/2) = (1.25, 1.50), and C2 = {P3, P4, P5, P6} yields μ2 = ((3+5+3.5+4.5)/4, (4+7+5+5)/4) = (4.00, 5.25). Computing Iteration 2 distances confirms every point remains in its exact cluster, terminating K-Means with final SSE = (0.562 + 0.562) + (1.602 + 2.022 + 0.562 + 0.562) = 0.625 + 7.268 = 7.893.
13.2 High-Dimensional Subspace Clustering and Validation Summary
In datasets with dozens or hundreds of attributes, full-space Euclidean distances lose contrast as irrelevant dimensions dilute true cluster boundaries (the curse of dimensionality). Subspace Clustering algorithms such as CLIQUE discover dense clusters embedded inside lower-dimensional axis-parallel subspaces by partitioning each dimension into equal-width intervals, identifying dense 1D grid units, and applying an Apriori-like downward-closure property to merge adjacent dense k-dimensional cells. Complementary PROCLUS (Projected Clustering) assigns each cluster its own subset of relevant dimensions around medoids. Finally, practitioners validate unsupervised partitions using Purity (external agreement with ground-truth classes), Davies-Bouldin Index (ratio of intra-cluster scatter to inter-cluster separation—lower is better), and the Elbow Method (plotting SSE against k = 1, 2, …, 10 to locate the sharp inflection point).
Chapter 14: Agglomerative Matrix Trace, BIRCH CF-Trees, and External Validation
14.1 Step-by-Step Agglomerative Distance Matrix Trace (Single vs. Complete Linkage)
Consider four objects A, B, C, and D with symmetric pairwise Euclidean distance matrix: d(A,B) = 2, d(A,C) = 6, d(A,D) = 9, d(B,C) = 5, d(B,D) = 8, d(C,D) = 3. In Step 1, the minimum off-diagonal entry is d(A,B) = 2, so {A} and {B} merge into cluster {A, B} at dendrogram height 2.0. Next, we update distances between {A, B} and remaining singletons C and D:
| Merge Step | Single-Linkage (min) | Complete-Linkage (max) | Resulting Dendrogram Height |
|---|---|---|---|
| Step 1: Merge {A, B} | d({A,B}, C) = min(6, 5) = 5; d({A,B}, D) = min(9, 8) = 8 | d({A,B}, C) = max(6, 5) = 6; d({A,B}, D) = max(9, 8) = 9 | Height = 2.0 |
| Step 2: Merge {C, D} | min entry is d(C, D) = 3 < 5 | min entry is d(C, D) = 3 < 6 | Height = 3.0 |
| Step 3: Merge {A,B} & {C,D} | d({A,B}, {C,D}) = min(5, 8) = 5.0 | d({A,B}, {C,D}) = max(6, 9) = 9.0 | Single: 5.0 | Complete: 9.0 |
14.2 BIRCH Clustering Feature (CF) Additivity and External Validation (Purity)
To cluster millions of points in O(n) single-pass I/O time, BIRCH summarizes each micro-cluster by a compact triple CF = (N, LS, SS), where N is the point count, LS = ∑xi is the linear vector sum, and SS = ∑xi2 is the squared sum. Crucially, CF vectors obey the CF Additivity Theorem: merging two disjoint micro-clusters CF1 and CF2 simply adds their components: CF1 + CF2 = (N1 + N2, LS1 + LS2, SS1 + SS2), allowing centroids, radii, and diameters to be updated incrementally without re-reading raw points from disk.
When ground-truth class labels are available for benchmarking, Cluster Purity measures the fraction of objects belonging to the dominant class inside each cluster: . For example, if 100 records are grouped into 3 clusters whose majority class counts are 28, 35, and 27 respectively, then Purity = (28 + 35 + 27) / 100 = 0.90 (90%).
Chapter 15: Advanced Density Clustering (OPTICS, DENCLUE) and Selection Guide
15.1 OPTICS Reachability Plots and DENCLUE Density Attractors
While DBSCAN excels at finding arbitrary shapes, its reliance on a single global ϵ threshold struggles when a dataset contains clusters of sharply varying densities (for example, one tight city-center cluster alongside a sparse suburban cluster). OPTICS (Ordering Points To Identify the Clustering Structure) resolves this limitation by generating an augmented ordering of objects rather than a single flat partition. For each point p, OPTICS computes two quantities with respect to generating distance ϵ and MinPts:
- core-dist(p): Minimum radius ≤ ϵ required for p to qualify as a core point (if p has fewer than MinPts neighbors, it has no core distance).
- reachability-dist(o, p): Maximum of p's core distance and Euclidean distance from p to o; plotting reachability distances in cluster-order forms a Reachability Plot where deep valleys correspond to dense clusters and high peaks mark cluster boundaries or noise.
Complementary DENCLUE (DENsity-based CLUstEring) models overall point density mathematically as the sum of smooth Gaussian kernel influence functions centered at each data point. Local maxima of this continuous density function are called density attractors; points are assigned to clusters by climbing the density gradient (hill-climbing) toward the same attractor, allowing DENCLUE to generalize both K-Means and DBSCAN while resisting high-dimensional noise.
15.2 Clustering Algorithm Selection Matrix and WEKA Interpretation
Choosing the right clustering algorithm in practice depends on dataset size, expected cluster geometry, attribute types, and outlier prevalence:
| Scenario / Data Characteristic | Recommended Algorithm | Key Parameter / Configuration | Analytical Rationale |
|---|---|---|---|
| Large numeric, compact spheres | K-Means / K-Means++ | k (via Elbow / Silhouette) | Linear O(tkn) scaling and crisp centroids. |
| Heavy outliers, small-to-medium data | K-Medoids (PAM) / CLARA | k medoids, Manhattan/Euclidean | Actual medoids resist extreme outlier pull. |
| Exploratory hierarchy, unknown k | AGNES / BIRCH | Complete or Ward's linkage | Dendrogram reveals multi-level granularity. |
| Non-convex shapes & spatial noise | DBSCAN / OPTICS | ϵ radius, MinPts | Tracks arbitrary contours and isolates noise. |
| High-dimensional feature spaces | CLIQUE / PROCLUS | Grid intervals ξ, density τ | Finds clusters inside lower-D subspaces. |
In WEKA's SimpleKMeans output, students inspect the Final cluster centroids table (comparing each cluster's mean attribute profile against the Full Data baseline), the Clustered Instances distribution, and the Within cluster sum of squared errors (SSE)—verifying that increasing k monotonically reduces SSE until reaching diminishing returns at the Elbow point.
Chapter 16: Constraint-Based, Model-Based (EM), and RFM Clustering
16.1 Probabilistic Clustering (EM / GMM) and Constraint-Based Clustering
Whereas K-Means performs hard assignment (each point belongs exclusively to a single cluster), Model-Based Clustering models each cluster as a continuous probability distribution—typically a Gaussian Mixture Model (GMM)—and assigns every point a soft probability of belonging to each cluster. Parameters (mean μk, covariance Σk, and mixing weight πk) are learned iteratively via the Expectation-Maximization (EM) Algorithm: the E-step computes expected cluster membership probabilities for every point given current parameters, and the M-step updates distribution parameters to maximize expected log-likelihood until convergence. Meanwhile, Constraint-Based Clustering incorporates domain knowledge directly into grouping—such as physical obstacle constraints (rivers/highways), minimum cluster capacity constraints, and instance-level Must-Link / Cannot-Link pairwise constraints enforced by COP-KMeans.
16.2 Applied Customer Segmentation Case Study (RFM Clustering)
In retail analytics, K-Means routinely segments customers across three standardized behavioral features known as RFM: Recency (days since last purchase), Frequency (total orders per year), and Monetary (total annual spend). Clustering 10,000 e-commerce accounts with k = 4 yields four immediately actionable business segments:
| Cluster Segment | Centroid Profile (R, F, M) | Interpretation | Targeted Marketing Action |
|---|---|---|---|
| Cluster 0: Champions | Low R (5 days), High F (24), High M (Rs. 85,000) | Recent, frequent, top-spending loyalists. | Early-access VIP tiers and referral rewards. |
| Cluster 1: Loyal Regulars | Med R (22 days), Med F (10), Med M (Rs. 32,000) | Steady repeat shoppers with growth potential. | Cross-sell bundles via Apriori rules. |
| Cluster 2: At-Risk | High R (110 days), High F (14), High M (Rs. 54,000) | Formerly high-value buyers lapsing away. | Urgent win-back discounts and churn outreach. |
| Cluster 3: Hibernating | Very High R (260 days), Low F (2), Low M (Rs. 4,500) | One-time bargain hunters unlikely to return. | Low-cost automated seasonal newsletters only. |
16.3 Clustering Tendency (Hopkins Statistic) and Outlier Remediation
Before running K-Means or DBSCAN, analysts verify whether a dataset actually contains non-random cluster structure using the Hopkins Statistic (H). By sampling m real points and m uniformly distributed synthetic points in the same bounding box, H compares nearest-neighbor distances: values near 0.5 indicate uniform random data (no meaningful clusters), whereas values approaching 0.75–1.0 confirm strong clustering tendency. Similarly, once outliers are flagged via IQR, Z-score, DBSCAN noise, or LOF, analysts apply one of four domain-driven actions: (1) Delete confirmed sensor/entry errors; (2) Winsorize (Cap) extreme tails to the 1st/99th percentile; (3) Log-Transform heavy-tailed monetary attributes; or (4) Route to Fraud Investigation when the outlier itself is the target discovery.
16.4 Worked Numerical Example: Z-Score Outlier Flagging & Remediation Matrix
Suppose daily ATM withdrawal amounts (in thousands) have mean μ = 12.0 and standard deviation σ = 4.0. For a transaction of x = 28.0 thousand, the standardized Z-score is z = (28.0 − 12.0) / 4.0 = +4.0. Because |z| = 4.0 > 3.0 (the standard 3σ threshold), the transaction is immediately flagged as a statistical outlier for fraud verification.
| Outlier Cause | Diagnostic Evidence | Recommended Remediation |
|---|---|---|
| Data Entry / Sensor Error | Impossible value (e.g., Age = 250 or −5) | Delete tuple or impute via attribute median. |
| Heavy-Tailed Skew | Valid extreme income / revenue values | Apply log-transformation or Winsorize at 99th percentile. |
| Adversarial / Fraud Event | Anomalous velocity, location, or high LOF | Preserve and route to anomaly alerting pipeline. |
Module V: Time-Series, Spatial, Web, and Text Mining
Chapter 13: Mining Time-Series and Spatial Data
13.1 Time-Series Components, Decomposition, and Similarity Search
A time-series is an ordered sequence of numeric observations recorded at successive, typically uniform time intervals—such as daily stock closing prices, hourly electricity load, or monthly rainfall totals. Classical time-series analysis decomposes a series Yt into four structural components: Trend (Tt) (long-term upward or downward movement), Seasonal (St) (fixed-period calendar fluctuations such as festival retail spikes), Cyclic (Ct) (multi-year macroeconomic oscillations without fixed period), and Irregular / Random (It) (unpredictable residual noise). These combine either through an Additive Model (, when seasonal amplitude stays constant) or a Multiplicative Model (, when seasonal swings scale with the trend level).
Trend estimation and short-term forecasting employ Moving Averages (averaging a sliding window of k past observations to damp short-term noise), Simple Exponential Smoothing (, assigning exponentially decaying weights via smoothing constant 0 < α < 1), and ARIMA (Autoregressive Integrated Moving Average) models that capture autocorrelation, differencing for stationarity, and lagged forecast errors. To search for similar patterns across long time-series databases despite slight phase shifts or speed variations, analysts reduce dimensionality via Discrete Fourier Transform (DFT) or Discrete Wavelet Transform (DWT) and measure elastic alignment using Dynamic Time Warping (DTW), which constructs a cumulative cost matrix warping the time axis non-linearly to match peaks and troughs. Relatedly, Sequential Pattern Mining—using GSP (Generalized Sequential Patterns) via Apriori-like candidate generation or PrefixSpan via recursive projected databases—discovers ordered event subsequences across customer histories (e.g., <(Laptop), (Printer), (Ink_Cartridge)>).
Worked Numerical Example (Exponential Smoothing): Suppose actual Q1 sales Y1 = 120 units, prior forecast F1 = 110 units, and smoothing constant α = 0.3. The Q2 forecast is F2 = 0.3(120) + (1 − 0.3)(110) = 36 + 77 = 113.0 units. If actual Q2 sales reach Y2 = 130, then F3 = 0.3(130) + 0.7(113) = 39 + 79.1 = 118.1 units—smoothly adapting upward without overreacting to a single spike.
13.2 Spatial Data Mining and Spatial OLAP
Spatial Data Mining extracts implicit, non-trivial patterns from geographic and geometric repositories stored in Geographic Information Systems (GIS), satellite imagery, and GPS telemetry. Unlike flat relational tables, spatial objects carry explicit geometry (points, lines, polygons) and exhibit spatial autocorrelation—Tobler's First Law of Geography stating that nearby locations tend to share similar characteristics. Spatial databases support Spatial Data Cubes and Spatial OLAP, aggregating numeric measures across spatial hierarchies (e.g., ward → district → state) alongside topological geometries.
Core spatial mining tasks include: (1) Spatial Association Rules—incorporating topological predicates such as close_to, adjacent_to, intersects, and contains (e.g., is_a(X, school) ∧ close_to(X, park) ⇒ high_property_value(X)), mined via progressive refinement (coarse spatial bounding-box approximation followed by exact geometric computation); (2) Spatial Clustering—grouping geographic hotspots using CLARANS, DBSCAN, or SD-CLARANS while respecting physical barriers like rivers or highways; and (3) Spatial Classification and Trend Analysis—predicting crop yield, flood risk, or urban sprawl across spatial grids using spatial decision trees and Kriging interpolation.
13.3 Dynamic Time Warping (DTW), Sequential Patterns, and Spatial Applications
Unlike rigid Euclidean distance—which aligns time series X = (x1, …, xn) and Y = (y1, …, ym) strictly one-to-one at identical timestamps—Dynamic Time Warping (DTW) computes an optimal elastic alignment path by recursively filling an n × m cumulative distance matrix D(i, j):
- D(i, j): Minimum cumulative warping cost aligning prefixes (x1…xi) and (y1…yj).
- |xi − yj|: Local pointwise distance between sample xi and sample yj, plus minimum predecessor cost along horizontal, vertical, or diagonal steps.
Worked Numerical Example (DTW): Align short series X = [1, 3, 2] and Y = [1, 1, 3, 2]. Notice Y simply stretches the initial value 1 across two steps. Under Euclidean alignment, X and Y cannot even be compared because lengths differ (3 vs. 4). Under DTW, the warping path maps x1=1 → (y1=1, y2=1) with zero local cost, then x2=3 → y3=3 (cost 0), and x3=2 → y4=2 (cost 0), yielding total DTW distance = 0.0! Spatial data mining similarly powers high-impact domains: Urban Planning (siting hospitals and transit hubs via spatial clustering), Precision Agriculture (correlating soil moisture rasters with crop yield), Disaster Management (floodplain inundation mapping), and Epidemiology (detecting spatial disease clusters).
Chapter 14: Mining the World Wide Web and Text Mining
14.1 Web Content, Web Structure (PageRank & HITS), and Web Usage Mining
The World Wide Web is a massive, dynamic, semi-structured hypertext graph. Web Mining applies data mining techniques across three complementary dimensions:
| Web Mining Branch | Primary Input Data | Core Techniques | Key Applications |
|---|---|---|---|
| Web Content Mining | HTML/XML text, images, tables, metadata inside web pages. | Wrapper induction, HTML DOM parsing, NLP classification, topic extraction. | Price comparison engines, vertical search indexing, sentiment extraction. |
| Web Structure Mining | Directed hyperlink graph connecting pages (nodes) via URLs (edges). | Link analysis algorithms: PageRank and HITS (Hubs & Authorities). | Search engine ranking, identifying authoritative communities and spam farms. |
| Web Usage Mining | Web server access logs, cookies, clickstreams, session histories. | Sessionization, sequential pattern mining, collaborative filtering. | Site navigation optimization, personalized product recommendations, caching. |
In Web Structure Mining, HITS (Hyperlink-Induced Topic Search) distinguishes between Authorities (pages with high-quality content pointed to by many hubs) and Hubs (directory pages linking to many authorities). Google's PageRank models a "random surfer" who follows outgoing hyperlinks with probability d (damping factor, typically 0.85) or jumps to a random page with probability (1 − d):
- PR(u): PageRank authority score of page u; Bu is the set of pages linking into u, L(v) is the outbound link count of page v, N is total pages, and d is the damping factor.
- wt,d: TF-IDF weight of term t in document d, multiplying Term Frequency TF(t,d) by Inverse Document Frequency log10(Ndoc / DF(t)), where Ndoc is corpus size and DF(t) is the number of documents containing term t.
Worked Numerical Example (PageRank Iteration): Consider N = 3 web pages A, B, and C with damping factor d = 0.85, initialized to PR0(A) = PR0(B) = PR0(C) = 1/3 ≈ 0.333. Suppose A links to B and C (L(A) = 2), B links only to C (L(B) = 1), and C links only to A (L(C) = 1). Random-jump baseline is (1 − 0.85)/3 = 0.05. In Iteration 1: PR1(A) = 0.05 + 0.85 × (PR0(C)/1) = 0.05 + 0.85(0.333) = 0.333; PR1(B) = 0.05 + 0.85 × (PR0(A)/2) = 0.05 + 0.85(0.167) = 0.192; PR1(C) = 0.05 + 0.85 × (PR0(A)/2 + PR0(B)/1) = 0.05 + 0.85(0.167 + 0.333) = 0.475. Notice C immediately rises to the highest authority because both A and B point to it.
Worked Numerical Example (TF-IDF Weighting): Suppose a corpus contains Ndoc = 1,000 documents. Term "mining" appears 5 times in Document D1 (TF = 5) and appears in DF = 100 documents overall. Its IDF is log10(1000 / 100) = log10(10) = 1.0, giving TF-IDF weight = 5 × 1.0 = 5.0. Meanwhile, common term "data" also appears 5 times in D1 but occurs in DF = 500 documents; its IDF is log10(1000 / 500) = log10(2) ≈ 0.301, yielding TF-IDF weight = 5 × 0.301 = 1.505—automatically down-weighting ubiquitous words.
14.2 Text Mining Pipeline and Document Analytics
Text Mining extracts structured knowledge from unstructured natural-language documents (emails, news articles, customer reviews, clinical notes). Because raw text lacks fixed numeric columns, documents undergo a standardized preprocessing pipeline: (1) Tokenization (splitting text streams into words, phrases, or n-grams while stripping punctuation); (2) Stop-word Removal (filtering high-frequency function words like the, is, and); (3) Stemming (chopping suffixes via heuristic rules like the Porter Stemmer, e.g., mining → mine, studies → studi) or Lemmatization (mapping inflected words to valid dictionary base lemmas using part-of-speech context, e.g., better → good); and (4) Vector Space Representation using Bag-of-Words weighted by TF-IDF. Once represented as sparse vectors, documents are classified using Multinomial Naïve Bayes or Support Vector Machines, grouped via Spherical K-Means with Cosine Similarity, analyzed for opinion polarity via Sentiment Analysis (lexicon-based scoring or supervised classifiers), or summarized into latent themes via Topic Modeling (Latent Semantic Analysis via SVD and Latent Dirichlet Allocation).
14.3 HITS Link Analysis, Web Usage Mining, and Document Cosine Similarity
Whereas PageRank computes a single global authority score across the entire web graph, the HITS (Hyperlink-Induced Topic Search) algorithm computes query-specific Authority a(p) and Hub h(p) scores iteratively over a focused subgraph: and , normalized after each step until convergence—a good hub points to many strong authorities, and a good authority is endorsed by many strong hubs. Meanwhile, Web Usage Mining executes four structured stages on raw server logs: (1) Data Cleaning (removing automated crawler/bot hits and image asset requests); (2) User & Session Identification (grouping IP + User-Agent requests separated by 30-minute inactivity timeouts); (3) Path Completion (inferring cached back-button clicks via referrer URLs); and (4) Pattern Discovery (mining frequent navigation paths and powering user-item collaborative filtering).
Worked Numerical Example (Document Cosine Similarity): Suppose two documents are represented as TF-IDF vectors over vocabulary (data, mining, cluster, tree): D1 = (2, 4, 0, 1) and D2 = (1, 3, 2, 0). Dot product D1 · D2 = (2)(1) + (4)(3) + (0)(2) + (1)(0) = 2 + 12 = 14. Vector norms: ||D1|| = √(4 + 16 + 0 + 1) = √21 ≈ 4.583; ||D2|| = √(1 + 9 + 4 + 0) = √14 ≈ 3.742. Therefore, Cosine Similarity = 14 / (4.583 × 3.742) = 14 / 17.15 = 0.816—indicating high topical overlap despite differing document lengths.
| Text / Web Mining Task | Input Representation | Primary Algorithm | Real-World Output |
|---|---|---|---|
| Spam / Email Filtering | TF-IDF / Bag-of-Words vectors | Multinomial Naïve Bayes / SVM | Binary Spam vs. Ham classification. |
| Topic Modeling | Document-Term matrix | LSA (SVD) / LDA | Latent thematic clusters across corpora. |
| Sentiment Analysis | N-grams, POS tags, lexicons | Logistic Regression / Lexicon scoring | Positive, Neutral, or Negative polarity. |
| Search Engine Ranking | Web hyperlink graph + anchor text | PageRank / HITS | Authoritative top-K ranked URLs. |
| Clickstream Personalization | Sessionized server access logs | PrefixSpan / Collaborative Filtering | Next-page caching & product suggestions. |
Chapter 15: End-to-End Practical Data Mining Pipeline (WEKA Lab Synthesis)
15.1 Integrating All Ten Practical Exercises into a Reproducible Workflow
Combining the ten practical exercises from the curriculum forms a complete, reproducible KDD pipeline in WEKA:
| Lab Exercise | WEKA Tab / Tool | Filter or Algorithm Used | Expected Analytical Output |
|---|---|---|---|
| 1. Create Table | Tools → ArffViewer | @relation, @attribute, @data |
Valid saved .arff dataset file. |
| 2. Attribute Types | Preprocess → Attributes | Nominal vs Numeric inspection | Separated list of categorical and real-valued attributes. |
| 3. Central Tendency | Preprocess / ArffViewer | Summary stats + sorted column | Mean, Median, and Mode per attribute. |
| 4. Preprocessing | Preprocess → Filter | Normalize, Standardize, Discretize |
Scaled [0, 1] or discretized nominal features. |
| 5. Missing Values | Preprocess → Filter | ReplaceMissingValues |
Imputed means (numeric) and modes (nominal). |
| 6. Association Rules | Associate | Apriori (nominal input) |
Top-N rules ranked by Confidence / Lift. |
| 7. Decision Tree | Classify | trees.J48 (10-fold CV) |
Pruned tree, Confusion Matrix, Accuracy, F1. |
| 8. Naïve Bayes | Classify | bayes.NaiveBayes (10-fold CV) |
Posterior probability table, Confusion Matrix, ROC. |
| 9. Clustering | Cluster | SimpleKMeans, HierarchicalClusterer |
Cluster centroids, SSE, dendrograms, cluster sizes. |
| 10. Outlier Detection | Preprocess / Cluster | InterquartileRange filter |
Appended Outlier and ExtremeValue flags. |
# Step A (Ex 1-5): Preprocess ARFF, handle missing values, normalize java weka.filters.unsupervised.attribute.ReplaceMissingValues \ -i dataset.arff -o step1_clean.arff java weka.filters.unsupervised.attribute.Normalize \ -i step1_clean.arff -o step2_norm.arff # Step B (Ex 6): Association Rule Mining via Apriori java weka.filters.unsupervised.attribute.Discretize \ -i step1_clean.arff -o step2_disc.arff java weka.associations.Apriori \ -N 10 -C 0.8 -M 0.2 -t step2_disc.arff # Step C (Ex 7-8): Supervised Classification (J48 & Naive Bayes) java weka.classifiers.trees.J48 -C 0.25 -M 2 -t step1_clean.arff java weka.classifiers.bayes.NaiveBayes -t step1_clean.arff # Step D (Ex 9-10): Unsupervised Clustering & Outlier Flagging java weka.clusterers.SimpleKMeans -N 3 -t step2_norm.arff java weka.filters.unsupervised.attribute.InterquartileRange \ -R first-last -i step1_clean.arff -o step3_outliers.arff
Chapter 16: Advanced Domain Mining Case Studies and Text/Time-Series Labs
16.1 Time-Series Seasonal Decomposition Worked Example
To isolate underlying long-term growth from recurring quarterly seasonality, analysts compute a 4-Quarter Centered Moving Average (CMA). Because 4 is an even period, averaging 4 consecutive quarters centers between Q2 and Q3; taking a 2-period average of adjacent 4-Q moving averages aligns the smoothed trend exactly with Q3:
| Period | Observed Sales Yt | 4-Q Moving Avg | Centered MA (Trend Tt) | Seasonal Residual (Yt − Tt) |
|---|---|---|---|---|
| Year 1 Q1 | 40 | — | — | — |
| Year 1 Q2 | 52 | (40+52+48+60)/4 = 50.0 | — | — |
| Year 1 Q3 | 48 | (52+48+60+44)/4 = 51.0 | (50.0+51.0)/2 = 50.5 | 48 − 50.5 = −2.5 |
| Year 1 Q4 | 60 | (48+60+44+56)/4 = 52.0 | (51.0+52.0)/2 = 51.5 | 60 − 51.5 = +8.5 |
| Year 2 Q1 | 44 | (60+44+56+52)/4 = 53.0 | (52.0+53.0)/2 = 52.5 | 44 − 52.5 = −8.5 |
| Year 2 Q2 | 56 | — | — | — |
Averaging seasonal residuals across multiple years for each quarter yields stable additive seasonal indices (e.g., Q4 consistently exhibits a +8.5 festival surge above the trend line, while Q1 dips by −8.5). Subtracting these seasonal indices from raw sales produces a deseasonalized series that reveals true organic business growth.
16.2 Sequential Pattern Mining, Spatial Predicates, and WEKA Text Mining
In Sequential Pattern Mining, each customer sequence is an ordered list of itemset transactions (events). For example, Customer 101's history <(Phone), (Case, Charger), (Earbuds)> contains the subsequence <(Phone), (Earbuds)> because Phone occurs strictly before Earbuds. GSP mines frequent sequences level-by-level using Apriori candidate generation with optional time-window constraints, whereas PrefixSpan avoids candidate generation by recursively projecting the database onto smaller suffix sub-databases sharing each frequent prefix—analogous to FP-Growth's divide-and-conquer speedup.
In Spatial Data Mining, topological predicates govern spatial joins and association rules: intersects(A, B) (boundaries or interiors overlap), contains(A, B) (polygon A encloses B), adjacent_to(A, B) (polygons share a boundary edge without interior overlap), and within_distance(A, B, r) (Euclidean/network distance ≤ r). Finally, in WEKA Text Mining, raw text documents stored as a string attribute in ARFF are converted into numeric Bag-of-Words or TF-IDF feature vectors using weka.filters.unsupervised.attribute.StringToWordVector (enabling IDFTransform, TFTransform, lowercase conversion, stop-word filtering, and Porter stemming) before running NaiveBayesMultinomial or SMO (SVM) classifiers.
Chapter 17: Text Mining Document-Term Matrix, ARIMA Forecasting, and Privacy
17.1 Complete Document-Term TF-IDF Matrix Worked Example
Suppose a 3-document corpus (Ndoc = 3) contains: D1 = "data mining trees", D2 = "data clustering algorithms", and D3 = "mining spatial data". After tokenization and stop-word removal, we compute Document Frequency (DF) and Inverse Document Frequency IDF = log10(3 / DF) for key terms:
| Term t | DF(t) | IDF = log10(3/DF) | TF-IDF in D1 | TF-IDF in D2 | TF-IDF in D3 |
|---|---|---|---|---|---|
| data | 3 | log10(1) = 0.000 | 1 × 0.000 = 0.000 | 1 × 0.000 = 0.000 | 1 × 0.000 = 0.000 |
| mining | 2 | log10(1.5) = 0.176 | 1 × 0.176 = 0.176 | 0 | 1 × 0.176 = 0.176 |
| trees | 1 | log10(3) = 0.477 | 1 × 0.477 = 0.477 | 0 | 0 |
| clustering | 1 | log10(3) = 0.477 | 0 | 1 × 0.477 = 0.477 | 0 |
| spatial | 1 | log10(3) = 0.477 | 0 | 0 | 1 × 0.477 = 0.477 |
Notice how the ubiquitous term "data" (appearing in all 3 documents) receives IDF = 0.000, automatically suppressing non-discriminative vocabulary while elevating rare domain-specific terms like "trees", "clustering", and "spatial" to 0.477.
17.2 ARIMA Stationarity and Privacy-Preserving Data Mining
In advanced time-series forecasting, ARIMA(p, d, q) integrates three mechanisms: Autoregression (AR, order p) regressing current values on p past observations; Integrated differencing (I, order d) subtracting consecutive values (Yt − Yt−1) d times to stabilize a drifting mean into stationarity; and Moving Average (MA, order q) modeling current shock via q past forecast errors. Across all domains—especially healthcare, finance, and web usage logs—Privacy-Preserving Data Mining protects sensitive individuals from re-identification using k-Anonymity (generalizing quasi-identifiers like age and zip code so every record is indistinguishable from at least k − 1 others) and Differential Privacy (injecting calibrated Laplacian noise into aggregate query responses).
Chapter 18: Web Search Indexing, Recommender Systems, and Stream Mining
18.1 Recommender Systems: Collaborative vs. Content-Based Filtering
Modern e-commerce and media platforms leverage web usage and text mining to power Recommender Systems. Content-Based Filtering recommends items similar to those a user liked in the past by matching item TF-IDF feature profiles against the user's historical preference vector. By contrast, Collaborative Filtering (CF) exploits wisdom-of-the-crowd rating matrices without needing item descriptions: User-Based CF identifies k-nearest peer users with similar rating histories (via Pearson correlation or Cosine similarity) and predicts missing ratings as a similarity-weighted average, whereas Item-Based CF precomputes item-to-item similarity (more stable at million-user scale).
- r̂u,i: Predicted rating for target user u on unseen item i.
- r̄u, r̄v: Mean ratings of target user u and neighbor v across their rated items (correcting generous vs. strict raters).
- sim(u, v): Similarity (Pearson or Cosine) between user u and peer v across co-rated items.
Worked Numerical Example (Collaborative Filtering): Suppose User U has mean rating r̄U = 3.5. Two similar peers V1 (sim = 0.80, r̄V1 = 3.0) and V2 (sim = 0.40, r̄V2 = 4.0) rated Movie M as rV1,M = 4.5 and rV2,M = 5.0. Deviations are (4.5 − 3.0) = +1.5 and (5.0 − 4.0) = +1.0. Weighted adjustment = (0.80 × 1.5 + 0.40 × 1.0) / (0.80 + 0.40) = (1.20 + 0.40) / 1.20 = +1.33. Predicted rating for U on Movie M is 3.5 + 1.33 = 4.83 / 5.0.
18.2 Web Search Indexing and High-Velocity Stream Data Mining
Search engines combine Focused Web Crawlers (prioritizing URLs topically relevant to a domain), an Inverted Index (mapping every stemmed vocabulary term t to a sorted posting list of document IDs and term frequencies for millisecond retrieval), and hybrid ranking merging TF-IDF / BM25 textual relevance with PageRank link authority. Finally, Stream Data Mining addresses continuous, unbounded, high-speed event streams (IoT telemetry, network packets, financial ticks) that cannot be stored in full or scanned twice. Algorithms operate in single-pass O(1) memory using Sliding Windows (retaining only the most recent W events), Reservoir Sampling (maintaining a uniform random sample of fixed size s over an unknown-length stream), and Hoeffding Trees (VFDT) (incrementally growing decision trees using the Hoeffding statistical bound to choose splits from finite stream buffers).
| Specialized Domain | Primary Data Structure | Signature Algorithm / Model | Core Challenge Solved |
|---|---|---|---|
| Time-Series Mining | Ordered temporal sequences | Seasonal Decomposition, DTW, ARIMA | Phase shifts, seasonality, non-stationarity. |
| Spatial Data Mining | Points, polygons, GIS rasters | Spatial OLAP, DBSCAN, CLARANS | Spatial autocorrelation & physical barriers. |
| Web Mining | DOM trees, link graphs, logs | PageRank, HITS, Collaborative Filtering | Authority ranking & clickstream sparsity. |
| Text Mining | Sparse TF-IDF vector space | Porter Stemmer, Multinomial NB, LDA | Unstructured vocabulary & high dimensionality. |
| Stream Mining | Unbounded single-pass tuples | Reservoir Sampling, Hoeffding Trees | Concept drift & strict memory/latency bounds. |
Chapter 19: Graph Mining, Social Network Analysis, and WEKA Text Lab
19.1 Graph Mining and Social Network Centrality Metrics
Many complex systems—social networks, molecular protein interactions, citation graphs, and payment-transfer networks—are naturally represented as labeled graphs G = (V, E). Frequent Subgraph Mining (using algorithms such as gSpan, which encodes graphs into canonical DFS codes to avoid duplicate isomorphism checks) discovers recurring structural motifs across graph collections. In Social Network Analysis (SNA), node importance is quantified via three structural centrality measures: Degree Centrality (number of direct edges connected to a node), Closeness Centrality (inverse of average shortest-path distance to all other nodes—measuring information broadcast speed), and Betweenness Centrality (fraction of all shortest paths passing through a node—identifying critical bridge brokers). Community detection partitions large networks into densely connected modules maximizing Modularity (Q).
19.2 WEKA Text Mining ARFF & StringToWordVector Walkthrough
To classify unstructured text documents in WEKA, documents are stored in ARFF using the string attribute type and transformed into TF-IDF vectors before training NaiveBayesMultinomial:
@relation news_sentiment
@attribute doc_text string
@attribute sentiment {Positive, Negative}
@data
"Excellent product quality and fast delivery", Positive
"Broken screen and terrible customer support", Negative
# Transform string attribute to TF-IDF vectors and classify
java weka.filters.unsupervised.attribute.StringToWordVector \
-I -T -L -S -stemmer weka.core.stemmers.IteratedLovinsStemmer \
-i news.arff -o news_tfidf.arff
java weka.classifiers.bayes.NaiveBayesMultinomial -t news_tfidf.arff19.3 Ethical Data Mining, Explainability, and Governance
Deploying data mining models across banking, healthcare, employment, and digital platforms carries profound ethical responsibilities. Analysts must audit training datasets for historical sampling bias and proxy discrimination (where attributes like pin code indirectly encode protected demographics), enforce statutory privacy compliance (such as India's Digital Personal Data Protection Act and GDPR data minimization principles), and pair black-box predictive models with post-hoc Explainable AI (XAI) tools—such as LIME and SHAP—so every automated loan denial, medical alert, or fraud flag remains transparent, contestable, and accountable to human stakeholders.
19.4 Inverted Index Posting Lists & Governance Audit Summary
To support sub-second keyword search across millions of web pages, search engines store an Inverted Index mapping each stemmed term to a sorted list of document IDs (posting list). For example, if "mining" → [D1, D3, D7, D12] and "spatial" → [D3, D12, D19], evaluating the Boolean query "mining AND spatial" intersects both sorted posting lists in linear O(m + n) time to return [D3, D12] instantly without scanning full documents. Alongside retrieval speed, enterprise KDD governance enforces four mandatory audit pillars:
| Governance Pillar | Technical Control | Verification Target |
|---|---|---|
| Algorithmic Fairness | Disparate impact & equalized odds audits | Zero proxy discrimination across protected groups. |
| Data Privacy | k-Anonymity & Differential Privacy noise | Prevent re-identification in released tables/models. |
| Model Explainability | SHAP feature attributions & J48 rule extraction | Human-interpretable justification per decision. |
| Lifecycle Monitoring | Concept drift & population stability index | Scheduled retraining when accuracy degrades. |
University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 4 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Data Mining (University of Kerala BCA Sem 4)
Data Mining (UK4DSCCAP202 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in data mining. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Data Mining Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to Data Mining
Modern enterprises, scientific observatories, healthcare networks, and e-commerce platforms generate vast volumes of digital records every second through point-of-sale terminals, web server logs, banking gateways, genomic sequencers, and Internet of Things (IoT) sensors. On its own, raw data consists of unprocessed facts, measurements, or discrete symbols—such as individual invoice line items, temperature readings, or customer click timestamps—that carry minimal decision value in isolation.
Data Preprocessing and Mining Frequent Patterns
Real-world enterprise databases are rarely ready for immediate algorithmic modeling. Operational data is routinely incomplete (lacking attribute values or containing only aggregate summaries), noisy (corrupted by sensor jitter, transcription typos, or transmission glitches), and inconsistent (exhibiting conflicting department codes, mixed date formats, or impossible values such as a negative age). Feeding flawed inputs into a learner triggers the "garbage-in, garbage-out" phenomenon, degrading accuracy and generating spurious rules.
Classification
Classification is a two-step supervised learning process that assigns unseen data objects to discrete, predefined categorical class labels. In the Learning (Training) Step, a classification algorithm analyzes a training set of tuples whose class labels are already known, inducing a mathematical or logical model (such as a decision tree, conditional probability table, or rule set) expressed as y = f(X).
Cluster Analysis: Basic Concepts and Methods
Cluster Analysis is an unsupervised learning methodology that partitions a collection of unlabeled data objects into meaningful groups called clusters such that objects within the same cluster exhibit high intra-cluster similarity while objects in different clusters exhibit low inter-cluster similarity. Unlike classification, clustering requires no pre-assigned class labels; instead, it discovers natural groupings directly from attribute proximity.
Time-Series, Spatial, Web, and Text Mining
A time-series is an ordered sequence of numeric observations recorded at successive, typically uniform time intervals—such as daily stock closing prices, hourly electricity load, or monthly rainfall totals. Classical time-series analysis decomposes a series Y t into four structural components: Trend (T t ) (long-term upward or downward movement), Seasonal (S t ) (fixed-period calendar fluctuations such as festival retail spikes), Cyclic (C t ) (multi-year macroeconomic oscillations without fixed period), and Irregular / Random (I t ) (unpredictable residual noise).
Core Curriculum & Key Topics
- Foundations of Data Mining and Knowledge Discovery in Databases (KDD)
- 1 Data, Information, Knowledge, and the Need for Data Mining
- 2 The Knowledge Discovery in Databases (KDD) Process
- 3 Types of Data Repositories and Data Warehouse / OLAP Basics
- 4 Data Mining Functionalities
- 5 Application Domains and Major Issues in Data Mining
- 6 Data Mining in Relation to Statistics, Machine Learning, and Databases
- Attribute Types and Statistical Descriptions of Data
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of data mining.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Data Mining
The evaluation framework for Data Mining (UK4DSCCAP202) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK4DSCCAP202 (Data Mining) examination: 1. Draw Clear Diagrams & Step-by-Step Traces: Illustrate trees, graphs, ER schemas, normalization tables, or ML pipeline diagrams neatly alongside dry-run traces. 2. State Complexity & Mathematical Formulas Explicitly: Include time/space complexity (Big-O notation), SQL query syntax, or model evaluation metrics (precision, recall, accuracy) accurately. 3. Compare Algorithms & Models in Tables: Use structured comparison tables (e.g., supervised vs. unsupervised, BFS vs. DFS, B-Tree vs. B+ Tree) for Part B analytical questions. 4. Allocate Time Strategically: Dedicate 25 minutes to Part A definitions, 50 minutes to Part B derivations and query/algorithm traces, and 75 minutes to Part C comprehensive problems.
Exam Preparation & Study Guides — Data Mining
What is Data, Information, Knowledge & Data Mining and why is it important in Data Mining?
Raw data consists of unprocessed facts, measurements, or discrete symbols; filtering and contextualizing data yields information; generalizing actionable patterns and predictive rules from large repositories produces knowledge.
What is Cluster Analysis and why is it important in Data Mining?
Unsupervised grouping maximizing intra-cluster similarity and minimizing inter-cluster similarity without class labels.
What is Data Cleaning Techniques and why is it important in Data Mining?
Remediates missing entries (under MCAR, MAR, or MNAR mechanisms) and smooths random measurement noise.
What is Classifier Comparison Criteria and why is it important in Data Mining?
Evaluated across Predictive Accuracy, Training/Inference Speed, Robustness to noise, Scalability to disk-resident data, and Interpretability.
What is Hierarchical, Density-Based & Grid-Based Methods and why is it important in Data Mining?
Multi-resolution trees, arbitrary-shape density regions, and quantized spatial grids.
What is the official course code and credit structure for Data Mining at University of Kerala?
Data Mining carries the official course code UK4DSCCAP202 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Data Mining?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Data Mining (UK4DSCCAP202) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 4 Subjects
Browse study notes for other courses in BCA Sem 4:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.