📚 Chapters

⛏️ Data Mining

Unit 2 — Regression, Supervised & Unsupervised Learning

📈Chapter 1 — Regression and ANOVA
📈 CHAPTER 1 — REGRESSION AND ANOVA MIND MAP
Regression → Predict a number: OLS fits the line that makes squared errors smallest
Residual → Actual − predicted. Small and random is good
Overfitting → Model too complex. Bias-variance trade-off
Regularization → Ridge (L2): shrink coefficients | Lasso (L1): shrink and select features
ANOVA → Compare the means of 3 or more groups using the F-test
Validation → Hold-out, k-fold, leave-one-out, metrics

1. Regression Recap and Residuals

📖 Regression predicts a number from one or more inputs (features). Simple regression has one input: y = β₀ + β₁x. Multiple regression has many: y = β₀ + β₁x₁ + β₂x₂ + … Here β₀ is the intercept and β₁, β₂ … are the coefficients (slopes).
💡 Example: Marks = 41.5 + 7.5 × hours studied (from Unit 1). A student who studies 3 hours is predicted to get ŷ = 41.5 + 7.5 × 3 = 64 marks. The symbol ŷ ("y-hat") means the predicted value.
📖 Residual = actual value − predicted value: e = y − ŷ. It is the part of the data that the model could not explain (the error of one data point).
Data and fitted lineResidual plot: e = y − ŷ0hours →hours →
Left: the dashed red segments are the residuals. Right: the same residuals drawn on their own, scattered around 0. Values: +1, −1.5, +1, −1.5, +1 (sum = 0).
Hours xActual yPredicted ŷResidual e = y − ŷ
15049+1
25556.5-1.5
36564+1
47071.5-1.5
58079+1
ResidualMeaning
PositiveActual is above the line: the model under-predicted
NegativeActual is below the line: the model over-predicted
ZeroPrediction is exact
Sum of residualsEquals 0 for OLS with an intercept
Residual plot looks likeIt means
Random cloud around 0Good model fit
A curve or patternRelationship is not linear, model is missing something
Funnel (spread grows)Error size changes with x (unequal variance)
One far-away pointOutlier that may be distorting the line

2. Ordinary Least Squares (OLS)

📖 OLS is the standard method to fit a regression line. Objective: choose the coefficients β₀, β₁, … that make the sum of squared residuals (SSE) as small as possible.
💡 Why squares? Plain residuals cancel out (+1 and −1 give 0). Squaring makes every error positive and punishes large errors more.
📐 OLS formulas
SSE = Σ (y − ŷ)² = Σ e² (minimise this)
Simple regression: β₁ = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)², β₀ = ȳ − β₁ x̄
Matrix form (many features): β = (XᵀX)⁻¹ Xᵀ y
R² = 1 − SSE / SST. It is the fraction of variation explained (0 to 1)
Worked example (hours vs marks)
  1. Using the Unit 1 data: β₁ = 75 / 10 = 7.5, β₀ = 64 − 7.5 × 3 = 41.5
  2. Residuals are +1, −1.5, +1, −1.5, +1, so SSE = 1 + 2.25 + 1 + 2.25 + 1 = 7.5
  3. SST = Σ(y − ȳ)² = 570, so R² = 1 − 7.5/570 = 0.987 (the line explains 98.7% of the variation)
OLS assumptions (LINE)Meaning
Linearityy is a straight-line function of the features
IndependenceErrors of different points are independent
NormalityErrors are roughly normally distributed
Equal varianceErrors have the same spread everywhere
Limits of OLS: sensitive to outliers, unstable when features are strongly correlated (multicollinearity), and can overfit when there are many features. Ridge and Lasso fix this.

3. Overfitting, Underfitting and the Bias–Variance Dichotomy

📖 Underfitting: the model is too simple, it misses the real pattern. Overfitting: the model is too complex, it memorises noise in the training data and fails on new data.
💡 Analogy: A student who studies only one chapter (underfit) fails. A student who memorises last year's paper word by word (overfit) fails when questions change. A student who understands the concepts (good fit) passes.
Underfithigh biasGood fitbalancedOverfithigh variance
Same 8 points. A straight line is too simple (underfit). A degree-7 curve passes through every point, including the noise (overfit).
📖 Bias = error from wrong or too-simple assumptions. Variance = how much the model changes if the training data changes.
High biasHigh variance
ModelToo simpleToo complex
Training errorHighVery low
Test errorHighHigh
ProblemUnderfittingOverfitting
FixMore features, more complex modelMore data, fewer features, regularization
📐 Expected test error
Error = Bias² + Variance + Irreducible noise
Making the model more complex lowers bias but raises variance. This is the bias–variance dichotomy (trade-off). We look for the sweet spot.
sweet spotTraining errorTest errorsimple modelcomplex model
Training error keeps falling as the model gets complex. Test error falls, then rises again (overfitting). Choose the model at the lowest test error.

