Guide to AI and Data Courses · Lecture Notes
Chapter 25: Data Mining
A supermarket has kept a year of receipts and asks a question nobody posed in advance: which products end up in the same basket? There is no hypothesis to test; the answer is in the data, waiting to be found. Data mining is the course about this kind of discovery: counting frequent itemsets, grouping similar records, picking out the ones that do not resemble the majority, and telling which of the findings are actually worth acting on. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.
Learning outcomes
- The discovery problem
- Split a data mining job into the steps of knowledge discovery; explain with an example how discovery differs from prediction.
- Association rules
- Find frequent itemsets in a small basket dataset with Apriori; compute the support, confidence and lift of rules.
- Clustering
- Carry out two steps of k-means by hand and show how the starting centroids change the result.
- Preprocessing
- Scale attributes with min-max and show how scaling changes distances; find an outlier with the interquartile range.
- Place of the course
- State what separates data mining from machine learning, data science, big data and statistics.
25.1What question does the course ask?
How are hidden, useful patterns found in large piles of data?
Data mining studies how to discover patterns in large data collections, patterns that are previously unknown, valid and useful. It uses the same algorithms as machine learning, but the goal is not prediction on new examples; it is finding rules, clusters and anomalies in the data itself.
In machine learning the question is usually "what will the label be on a new example?", and success is measured on data the model has never seen. In data mining the data at hand is itself the object of curiosity: what regularities does this data contain? That is why the two courses often share algorithms (clustering, decision trees) but read the output differently. One wants a prediction; the other wants a pattern to explain to a person.
Discovery has a danger of its own: search long enough and coincidences start to look like patterns. So the course is not only about finding things but about measuring what is found: support, confidence and lift for rules, the within-cluster sum of squares for clusters, threshold rules for outliers. None of these says "this knowledge is valuable" by itself; the last word belongs to a person who knows the domain, at the last link of the knowledge discovery (KDD) chain.
25.1.1How data becomes knowledge
The process has five steps: select the relevant data, clean it (preprocessing), transform it into a suitable form, run the algorithm (the mining proper) and interpret the pattern that comes out. In practice most of the time goes into the first three. The third core section shows why: even when the algorithm stays the same, the scale of the data changes the result.
25.1.2At a glance
| Criterion | Data Mining |
|---|---|
| Approach | discovery-driven analysis |
| Input | large tables or transaction data |
| Output | rules, clusters, outliers |
| Success measure | interestingness, support, confidence |
| Math load | medium |
| Data needs | large |
25.2A short history
| Year | Milestone |
|---|---|
| 1967 | MacQueen publishes the clustering method he names "k-means". |
| 1989 | The first workshop on knowledge discovery in databases (KDD) is held; the field gets its name. |
| 1994 | Agrawal and Srikant popularize association rule mining with the Apriori algorithm. |
| 1996 | Fayyad and colleagues define the KDD process; density-based DBSCAN is published the same year. |
| 2000 | CRISP-DM 1.0 is released: an industry-neutral process model for data mining projects. |
| 2006 | The Netflix Prize opens: one million dollars for improving recommendation accuracy by 10 percent. |
25.3Core concepts
The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.
| Concept | Meaning |
|---|---|
| Knowledge discovery (KDD) | Selection, preprocessing, transformation, mining, interpretation. |
| Frequent itemsets | Products often bought together: Apriori, FP-growth. |
| Association rule | If X then Y; measured by support, confidence and lift. |
| Clustering | k-means, hierarchical, DBSCAN; unlabeled groups. |
| Outlier | A record unlike the rest: an error or fraud? |
| Descriptive model | Readable, explanatory models such as decision trees. |
| Preprocessing | Missing values, noise, discretization, normalization. |
| Sequential pattern | Event sequences that recur in time order. |
25.4Frequent itemsets and association rules
A transaction (basket) is a set of items. The aim is to find itemsets that occur together often across many transactions and to turn them into rules of the form "if X then Y". Three numbers are enough.
support(X) = transactions containing X / all transactions. For a rule X → Y: confidence = support(X ∪ Y) / support(X), that is, of those who buy X, how many also buy Y. lift = confidence / support(Y): how many times more often the two occur together than they would under independence. A lift near 1 means there is no relation between X and Y; below 1 the items tend to exclude each other.
Counting every itemset by brute force is hopeless: m items generate 2m − 1 non-empty sets. Apriori prunes with a single observation: every subset of a frequent itemset is frequent. So if any subset of a set is infrequent, the set itself is infrequent and need not be counted.
Eight transactions: T1 {pasta, sauce, cheese}; T2 {pasta, sauce}; T3 {pasta, bread}; T4 {sauce, cheese}; T5 {pasta, sauce, bread}; T6 {bread, milk}; T7 {pasta, sauce, milk}; T8 {bread, milk, cheese}. The minimum support count is 2 (that is, 2/8 = 0.25).
- Single items. pasta 5, sauce 5, bread 4, cheese 3, milk 3. All are ≥ 2, all frequent.
- Candidate pairs. From 5 items there are C(5,2) = 10 candidates. Counts: pasta-sauce 4; bread-pasta 2; bread-milk 2; cheese-sauce 2; bread-cheese 1; bread-sauce 1; pasta-cheese 1; pasta-milk 1; cheese-milk 1; sauce-milk 1. Four pairs are frequent.
- Candidate triples. Take {bread, pasta, milk}: its subset {pasta, milk} is infrequent (1), so it is pruned and never counted. {pasta, sauce, bread} is eliminated too, because of {sauce, bread}. No triple survives pruning; the algorithm stops.
- Rules. Let the minimum confidence be 0.6. For lift: support(pasta) = 5/8, support(sauce) = 5/8, support(bread) = 4/8, support(milk) = support(cheese) = 3/8.
| Rule | Support | Confidence | Lift |
|---|---|---|---|
| pasta → sauce | 4/8 = 0.50 | 4/5 = 0.80 | 0.80 / 0.625 = 1.28 |
| sauce → pasta | 0.50 | 4/5 = 0.80 | 1.28 |
| milk → bread | 2/8 = 0.25 | 2/3 ≈ 0.67 | 0.67 / 0.50 ≈ 1.33 |
| cheese → sauce | 0.25 | 2/3 ≈ 0.67 | 0.67 / 0.625 ≈ 1.07 |
Pasta and sauce really are chosen together (lift 1.28). The rule cheese → sauce looks safe but its lift is near 1: sauce is already in 62.5% of baskets, and cheese hardly changes that.
Looking at confidence alone. In the example, the rule bread → pasta has a middling confidence of 2/4 = 0.50, but its lift is 0.50 / 0.625 = 0.8: people who buy bread buy pasta less often than a random customer. When the target item is very common, almost every rule gets a high confidence; a measure such as lift is what tells the interesting rules apart. And an association is not a cause.
25.5Clustering with k-means
In clustering there are no labels; the aim is to put similar records in the same group. The most common method is k-means. The number of clusters k is chosen in advance and this loop is repeated until the clusters stop changing: (1) assign every point to the nearest centroid; (2) move each centroid to the mean of the points in its cluster. Success is measured by the within-cluster sum of squares (WCSS): the sum of squared distances from each point to its own centroid. A small WCSS means tight clusters.
Six points: A(1,1), B(2,1), C(4,3), D(5,4), E(7,5), F(8,6); k = 2. We start with A and B as the initial centroids.
- Assignment 1. The centroids are (1,1) and (2,1). A goes to the first. B goes to the second (distance 0). For C the distances are 3.61 and 2.83; for D 5.00 and 4.24; E and F are also closer to the second. Clusters: {A} and {B, C, D, E, F}.
- Update 1. The centroids are (1, 1) and ((2+4+5+7+8)/5, (1+3+4+5+6)/5) = (5.2, 3.8).
- Assignment 2. For B the distances are 1.00 and 4.25: it moves to the first. For C they are 3.61 and 1.44: it stays in the second. Clusters: {A, B} and {C, D, E, F}.
- Update 2. The centroids are (1.5, 1) and (6, 4.5). In assignment 3 the distances for C are 3.20 and 2.50; nobody changes cluster and the algorithm stops.
- WCSS. First cluster 0.25 + 0.25 = 0.5; second cluster 6.25 + 1.25 + 1.25 + 6.25 = 15; total 15.5.
Had we started with A and F instead: the first assignment gives {A, B, C} and {D, E, F}, the centroids are (7/3, 5/3) and (6.67, 5), WCSS = 14 and the algorithm stops there. Same data, same algorithm, two different results; the second is better.
k-means lowers the WCSS only locally; no step increases it, but a poor start can leave it stuck in a poor solution. So the algorithm is run from several starting points and the result with the smallest WCSS is kept; initialization schemes such as k-means++ help by placing the centroids far from each other.
25.5.1Choosing k
WCSS always shrinks as k grows (it is zero when k equals the number of points), so it cannot choose k by itself. The elbow method looks for the place where the drop slows down; measures such as the silhouette score assess how well separated the clusters are. In every case the number of clusters and the distance measure are interpretive decisions; there is no "one right clustering".
Treating the clusters k-means finds as "the real groups in the data". The algorithm returns k clusters even if the data contains none. Whether the result is meaningful is checked with cluster validity measures and domain knowledge.
25.6Preprocessing: scaling and outliers
Real data does not arrive ready for an algorithm: it has missing values, mixed units, typing errors and odd records. Preprocessing looks dull but can affect the result more than the choice of algorithm. Two classic examples are scaling and outliers.
25.6.1Scaling
Distance-based methods (k-means, nearest neighbor) add up the attributes. If one attribute is measured in thousands and another in tens, the first rules everything. Min-max scaling squeezes a value into [0, 1]: x' = (x − min) / (max − min).
Five customers (age, monthly income in TL): P(25; 30,000), Q(55; 31,000), R(26; 40,000), S(40; 35,000), T(34; 38,000). Question: is P closer to Q or to R?
- Raw distance. d(P,Q) = √(302 + 10002) ≈ 1000.4; d(P,R) = √(12 + 100002) ≈ 10000.0. P looks ten times closer to Q: the 30-year age gap counts for nothing beside thousands of liras.
- Scaling. Age: min 25, max 55, range 30. Income: min 30,000, max 40,000, range 10,000. P → (0, 0), Q → (1, 0.1), R → (0.033, 1).
- New distance. d(P,Q) = √(12 + 0.12) ≈ 1.005; d(P,R) = √(0.0332 + 12) ≈ 1.001.
After scaling, P is (slightly) closer to R: the ranking has flipped. Scaling gives the two attributes an equal say; whether that is right is a decision for domain knowledge.
25.6.2Outliers
An outlier is a record that does not fit the rest of the data: it may be an entry error or it may be fraud. A simple rule uses the interquartile range (IQR): IQR = Q3 − Q1; anything below Q1 − 1.5·IQR or above Q3 + 1.5·IQR is called an outlier.
Incomes (thousand TL): 30, 32, 33, 35, 36, 38, 40, 95.
- Quartiles. With 8 sorted values, Q1 = 32 + 0.75 · (33 − 32) = 32.75 and Q3 = 38 + 0.25 · (40 − 38) = 38.5; IQR = 5.75.
- Fences. Lower 32.75 − 8.625 = 24.125, upper 38.5 + 8.625 = 47.125. 95 is far above the upper fence: an outlier.
- Compare with the z-score. The mean is 42.375 and the (population) standard deviation ≈ 20.12. For 95, z = (95 − 42.375)/20.12 ≈ 2.62, below the common threshold of 3; the z-score misses the outlier.
Why? The outlier pulls both the mean and the standard deviation toward itself and shrinks its own z-score. Quartiles are robust to extreme values.
Deleting an outlier without asking, or scaling before dealing with the outliers. If the incomes above are min-max scaled, 95 becomes 1 and 40 becomes only 10/65 ≈ 0.15; the other seven records are squeezed between 0 and 0.15. Look at the outlier first (is it an error or real?), then scale. In a fraud dataset the outlier is not something to throw away but the thing being looked for.
25.7How is the course taught?
25.7.1A typical workflow
A supermarket selects a year of receipts, removes returns and bad records, turns each receipt into an itemset, finds rules such as "customers who buy pasta also buy sauce" with Apriori, and presents the high-lift rules to the manager for shelf layout.
25.7.2Topics over the semester
- The data mining process: KDD and CRISP-DM
- Getting to know data: attribute types, similarity
- Preprocessing: cleaning, integration, reduction
- Data warehouses and OLAP cubes
- Frequent itemsets: Apriori and FP-growth
- Association rules and interestingness measures
- Classification: decision trees, rule-based methods
- Evaluating classifiers and imbalanced classes
- Clustering: k-means and hierarchical methods
- Density-based clustering and cluster validity
- Outlier detection
- Sequential pattern, text and graph mining
This is a typical semester; the order and coverage vary between universities.
25.7.3Skills you will gain
- data preparation with pandas and SQL
- mining association rules with mlxtend
- quick experiments in Weka or Orange
- measuring and interpreting clusters
- translating findings for the business
25.7.4Try it yourself
The Try It: Hidden Rules in the Shopping Basket slide in the presentation lets you solve a typical problem of this course yourself: A corner shop looks at 14 receipts: nobody asked a question; let the data tell which items are bought together. Change the thresholds and Apriori finds the rules again; click a rule to see it in the baskets.
25.8Are you ready for this course?
25.8.1Prerequisites
| Course | Why it is needed |
|---|---|
| Probability and Statistics | support, confidence, significance |
| Databases and SQL | tables, joins and grouping: where the data comes from |
| Data Structures | hash tables and trees: building blocks of algorithms such as FP-growth |
| Algorithms | complexity: understanding the exponential growth of candidate sets |
25.8.2Ask yourself
For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.
| Question | If not, start with |
|---|---|
| Can you join and group two tables in one SQL query? | SQL from a database course: JOIN and GROUP BY |
| Can you explain conditional probability and independence with an example? | Probability and Statistics |
| Can you explain when a hash table beats a tree? | A data structures course: hash tables and trees |
| Can you read a CSV file in Python and count its missing values? | An intro programming course, then a short pandas tutorial |
25.9Neighboring courses
25.9.1Where it overlaps
| Relation | Course | Shared ground |
|---|---|---|
| builds on | This course builds on Probability and Statistics | support, confidence, significance |
| application | Bioinformatics applies the methods of this course | sequence motifs, clustering |
| shares methods | Shares methods with Machine Learning | same algorithms; the goal is discovery, not prediction |
| shares methods | Shares methods with Natural Language Processing and Text Mining | text classification, topic modeling |
| shares methods | Shares methods with Data Science | exploratory data analysis |
| shares methods | Shares methods with Big Data Systems | scalable mining |
| shares methods | Shares methods with Information Retrieval and Recommender Systems | association, collaborative filtering |
| shares methods | Shares methods with Social Network Analysis | community detection |
25.9.2Where it differs
- Machine Learning: They share algorithms; ML aims at prediction on new examples, data mining at discovery in the data at hand.
- Data Science: Data science covers the whole path from question to decision; data mining focuses on the pattern-finding step.
- Big Data Systems: Big data systems store and process data in a distributed way; data mining asks which patterns to look for in it.
- Probability and Statistics: Statistics tests a hypothesis set in advance; data mining generates hypotheses from data, which must then be tested.
25.10In practice
25.10.1Applications
| Area | What is done |
|---|---|
| Market basket | Items bought together, shelves and promotions. |
| Customer segmentation | Grouping similar customers. |
| Fraud detection | Flagging unusual transactions. |
| Web usage | Visitors' navigation patterns. |
| Failure logs | Error codes that occur together. |
| Medical records | Diagnoses and drugs that occur together. |
25.10.2Risks and ethics
| Risk | Explanation |
|---|---|
| Inferring sensitive facts | Pregnancy, illness or money trouble can be inferred from a shopping basket, even if the person never shared it. |
| Anonymous data is not anonymous | Netflix Prize data was linked to IMDb ratings to identify some users; the planned second contest was cancelled over it. |
| Data dredging | Search for enough patterns and chance ones look significant; multiple comparison corrections and testing on fresh data are needed. |
| Discriminatory profiling | Customer segments built from ZIP codes or shopping patterns can indirectly give some groups different prices and service. |
These issues are discussed in depth in Explainable AI and AI Ethics.
25.10.3Tools and datasets
Tools: Weka, KNIME, Orange, RapidMiner, scikit-learn, mlxtend, R (arules).
Well-known datasets: Groceries (arules), Online Retail (UCI), Instacart Market Basket, Adult (income), KDD Cup 1999, Mushroom.
25.11Common misconceptions
Data mining is collecting data.
The name misleads: what is mined is knowledge, not data; the data already exists.
Every rule found is useful.
Thousands of rules come out; most are obvious or accidental. Interestingness measures and expert review are needed.
A strong association means causation.
Occurring together does not mean one causes the other; there may be a common cause.
Clustering has one right answer.
The result depends on the number of clusters, distance and scaling; different choices, different clusters.
25.12Summary
- Data mining discovers patterns in the data at hand; the process is selection, preprocessing, transformation, mining and interpretation, and most of the time goes into the first three.
- Apriori prunes the candidates to count with the observation that every subset of a frequent itemset is frequent; rules are judged by support, confidence and lift.
- High confidence alone is not interesting: a lift near or below 1 means the rule is useless; an association is not a cause.
- k-means repeats assignment and centroid updates and lowers the WCSS locally; the result depends on the start and k is an interpretive decision.
- Scaling changes distances and an outlier changes the mean and standard deviation; preprocessing affects the result at least as much as the algorithm.
25.13Test Yourself
In the eight receipts above, compute the support, confidence and lift of the rule cheese → sauce.
Answer
Cheese and sauce occur together in T1 and T4: support 2/8 = 0.25. Cheese is in 3 receipts: confidence 2/3 ≈ 0.67. Sauce is in 5: lift 0.667/0.625 ≈ 1.07; the association is very close to independence.
Among items a, b, c, d the frequent pairs are {a,b}, {a,c}, {b,c}, {b,d}. Which candidate triples does Apriori count? Why are the others pruned?
Answer
A triple is counted only if all its pairs are frequent: {a,b,c} (ab, ac, bc frequent) is counted. {a,b,d} is pruned because {a,d} is not frequent; {b,c,d} because {c,d} is not; {a,c,d} also because of {a,d}. So only 1 candidate is counted.
One-dimensional points 1, 2, 6, 7, 10; k = 2, initial centroids 1 and 10. Find the clusters and centroids and compute the WCSS.
Answer
1 and 2 go to the first centroid; 6 (distances 5 and 4), 7 and 10 go to the second. The new centroids are 1.5 and 23/3 ≈ 7.67. In the next assignment the distances for 6 are 4.5 and 1.67: nobody changes. WCSS = 0.25 + 0.25 + (1.672 + 0.672 + 2.332) ≈ 0.5 + 8.67 ≈ 9.17.
Min-max scale the income 36 (thousand TL): (a) over the range 30–95, (b) over the range 30–40. What does the difference show?
Answer
(a) (36 − 30)/65 ≈ 0.09. (b) (36 − 30)/10 = 0.6. A single outlier (95) changes the scale and squeezes the other values together; outliers must be handled before scaling.
A rule has confidence 0.90. The target item is in 90% of all baskets. What is the lift, and is the rule interesting?
Answer
0.90 / 0.90 = 1: the item is bought this often anyway, and X does not raise it. The confidence is high but the rule is not interesting.
An analyst tests 1000 randomly generated "rules" at the 5% significance level; none has a real relationship. About how many come out "significant"? What does this mean for data mining?
Answer
1000 × 0.05 = 50 rules look significant by chance. When many patterns are searched, false findings are unavoidable; a multiple-comparison correction and testing the finding on fresh data are needed.
25.14After this course
Data mining is the discovery side of the data courses. From here you can move to recommender systems through rules, to social network analysis through community detection, to big data systems through scalable mining, or to machine learning to focus on prediction.
Courses that build on or extend this one: Bioinformatics.
Related careers: Data mining specialist, Data analyst, Business intelligence specialist, Customer analytics specialist, Fraud analyst.
25.15Further reading
- J. Han, M. Kamber, J. Pei, Data Mining: Concepts and Techniques (3rd ed., 2011): Apriori, FP-growth, clustering and outlier detection at textbook level.
- P.-N. Tan, M. Steinbach, A. Karpatne, V. Kumar, Introduction to Data Mining (2nd ed., 2019): association analysis and clustering worked through with many small examples.
- I. H. Witten, E. Frank, M. A. Hall, C. J. Pal, Data Mining: Practical Machine Learning Tools and Techniques (4th ed., 2017): a hands-on, experiment-driven view built around Weka.
25.16References
- Han, Kamber and Pei, Data Mining: Concepts and Techniques, 3rd ed., Morgan Kaufmann, 2011.
- Tan, Steinbach, Karpatne and Kumar, Introduction to Data Mining, 2nd ed., Pearson, 2019.
- Witten, Frank, Hall and Pal, Data Mining: Practical Machine Learning Tools and Techniques, 4th ed., Morgan Kaufmann, 2017.
- Leskovec, Rajaraman and Ullman, Mining of Massive Datasets, 3rd ed., Cambridge University Press, 2020.
Related pages: Slides · Slides (PDF) · Course page