Data Mining and Data Warehousing
Everything in your syllabus, explained from zero, with worked numerical examples, diagrams you can redraw in the answer sheet, and the exact points examiners look for.
How to use this book
Read a unit top to bottom once. Then re-read only the yellow Exam boxes. Those are the sentences that actually earn marks. The green boxes are numerical examples; in this subject numericals are the easiest marks in the paper (Apriori, information gain, k-means, naive Bayes, normalization all repeat almost every year).
- Definition first. Every answer starts with a one or two line definition. Examiners tick that line before reading anything else.
- Diagram = 2-3 marks. Almost every long question here has a standard diagram (KDD process, DW architecture, star schema, decision tree, DBSCAN points). Draw it, label it, box it.
- Points, not paragraphs. Write in numbered points with a bold heading each. A page of unbroken prose scores lower than the same content in six labelled points.
- Show every step in numericals. Formula → substitution → answer. Even a wrong final answer keeps most of the marks if steps are visible.
- Give an example. One line of AllElectronics/supermarket example after a definition converts a 3/5 into a 5/5.
A data warehouse is where you store cleaned, historical, subject-oriented data; data mining is the set of algorithms you run on it to discover patterns you did not already know. Units 1-2 are the warehouse (storage). Units 3-6 are the mining (algorithms). Keep that split in your head and nothing will feel disconnected.
Introduction
4 hrs1.1 What is data mining?
Data mining is the process of extracting interesting (non-trivial, implicit, previously unknown and potentially useful) patterns or knowledge from huge amounts of data.
The name is slightly wrong, and examiners love this remark: we do not mine data, we mine knowledge from data, just as gold mining is named after gold, not after sand. A more accurate name is Knowledge Discovery from Data (KDD). Data mining is one step of KDD, though in industry the two words are used interchangeably.
Why did data mining appear?
- Data explosion. Cheap storage, bar-code scanners, ATMs, e-commerce, sensors and the Web created terabytes of data. We are "data rich but information poor". Write this exact phrase, it is from the textbook.
- Queries are not enough. SQL answers "how many TVs did we sell in Pokhara in Ashad?" It cannot answer "which customers are about to leave us and why?"
- Competition. Business needs decision support, not just record keeping.
Easily understandable · valid on new/test data · potentially useful · novel. Plus: it validates a hypothesis the user wanted to confirm. A pattern is objectively interesting if it passes thresholds (support, confidence, accuracy) and subjectively interesting if it is unexpected or actionable to the user.
1.2 The KDD process near-certain question
KDD is the complete pipeline from raw database to usable knowledge. Data mining sits in the middle of it. Learn the seven steps in order, because this figure alone is often a full 5-mark answer.
- Data cleaning: remove noise and inconsistent records, fill in missing values.
- Data integration: combine multiple heterogeneous sources into one store.
- Data selection: retrieve only the data relevant to the analysis task.
- Data transformation: normalise, aggregate, summarise into forms fit for mining.
- Data mining: apply intelligent algorithms to extract patterns.
- Pattern evaluation: keep only truly interesting patterns using interestingness measures.
- Knowledge presentation: visualise with charts, trees, rules and tables.
Steps 1-4 are data preprocessing and take roughly 60-70 % of the total effort of any KDD project. The process is iterative: results of evaluation feed back and the earlier steps are repeated.
1.3 Architecture of a typical data mining system
Knowledge base holds domain knowledge such as concept hierarchies, user beliefs and thresholds, and guides the search and evaluates interestingness. Tight coupling of the mining engine with the database (mining primitives pushed into the DB engine) gives the best performance; no coupling is the worst.
1.4 Classification of data mining systems frequent
A DM system can be categorised along four criteria. Remember the mnemonic D-K-T-A: Database, Knowledge, Technique, Application.
| Criterion | Categories |
|---|---|
| Kind of database mined | Relational, transactional, object-relational, data warehouse, spatial, temporal/time-series, text, multimedia, stream, WWW, heterogeneous/legacy |
| Kind of knowledge mined (the mining functionality) | Characterisation, discrimination, association & correlation, classification, prediction, clustering, outlier analysis, evolution analysis. Also by granularity: generalised, primitive-level, multilevel |
| Kind of technique used | By data analysis approach: machine learning, statistics, neural networks, genetic algorithms, database-oriented, visualisation; by degree of user interaction: autonomous, interactive, query-driven |
| Application adapted | Finance, telecom, retail/market analysis, DNA and bioinformatics, stock market, e-mail, intrusion detection |
1.5 Data mining functionalities (techniques) write with examples
Split them into two families first, since this framing earns a mark by itself.
- Descriptive mining: characterises general properties of the data (characterisation, discrimination, association, clustering).
- Predictive mining: infers on current data to make predictions (classification, prediction/regression, outlier & evolution analysis).
| Functionality | What it does | One-line example |
|---|---|---|
| Concept/class characterisation | Summarises the general features of a target class | Profile of customers who spend > Rs 50,000/yr |
| Concept/class discrimination | Compares target class against contrasting class(es) | Compare frequent buyers vs rare buyers |
| Association & correlation | Finds attribute-value conditions occurring together | buys(bread) ⇒ buys(milk) [s = 2 %, c = 60 %] |
| Classification | Builds a model to predict a categorical class label from labelled training data | Predict credit risk = safe/risky |
| Prediction | Predicts a continuous numeric value | Predict next month's sales in rupees |
| Cluster analysis | Groups objects without class labels; maximise intra-class similarity, minimise inter-class similarity | Segment customers into 5 groups |
| Outlier analysis | Finds objects that do not comply with general behaviour | Credit-card fraud detection |
| Evolution analysis | Models regularities for objects whose behaviour changes over time | Stock price trend, seasonality |
Do not say clustering and classification are the same. Classification is supervised (class labels are known in the training data). Clustering is unsupervised (no labels; the classes are produced by the algorithm). Also: classification predicts a discrete label, prediction predicts a continuous value.
1.6 Major issues and challenges in data mining very frequent
Group them under five headings and give two sub-points each. Never write a plain list.
(a) Mining methodology issues
- Mining different kinds of knowledge in the same database, since users want many functionalities.
- Mining knowledge at multiple levels of abstraction (roll-up / drill-down of patterns).
- Incorporating background knowledge (concept hierarchies, user beliefs).
- Handling noise and incomplete data: otherwise overfitting occurs.
- Pattern evaluation, the interestingness problem: algorithms generate thousands of patterns, most of them useless.
(b) User interaction issues
- Interactive mining: the user must be able to refine the search dynamically.
- Data mining query languages and ad-hoc mining (DMQL, integration with SQL).
- Presentation and visualisation of results (trees, rules, cubes, charts).
(c) Performance issues
- Efficiency and scalability: runtime must be predictable and acceptable on huge data.
- Parallel, distributed and incremental mining algorithms: data is partitioned, results merged; incremental updating avoids mining from scratch.
(d) Diversity of data types
- Handling relational and complex types: spatial, multimedia, time-series, text, graphs.
- Mining heterogeneous, global information systems (the Web); Web mining is a whole research area.
(e) Social issues
- Privacy and data security: mining personal records raises legal/ethical problems; privacy-preserving data mining is the response.
- Misuse and misinterpretation of discovered patterns (correlation ≠ causation).
1.7 DBMS vs data mining, and KDD vs data mining short question
| DBMS (query processing) | Data mining | |
|---|---|---|
| Task | Store, retrieve and manage data reliably | Discover hidden patterns and knowledge |
| Question asked | "What was the sale of TV in June?"; the user knows what to ask | "Which products are bought together, and who will churn?"; the user does not know what to ask |
| Answer | Facts already present in the database | New, implicit, previously unknown information |
| Query language | SQL: deterministic, exact | DMQL / algorithms: heuristic, approximate |
| Data state | Current, operational, detailed | Historical, summarised, cleaned |
| Output | Tables/records | Rules, trees, clusters, models |
| Verification vs discovery | Verification-driven (user hypothesises, system verifies) | Discovery-driven (system hypothesises) |
KDD is the overall process of converting raw data into useful knowledge (7 steps); data mining is one essential step within KDD in which intelligent algorithms are applied to extract patterns. In common usage the terms are treated as synonyms.
1.8 Applications of data mining
- Market basket / retail analysis: product placement, catalogue design, cross-selling, loyalty analysis.
- Finance and banking: credit scoring, loan default prediction, risk analysis, money laundering detection.
- Telecommunication: fraudulent call pattern detection, churn prediction, network fault isolation.
- Healthcare and bioinformatics: disease diagnosis, DNA sequence and gene expression analysis, drug discovery.
- Intrusion detection and cyber security: anomaly and misuse detection.
- Science and engineering: remote sensing, astronomy sky surveys, weather.
- Web and social media: recommendation systems, search engine ranking, personalisation, sentiment analysis.
- Government: census analysis, tax fraud, policy planning.
1.9 Likely exam questions from this unit
- Define data mining. Explain the KDD process with a neat diagram. 10
- Explain the architecture of a typical data mining system. 5-10
- On what criteria are data mining systems classified? Explain each. 5
- Explain data mining functionalities with suitable examples. 10
- Discuss the major issues and challenges in data mining. 10
- Differentiate DBMS and data mining / OLTP and data mining. 5
- What makes a pattern interesting? List the applications of data mining. 5
Data Warehousing
5 hrs2.1 What is a data warehouse? definition + 4 features = guaranteed
"A data warehouse is a subject-oriented, integrated, time-variant and non-volatile collection of data in support of management's decision-making process." (W. H. Inmon)
Then explain the four keywords. Each one is worth a mark.
| Feature | Meaning | Example |
|---|---|---|
| Subject-oriented | Organised around major subjects (customer, product, sales) rather than around day-to-day operations/transactions. Excludes data not useful for decision support. | A "Sales" subject area instead of an "order-entry" application |
| Integrated | Built by integrating multiple heterogeneous sources; data cleaning and integration make naming, encoding, units and measures consistent. | Gender coded M/F in one source and 1/0 in another becomes one standard |
| Time-variant | Data is stored to provide information from a historical perspective (typically 5-10 years). Every key structure contains a time element, explicitly or implicitly. | Sales of 2019, 2020, 2021 all kept for trend analysis |
| Non-volatile | Physically separate store; it does not require transaction processing, recovery and concurrency control. Only two operations occur: initial loading of data and read access. No online update/delete. | Yesterday's loaded sales rows are never edited |
Data warehouse vs data mart vs virtual warehouse
- Enterprise warehouse: the whole organisation; large, months/years to build.
- Data mart: a subset for a specific group/department (e.g. marketing data mart). Independent data mart = sourced directly from operational systems; dependent data mart = sourced from the enterprise warehouse.
- Virtual warehouse: only a set of views over operational databases; easy to build, but it puts extra load on operational servers.
ETL is the loading machinery: Extract from sources, Transform (clean, standardise, aggregate), Load into the warehouse. Add refresh as the fourth ongoing operation.
2.2 OLTP vs OLAP asked almost every year
| Feature | OLTP (operational DB) | OLAP (data warehouse) |
|---|---|---|
| Purpose | Day-to-day operations, transaction processing | Decision support, analysis |
| Users | Clerks, DBAs, IT professionals | Managers, executives, analysts |
| Data | Current, detailed, up-to-date | Historical, summarised, consolidated |
| Design | ER model, application-oriented, normalised (3NF) | Star/snowflake schema, subject-oriented, denormalised |
| Access | Read/write, short atomic transactions, index on primary key | Mostly read, complex scans and aggregations |
| Unit of work | Simple transaction | Complex query |
| Records accessed | Tens | Millions |
| Size | 100 MB - GB | 100 GB - TB |
| Metric | Transaction throughput | Query throughput, response time |
Three reasons: (1) Performance: complex OLAP queries would degrade transaction performance of mission-critical operational systems; the two workloads need different access methods and indexes. (2) Data quality and history: operational data is not cleaned, not integrated and holds only current values, while decision support needs consolidated history. (3) Concurrency and recovery: mixing them would complicate transaction control.
2.3 Multi-dimensional data model
The warehouse is modelled as a data cube which allows data to be viewed in multiple dimensions.
- Dimension: a perspective or entity with respect to which the organisation keeps records: time, item, branch, location. Each has a dimension table describing it.
- Fact table: contains the numeric measures (dollars_sold, units_sold, average_sales) plus foreign keys to the dimension tables.
- Measure: a numeric function evaluated at each point of the cube space. Three types: distributive (count, sum, min, max, which can be computed by partitioning), algebraic (avg, standard deviation, obtained from distributive functions), holistic (median, mode, rank, for which no constant-size sub-aggregate exists).
- Cuboid: the cube for a given set of dimensions. The base cuboid is
the lowest level (all n dimensions); the apex cuboid (denoted
all) is the total summary. The lattice of all cuboids is the data cube.
For n dimensions the cube contains 2n cuboids. With concept hierarchies of Li levels per dimension the total is T = ∏i=1..n (Li + 1). Example: 4 dimensions with 3 levels each → (3+1)4 = 256 cuboids. This explains why full materialisation is impossible.
2.4 Schemas: star, snowflake, fact constellation draw all three
| Star | Snowflake | Fact constellation (galaxy) | |
|---|---|---|---|
| Structure | One fact table + denormalised dimension tables | One fact table + normalised dimension hierarchies | Multiple fact tables sharing dimension tables |
| Redundancy | High | Low | Depends |
| Joins per query | Few, so fastest | More joins, so slower | Many |
| Storage | More | Less | Most |
| Best for | Data marts, most common in practice | Very large dimension tables | Enterprise warehouse (e.g. sales + shipping facts sharing time, item, location) |
Data marts usually use star or snowflake since they model a single subject; the enterprise warehouse uses fact constellation since it models multiple subjects.
2.5 Data cubes and OLAP operations guaranteed question
For each operation write: name → definition → example on the AllElectronics cube. E.g. Roll-up: aggregation on a cube either by climbing a concept hierarchy or by dimension reduction. Example: rolling up on location from the level of city to the level of country aggregates Kathmandu + Pokhara + Biratnagar into Nepal.
OLAP server types short question
- ROLAP: relational OLAP. Data stays in relational tables; uses star schema plus bitmap/join indexes. Scalable to huge data, slower queries.
- MOLAP: multidimensional OLAP. Data stored in a multidimensional array; fast indexing to precomputed summaries, but sparse cubes waste space (needs two-level sparse compression).
- HOLAP: hybrid. Detailed data in relational store, aggregations in multidimensional store. Best of both, e.g. Microsoft SQL Server Analysis Services.
- Specialised SQL servers: SQL engines optimised for star queries.
2.6 Data warehouse architecture draw the 3-tier
Design approaches
- Top-down: build the enterprise warehouse first, then dependent data marts. Consistent, but expensive and slow.
- Bottom-up: build data marts first and integrate later. Fast, low cost, but risks inconsistency.
- Recommended (incremental/hybrid): define a high-level enterprise model, implement independent marts in parallel, then integrate.
The four warehouse design views
Top-down view (what information the enterprise needs) · data source view (what the operational systems hold) · data warehouse view (fact and dimension tables) · business query view (what the end user sees).
Metadata repository: list its contents
- Warehouse structure: schema, view, dimension, hierarchy, derived-data definitions, mart location.
- Operational metadata: data lineage (history of migrated data), currency (active/archived/purged), monitoring information.
- Algorithms for summarisation and mapping from operational environment to warehouse.
- Business metadata: business terms, ownership, charging policies.
2.7 Data warehouse implementation
(a) Efficient cube computation: the materialisation question
- No materialisation: compute every cuboid on the fly. Slow queries.
- Full materialisation: precompute all 2n cuboids. Fastest queries but explosive storage.
- Partial materialisation: precompute a selected subset. This is the practical choice. Selection uses query frequency, cost, and storage constraints; iceberg cubes store only cells above a minimum-support threshold.
The compute cube operator generates the lattice; algorithms include multiway array aggregation (MOLAP, bottom-up), BUC (bottom-up computation for iceberg cubes, top-down order) and Star-Cubing.
(b) Indexing OLAP data
- Bitmap index: for each distinct value of a low-cardinality attribute, a bit vector of length = number of rows. Comparison, join and aggregation become fast bit operations (AND/OR). Inefficient for high-cardinality attributes.
- Join index: pre-computes the join between the fact table and a dimension table by registering the joinable rows. A bitmapped join index combines both.
Attribute region ∈ {Asia, Europe} over 4 rows (Asia, Europe, Asia, Asia):
Asia = 1 0 1 1, Europe = 0 1 0 0. Query "region = Asia AND type = home" is
answered by ANDing two bit vectors.
(c) Efficient query processing: three steps
- Determine which operations should be performed on the available cuboids (transform the selection, roll-up, drill-down into corresponding SQL/OLAP operations).
- Determine to which materialised cuboid(s) the relevant operations should be applied.
- Choose the cuboid with the least cost: prefer one with fewer, smaller cells, matching dimensions, and available indexes.
(d) From data warehousing to data mining
Three uses of a warehouse: information processing (querying, reporting), analytical processing (OLAP: slice, dice, roll-up), and data mining (knowledge discovery of hidden patterns, rules, models). OLAM (Online Analytical Mining) integrates OLAP with mining so the user can mine interactively at different abstraction levels; it sits between the OLAP engine and the user interface and shares the same cube infrastructure.
OLAP is a deductive, user-driven summarisation tool: the user must know what to look for and the system verifies it. Data mining is inductive, discovery-driven: the system finds patterns the user did not anticipate. OLAP answers "what happened"; data mining answers "why did it happen and what will happen next".
2.8 Likely exam questions from this unit
- Define a data warehouse. Explain its four key features with examples. 5-10
- Differentiate OLTP and OLAP. Why is a separate data warehouse required? 10
- Explain the multi-dimensional data model. Draw star, snowflake and fact constellation schemas for a sales warehouse and compare them. 10
- What is a data cube? Explain OLAP operations with an example each. 10
- Explain the three-tier data warehouse architecture with a diagram. 10
- Discuss data cube materialisation and OLAP indexing (bitmap, join index). 5-10
- Differentiate ROLAP, MOLAP and HOLAP. 5
- How many cuboids does a 5-dimensional cube with 3-level hierarchies contain? 2-5
Data Processing & Data Mining
12 hrsReal-world data is dirty: incomplete (missing attribute values), noisy (errors, outliers) and inconsistent (discrepancies in codes or names). "No quality data, no quality mining results". Garbage in, garbage out. Preprocessing improves data quality along the dimensions of accuracy, completeness, consistency, timeliness, believability and interpretability.
3.1 Data cleaning
(a) Missing values: six methods, in increasing order of quality
- Ignore the tuple: usually done when the class label is missing; poor when the percentage of missing values per attribute is large.
- Fill in manually: accurate but tedious and infeasible for large data.
- Use a global constant such as "Unknown" or −∞: simple, but the mining program may mistakenly treat "Unknown" as an interesting concept.
- Use the attribute mean for all samples.
- Use the attribute mean for samples of the same class: better.
- Use the most probable value: inferred by regression, Bayesian inference or a decision tree. This is the most popular and most accurate strategy, so say so.
(b) Noisy data: smoothing techniques
Noise = random error or variance in a measured variable.
- Binning: sort values, partition into equal-frequency (equi-depth) bins, then smooth by bin means, bin medians or bin boundaries (each value is replaced by the nearer boundary).
- Regression: fit the data to a function (linear/multiple) and use fitted values.
- Clustering: values falling outside every cluster are detected as outliers.
- Combined computer-and-human inspection: the computer flags suspicious values, a human confirms.
Sorted price data: 4, 8, 15, 21, 21, 24, 25, 28, 34. Partition into 3 equal-frequency
bins of 3 values each.
Bins: B1 = 4, 8, 15 · B2 = 21, 21, 24 · B3 = 25, 28, 34
Smoothing by bin means (mean of B1 = 27/3 = 9, B2 = 66/3 = 22, B3 = 87/3 = 29):
B1 = 9, 9, 9 · B2 = 22, 22, 22 · B3 = 29, 29, 29
Smoothing by bin boundaries (replace each value by the closer of min and max):
B1 = 4, 4, 15 · B2 = 21, 21, 24 · B3 = 25, 25, 34
Smoothing by bin medians: B1 = 8, 8, 8 · B2 = 21, 21, 21 · B3 = 28, 28, 28
3.2 Data integration
Combining data from multiple sources into a coherent store. Three problems to write about:
- Entity identification problem: is
cust_idin one database the same ascustomer_numberin another? Solved using metadata (name, meaning, data type, range, null rules). - Redundancy: an attribute derivable from another (annual revenue from monthly sales). Detected by correlation analysis.
- Duplication and conflict detection: the same real-world entity with different attribute values, e.g. price in NPR vs USD, weight in kg vs pounds.
Correlation analysis: two formulas to remember
2×2 table, n = 1500. Observed: (male, fiction) = 250, (male, non-fiction) = 200,
(female, fiction) = 200, (female, non-fiction) = 850.
Row totals 450 and 1050; column totals 450 and 1050.
e(male,fiction) = 450 × 450 / 1500 = 135. Similarly 315, 315, 735.
χ² = (250−135)²/135 + (200−315)²/315 + (200−315)²/315 + (850−735)²/735 = 97.98 + 41.98 + 41.98 + 17.99
= 199.93.
With df = 1, the 0.001 significance threshold is 10.83. Since 199.93 > 10.83, gender and preferred
reading are strongly correlated.
3.3 Data transformation
- Smoothing: remove noise (binning, regression, clustering).
- Aggregation: summarise; e.g. daily sales aggregated to monthly, building a cube.
- Generalisation: replace low-level data with higher-level concepts using a concept hierarchy (street → city → country).
- Normalisation: scale into a small specified range.
- Attribute/feature construction: add new attributes derived from existing ones (area from height × width).
Three normalisation methods numerical: learn all three
Income ranges from 12,000 to 98,000. Normalise 73,600 to [0.0, 1.0]:
v' = (73600 − 12000)/(98000 − 12000) × (1 − 0) + 0 = 61600/86000 = 0.716
If mean = 54,000 and σ = 16,000, z-score of 73,600:
v' = (73600 − 54000)/16000 = 1.225
Decimal scaling with values in the range −986 to 917: max |v| = 986, so j = 3 → −986 becomes −0.986 and 917 becomes 0.917.
3.4 Data reduction
Obtain a reduced representation that produces (almost) the same analytical results in far less volume. Five strategies:
- Data cube aggregation: aggregate to the smallest cuboid that still answers the task.
- Attribute subset selection: remove irrelevant/redundant attributes. Heuristic
methods since 2n subsets exist:
- Stepwise forward selection: start empty, add the best attribute each round.
- Stepwise backward elimination: start full, remove the worst each round.
- Combination of forward and backward.
- Decision-tree induction: attributes appearing in the tree are the relevant ones.
- Dimensionality reduction: encode data to a compressed form. Wavelet transform (DWT: keeps a small fraction of the strongest coefficients, lossy but good for sparse/skewed data) and Principal Component Analysis (finds k orthonormal vectors, the principal components, that best represent the data; the components are sorted by variance and the weak ones are dropped).
- Numerosity reduction: replace data by smaller representations: parametric (regression, log-linear models, which store only the parameters) and non-parametric (histograms, clustering, sampling).
- Discretisation and concept hierarchy generation: see next section.
Sampling methods (write all four)
SRSWOR: simple random sample without replacement · SRSWR: with replacement · Cluster sample: the data is grouped into M clusters, a random sample of clusters is taken · Stratified sample: data is divided into strata and a sample is drawn from each, which guarantees representation of rare classes.
3.5 Discretisation and concept hierarchy generation
Discretisation divides the range of a continuous attribute into intervals and replaces the actual values by interval labels. A concept hierarchy for an attribute defines a sequence of mappings from low-level concepts to higher-level, more general concepts (young → age 20-39). Supervised discretisation uses class information; unsupervised does not. Top-down (splitting) starts with one interval and splits; bottom-up (merging) starts with all points as intervals and merges.
For numeric attributes: five techniques
- Binning: equal-width or equal-frequency, applied recursively. Unsupervised, top-down, sensitive to outliers.
- Histogram analysis: equal-width or equal-depth histograms, applied recursively until a minimum interval size is reached. Unsupervised.
- Entropy-based discretisation: supervised, top-down. Choose the split point that minimises the expected information requirement; recurse until the information gain is below a threshold. This is the most commonly used and worth naming explicitly.
- χ²-merging (ChiMerge): supervised, bottom-up. Adjacent intervals with the lowest χ² (i.e. most similar class distributions) are merged recursively.
- Cluster analysis / natural partitioning (3-4-5 rule): the 3-4-5 rule partitions a range into 3, 4 or 5 relatively uniform intervals depending on the most significant digit, giving "natural" looking boundaries.
For categorical attributes: four methods of generating hierarchies
- Explicit specification of a partial/total order by the user at the schema level: street < city < province < country.
- Explicit data grouping for a small portion of intermediate-level data: {Kathmandu, Lalitpur, Bhaktapur} ⊂ Bagmati.
- Specification of a set of attributes but not their order: the system generates the order automatically using the heuristic that an attribute with more distinct values is at a lower level of the hierarchy (country 15 values < province 65 < city 3567 < street 674,339).
- Specification of only a partial set of attributes: the system uses the database schema and semantic ties to fill in the rest.
3.6 Data mining primitives and DMQL
A data mining task is specified in the form of a data mining query, built from five primitives. Memorise them as T-K-B-I-P.
| Primitive | What it specifies | DMQL clause |
|---|---|---|
| 1. Task-relevant data | Database/warehouse, tables, conditions, relevant attributes/dimensions, grouping and ordering | use database … from … where … in relevance to … |
| 2. Kind of knowledge to be mined | Characterisation, discrimination, association, classification, prediction, clustering, evolution | mine characteristics /
mine associations / classify according to … |
| 3. Background knowledge | Concept hierarchies (schema, set-grouping, operation-derived, rule-based) and user beliefs, allowing mining at multiple abstraction levels | use hierarchy … for … |
| 4. Interestingness measures | Thresholds that filter uninteresting patterns: support, confidence, simplicity, certainty (accuracy), novelty | with support threshold = 5 % with confidence threshold = 70 % |
| 5. Presentation and visualisation | Form of the discovered pattern: rules, tables, crosstabs, pie/bar charts, decision trees, cubes; plus drill/roll operations on results | display as table / rules |
DMQL was designed on the model of SQL so that mining can be embedded in relational query processing. An alternative is Microsoft's OLE DB for Data Mining (DMX).
3.7 Concept description: characterisation, discrimination and class comparison
Concept description = characterisation + comparison. It generates descriptions for data classes at a general level.
Attribute-Oriented Induction (AOI): the standard algorithm
- Collect the task-relevant data with a relational query (the initial working relation).
- Perform attribute removal: if an attribute has a large number of distinct values and there is no higher-level concept for it (e.g. name, phone), remove it.
- Perform attribute generalisation: if there is a higher-level concept in the concept hierarchy, replace the values by the generalised value (birth_place: Kathmandu → Nepal).
- Apply attribute generalisation control: generalise until the number of distinct values of the attribute is under the attribute generalisation threshold (typically 2-8), or until the total number of tuples is under the generalised relation threshold (typically 10-30).
- Aggregate identical tuples and accumulate a count (and other aggregates like sum), then present the result as a generalised relation, crosstab, chart or a set of quantitative rules.
Class comparison (discrimination): how it differs from characterisation
The procedure is the same as AOI but applied to two or more classes: a target class and one or more contrasting classes. Critically, all classes must be generalised to the same level of abstraction (synchronous generalisation) so they are comparable. The output includes a t-weight (typicality of a tuple within its own class) and a d-weight (discriminating weight: how much a tuple belongs to the target rather than the contrasting class).
Compare graduate students (target) with undergraduate students (contrasting) at AllElectronics University. If for the tuple (major = "science", birth_country = "Nepal", age = "25-30") the graduate count is 90 and the undergraduate count is 210, then d-weight = 90/(90+210) = 30 %, which means the tuple is more typical of undergraduates.
3.8 Association rule mining the highest-yield topic in the paper
Let I = {i1,…,im} be a set of items and D a set of transactions. An association rule is an implication A ⇒ B where A ⊂ I, B ⊂ I and A ∩ B = ∅.
An itemset whose support ≥ min_sup is a frequent itemset. A rule that satisfies both min_sup and min_conf is a strong rule. A k-itemset contains k items.
The two-step process: say this before any algorithm:
- Find all frequent itemsets (support ≥ min_sup). This is the expensive step.
- Generate strong association rules from them (confidence ≥ min_conf). This is straightforward.
Classification of association rules: the syllabus asks this directly
| Basis | Types | Example |
|---|---|---|
| Type of values | Boolean (presence/absence) vs quantitative (numeric values, needs discretisation) | buys(bread) ⇒ buys(butter) | age(30..39) ∧ income(42K..48K) ⇒ buys(TV) |
| Dimensions involved | Single-dimensional (one predicate, repeated) vs multidimensional (two or more predicates) | buys(X,"milk") ⇒ buys(X,"bread") | age(X,"20..29") ∧ occupation(X,"student") ⇒ buys(X,"laptop") |
| Levels of abstraction | Single-level vs multilevel | buys("laptop") ⇒ buys("printer") | buys("computer") ⇒ buys("printer") |
| Nature of the pattern | Frequent itemsets, closed itemsets, max-patterns, correlation rules | - |
"Single-dimensional" because only one predicate, buys, is repeated; "Boolean" because we only care whether an item is present, not how many. This is exactly what market basket analysis and the Apriori algorithm deal with. If a question says "mine single-dimensional Boolean association rules", it is asking you to run Apriori.
3.9 The Apriori algorithm practise this until automatic
All non-empty subsets of a frequent itemset must also be frequent. Equivalently: if an itemset is infrequent, all of its supersets are infrequent and can be pruned. Apriori is a level-wise, iterative algorithm: k-itemsets are used to explore (k+1)-itemsets.
The two sub-steps of each iteration
- Join step: Ck is generated by joining Lk−1 with itself. Two itemsets are joinable only if their first (k−2) items are identical and the last items are in lexicographic order (l1[k−1] < l2[k−1]), which avoids duplicates.
- Prune step: remove any candidate in Ck that has some (k−1)-subset not in Lk−1. Then scan the database once to count the survivors and keep those with count ≥ min_sup.
Nine transactions, min_sup count = 2 (i.e. 22 %), min_conf = 70 %.
| TID | Items | TID | Items | TID | Items |
|---|---|---|---|---|---|
| T100 | I1, I2, I5 | T400 | I1, I2, I4 | T700 | I1, I3 |
| T200 | I2, I4 | T500 | I1, I3 | T800 | I1, I2, I3, I5 |
| T300 | I2, I3 | T600 | I2, I3 | T900 | I1, I2, I3 |
Pass 1. Scan D and count each item. C1: I1 = 6, I2 = 7, I3 = 6, I4 = 2, I5 = 2. All ≥ 2, so L1 = {I1, I2, I3, I4, I5}.
Pass 2. C2 = L1 ⋈ L1 gives 10 candidates. Counts:
{I1,I2}=4, {I1,I3}=4, {I1,I4}=1, {I1,I5}=2, {I2,I3}=4, {I2,I4}=2, {I2,I5}=2, {I3,I4}=0, {I3,I5}=1,
{I4,I5}=0.
L2 = {I1,I2}:4, {I1,I3}:4, {I1,I5}:2, {I2,I3}:4, {I2,I4}:2, {I2,I5}:2
Pass 3. Join L2 ⋈ L2 → {I1,I2,I3}, {I1,I2,I5}, {I1,I3,I5},
{I2,I3,I4}, {I2,I3,I5}, {I2,I4,I5}.
Prune: {I1,I3,I5} contains {I3,I5} ∉ L2 → drop. {I2,I3,I4} contains {I3,I4} → drop.
{I2,I3,I5} contains {I3,I5} → drop. {I2,I4,I5} contains {I4,I5} → drop.
So C3 = {I1,I2,I3}, {I1,I2,I5}. Scanning gives counts 2 and 2.
L3 = {I1,I2,I3}:2, {I1,I2,I5}:2
Pass 4. C4 = {I1,I2,I3,I5}; its subset {I1,I3,I5} ∉ L3, so it is pruned. C4 = ∅ → algorithm terminates.
Rule generation from l = {I1, I2, I5} (support count 2 → support 2/9 = 22 %). All non-empty proper subsets: {I1}, {I2}, {I5}, {I1,I2}, {I1,I5}, {I2,I5}.
| Rule | Confidence computation | Confidence | Strong? (≥70 %) |
|---|---|---|---|
| I1 ∧ I2 ⇒ I5 | 2 / 4 | 50 % | No |
| I1 ∧ I5 ⇒ I2 | 2 / 2 | 100 % | Yes |
| I2 ∧ I5 ⇒ I1 | 2 / 2 | 100 % | Yes |
| I1 ⇒ I2 ∧ I5 | 2 / 6 | 33 % | No |
| I2 ⇒ I1 ∧ I5 | 2 / 7 | 29 % | No |
| I5 ⇒ I1 ∧ I2 | 2 / 2 | 100 % | Yes |
Output: three strong rules. Always present rule generation as a table like this, since it is fast to write and easy for the examiner to mark.
Improving the efficiency of Apriori: six methods
- Hash-based technique (DHP): while counting C1, hash 2-itemsets into buckets; a bucket whose count is below min_sup cannot contain a frequent 2-itemset, so those candidates are removed.
- Transaction reduction: a transaction that contains no frequent k-itemset cannot contain any frequent (k+1)-itemset, so mark it and skip it in later scans.
- Partitioning: requires only two database scans. Partition D so each part fits in memory, find local frequent itemsets in each partition (any global frequent itemset must be frequent in at least one partition), then a second scan counts the global support of these candidates.
- Sampling: mine a random sample with a slightly lowered support threshold, then verify against the full database; trades accuracy for efficiency.
- Dynamic itemset counting (DIC): new candidates are added at start points during the scan rather than only at the end of a pass, reducing the number of scans.
- Vertical data format (ECLAT): store item → TID_set; support = length of the TID set, and k-itemsets are obtained by intersecting TID sets.
3.10 FP-Growth: mining without candidate generation compare with Apriori
Two bottlenecks of Apriori that FP-growth removes: (i) it generates a huge number of candidates (104 frequent 1-itemsets produce ~107 candidate 2-itemsets); (ii) it needs to scan the database k+1 times for the longest pattern of length k.
Steps of FP-growth
- First scan: find frequent 1-itemsets and sort them in descending order of support, the F-list. For our dataset: I2:7, I1:6, I3:6, I4:2, I5:2.
- Second scan: build the FP-tree. For each transaction, keep only frequent items, sort by the F-list order, and insert as a branch, incrementing counts on shared prefixes. A header table links all nodes of the same item.
- Mine the tree by starting from the least frequent item and, for each item, collecting its conditional pattern base (the set of prefix paths), constructing its conditional FP-tree, and recursively mining it. Concatenate the suffix to produce the frequent patterns.
| Item | Conditional pattern base | Conditional FP-tree | Frequent patterns generated |
|---|---|---|---|
| I5 | {(I2 I1 : 1), (I2 I1 I3 : 1)} | ⟨I2:2, I1:2⟩ | {I2,I5}:2, {I1,I5}:2, {I2,I1,I5}:2 |
| I4 | {(I2 I1 : 1), (I2 : 1)} | ⟨I2:2⟩ | {I2,I4}:2 |
| I3 | {(I2 I1 : 2), (I2 : 2), (I1 : 2)} | ⟨I2:4, I1:2⟩, ⟨I1:2⟩ | {I2,I3}:4, {I1,I3}:4, {I2,I1,I3}:2 |
| I1 | {(I2 : 4)} | ⟨I2:4⟩ | {I2,I1}:4 |
The result is identical to Apriori's, obtained with only two database scans and no candidate generation.
| Apriori | FP-growth | |
|---|---|---|
| Approach | Breadth-first, candidate generate-and-test | Depth-first, divide-and-conquer, pattern growth |
| Candidates | Generates and tests huge candidate sets | No candidate generation |
| DB scans | k + 1 scans | Only 2 scans |
| Data structure | Hash tree / array | FP-tree (compressed prefix tree) |
| Memory | Lower per pass, but repeated I/O | Whole FP-tree must fit in memory |
| Speed | Slower, degrades with long patterns | About an order of magnitude faster |
3.11 Multilevel and multidimensional association rules
(a) Multilevel association rules
Rules mined at multiple levels of a concept hierarchy (all → computer → laptop computer → IBM laptop). Strong rules are often hard to find at the primitive level because support there is low, so we mine top-down, level by level.
Four support strategies (name them all):
- Uniform support: the same min_sup at every level. Simple; search can be optimised (if an ancestor is infrequent, its descendants are ignored). Problem: a high threshold misses low-level rules, a low threshold generates too many high-level rules.
- Reduced support: each lower level has a smaller min_sup. This is the recommended approach. Search strategies within it: level-by-level independent, level-cross filtering by single item, level-cross filtering by k-itemset, and controlled level-cross filtering using a "level passage threshold".
- Group-based support: the user or expert sets a group-wise threshold per subset of items (e.g. lower threshold for expensive laptops).
- Redundancy filtering: a rule is redundant if its support and confidence are close to the "expected" values based on its ancestor rule. E.g. if computer ⇒ printer [8 %, 70 %] holds and laptops are one quarter of computers, then laptop ⇒ printer [2 %, 72 %] adds nothing new and should be filtered out.
(b) Multidimensional association rules
Rules involving two or more distinct predicates/dimensions, typically mined from a relational table or data warehouse rather than a transaction table.
Since dimensions can be numeric, there are three ways to handle them:
- Static discretisation using predefined concept hierarchies; the data is transformed into a cube and cells are counted (a cube is well suited because cells already store counts).
- Dynamic quantitative association rules: numeric attributes are discretised dynamically to maximise the confidence or compactness of the rules; adjacent 2-D cells (a "grid") are clustered/merged into larger rectangular regions.
- Distance-based association rules: a dynamic discretisation that considers the distance between data points, giving intervals that are semantically more meaningful.
3.12 From association analysis to correlation analysis very likely 5 marks
10,000 transactions: 6,000 include computer games, 7,500 include videos, 4,000 include both.
Rule buys(games) ⇒ buys(videos) has support = 4000/10000 = 40 % and confidence = 4000/6000 =
66.7 %, a "strong" rule at min_sup = 30 %, min_conf = 60 %.
But it is misleading: the prior probability of buying videos is 7500/10000 = 75 %, which
is higher than 66.7 %. Buying games actually decreases the chance of buying videos. The
two are negatively correlated. Support and confidence alone are not enough.
Other measures worth naming: χ², all_confidence, cosine. Lift and χ² are not null-invariant (they are affected by the number of transactions containing neither item), whereas all_confidence and cosine are. A good sentence to include for full marks.
Also mention constraint-based mining, where the user supplies knowledge, data, dimension, rule or interestingness constraints. Constraints are classified as anti-monotone (if violated, all supersets violate, e.g. sum(price) ≤ 100), monotone, succinct (candidates can be enumerated up-front) and convertible.
3.13 Likely exam questions from this unit
- Why is data preprocessing needed? Explain the major tasks of data preprocessing. 10
- Explain the methods of handling missing values and noisy data. Apply binning (means / boundaries) to the given data. 10
- Explain normalisation. Normalise the given value using min-max, z-score and decimal scaling. 5
- Explain data reduction strategies. What is attribute subset selection? 10
- What is discretisation and concept hierarchy generation? Explain the methods for numeric and categorical data. 10
- Explain the primitives of a data mining task. Write a DMQL query for a given scenario. 10
- Explain attribute-oriented induction. How is class comparison performed? Define t-weight and d-weight. 10
- Define support and confidence. Find all frequent itemsets and strong association rules using Apriori for the given transactions. 10-15
- Explain FP-growth with the FP-tree for the given data and compare it with Apriori. 10
- Explain multilevel and multidimensional association rules. What is a redundant multilevel rule? 10
- Show with an example that support and confidence can be misleading. Explain lift/correlation. 5
Classification and Prediction
12 hrs4.1 Classification vs prediction, and the two-step process
Classification predicts categorical (discrete, unordered) class labels; it builds a model based on a training set and uses it to classify new data. Prediction models continuous-valued functions, i.e. it predicts unknown or missing numeric values. Both are supervised learning, because the training tuples come with known class labels.
Preparing the data for classification
Data cleaning · relevance analysis (remove redundant/irrelevant attributes, also called feature selection) · data transformation (normalisation, generalisation).
Criteria for comparing classification methods short question
Accuracy (predictive accuracy of the classifier/predictor) · Speed (model construction and usage time) · Robustness (handling noise and missing values) · Scalability (efficiency on disk-resident large databases) · Interpretability (how understandable the model is) · Goodness of rules (tree size, compactness of rules).
4.2 Decision tree induction certain 10-15 marks
A decision tree is a flowchart-like tree structure in which each internal node denotes a test on an attribute, each branch represents an outcome of the test, and each leaf node holds a class label. The topmost node is the root. A path from the root to a leaf translates directly into an IF-THEN rule.
Tree construction principle
The tree is built top-down, recursively, in a divide-and-conquer manner. At each node the algorithm selects the attribute that best separates the tuples into individual classes (highest purity) using an attribute selection measure. The classic algorithms are ID3 (Quinlan, 1986, uses information gain), C4.5 (its successor, uses gain ratio) and CART (binary trees, uses the Gini index).
The generic algorithm Generate_decision_tree(D, attribute_list)
- Create a node N.
- If all tuples in D belong to the same class C, return N as a leaf labelled C.
- If attribute_list is empty, return N as a leaf labelled with the majority class in D.
- Apply the attribute selection method to find the splitting criterion (best attribute, and split point/subset if needed); label N with it.
- For each outcome j of the splitting criterion, let Dj be the partition of tuples. If Dj is empty, attach a leaf labelled with the majority class of D; otherwise attach the subtree returned by recursively calling the algorithm on Dj.
- Return N. Terminating conditions: all tuples of one class, no attributes remain, or the partition is empty.
(i) A discrete-valued attribute A: one branch per known value. (ii) A continuous-valued attribute: a binary split at the best split-point, A ≤ split_point and A > split_point. (iii) A discrete-valued attribute with a binary tree requirement (CART): the test is A ∈ SA? giving a two-way split.
Attribute selection measures
Information gain is biased towards attributes with many values (an ID attribute would give maximum gain and a useless tree). Gain ratio tends to prefer unbalanced splits where one partition is much smaller. Gini index is biased towards multi-valued attributes and has difficulty when the number of classes is large; it also favours equal-sized partitions with high purity.
| RID | age | income | student | credit_rating | buys_computer |
|---|---|---|---|---|---|
| 1 | youth | high | no | fair | no |
| 2 | youth | high | no | excellent | no |
| 3 | middle_aged | high | no | fair | yes |
| 4 | senior | medium | no | fair | yes |
| 5 | senior | low | yes | fair | yes |
| 6 | senior | low | yes | excellent | no |
| 7 | middle_aged | low | yes | excellent | yes |
| 8 | youth | medium | no | fair | no |
| 9 | youth | low | yes | fair | yes |
| 10 | senior | medium | yes | fair | yes |
| 11 | youth | medium | yes | excellent | yes |
| 12 | middle_aged | medium | no | excellent | yes |
| 13 | middle_aged | high | yes | fair | yes |
| 14 | senior | medium | no | excellent | no |
Step 1, entropy of D. 9 "yes" and 5 "no" out of 14:
Info(D) = −(9/14)log₂(9/14) − (5/14)log₂(5/14) = 0.410 + 0.531 = 0.940 bits
Step 2, Info for age. youth (2 yes, 3 no), middle_aged (4 yes, 0 no),
senior (3 yes, 2 no):
Infoage(D) = (5/14)(0.971) + (4/14)(0) + (5/14)(0.971) = 0.694 bits
Gain(age) = 0.940 − 0.694 = 0.246 bits
Step 3, the other attributes. Gain(income) = 0.029, Gain(student) = 0.151, Gain(credit_rating) = 0.048.
Step 4, choose the root. age has the highest gain → it becomes the root. The middle_aged branch is pure ("yes"), so it becomes a leaf immediately. Recurse on the youth and senior partitions: student is selected for youth and credit_rating for senior.
Gain ratio check for income: SplitInfoincome(D) = −(4/14)log₂(4/14) −(6/14)log₂(6/14) −(4/14)log₂(4/14) = 1.557 → GainRatio(income) = 0.029/1.557 = 0.019.
Gini of D: 1 − (9/14)² − (5/14)² = 1 − 0.413 − 0.128 = 0.459.
4.3 Tree construction with presorting: scalable decision trees
Classical ID3/C4.5/CART assume the whole training set fits in memory; they thrash when data is disk-resident. Presorting sorts each numeric attribute once at the start so that the best split point can be found in a single linear pass at every node, instead of re-sorting at every node.
| Algorithm | Key idea | Limitation |
|---|---|---|
| SLIQ (Supervised Learning In Quest) | Uses a disk-resident attribute list for each attribute (attribute value, tuple index), presorted once, plus a memory-resident class list (class label, node reference) that is updated as the tree grows. | The class list must fit in memory, so the training-set size is limited by memory. |
| SPRINT (Scalable PaRallelizable INduction of decision Trees) | Removes all memory restrictions: each attribute list holds (attribute value, class label, RID), so no separate class list is needed. Lists are split along with the nodes using a hash table of RIDs. | The hash table used for splitting must fit in memory; needs a costly hash join. |
| RainForest | Keeps an AVC-set (Attribute-Value, Classlabel) per attribute at each node; its size depends only on the number of distinct values, not on the number of tuples. The AVC-group of a node is the set of AVC-sets for all attributes. | Still needs several scans. |
| BOAT (Bootstrapped Optimistic Algorithm for Tree construction) | Uses bootstrapping on samples that fit in memory to build several trees, then constructs a "coarse" tree that is refined. Needs only two scans, is 2-3× faster, and uniquely supports incremental updates to the tree. | - |
4.4 Pruning techniques frequent
Because of noise and outliers, the fully grown tree overfits the training data, so it has branches that reflect anomalies rather than real structure, so accuracy on unseen data drops. Pruning removes the least reliable branches, producing a smaller, faster and more accurate tree that is also easier to understand.
| Prepruning | Postpruning | |
|---|---|---|
| When | Halts tree construction early; a node is not split and becomes a leaf | Removes subtrees from an already fully grown tree, replacing them with a leaf labelled with the majority class |
| Decision made using | A threshold on the goodness measure (information gain, Gini, χ²) or on the number of tuples at the node | Cost-complexity, pessimistic error or MDL after the tree is built |
| Problem | Choosing an appropriate threshold; too high gives an oversimplified tree, too low leaves the tree unchanged | More computation than prepruning, since the full tree is built first |
| In practice | Cheaper | More reliable and generally preferred |
Postpruning methods to name
- Cost-complexity pruning (CART): cost = f(number of leaves, error rate). Uses a separate pruning set; a subtree is replaced by a leaf if that reduces the cost.
- Pessimistic pruning (C4.5): uses only the training set but adds a penalty (continuity correction) to the training error to compensate for its optimistic bias, so no separate pruning set is needed.
- MDL, Minimum Description Length: chooses the tree that requires the fewest bits to encode both the tree and the exceptions; needs no test set and is less biased toward large trees.
Integration of pruning and construction syllabus term
Two-phase build-then-prune is wasteful: effort is spent expanding nodes that will be pruned away. PUBLIC (PrUning and BuiLding Integrated in Classification) integrates the two: during building, before a node is expanded, it computes a lower bound on the minimum cost of the subtree rooted at that node. If the node would certainly be pruned later, it is turned into a leaf immediately. The result is identical to the tree produced by build-then-prune, but built faster. The same idea appears in Rainforest + pruning and in the interleaved pruning of MDL-based methods.
Other issues in tree induction
- Repetition: an attribute is repeatedly tested along a path (A < 60, then A < 45).
- Replication: duplicate subtrees exist within the tree. Both are solved by multivariate splits (tests on a combination of attributes) and attribute construction.
- Extracting rules: one IF-THEN rule per root-to-leaf path; rules are mutually exclusive and exhaustive, and can be pruned individually.
4.5 Bayesian classification numerical certain
The naive Bayesian classifier assigns X to the class Ci that maximises P(Ci|X). Since P(X) is constant, we maximise P(X|Ci)·P(Ci). The class-conditional independence assumption ("naive") says the attributes are conditionally independent given the class, so:
Classify X = (age = youth, income = medium, student = yes, credit_rating = fair).
Priors: P(buys = yes) = 9/14 = 0.643 · P(buys = no) = 5/14 = 0.357
| Conditional probability | Class = yes | Class = no |
|---|---|---|
| P(age = youth | C) | 2/9 = 0.222 | 3/5 = 0.600 |
| P(income = medium | C) | 4/9 = 0.444 | 2/5 = 0.400 |
| P(student = yes | C) | 6/9 = 0.667 | 1/5 = 0.200 |
| P(credit_rating = fair | C) | 6/9 = 0.667 | 2/5 = 0.400 |
| P(X | C) | 0.222×0.444×0.667×0.667 = 0.044 | 0.600×0.400×0.200×0.400 = 0.019 |
| P(X | C) × P(C) | 0.044 × 0.643 = 0.028 | 0.019 × 0.357 = 0.007 |
0.028 > 0.007, so the naive Bayesian classifier predicts buys_computer = yes for X.
If one conditional probability is 0, the whole product becomes 0. Laplacian correction adds 1 to each count (and the number of classes/values to the denominator), e.g. counts 0, 990, 10 become 1/1003, 991/1003, 11/1003; the estimates stay close but no probability is zero.
Bayesian belief networks syllabus term
Naive Bayes assumes total independence, which is rarely true. A Bayesian belief network (belief network, Bayesian network, probabilistic network) allows conditional independence between subsets of attributes and so is a more realistic model.
It is defined by two components:
- A directed acyclic graph (DAG): nodes are random variables (discrete or continuous), arcs are causal dependencies. An arc from Y to Z makes Y a parent of Z, and Z is conditionally independent of its non-descendants given its parents.
- A conditional probability table (CPT) for each variable, giving P(Z | parents(Z)) for every combination of parent values.
Training belief networks: if the structure is known and all variables observable, we simply compute the CPT entries from the data. If the structure is known but some variables are hidden, a gradient descent method (or EM) trains the CPT entries. If the structure is unknown, structure-learning/discrete-optimisation algorithms infer it. Human experts commonly supply the structure using their causal knowledge, which is a major advantage over black-box models.
4.6 Neural networks and backpropagation
A neural network is a set of connected input/output units in which each connection has a weight. Learning means adjusting these weights so the network can predict the correct class label of the input tuples. Also called connectionist learning.
Structure of a multilayer feed-forward network: an input layer (one unit per attribute, values usually normalised to [0,1]), one or more hidden layers, and an output layer. It is feed-forward because no weight cycles back; fully connected because every unit feeds every unit of the next layer. A network with two hidden layers is called a three-layer network (input layer is not counted). Given enough hidden units, such a network can approximate any function.
Backpropagation algorithm write the six steps + formulas
- Initialise the weights and biases to small random numbers (e.g. −1.0 to 1.0).
- Propagate the inputs forward. For a hidden or output unit j:
Ij = Σi wijOi + θjthenOj = 1 / (1 + e−Ij). - Backpropagate the error. Output unit:
Errj = Oj(1 − Oj)(Tj − Oj). Hidden unit:Errj = Oj(1 − Oj) Σk Errkwjk. - Update weights:
Δwij = l · Errj · Oi,wij = wij + Δwij, where l is the learning rate (often 1/t for epoch t). Small l = slow learning; large l = oscillation. - Update biases:
Δθj = l · Errj. - Terminate when all Δw are below a threshold, or the misclassified percentage is below a threshold, or the maximum number of epochs is reached. (Updating after each tuple = case updating; after the whole epoch = epoch updating.)
Advantages: high tolerance to noisy data, can classify untrained patterns, well suited
to continuous-valued inputs and outputs, inherently parallel, successful on real-world data (handwriting,
speech, pathology).
Disadvantages: long training time, requires many parameters set empirically (network
topology, learning rate), and poor interpretability, the "black box" criticism: it is hard
to interpret the meaning of the learned weights.
Unsupervised learning in neural nets
Backpropagation is supervised. Unsupervised neural learning has no target output; the network discovers structure by itself:
- Self-Organising Map (SOM / Kohonen map): the winning output unit (whose weight vector is closest to the input) and its neighbours adjust their weights toward the input. Result: a topology-preserving 2-D map where similar inputs land near each other. Used for clustering and visualisation, e.g. web document clustering.
- Competitive / winner-take-all learning: only the winner updates.
- Adaptive Resonance Theory (ART): creates new clusters when an input does not match any existing prototype within a vigilance threshold.
Data mining using a neural net: rule extraction
To beat the black-box criticism, several techniques extract symbolic knowledge:
- Network pruning: remove weighted links that do not change classification accuracy, producing a simpler network.
- Rule extraction: cluster the activation values of hidden units, then derive rules that relate input activations to hidden clusters, and hidden clusters to output classes; finally combine them into IF-THEN rules on the original inputs.
- Sensitivity analysis: vary one input while holding the others fixed and observe the change in output; the result is expressed as a rule such as "IF X decreases 5 % THEN Y increases 8 %".
4.7 Other classification methods
(a) Genetic algorithms
An evolutionary search inspired by biology. Rules are encoded as bit strings: e.g.
IF A1 AND NOT A2 THEN C2 is encoded as 100. An initial population of random
rules is created; the fitness of a rule is its classification accuracy on a set of
training samples. A new population is formed from the fittest rules using
selection, crossover (substrings from two rules are swapped) and
mutation (randomly flipped bits). The process repeats until the population meets a
fitness threshold. GAs are easily parallelised and are also used to evaluate the fitness of other
algorithms.
(b) Rough set theory short question
Introduced by Pawlak for imprecise or noisy data; applies to discrete-valued attributes, so continuous ones must be discretised first. A class C that cannot be described exactly is approximated by two sets:
- Lower approximation: the tuples that, based on the attribute values, certainly belong to C.
- Upper approximation: the tuples that cannot be described as not belonging to C (i.e. certainly or possibly belong).
The difference between the two is the boundary region. Rough sets are also used for feature reduction (finding reducts: minimal attribute subsets that describe all concepts) and relevance analysis. Finding all reducts is NP-hard, so a discernibility matrix is used.
(c) Fuzzy set approaches
Classical rules use sharp cut-offs: income > 50K ⇒ high. Then 50,000 is "medium" and 50,001 is "high", which is unnatural. Fuzzy set theory (Zadeh) replaces this with membership functions: a value can belong to "medium income" with degree 0.4 and to "high income" with degree 0.6, and membership values need not sum to 1. In classification, rules from several fuzzy categories are applied, their truth values are combined (usually by summing/averaging), and the class with the highest score wins. Fuzzy logic is valuable in expert systems and data mining because it works at a high level of abstraction and handles vagueness gracefully.
(d) Support Vector Machines (SVM)
An SVM searches for the maximum marginal hyperplane (MMH): the decision boundary with the largest margin between two classes, because that gives the highest expected accuracy on unseen data. The training tuples lying on the margin are the support vectors; they alone define the classifier. For data that is not linearly separable, the input is mapped by a nonlinear kernel function into a higher-dimensional space where a linear separator does exist (polynomial kernel, Gaussian radial basis function kernel, sigmoid kernel). This is the kernel trick: we never compute the mapping explicitly, only the dot products.
(e) Case-based reasoning (CBR)
An instance-based (lazy) learner that stores training tuples as cases: typically complex symbolic descriptions rather than plain points. When a new case arrives, CBR searches for identical cases and returns their solution; if none exists, it finds similar cases (graph/subgraph similarity), combines and adapts their solutions, and may backtrack. Used in customer help desks, legal reasoning and medical diagnosis. Challenges: finding a good similarity metric, efficient indexing of cases, and the trade-off between the size of the case base and the search time.
Eager learners (decision tree, Bayes, neural net, SVM) build a generalised model before receiving test tuples: slow training, fast classification. Lazy learners (k-nearest-neighbour, CBR) simply store the training tuples and do the work at classification time: no training cost, but slow prediction and high storage. Lazy learners naturally support incremental learning and can model complex decision spaces.
4.8 Prediction: regression short numerical
x (years) = 3, 8, 9, 13, 3, 6, 11, 21, 1, 16 and y (salary in ₹ thousands) = 30, 57, 64, 72, 36, 43,
59, 90, 20, 83. Then x̄ = 9.1 and ȳ = 55.4.
w = Σ(x−x̄)(y−ȳ) / Σ(x−x̄)² = 3.5 and b = 55.4 − 3.5 × 9.1 = 23.6.
Model: y = 23.6 + 3.5x. Predicted salary for 10 years of experience =
23.6 + 35 = ₹58.6 thousand.
Other predictors to name: generalised linear models (logistic regression for categorical outcomes, Poisson regression for counts), log-linear models (approximate discrete multidimensional probability distributions; also used for data compression and smoothing), and regression trees / model trees (CART: leaves hold the mean value, or a linear equation in a model tree).
4.9 Classifier accuracy certain question
Estimating accuracy: four methods
- Holdout: randomly split, typically 2⁄3 training and 1⁄3 testing. Random subsampling repeats holdout k times and averages.
- k-fold cross-validation: partition into k mutually exclusive folds of equal size; in iteration i, fold i is the test set and the rest is training. Each tuple is used once for testing. 10-fold cross-validation is recommended because of its relatively low bias and variance. Leave-one-out is the case k = number of tuples; stratified folds keep the class distribution of the whole data.
- Bootstrap: sample with replacement. In .632 bootstrap, a tuple has probability (1 − 1/d)d ≈ e−1 = 0.368 of never being chosen, so about 63.2 % of the tuples form the training set and 36.8 % form the test set. Accuracy = Σ (0.632 × acctest + 0.368 × acctrain) / k. Best for small data sets.
- ROC curve: plots the true-positive rate against the false-positive rate as the threshold varies. The larger the area under the curve (AUC) the more accurate the model; the diagonal represents random guessing.
Increasing accuracy: ensemble methods
- Bagging (bootstrap aggregation): build k models on k bootstrap samples and take a majority vote (average for prediction). Reduces variance and is more robust to noise; often significantly better than a single classifier.
- Boosting (AdaBoost): models are built sequentially and each training tuple carries a weight; after each round, misclassified tuples get higher weights so the next model focuses on them. Final vote is weighted by each model's accuracy. Usually more accurate than bagging but risks overfitting the misclassified data.
- Random forest: bagging of decision trees where each split considers a random subset of attributes; accurate, robust to outliers and fast.
No. With a class imbalance (e.g. only 3 % fraud), a classifier that predicts "not fraud" always achieves 97 % accuracy but is useless. Use sensitivity, specificity, precision, recall, F-measure or cost-sensitive measures instead. Also consider speed, robustness, scalability and interpretability.
4.10 Likely exam questions from this unit
- What is classification? Explain the two-step process. How does it differ from prediction? 5-10
- Construct a decision tree for the given training data using information gain (show all calculations). 15
- Define entropy, information gain, gain ratio and Gini index. Compare their biases. 10
- Explain tree construction with presorting (SLIQ / SPRINT / RainForest). 10
- What is overfitting? Explain prepruning and postpruning; explain integration of pruning and construction. 10
- Classify the given tuple using the naive Bayesian classifier (show all probabilities). 10
- What is a Bayesian belief network? Draw one with its CPT and write the joint probability formula. 10
- Explain the backpropagation algorithm with a neural network diagram. 10-15
- How is knowledge extracted from a trained neural network? Explain unsupervised learning / SOM. 5-10
- Write short notes on: genetic algorithm, rough sets, fuzzy sets, SVM, case-based reasoning. 5 each
- Explain prediction using linear and nonlinear regression with an example. 10
- Define confusion matrix, accuracy, precision, recall and F-measure. Explain holdout, k-fold cross-validation and bootstrap. 10
- Differentiate bagging and boosting. 5
Cluster Analysis
6 hrsClustering is the process of grouping a set of physical or abstract objects into classes of similar objects, such that objects within a cluster have high similarity to one another and are very dissimilar to objects in other clusters. It is unsupervised learning: the class labels are not known in advance. It is also called segmentation or data partitioning, and is used as a stand-alone tool or as a preprocessing step for other algorithms.
Requirements of clustering in data mining easy 5 marks
- Scalability: must work on millions of objects, not just a few hundred.
- Ability to deal with different types of attributes: numeric, binary, nominal, ordinal, or mixtures.
- Discovery of clusters with arbitrary shape: not just spherical clusters.
- Minimal requirements for domain knowledge to determine input parameters (like k).
- Ability to deal with noise and outliers.
- Insensitivity to the order of input records.
- High dimensionality: data may have hundreds of dimensions (sparse and skewed).
- Constraint-based clustering: e.g. place ATMs considering rivers and highways.
- Interpretability and usability of the results.
5.1 Types of data in cluster analysis syllabus point: do not skip
Two common data structures: the data matrix (n objects × p attributes, "two-mode") and the dissimilarity matrix (n × n triangular matrix of d(i,j), "one-mode"). Most clustering algorithms operate on the dissimilarity matrix, so the first job is to convert the data into distances.
| Variable type | How similarity/distance is computed |
|---|---|
| Interval-scaled (continuous: weight, height, temperature) | Standardise first: compute mean absolute deviation sf = (1/n)Σ|xif − mf| and the z-score zif = (xif − mf)/sf (more robust to outliers than standard deviation). Then use Euclidean, Manhattan or Minkowski distance. |
| Binary | Build a 2×2 contingency table (q = both 1, r = 1&0, s = 0&1,
t = both 0). Symmetric (both states equally valuable, e.g. gender): d(i,j) = (r+s)/(q+r+s+t). Asymmetric (rare positive is more important, e.g. a disease test): Jaccard coefficient d(i,j) = (r+s)/(q+r+s); negative matches (t) are ignored. |
| Nominal / categorical (red, yellow, blue) | d(i,j) = (p − m)/p where m = number of matching attributes and p = total attributes. Alternatively create one asymmetric binary attribute per state. |
| Ordinal (rank: gold, silver, bronze) | Replace the value by its rank rif ∈ {1..Mf}, map to zif = (rif − 1)/(Mf − 1) ∈ [0,1], then treat as interval-scaled. |
| Ratio-scaled (exponential growth: bacterial population, ABCt) | Three options: treat as interval (poor); apply a logarithmic transform y = log(x) then treat as interval; or treat as continuous ordinal data and rank it. |
| Mixed types | Use one weighted formula that processes all types together: d(i,j) = Σf δ(f)ij d(f)ij / Σf δ(f)ij, where each attribute's contribution is normalised to [0,1]. |
| Vector objects (documents, gene sequences) | Cosine similarity s(x,y) = x·y / (‖x‖‖y‖), or the Tanimoto coefficient. |
5.2 The five major categories of clustering methods always asked
| Category | Idea | Typical algorithms |
|---|---|---|
| Partitioning | Construct k partitions and iteratively relocate objects to improve the partitioning | k-means, k-medoids (PAM), CLARA, CLARANS |
| Hierarchical | Create a hierarchical (tree) decomposition, agglomerative or divisive | AGNES, DIANA, BIRCH, ROCK, CURE, Chameleon |
| Density-based | Grow a cluster as long as the density in its neighbourhood exceeds a threshold | DBSCAN, OPTICS, DENCLUE |
| Grid-based | Quantise the object space into a finite number of cells that form a grid structure | STING, WaveCluster, CLIQUE |
| Model-based | Hypothesise a model for each cluster and find the best fit of the data to it | EM, COBWEB, SOM (neural network approach) |
5.3 Partitioning methods
k-means numerical certain
- Arbitrarily choose k objects as the initial cluster centres (means).
- Assign each remaining object to the cluster with the nearest mean.
- Recompute the mean of each cluster.
- Repeat steps 2-3 until no object changes cluster / the criterion function converges.
Data: {2, 3, 4, 10, 11, 12, 20, 25, 30}, k = 2, initial means m₁ = 2, m₂ = 4.
| Iter. | Cluster 1 | Cluster 2 | New m₁ | New m₂ |
|---|---|---|---|---|
| 1 | {2, 3} | {4, 10, 11, 12, 20, 25, 30} | 2.5 | 16 |
| 2 | {2, 3, 4} | {10, 11, 12, 20, 25, 30} | 3 | 18 |
| 3 | {2, 3, 4, 10} | {11, 12, 20, 25, 30} | 4.75 | 19.6 |
| 4 | {2, 3, 4, 10, 11, 12} | {20, 25, 30} | 7 | 25 |
| 5 | {2, 3, 4, 10, 11, 12} | {20, 25, 30} | 7 | 25 |
No object changes cluster in iteration 5, so the algorithm converges with C₁ = {2,3,4,10,11,12}, m₁ = 7 and C₂ = {20,25,30}, m₂ = 25.
(1) The number k must be specified in advance. (2) It is sensitive to noise and outliers because a single extreme value distorts the mean. (3) It is sensitive to the initial seeds and converges only to a local optimum. (4) It cannot find clusters of non-convex shape or very different size. (5) It requires the mean to be defined, so it is not applicable to categorical data (use k-modes, which replaces means with modes and uses a matching dissimilarity; k-prototypes handles mixed data).
k-medoids (PAM), CLARA and CLARANS
k-medoids uses the most centrally located actual object (the medoid) instead of the mean, which makes it far more robust to outliers. PAM (Partitioning Around Medoids) repeatedly tries replacing a medoid oj by a non-medoid orandom and keeps the swap if the total cost S = Enew − Eold < 0. Cost per iteration is O(k(n−k)²), so PAM is not scalable.
- CLARA (Clustering LARge Applications) draws multiple samples of the data, applies PAM to each and returns the best clustering. Efficient, but the result depends on sample quality (a good medoid may never be sampled).
- CLARANS (Clustering Large Applications based upon RANdomized Search) draws a fresh random sample of neighbours at every step of the search, i.e. it searches a graph where each node is a set of k medoids. More effective than PAM and CLARA; can be improved with spatial index structures (R*-tree).
5.4 Hierarchical methods
- AGNES (AGglomerative NESting): bottom-up. Start with each object as its own cluster and merge the two closest clusters at each step, until all objects are in one cluster or a termination condition holds.
- DIANA (DIvisive ANAlysis): top-down. Start with all objects in one cluster and split at each step, until each object forms its own cluster.
Pure hierarchical clustering cannot undo what was already done: a merge or split is never revisited, so a bad early decision propagates. Complexity is at least O(n²). The remedy is to integrate hierarchical clustering with other techniques, as BIRCH, CURE, ROCK and Chameleon do.
| Algorithm | Core idea | Strength |
|---|---|---|
| BIRCH (Balanced Iterative Reducing and Clustering using Hierarchies) | Builds a CF-tree, a height-balanced tree of clustering features CF = (N, LS, SS): the number of points, linear sum and square sum. Phase 1 scans the database to build the CF-tree; phase 2 applies any clustering algorithm to the leaf nodes. | Incremental, needs only one scan, complexity O(n); handles only numeric data and finds spherical clusters (it is order-sensitive) |
| ROCK | Agglomerative clustering for categorical data using links (number of common neighbours) rather than distance | Robust for market-basket type data |
| CURE (Clustering Using REpresentatives) | Represents a cluster by a fixed number of scattered representative points shrunk toward the centroid by a fraction α | Finds non-spherical shapes and is robust to outliers |
| Chameleon | Uses a k-nearest-neighbour graph, partitions it, then merges sub-clusters based on dynamic modelling of both interconnectivity and closeness | Discovers clusters of arbitrary shape and varying density |
5.5 Density-based methods
Two parameters: ε (Eps) the radius of the neighbourhood, and MinPts the minimum number of points required in that neighbourhood.
- ε-neighbourhood of p: all objects within distance ε of p.
- Core object: an object whose ε-neighbourhood contains at least MinPts objects.
- Directly density-reachable: q is directly density-reachable from p if q is in the ε-neighbourhood of p and p is a core object.
- Density-reachable: there is a chain p₁,…,pn where each is directly density-reachable from the previous (this relation is transitive but not symmetric).
- Density-connected: p and q are both density-reachable from some object o (symmetric).
- A cluster is a maximal set of density-connected points; points in no cluster are noise; a non-core point inside a cluster is a border point.
DBSCAN algorithm: pick an arbitrary unvisited point p; retrieve all points density-reachable from p using ε and MinPts. If p is a core object, a cluster is formed; if p is a border object with nothing density-reachable, DBSCAN moves on. Repeat until all points are visited. Complexity is O(n log n) with a spatial index (R*-tree), otherwise O(n²).
- Advantages: discovers clusters of arbitrary shape, handles noise explicitly, and does not need k in advance.
- Disadvantages: very sensitive to ε and MinPts, and it fails on data with widely varying density.
- OPTICS (Ordering Points To Identify the Clustering Structure) fixes the parameter problem by producing a cluster ordering with core-distance and reachability-distance, which represents the density-based clustering for a broad range of parameter settings at once (visualised as a reachability plot).
- DENCLUE (DENsity-based CLUstEring) models the overall density as the sum of influence functions (e.g. Gaussian) of each point; clusters are defined by density attractors: local maxima of the density function found by hill climbing. It has a solid mathematical foundation, is good for highly noisy data and is faster than DBSCAN, but needs careful choice of σ and ξ.
5.6 Grid-based methods
The object space is quantised into a finite number of cells forming a grid; all clustering is done on the grid. The main advantage is fast processing time, which depends only on the number of cells, not on the number of data objects.
- STING (STatistical INformation Grid) divides the space into rectangular cells at several levels of resolution, forming a hierarchy. Each cell stores precomputed statistical parameters: count, mean, standard deviation, min, max and the type of distribution. Queries are answered top-down: irrelevant cells are pruned using confidence intervals. Query time is O(g) where g is the number of grid cells at the lowest level, g ≪ n. Weakness: cluster boundaries are horizontal or vertical only, since it uses the axis-parallel grid.
- WaveCluster: imposes a grid, then applies a wavelet transform to the feature space; clusters appear as dense regions in the transformed space. It automatically removes outliers, is multi-resolution (a natural roll-up/drill-down), finds arbitrary shapes, and runs in O(n): but is effective only in low-dimensional space.
- CLIQUE (CLustering In QUEst) is both grid-based and density-based, designed for subspace clustering of high-dimensional data. It partitions each dimension into intervals, finds dense units in 1-D, then uses the Apriori principle (a k-dimensional dense unit must have dense (k−1)-dimensional projections) to build higher-dimensional dense units, and finally generates a minimal description of each cluster as DNF expressions. Insensitive to the input order, scales linearly with n, but accuracy may drop due to the simplicity of the method.
5.7 Model-based clustering
Each cluster is assumed to be generated by an underlying probability distribution or concept, and the algorithm finds the best fit between the data and the model. It gives a robust way of automatically determining the number of clusters, using statistics and noise/outlier tolerance.
- Expectation-Maximisation (EM): a generalisation of k-means in which each object is assigned to a cluster with a probability of membership (soft/fuzzy assignment) rather than exclusively. The data is modelled as a mixture of Gaussian distributions. Two steps iterate: E-step: compute the probability that each object belongs to each cluster; M-step: re-estimate the model parameters (mean, covariance, mixture weight) to maximise the expected likelihood. It converges to a local maximum; complexity is linear in the data size.
- COBWEB: an incremental conceptual clustering method for categorical data. It builds a classification tree whose nodes hold probabilistic descriptions of a concept, guided by the category utility measure, using operators insert, create, merge and split. Weaknesses: it assumes attributes are independent, the tree can be expensive in space and time, and it is not suited to skewed data. CLASSIT is its extension for continuous data; AutoClass is a Bayesian variant.
- SOM (Self-Organising Map): the neural-network approach described in Unit 4. Objects are mapped onto a 2-D grid of neurons that preserves the topology of the input space, so it is useful for clustering and visualisation of high-dimensional data (e.g. WEBSOM for web documents).
Outlier analysis often bundled with this unit
An outlier is a data object that is grossly different from or inconsistent with the remaining data. Four detection approaches:
- Statistical (distribution-based): assume a distribution and use a discordancy test; objects with low probability are outliers. Requires knowing the distribution in advance and works mostly in single dimensions.
- Distance-based: an object o is a DB(p, d)-outlier if at least a fraction p of the objects lie further than distance d from o. Algorithms: index-based, nested-loop, cell-based.
- Density-based (local outlier): uses the local outlier factor (LOF), which compares the local density of an object with that of its neighbours, so it can find outliers within clusters of different densities.
- Deviation-based: identifies outliers by examining the main characteristics of a group; the sequential exception technique uses a dissimilarity function and smoothing factor; the OLAP data cube approach flags deviating cells for drill-down.
5.8 Likely exam questions from this unit
- What is cluster analysis? How does it differ from classification? List the requirements of clustering. 10
- Explain the types of data in cluster analysis and how dissimilarity is computed for each. 10
- Explain the k-means algorithm. Apply it to the given data set and show all iterations. 10-15
- Differentiate k-means and k-medoids. Explain PAM, CLARA and CLARANS. 10
- Explain agglomerative and divisive hierarchical clustering with a dendrogram. Explain BIRCH / CURE. 10
- Explain DBSCAN with definitions of core object, density-reachable and density-connected. 10
- Explain grid-based clustering: STING, WaveCluster and CLIQUE. 10
- Explain model-based clustering: EM, COBWEB and SOM. 10
- What are outliers? Explain the approaches to outlier detection. 5-10
Mining Complex Data Types
6 hrsThis unit is descriptive, so there are no numericals. Answers are scored on definition → why it is different from relational mining → the specific tasks/techniques → applications. Learn that four-part skeleton once and reuse it for all five topics.
6.1 Mining spatial databases
A spatial database stores data with spatial (geographic) attributes: points, lines, polygons, satellite images, maps, medical images. Spatial data mining is the extraction of knowledge, spatial relationships and other interesting patterns not explicitly stored in spatial databases.
Why is it harder than relational mining? Spatial data is huge, has complex data types, and carries implicit spatial relationships (adjacent, inside, close_to, intersects) that must be computed rather than looked up. Neighbours also influence each other, so objects are autocorrelated, violating the independence assumption of ordinary mining.
Techniques and tasks
- Spatial data cube and spatial OLAP: dimensions can be non-spatial (temperature = hot), spatial-to-non-spatial (a region generalised to "Nepal"), or spatial-to-spatial. Measures may be numerical or spatial (a collection of merged regions). Precomputing merged regions is costly, so on-line merging with pointers is used.
- Spatial association rules: of the form A ⇒ B [s %, c %] where the predicates are spatial, e.g. is_a(X, "school") ∧ close_to(X, "sports_centre") ⇒ close_to(X, "park") [0.5 %, 80 %]. Mining uses a progressive refinement approach: apply a rough, cheap spatial predicate (g_close_to, using MBR or R-tree approximation) first, then apply the expensive precise test only to the surviving candidates.
- Spatial classification and trend analysis: classify spatial objects using relevant neighbourhood attributes; spatial trend analysis detects changes of a non-spatial attribute as one moves away from a reference point (e.g. economic level decreasing with distance from Kathmandu).
- Spatial clustering: CLARANS, DBSCAN, STING and WaveCluster all originated in this area.
- Mining raster/image databases: generalisation-based mining of remote sensing images.
Applications: GIS, urban planning, environmental studies, epidemiology (mapping disease outbreaks), navigation and traffic, and marketing by geography.
6.2 Mining multimedia databases
A multimedia database stores images, audio, video and sequence data. Multimedia mining extracts patterns from such data, which is unstructured and very high-dimensional.
Main topics to write
- Similarity search: two families: description-based retrieval (using keywords, captions, size, creation time, which is labour intensive and subjective) and content-based retrieval (using the actual image content: colour histogram, texture, shape, edges). Content-based systems support image-sample-based queries (find images similar to a given one) and image feature specification queries (specify colour, texture, shape). Indexing uses the colour histogram, multi-feature composite signatures, and wavelet-based signatures, usually inside an R-tree or a similarity index.
- Multidimensional analysis: a MultiMediaMiner-style image data cube with dimensions such as size, width, height, Internet domain, colours, keywords, edge-orientation.
- Classification and prediction: e.g. classifying sky images or detecting tumours; decision trees are commonly used on extracted features.
- Mining associations in multimedia data: three categories: associations between image content and non-image content features; associations among image contents not related to spatial relationships; and associations among image contents related to spatial relationships (e.g. "if two circles are touching and of similar size, they are likely to be balls"). Progressive resolution refinement is used: mine at a coarse resolution first, then refine only the frequent candidates at higher resolution.
- Audio and video data mining: indexing motion, scene change detection, speech transcription; audio can also be used to present mined patterns (audio data mining).
6.3 Mining time-series and sequence data
A time-series database consists of sequences of values obtained over repeated measurements of time (stock prices, temperature, ECG, sales per day); the time gaps are usually equal. A sequence database consists of sequences of ordered events, with or without a concrete notion of time (web click streams, customer purchase sequences, DNA sequences).
(a) Trend analysis: the four components of a time series
- Trend (long-term) movement: the general direction over a long period, found with the moving average, weighted moving average, or the least-squares/freehand method. A moving average of order n smooths the series and eliminates cyclic/seasonal variation, but it loses data at the ends and may be affected by outliers.
- Cyclic movements: long-term oscillations about a trend line, which may or may not be periodic (business cycles).
- Seasonal variations: nearly identical patterns that a series follows during corresponding months/seasons (sales rising during Dashain-Tihar). Quantified as a seasonal index; dividing by it gives deseasonalised data.
- Irregular / random movements: sporadic motion due to chance events (strikes, earthquakes).
(b) Similarity search in time-series data
Unlike normal queries, similarity search looks for sequences that differ only slightly. Subsequence matching finds the sequences containing a short query pattern; whole sequence matching compares entire sequences. Typical steps: apply a transform to reduce dimensionality, using DFT (discrete Fourier transform) keeping only the first few coefficients, or DWT, then index the result in an R*-tree, and search. Preprocessing needed before comparison: offset translation, amplitude scaling, noise removal, time warping (DTW, dynamic time warping, handles sequences that run at different speeds).
(c) Sequential pattern mining name the algorithms
Finds frequent subsequences in a sequence database, e.g. customers who buy a laptop tend to buy a printer within 3 months. Given min_sup, a sequence is frequent if it occurs in at least that fraction of sequences. Algorithms: GSP (Apriori-based, candidate generate-and-test), SPADE (vertical format, ID-list joins) and PrefixSpan (pattern-growth, projected databases, generally the fastest). Constraint-based versions add duration, gap and event-folding window constraints. Periodicity analysis mines full, partial and cyclic periodic patterns.
Biological sequence analysis is a major application: alignment of DNA/protein sequences using BLAST and dynamic programming, plus hidden Markov models (HMM) with the forward, Viterbi and Baum-Welch algorithms.
6.4 Web mining draw the taxonomy
Web mining is the application of data mining techniques to discover patterns from the World Wide Web. The Web is challenging because it is huge and growing, has diverse and unstructured content, is highly dynamic, has a complex hyperlink structure, contains a lot of noise, and only a small fraction of it is relevant to any given user ("the Web is a broad, diverse and largely unstructured but interconnected information repository").
(a) Web content mining
Extracts useful information from page content. Includes automatic classification and clustering of documents, extraction of structured data from pages using wrappers, and building multilayered web information bases where layer 0 is the raw Web and higher layers hold progressively more generalised, structured descriptions.
(b) Web structure mining: PageRank and HITS
The insight: a hyperlink from page A to page B is an implicit endorsement of B by A, so the link graph encodes human judgement about page quality.
HITS (Hyperlink-Induced Topic Search) defines two mutually reinforcing scores: an authority is a page with many in-links from good hubs; a hub is a page that points to many good authorities. The scores are computed iteratively: a(p) = Σ h(q) over pages q linking to p, and h(p) = Σ a(q) over pages q that p links to, normalised each round until convergence (this is the principal eigenvector of the adjacency matrix). HITS is query-dependent; PageRank is query-independent and computed offline.
Both are vulnerable to link spam / link farms and to topic drift (HITS may drift to a broader, more popular topic). PageRank favours older, established pages.
(c) Web usage mining
Mines web server logs, browser logs, proxy logs, cookies and click streams to discover user access patterns. The process has three phases:
- Preprocessing: data cleaning (remove image/script requests, robots), user identification, session identification (usually a 30-minute timeout), path completion because of browser caching.
- Pattern discovery: association rules ("70 % who visit /laptops also visit /printers"), sequential patterns of page visits, clustering of users or pages, classification of user profiles.
- Pattern analysis: filter out uninteresting rules and present them via visualisation or an OLAP weblog cube.
Applications: personalisation and recommender systems, improving site structure and navigation, targeted advertising, prefetching and caching, e-commerce customer profiling, and fraud detection.
6.5 Text mining
Text mining is the discovery of interesting, non-trivial knowledge from large collections of unstructured or semi-structured text documents. About 80 % of organisational data is text (emails, reports, papers, web pages), and its lack of structure is exactly why ordinary mining cannot be applied directly. Text mining is more than information retrieval: IR finds the documents you asked for, text mining finds patterns you did not ask for.
The text mining pipeline
- Text preprocessing: tokenisation, removal of stop words (the, is, of), stemming (computing/computer/computed → comput), case folding, and part-of-speech tagging.
- Feature/term extraction and representation: build the vector space model: each document becomes a vector of term weights in a term-frequency matrix (bag of words).
- Dimensionality reduction: remove terms with low discriminating power; Latent Semantic Indexing (LSI) using SVD, Locality Preserving Indexing (LPI), or probabilistic LSI.
- Mining: document classification (naive Bayes, SVM, k-NN, association-based), document clustering (spectral, mixture model, k-means on the vectors), keyword-based association analysis, document summarisation, topic detection, sentiment analysis, and information extraction.
- Evaluation and visualisation: precision, recall, F-score of the retrieved/labelled set.
Keyword-based, tagging-based and information-extraction-based approaches form a spectrum from simple to sophisticated. Modern systems also build document concept hierarchies so that text can be placed in a text cube and analysed with OLAP operations. Applications: spam filtering, plagiarism detection, sentiment/opinion mining, resume screening, biomedical literature mining, legal e-discovery and customer feedback analysis.
6.6 Likely exam questions from this unit
- What is spatial data mining? Explain spatial data cubes, spatial association rules and progressive refinement. 10
- Explain multimedia data mining. What is content-based retrieval? Explain multimedia association rules. 10
- What is time-series data? Explain trend analysis and its four components. 10
- Explain similarity search and sequential pattern mining in sequence databases. 10
- What is web mining? Explain its three categories with examples. 10
- Explain PageRank and HITS (hubs and authorities). 5-10
- Explain the phases of web usage mining and its applications. 10
- What is text mining? Explain the text mining process and the vector space model / TF-IDF. 10
How to write the exam
The structure that scores
For a 10-mark question, plan roughly one and a half to two pages, in this order:
- Definition (2-3 lines, underlined). Use the textbook wording.
- Why / context (2 lines): the problem this concept solves.
- Diagram, drawn with a pencil and ruler, fully labelled, with a caption "Fig: KDD process".
- Main body in numbered points: each point starts with a bold keyword, then one or two sentences. Aim for 5-8 points.
- Example or numerical: one small worked instance.
- Advantages / limitations / comparison: two or three lines. This is where most students stop early and lose the last 2 marks.
- Data mining is a step in KDD; the whole process has 7 steps.
- Preprocessing takes ~60-70 % of the effort in a KDD project.
- Interesting = valid, novel, useful, understandable.
- Inmon's 4 features: subject-oriented, integrated, time-variant, non-volatile.
- n dimensions → 2n cuboids; with hierarchies ∏(Li+1).
- OLAP operations: roll-up, drill-down, slice, dice, pivot.
- Star = denormalised, snowflake = normalised, constellation = multiple fact tables.
- Distributive (count, sum, min, max), algebraic (avg), holistic (median, rank) measures.
- The best way to fill a missing value is the most probable value (regression/Bayes/tree).
- Three normalisations: min-max, z-score, decimal scaling.
- support = P(A∪B), confidence = P(B|A) = sup(A∪B)/sup(A).
- Apriori property: every subset of a frequent itemset is frequent.
- FP-growth needs only 2 database scans and no candidate generation.
- lift < 1 → negative correlation; support and confidence alone can mislead.
- Classification = discrete label (supervised); prediction = continuous value; clustering = unsupervised.
- Gain(A) = Info(D) − InfoA(D); pick the highest gain. Info(D) for 9 yes/5 no = 0.940.
- Naive Bayes assumes class-conditional independence; Laplacian correction fixes zero probabilities.
- Backpropagation: Errj = Oj(1−Oj)(Tj−Oj) for output units.
- 10-fold cross-validation is the recommended accuracy estimate; .632 bootstrap for small data.
- DBSCAN needs ε and MinPts, finds arbitrary shapes and marks noise; k-means cannot.
- Writing support as a count instead of a ratio, or forgetting to state min_sup and min_conf.
- Forgetting the prune step in Apriori, losing 2 marks even with a correct final answer.
- Using log base 10 instead of log₂ in entropy.
- Writing A ⇒ B where A and B share an item; the definition requires A ∩ B = ∅.
- Mixing up precision (TP/(TP+FP)) with recall (TP/P).
- Saying "data warehouse and data mart are the same thing".
- Drawing a star schema with the dimension tables joined to each other; they must all join only to the fact table.
- Describing prepruning as "removing branches after building"; that is postpruning.
- Leaving out the diagram because of time. Draw the diagram first, then write around it.
Time budgeting for a 3-hour, 80-mark paper
- First 5 minutes: read all questions and mark the ones you know cold. Attempt those first, because momentum matters.
- Roughly 1.5 minutes per mark. A 10-mark question = 15 minutes, no more.
- Do the numericals early (Apriori, decision tree, naive Bayes, k-means) while you are fresh; they carry the most guaranteed marks.
- Leave 10 minutes at the end to add diagrams or headings to any answer that looks thin.
- Never leave a question blank; a definition plus a diagram still earns 3-4 out of 10.
One-page formula sheet
Revise only this on the morning of the exam.
Fourteen-day plan from zero
You have attended one class. This is the order that gets you from nothing to confident, spending about three focused hours a day.
| Day | What to do | Proof you have learned it |
|---|---|---|
| 1 | Unit 1 completely. Draw the KDD diagram five times from memory. | Explain KDD and the DM functionalities to a friend without notes |
| 2 | Unit 2 up to schemas. Draw star, snowflake and constellation. | Write the 4 features of a warehouse and the OLTP/OLAP table from memory |
| 3 | Unit 2 rest: cubes, OLAP operations, 3-tier architecture, implementation. | Solve: "How many cuboids for 4 dimensions with 3-level hierarchies?" |
| 4 | Unit 3 preprocessing: cleaning, integration, transformation. | Do a binning problem and all three normalisations by hand |
| 5 | Unit 3: reduction, discretisation, concept hierarchies, DM primitives, DMQL. | Write a full DMQL query from a word problem |
| 6 | Association rules + Apriori. Do the 9-transaction example three times. | Complete Apriori on a fresh dataset in under 15 minutes |
| 7 | FP-growth, multilevel, multidimensional, correlation/lift. AOI and class comparison. | Build an FP-tree and its conditional pattern base table |
| 8 | Decision trees: entropy, gain, gain ratio, Gini. Work the 14-tuple example. | Compute Gain for all 4 attributes and draw the tree unaided |
| 9 | Presorting (SLIQ/SPRINT/RainForest/BOAT), pruning, PUBLIC. Naive Bayes numerical. | Classify a new tuple with naive Bayes and get 0.028 vs 0.007 |
| 10 | Neural nets + backpropagation + SOM + rule extraction. | Write the 6 backpropagation steps with formulas from memory |
| 11 | GA, rough sets, fuzzy sets, SVM, CBR, regression, classifier accuracy, ensembles. | Draw the confusion matrix and derive all five measures |
| 12 | Unit 5 completely. Work the k-means numerical. | Run k-means to convergence and define all DBSCAN terms |
| 13 | Unit 6 completely. Draw the web mining taxonomy. | Write the 4-part skeleton answer for all five complex data types |
| 14 | Solve two past papers under timed conditions. Then revise only the formula sheet and the exam-box highlights. | Score above 70 % on a self-marked past paper |
If time runs out, guarantee these seven: KDD process, data warehouse features + OLTP/OLAP + schemas + OLAP operations, preprocessing tasks, Apriori numerical, decision tree with information gain, naive Bayes numerical, k-means + DBSCAN. Those alone historically cover well over half the paper.