4. Ridge Regression (L2 Regularization)

📖 Ridge regression is OLS with a penalty on the size of the coefficients. It minimises SSE + λ Σ βⱼ². The penalty is the sum of squares (L2 norm), and λ (lambda) controls its strength.
💡 Analogy: A teacher says: "You may use any formula, but every large coefficient costs you marks." The student then avoids wild, huge coefficients.
📐 Ridge
Minimise: Σ (y − ŷ)² + λ Σ βⱼ²
λ = 0 gives plain OLS. A very large λ pushes all coefficients towards 0 (underfit)
Closed form: β = (XᵀX + λI)⁻¹ Xᵀ y. The λI term also makes the matrix invertible
Standardize the features first. Choose λ by cross-validation
How ridge reduces overfitting
  1. Overfit models have very large coefficients that bend the curve to fit the noise
  2. The penalty makes large coefficients expensive, so they are shrunk towards zero
  3. Shrinking adds a little bias but removes a lot of variance, so test error falls
  4. With correlated features, ridge shares the weight between them instead of giving them huge opposite values
Worked example: two almost identical features
💡 Setup: the true relation is y = 2·x₁ + 1. The feature x₂ is nearly a copy of x₁ (x₂ ≈ x₁ + small noise). We have only 8 training points.
x₁x₂y
10.93.6
224.3
336.6
43.98.1
559.3
65.910.8
77.115.1
8816.2
β₁ (for x₁)β₂ (for x₂)β₁ + β₂Test MSE (300 new points)
OLS-4.466.251.784.83
Ridge (λ = 1)0.830.991.831.78
Result: OLS gives huge opposite coefficients (−4.46 and +6.25) because it cannot tell the two copies apart. Ridge gives about 0.8 and 1.0, which together are close to the true 2. The test error drops from 4.83 to 1.78.
Ridge shrinks coefficients but rarely makes them exactly 0, so it keeps all features.

5. Lasso Regression (L1 Regularization)

📖 Lasso (Least Absolute Shrinkage and Selection Operator) adds a penalty on the absolute values of the coefficients (L1 norm): minimise SSE + λ Σ |βⱼ|. Unlike ridge, it can shrink some coefficients exactly to 0, so it also does feature selection.
Ridge (circle)β₁β₂Lasso (diamond)β₁β₂solution on an axis: β₂ = 0
Schematic. Orange ellipses = error contours of OLS. Blue shape = allowed region. The diamond has corners on the axes, so Lasso often lands on a corner (a coefficient becomes exactly 0). The circle has no corners.
Using Lasso to reduce the number of predictors
  1. Start with many predictors (some useless)
  2. Standardize them, then fit Lasso with a chosen λ
  3. Predictors whose coefficient becomes 0 are removed from the model
  4. Keep the remaining predictors and choose λ by cross-validation
Example: house price with 6 predictors
💡 Illustrative synthetic data (80 houses): the price really depends on area and location score only. The other four predictors are noise. Lasso with λ = 0.10.
PredictorOLS coefficientLasso coefficient
Area5.064.93
Location score2.932.82
Street number-0.080 (removed)
Owner age0.000 (removed)
Gate colour code-0.010 (removed)
Plot ID-0.100 (removed)
Result: Lasso keeps 2 predictors out of 6 and removes the 4 useless ones. The model becomes simpler, easier to explain and less likely to overfit.
With strongly correlated features, Lasso tends to keep one and drop the others. Elastic Net mixes both penalties (L1 + L2).

6. Ridge vs Lasso vs OLS

OLSRidge (L2)Lasso (L1)
PenaltyNoneλ Σ β²λ Σ |β|
CoefficientsCan be very largeSmall, rarely exactly 0Many become exactly 0
Feature selectionNoNoYes
Correlated featuresUnstableShares weight, stablePicks one, drops others
Best whenFew features, plenty of dataMany correlated featuresMany features, only a few matter
OverfittingHigh riskReducedReduced

7. ANOVA — Analysis of Variance

📖 ANOVA tests whether the means of three or more groups are really different, or only look different by chance. It compares the variation between groups with the variation within groups.
💡 Example: Three teaching methods A, B, C are tried on 5 students each. Do the methods give different average marks?
Method AMethod BMethod Csolid bar = group mean, dashed = overall mean
📐 One-way ANOVA
H₀: all group means are equal. H₁: at least one mean is different
SSB (between) = Σ nⱼ (mean of group j − overall mean)², df = k − 1
SSW (within) = Σ (value − its group mean)², df = N − k
MSB = SSB / (k − 1), MSW = SSW / (N − k), F = MSB / MSW
Big F (small p-value) → reject H₀
SourceSSdfMSF
Between groups509.22254.621.46
Within groups142.41211.87
Total651.614
Decision: At 5% significance the critical value F(2, 12) = 3.89. Our F = 21.46 is larger (p ≈ 0.0001), so we reject H₀: the teaching methods give different average marks.
ANOVA says that some mean differs, not which. A post-hoc test (e.g. Tukey) finds the pair. In regression, the same F-test checks whether the whole model is useful.

8. Model Validation Approaches

📖 Model validation: Checking how well a model will work on new, unseen data. A model must never be judged only on the data it was trained on.
ApproachHow it worksRemark
Hold-outSplit the data, e.g. 70% train and 30% testSimple, result depends on the split
k-fold cross-validationSplit into k folds. Train on k−1, test on 1, repeat k times, averageTypical k = 5 or 10. Uses all data
Leave-one-out (LOOCV)k = n. Each single record is the test set onceVery thorough, slow for big data
Stratified k-foldEach fold keeps the same class proportionsFor classification
BootstrapRepeatedly sample with replacementGood for small data
5-fold cross-validation: every fold is the test set once
Test
Train
Train
Train
Train
Train
Test
Train
Train
Train
Train
Train
Test
Train
Train
Train
Train
Train
Test
Train
Train
Train
Train
Train
Test
Average the 5 test scores for a stable estimate of how the model will behave on new data.
Use a validation set to tune settings (like λ or k) and keep the test set untouched for the final check. Using test data during tuning is called data leakage.
TaskCommon metrics
RegressionMSE, RMSE, MAE, R²
ClassificationAccuracy, precision, recall, F1-score, confusion matrix
Predicted YesPredicted No
Actual YesTP = 40FN = 5
Actual NoFP = 10TN = 45
📐 Metrics from the matrix
Accuracy = (TP + TN) / total = 85/100 = 0.85
Precision = TP / (TP + FP) = 40/50 = 0.80
Recall = TP / (TP + FN) = 40/45 = 0.889
F1 = 2PR / (P + R) = 0.842
🌳Chapter 2 — Supervised and Predictive Analysis
🌳 CHAPTER 2 — SUPERVISED AND PREDICTIVE ANALYSIS MIND MAP
k-NN → Look at the k closest known points and vote
Trees → Questions split data. Classification tree → class. Regression tree → number
SVM → Best boundary = maximum margin; support vectors; kernels for curves
Dimensionality reduction → Fewer features: feature selection or PCA

1. k-Nearest Neighbors (k-NN)

📖 k-NN: To classify a new point, find the k closest points in the training data and take a vote (classification) or an average (regression).
💡 Analogy: New in a colony? Ask the 3 nearest neighbours which shop is good and follow the majority.
Steps
  1. Choose k (an odd number avoids ties) and a distance (Euclidean: d = √[(x₁−y₁)² + (x₂−y₂)²])
  2. Compute the distance from the new point to every training point
  3. Pick the k smallest distances
  4. Classification: majority class. Regression: mean value
Worked example: Pass or Fail?
Student (hours studied, hours revised)Class
(1, 2)Fail
(2, 1)Fail
(3, 3)Fail
(6, 5)Pass
(7, 8)Pass
(8, 6)Pass
Training pointClassDistance to new student (5, 4)
(6, 5)Pass1.414
(3, 3)Fail2.236
(8, 6)Pass3.606
(2, 1)Fail4.243
(1, 2)Fail4.472
(7, 8)Pass4.472
?FailPass? = new studentdashed circle: k = 3
The 3 nearest points are (6,5) Pass, (3,3) Fail and (8,6) Pass. Two of three say Pass, so the new student is Pass.
Result (k = 3): nearest are (6,5) Pass, (3,3) Fail, (8,6) Pass → Pass (2 votes to 1).
PointDetail
Lazy learnerNo training step. All work happens at prediction time
Scaling neededFeatures must be normalized (Unit 1), or big-number columns dominate
Choosing kSmall k: noisy, overfits. Large k: smooth, underfits. Use cross-validation
WeaknessSlow on big data, suffers when there are many features

2. Classification and Regression Trees

📖 Decision tree: A flowchart of yes/no questions. The top is the root, questions are internal nodes, and the final answers are leaves. Each split is chosen to make the groups as pure (or similar) as possible.
Income > 50k?YesNoApproveAge > 30?YesNoApproveReject
A classification tree: each question splits the data, and each leaf gives a class.
Classification treeRegression tree
PredictsA class (Approve / Reject)A number (price, sales)
Leaf valueMajority class of the training points in the leafMean of the training values in the leaf
Split criterionGini impurity or entropy (information gain)Smallest SSE / variance after the split
TargetCategoricalContinuous
ExampleWill the loan be approved?What is the house price?
Error measureMisclassification rate, accuracyMSE, RMSE
📐 Impurity measures
Gini = 1 − Σ pᵢ² (0 = pure)
Entropy = − Σ pᵢ log₂ pᵢ Information gain = parent entropy − weighted child entropy
Worked example: classification split (10 loans: 6 Yes, 4 No)
  1. Parent Gini = 1 − (0.6² + 0.4²) = 0.48
  2. Split "Income > 50k": left has 4 loans (4 Yes, 0 No) → Gini = 0. Right has 6 loans (2 Yes, 4 No) → Gini = 1 − (⅓² + ⅔²) = 0.444
  3. Weighted Gini = 0.4 × 0 + 0.6 × 0.444 = 0.267
  4. Gini gain = 0.48 − 0.267 = 0.213. A good split
Worked example: regression split (area → price in lakh)
  1. Data: areas 500, 600, 700, 1200, 1300, 1400 with prices 20, 22, 25, 60, 65, 70
  2. Best split "area < 950" has the smallest SSE = 62.67
  3. Left leaf predicts the mean = 22.33, right leaf predicts 65.00
  4. A house of 650 sq ft falls in the left leaf, so predicted price = 22.33 lakh
Overfitting: A deep tree memorises the training data. Control it with a maximum depth, a minimum number of samples per leaf, or pruning.

3. Support Vector Machines (SVM)

📖 SVM: A classifier that finds the best separating line (hyperplane) between two classes. "Best" means the one with the maximum margin.
💡 Analogy: Building a road between two villages. Many roads are possible, but the best one leaves the widest empty space on both sides.
solid = max-margin hyperplanedashed = margins, circled = support vectorsmargin = 2/‖w‖ = 1.41
Hyperplane x + y = 6, so w = (1, 1) and b = −6. Margin lines x + y = 5 and x + y = 7. The 4 circled points are the support vectors.
TermMeaning
HyperplaneThe boundary w·x + b = 0 (a line in 2D, a plane in 3D)
MarginGap between the hyperplane and the closest points of each class. Width = 2 / ‖w‖
Support vectorsThe closest points. Only they decide the boundary
Maximum marginChoose w and b with the widest margin (minimise ‖w‖), so the model generalizes better
📐 Maximum margin for two linearly separable classes
Class +1 points satisfy w·x + b ≥ +1. Class −1 points satisfy w·x + b ≤ −1
Distance of the margin line from the hyperplane = 1 / ‖w‖, margin width = 2 / ‖w‖
Maximising the margin = minimising ‖w‖ subject to yᵢ (w·xᵢ + b) ≥ 1
Example: w = (1, 1), b = −6 gives ‖w‖ = √2, margin = 2/√2 = 1.41. Point (4,3): 4 + 3 − 6 = +1, so it sits on the +1 margin
ExtensionIdea
Soft margin (C)Allow a few points inside the margin. Small C = wide margin, more errors. Large C = narrow margin, fewer errors
Kernel trickHandles curved boundaries by implicitly mapping data to higher dimensions: linear, polynomial, RBF kernels

4. Dimensionality Reduction

📖 Dimensionality reduction means using fewer features while keeping most of the information. Too many features cause the curse of dimensionality: data becomes sparse, models slow down and overfit.
ApproachIdeaExamples
Feature selectionKeep the useful original features, drop the restFilter methods, Lasso (embedded), forward / backward selection
Feature extractionCreate new, fewer features from the old onesPCA, LDA
Principal Component Analysis (PCA)
PCA steps
  1. Standardize (or centre) the data
  2. Compute the covariance matrix
  3. Find its eigenvalues and eigenvectors
  4. Sort by eigenvalue. Eigenvectors are the principal components; a bigger eigenvalue means more variance
  5. Keep the top k components and project the data onto them
💡 Example: 10 points with 2 features. Covariance matrix = [0.617 0.615; 0.615 0.717]. Eigenvalues = 1.284 and 0.049.
PC1 keeps 96.3% of the variancefeature 1 →
PC1 is the direction along which the data is most spread. Projecting each point on PC1 turns 2 features into 1 with little loss.
Result: PC1 explains 1.284 / (1.284 + 0.049) = 96.3% of the variance. Dropping PC2 loses only 3.7%, so 2 features become 1.
Principal components are orthogonal (uncorrelated). PCA is unsupervised. Plot the eigenvalues (scree plot) to decide how many components to keep.
🔍Chapter 3 — Unsupervised Learning
🔍 CHAPTER 3 — UNSUPERVISED LEARNING MIND MAP
K-means → Group into k clusters around centroids
Hierarchical → Merge step by step, draw a dendrogram
Apriori → Find frequent itemsets, then association rules
Recommendation → Suggest items: content-based, collaborative

1. Clustering and K-Means

📖 Clustering: Grouping data so that items in a group are similar and items in different groups are different. No labels are given (unsupervised).
📖 K-means: Split data into k clusters. Each cluster has a centre called a centroid (the mean of its points). Every point belongs to the nearest centroid.
K-means steps
  1. Choose k and k starting centroids (random points, or k-means++)
  2. Assign each point to the nearest centroid
  3. Update each centroid to the mean of its points
  4. Repeat steps 2 and 3 until the assignments stop changing
Worked example (k = 2)
PointCoordinates
P1(1, 1)
P2(2, 1)
P3(1, 2)
P4(5, 4)
P5(6, 5)
P6(7, 5)
IterationCentroids usedAssignmentNew centroids
1(1.00, 1.00) and (5.00, 4.00)C1: P1, P2, P3 | C2: P4, P5, P6(1.33, 1.33) and (6.00, 4.67)
2(1.33, 1.33) and (6.00, 4.67)C1: P1, P2, P3 | C2: P4, P5, P6(1.33, 1.33) and (6.00, 4.67)
✕✕✕ = centroid of each cluster
Result: The centroids did not move in the last iteration, so the algorithm has converged: cluster 1 = {P1, P2, P3}, cluster 2 = {P4, P5, P6}.
Choosing k: the elbow method
Run k-means for k = 1, 2, 3 … and plot WCSS (within-cluster sum of squares, the total spread inside clusters). It always falls as k grows. Pick the k where the fall suddenly slows, the "elbow".
123456elbow: k = 3WCSS (total spread inside clusters)number of clusters k →
PointDetail
ObjectiveMinimise WCSS
WeaknessNeeds k in advance, depends on the starting centroids, sensitive to outliers, finds round clusters
RememberScale the features first (Unit 1 normalization)

2. Hierarchical Clustering

📖 Hierarchical clustering builds a tree of clusters (a dendrogram) without fixing k first. Agglomerative (bottom-up): start with every point as its own cluster and repeatedly merge the two closest clusters. Divisive is the top-down opposite.
Agglomerative steps
  1. Treat each point as a cluster and compute the distance matrix
  2. Merge the two closest clusters
  3. Recompute distances to the new cluster (using a linkage rule)
  4. Repeat until one cluster remains, then cut the dendrogram at the height you want
LinkageDistance between two clusters
SingleSmallest distance between any two points
CompleteLargest distance between any two points
AverageAverage of all pairwise distances
126710134dashed cut at distance 3.5 → 2 clusters
Single linkage on points 1, 2, 6, 7, 10. (1,2) and (6,7) join at distance 1, then 10 joins at 3, and the two groups join at 4.
K-meansHierarchical (agglomerative)
MechanismIteratively assigns points to k centroids and updates the centroidsRepeatedly merges the closest clusters, building a tree
k needed in advance?YesNo, choose it by cutting the dendrogram
OutcomeOne flat set of k clustersA dendrogram showing clusters at every level
Starting pointRandom centroids, results can changeDeterministic, same result every run
Cluster shapeRound (spherical) clustersDepends on linkage, can be any shape
Speed on big dataFast, scales to large dataSlow, needs an n × n distance matrix
Undo a step?Points can move between clustersNo, a merge is final
Best forLarge datasets, clear kSmall datasets, want the cluster hierarchy

3. Association Rules and Market Basket Analysis — Apriori

📖 Market basket analysis finds which items are bought together. Association rule: A → B (people who buy A also buy B). Apriori is the classic algorithm to find them.
📐 Measures
Support(A → B) = (transactions with A and B) / (all transactions)
Confidence(A → B) = support(A and B) / support(A)
Lift(A → B) = confidence / support(B). Lift > 1: positive link. Lift = 1: independent. Lift < 1: negative link
Frequent itemset = itemset with support ≥ minimum support
Apriori property: every subset of a frequent itemset must also be frequent. So if {bread, beer} is not frequent, no bigger set containing it can be frequent. This lets us prune candidates early.
Apriori steps
  1. Count single items and keep those with support ≥ minimum (L1)
  2. Join L1 items to make 2-item candidates (C2), count them, keep frequent ones (L2)
  3. Repeat with 3-item, 4-item sets… until none is frequent
  4. From each frequent itemset, make rules and keep those with confidence ≥ minimum confidence
Worked example (minimum support count = 3 out of 5)
TransactionItems
T1bread, milk
T2beer, bread, diaper, eggs
T3beer, cola, diaper, milk
T4beer, bread, diaper, milk
T5bread, cola, diaper, milk
Item (C1)CountFrequent (L1)?
beer3Yes
bread4Yes
cola2No (removed)
diaper4Yes
eggs1No (removed)
milk4Yes
2-itemset (C2)CountFrequent (L2)?
{beer, bread}2No
{beer, diaper}3Yes
{beer, milk}2No
{bread, diaper}3Yes
{bread, milk}3Yes
{diaper, milk}3Yes
3-itemset (C3)CountFrequent?
{beer, bread, diaper}2No
{beer, bread, milk}1No
{beer, diaper, milk}2No
{bread, diaper, milk}2No
Result: Frequent itemsets are the 4 single items and 4 pairs: {bread, milk}, {bread, diaper}, {milk, diaper}, {diaper, beer}. No 3-item set reaches count 3, so the algorithm stops.
RuleSupportConfidenceLift
beer → diaper60%100%1.25
diaper → beer60%75%1.25
bread → diaper60%75%0.94
diaper → bread60%75%0.94
bread → milk60%75%0.94
milk → bread60%75%0.94
diaper → milk60%75%0.94
milk → diaper60%75%0.94
💡 Reading a rule: beer → diaper has support 60%, confidence 100% and lift 1.25. Every beer buyer also bought diapers, and this is 1.25 times more often than by chance. A shop can keep these items close or offer a combo.
Uses of market basket analysis: store layout, combo offers and cross-selling, recommendations, stock planning.

4. Recommendation Systems

📖 Recommendation system: Software that suggests items (movies, products, songs) a user is likely to like, using past behaviour. Seen on Netflix, Amazon, YouTube and Spotify.
TypeIdeaExample
Content-basedRecommend items similar to what the user liked (uses item features)Liked a comedy by actor X, so show more comedies with X
Collaborative filteringRecommend what similar users liked (uses ratings only)Users like you also watched…
HybridCombine bothMany real systems
Collaborative filtering example (user-based)
Data is a user–item matrix of ratings. Goal: predict the missing rating (?) of Alice for Movie 3.
Movie 1Movie 2Movie 3Movie 4
Alice53?4
Bob5344
Carol1521
Dave4355
Prediction steps
  1. Compute the similarity of Alice with every other user using the movies they have all rated (cosine similarity)
  2. Cosine: Bob = 1.00, Carol = 0.65, Dave = 0.98
  3. Predicted rating = Σ (similarity × neighbour's rating for Movie 3) / Σ similarity
  4. = (1.00×4 + 0.65×2 + 0.98×5) / (1.00 + 0.65 + 0.98) = 3.88
Result: Alice is predicted to rate Movie 3 about 3.9 out of 5, so it is a good recommendation.
ChallengeMeaning
Cold startA new user or item has no history
SparsityMost of the user–item matrix is empty
ScalabilityMillions of users and items
RemedyMatrix factorization (e.g. SVD), hybrid methods
Quality is measured with RMSE on predicted ratings, or precision@k for the top-k list.
⚡Ready for Exam?Sab padh liya? Ab Quick Revision karo — definition, example aur diagram ek jagah!Quick Revision Karo →
⚡Quick Revision — Last Minute Exam Prep!
📌 How to use: Har topic mein pehle Definition, phir Example, phir Diagram hai.

📈 Chapter 1 — Regression and ANOVA

1. OLS and Residuals
📖 Definition: OLS chooses the line that minimises SSE = Σ(y − ŷ)². Residual e = y − ŷ.
💡 Example: Marks = 41.5 + 7.5 × hours. Residuals +1, −1.5, +1, −1.5, +1, SSE = 7.5, R² = 0.987.
Data and fitted lineResidual plot: e = y − ŷ0hours →hours →
Left: the dashed red segments are the residuals. Right: the same residuals drawn on their own, scattered around 0. Values: +1, −1.5, +1, −1.5, +1 (sum = 0).
2. Bias–Variance
📖 Definition: Bias = too simple. Variance = too sensitive. Error = bias² + variance + noise.
💡 Example: Straight line underfits. Degree-7 curve overfits.
Underfithigh biasGood fitbalancedOverfithigh variance
Same 8 points. A straight line is too simple (underfit). A degree-7 curve passes through every point, including the noise (overfit).
3. Ridge (L2)
📖 Definition: Minimise SSE + λ Σβ². Shrinks coefficients, reduces variance.
💡 Example: Correlated x₁, x₂: OLS −4.46 and +6.25, ridge 0.83 and 0.99. Test MSE 4.83 → 1.78.
sweet spotTraining errorTest errorsimple modelcomplex model
Training error keeps falling as the model gets complex. Test error falls, then rises again (overfitting). Choose the model at the lowest test error.
4. Lasso (L1)
📖 Definition: Minimise SSE + λ Σ|β|. Sets some coefficients exactly to 0 (feature selection).
💡 Example: 6 predictors → Lasso keeps area and location, removes 4.
Ridge (circle)β₁β₂Lasso (diamond)β₁β₂solution on an axis: β₂ = 0
Schematic. Orange ellipses = error contours of OLS. Blue shape = allowed region. The diamond has corners on the axes, so Lasso often lands on a corner (a coefficient becomes exactly 0). The circle has no corners.
5. ANOVA
📖 Definition: F = MSB / MSW compares 3 or more group means.
💡 Example: Methods A, B, C: F = 21.46 > critical 3.89, so means differ.
Method AMethod BMethod Csolid bar = group mean, dashed = overall mean
6. Model Validation
📖 Definition: Test on unseen data: hold-out, k-fold, leave-one-out.
💡 Example: TP 40, FP 10, FN 5, TN 45 → accuracy 0.85, precision 0.80, recall 0.89.
5-fold cross-validation: every fold is the test set once
Test
Train
Train
Train
Train
Train
Test
Train
Train
Train
Train
Train
Test
Train
Train
Train
Train
Train
Test
Train
Train
Train
Train
Train
Test
Average the 5 test scores for a stable estimate of how the model will behave on new data.

🌳 Chapter 2 — Supervised and Predictive Analysis

1. k-NN
📖 Definition: Vote of the k nearest points. Lazy learner, needs scaling.
💡 Example: New student (5,4), k = 3 → Pass (2 of 3).
?FailPass? = new studentdashed circle: k = 3
The 3 nearest points are (6,5) Pass, (3,3) Fail and (8,6) Pass. Two of three say Pass, so the new student is Pass.
2. Decision Trees
📖 Definition: Classification tree gives a class (Gini / entropy). Regression tree gives the mean of the leaf (smallest SSE).
💡 Example: Gini 0.48 → 0.267 after the split. House of 650 sq ft → 22.33 lakh.
Income > 50k?YesNoApproveAge > 30?YesNoApproveReject
A classification tree: each question splits the data, and each leaf gives a class.
3. SVM
📖 Definition: Maximum margin hyperplane. Margin = 2/‖w‖. Support vectors define it.
💡 Example: w = (1,1), b = −6: margin 1.41.
solid = max-margin hyperplanedashed = margins, circled = support vectorsmargin = 2/‖w‖ = 1.41
Hyperplane x + y = 6, so w = (1, 1) and b = −6. Margin lines x + y = 5 and x + y = 7. The 4 circled points are the support vectors.
4. PCA
📖 Definition: Keep the top eigenvector directions (principal components).
💡 Example: Eigenvalues 1.284 and 0.049: PC1 keeps 96.3%.
PC1 keeps 96.3% of the variancefeature 1 →
PC1 is the direction along which the data is most spread. Projecting each point on PC1 turns 2 features into 1 with little loss.

🔍 Chapter 3 — Unsupervised Learning

1. K-means
📖 Definition: Assign to the nearest centroid, update centroids, repeat.
💡 Example: Points converge to {P1,P2,P3} and {P4,P5,P6}. Elbow picks k.
✕✕✕ = centroid of each cluster123456elbow: k = 3WCSS (total spread inside clusters)number of clusters k →
2. Hierarchical
📖 Definition: Merge the closest clusters step by step. Result is a dendrogram, no k needed.
💡 Example: Points 1, 2, 6, 7, 10: merge heights 1, 1, 3, 4.
126710134dashed cut at distance 3.5 → 2 clusters
Single linkage on points 1, 2, 6, 7, 10. (1,2) and (6,7) join at distance 1, then 10 joins at 3, and the two groups join at 4.
3. Apriori
📖 Definition: Frequent itemsets via the Apriori property. Support, confidence, lift.
💡 Example: beer → diaper: support 60%, confidence 100%, lift 1.25.
📐 Formulas
Support = (A and B) / all
Confidence = support(A and B) / support(A)
Lift = confidence / support(B)
4. Recommendation
📖 Definition: Content-based, collaborative, hybrid. Cold start problem.
💡 Example: User-based CF predicts Alice's rating of Movie 3 = 3.88.
Movie 1Movie 2Movie 3Movie 4
Alice53?4
Bob5344
Carol1521
Dave4355
📄Previous Year Questions
📝 In Semester Test-2 (2026-27)
Branch: BE(CSE/IT)
Subject: Data Mining (24CST-381 / 24ITT-381)
Semester: 5  ·  Time: 1 Hour  ·  Max Marks: 20
Section A: 5 × 2 = 10 marks  ·  Section B: 2 × 5 = 10 marks
Attempt all questions

Section A — 2 Marks Questions

2M2026-27
Q1. Describe the objective of the OLS method in regression analysis. [CO2]▼
Answer:
Objective of OLS: to find the regression line (coefficients β₀, β₁ …) that minimises the sum of squared residuals SSE = Σ (y − ŷ)², giving the best fit to the data.
  • Squaring stops positive and negative errors from cancelling and punishes large errors
  • Simple regression: β₁ = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)², β₀ = ȳ − β₁x̄
  • Example: marks = 41.5 + 7.5 × hours has SSE = 7.5
2M2026-27
Q2. Use Lasso regression to reduce the number of predictor variables in a regression model by taking suitable example. [CO3]▼
Answer:
Lasso regression minimises SSE + λ Σ|βⱼ|. The L1 penalty pushes the coefficients of useless predictors to exactly 0, so those predictors are dropped.
Example (house price, 6 predictors): area, location score, street number, owner age, gate colour code, plot ID.
PredictorOLSLasso
Area5.064.93
Location score2.932.82
Street number-0.080 (removed)
Owner age0.000 (removed)
Gate colour code-0.010 (removed)
Plot ID-0.100 (removed)
Lasso keeps only area and location score: 6 predictors reduced to 2, giving a simpler model.
2M2026-27
Q3. Interpret the meaning of residuals in OLS regression. [CO2]▼
Answer:
Residual = actual value − predicted value, e = y − ŷ. It is the part of each observation that the regression line cannot explain (the error of that point).
  • Positive residual: model under-predicted. Negative: model over-predicted
  • OLS makes the sum of residuals 0 and minimises the sum of their squares
  • Residual plots check the model. A random scatter around 0 means a good fit; a pattern means the model is wrong
Data and fitted lineResidual plot: e = y − ŷ0hours →hours →
Left: the dashed red segments are the residuals. Right: the same residuals drawn on their own, scattered around 0. Values: +1, −1.5, +1, −1.5, +1 (sum = 0).
2M2026-27
Q4. Apply the concept of maximum margin to explain how SVM classifies two linearly separable classes. [CO3]▼
Answer:
Maximum margin: Among all lines that separate two linearly separable classes, SVM chooses the one with the widest gap (margin) to the nearest point of each class.
solid = max-margin hyperplanedashed = margins, circled = support vectorsmargin = 2/‖w‖ = 1.41
Hyperplane x + y = 6, so w = (1, 1) and b = −6. Margin lines x + y = 5 and x + y = 7. The 4 circled points are the support vectors.
  • Hyperplane: w·x + b = 0. Margin lines: w·x + b = +1 and −1
  • Margin width = 2/‖w‖, so maximising the margin means minimising ‖w‖ with yᵢ(w·xᵢ + b) ≥ 1
  • Only the nearest points (support vectors) decide the boundary. A wide margin generalizes better to new data
2M2026-27
Q5. Differentiate between a regression tree and a classification tree. [CO3]▼
Answer:
Regression treeClassification tree
PredictsA continuous numberA class label
Leaf outputMean of the values in the leafMajority class in the leaf
Split criterionMinimum SSE / varianceGini impurity or entropy
ExampleHouse price predictionLoan approved or rejected

Section B — 5 Marks Questions

5M2026-27
Q6. Distinguish between K-Means clustering and hierarchical clustering based on their clustering mechanisms and outcomes. [CO4]▼
Answer:
Both group unlabelled data, but they work in very different ways.
K-meansHierarchical (agglomerative)
MechanismAssigns points to the nearest of k centroids, updates centroids, repeats until stableStarts with every point as a cluster and repeatedly merges the two closest clusters
k in advance?YesNo (cut the dendrogram)
OutcomeOne flat partition into k clustersA dendrogram: clusters at every level
RepeatabilityDepends on starting centroidsSame result every run
ShapeRound clustersDepends on linkage
ScalabilityFast for large dataSlow, needs n × n distances
Merges / movesPoints can switch clustersA merge cannot be undone
✕✕✕ = centroid of each cluster126710134dashed cut at distance 3.5 → 2 clusters
Single linkage on points 1, 2, 6, 7, 10. (1,2) and (6,7) join at distance 1, then 10 joins at 3, and the two groups join at 4.
Use k-means for large data with a known k. Use hierarchical for small data when the cluster hierarchy matters or k is unknown.
5M2026-27
Q7. How ridge regression reduces overfitting in predictive models? Give example to justify your answer. [CO3]▼
Answer:
Overfitting happens when a model learns the noise of the training data, which usually shows up as very large coefficients. Ridge regression adds a penalty: minimise SSE + λ Σβⱼ².
How ridge reduces overfitting
  1. The penalty makes large coefficients expensive, so they are shrunk towards 0
  2. This adds a little bias but greatly reduces variance (the bias–variance trade-off)
  3. With correlated features, weight is shared instead of exploding in opposite directions
  4. λ is chosen by cross-validation (λ = 0 is OLS, a huge λ underfits)
Example: true relation y = 2x₁ + 1, and x₂ is almost a copy of x₁. Only 8 training points.
β₁β₂β₁ + β₂Test MSE
OLS-4.466.251.784.83
Ridge (λ = 1)0.830.991.831.78
Justification: OLS overfits with large opposite coefficients (−4.46, +6.25). Ridge keeps both near 0.8 and 1.0 (sum ≈ 2, the true value) and the error on 300 new points falls from 4.83 to 1.78.
sweet spotTraining errorTest errorsimple modelcomplex model
Training error keeps falling as the model gets complex. Test error falls, then rises again (overfitting). Choose the model at the lowest test error.