Skip to main content
Data Mining

Classification, Performance Measures, and Overfitting

Published: 2026-08-05
Level: postgraduate
Audience: Postgraduate students in Data Mining

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • Supervised versus unsupervised learning — covered in Lecture 5 (Supervised versus Unsupervised Learning)
  • Classification and regression — covered in Lecture 5 (Classification versus Regression) and Lecture 2 (Classification, Regression)
  • Training data and test data — covered in Lecture 2 (The Classification Dataset: Attributes, Train and Test)
  • Hypothesis space and performance measures — covered in Lecture 5 (Hypothesis Space and Performance Measures)

This lecture is a working session on classification. We revise supervised versus unsupervised learning and the split between classification and regression, then follow a full classification project from raw table to deployed model. The middle of the lecture is devoted to performance measures: how to score a regression model, how to score a classification model, the confusion matrix, accuracy, precision, recall, and F1. We then look at how to divide data into train and test sets, including cross-validation, at the practical issues that matter when you choose a classifier, and at the two failure modes every learner must recognize: underfitting and overfitting.

By the end of this session you should be able to answer three kinds of questions: Is this problem supervised or unsupervised, and classification or regression? — the taxonomy from the first sections; How good is my model, and in what sense? — the performance measures in the middle; and Where did the model go wrong, and how do I stop it happening again? — the train-test split, cross-validation, and the underfitting-overfitting tradeoff at the end. The same arc — build, measure, validate, diagnose — is what you will repeat on every real project.

6.1 Supervised and Unsupervised Learning

6.1.1 The Two Families of Data Mining Methods

Data mining offers two families of methods: supervised learning and unsupervised learning.

Hook. How can a machine learn if nobody ever tells it the right answer? And if somebody does tell it, what exactly can it then do? These two questions split the whole field of data mining into two families.

In supervised learning you are given the data and the corresponding class labels, and the job is prediction. The word supervised is the key: a supervisor — the data set itself — already knows the answer for every training example, and the model's job is to learn the pattern that connects the inputs to those known answers, so it can predict answers for new, unseen examples. Weather prediction systems, tsunami detection systems, and credit card fraud detection systems are all supervised prediction tasks: each one is trained on past cases where the outcome is already known (yesterday's weather, past tsunamis, historical fraud cases) and then asked to predict the outcome for new cases.

In unsupervised learning you are only given . You are not predicting anything; you are finding patterns and structure inside the data. There is no answer key to check against. The classic example is clustering, which we come back to later in the course — grouping customers, documents, or genes by how similar they are, without anyone having labelled the groups beforehand.

The training class labels are known in supervised learning and unknown in unsupervised learning. That single fact is the cleanest way to tell the families apart: ask "does the training data carry an answer column?" If yes, supervised; if no, unsupervised.

Intuition. Think of a classroom. In supervised learning the student trains on worked problems that come with a marked answer key — each practice question has its correct answer written in the margin, and the student learns what kinds of answers the teacher expects. In unsupervised learning the student is handed a pile of unmarked essays and asked: are there any natural groups here? Argumentative essays, narrative essays, essays about the same historical event? Nobody has labelled them; the structure has to be found, not read off.

Where the analogy breaks: in real data mining the "student" has no understanding of meaning at all — it only finds statistical regularities, and it is your job to decide whether those regularities are useful.

Real-world & domain connection. Supervised learning runs production systems that most people use daily without noticing: email spam filters trained on labelled spam/ham archives, credit card fraud scorers trained on labelled transactions, and weather services whose forecasts are supervised models over years of labelled historical weather. Unsupervised learning is the standard tool for exploration phases: market segmentation (find customer groups without pre-defined categories), document clustering, and anomaly scanning before you know what you are looking for. The two families are not competitors — a typical industrial pipeline uses unsupervised methods first to explore and clean data, then supervised methods to make the final predictions.

6.1.2 Classification versus Regression

Supervised learning divides into two types: classification and regression. In both cases you are given and .

If takes discrete values, we call those values class labels and the problem is classification. A discrete value means a value chosen from a fixed, countable set — "spam" or "not spam", "malware" or "benign", "yes" or "no". If is a continuous value, the problem is regression. A continuous value means any number on a scale — 74.3 dollars, 101.5 degrees, 12,845 transactions. Petrol price prediction, oil price prediction, and gold price prediction are regression problems: the price is a number on a scale, not a label from a fixed list.

Both families are prediction models; the difference is only what they predict. Classification predicts discrete, nominal values — the class labels. Regression predicts a continuous value.

Dimension Classification Regression
Target Discrete, nominal (class labels) Continuous (a number on a scale)
Typical question "Which category does this belong to?" "How much / how many / what value?"
Example Is this email spam? What will petrol cost tomorrow?
Output of the model A class label, e.g., spam / non-spam A number, e.g., 74.3 dollars

When to pick which: look at the answer column in your table. If the answers you want to predict are labels, it is classification; if they are numbers on a scale, it is regression. When the professor's definition comes up, keep the pair in mind: discrete Y means classification, continuous Y means regression.

Scope. This two-way split assumes the target is the thing you want to predict. If your question is not "predict " at all — find groups, find rare weird events, reduce dimensions — you have left the supervised branch and the classification-versus-regression split no longer applies. Also note the boundary cases: an ordinal rating such as a 1–5 star review is written as numbers but is usually treated as a discrete label problem, because the values form a small fixed list rather than any number on a scale.

Recap + bridge. Supervised learning predicts from labelled data; unsupervised learning finds structure in unlabelled data. Within supervised learning, discrete targets mean classification and continuous targets mean regression. Next we look at three real classification problems to sharpen the test for "is this classification?" before we ever build a model.

6.2 Classification Problems in the Wild

6.2.1 Spam Detection

The email inbox is a classification stage: for each incoming mail, decide whether it is spam or non-spam. The class labels of this problem are "spam" and "non-spam."

Every message that arrives lands in exactly one of two buckets, and the decision is made by a model long before you see it. The training material is easy to gather at scale: users label messages by reporting spam or by letting a message sit in the inbox, so the data set naturally carries its answer column — exactly what supervised learning needs. The features used by modern spam filters include the sender address, header fields, word frequencies, links, and metadata such as whether the message arrived in a burst.

6.2.2 Malware Detection

An antivirus takes a test file and tells you whether it is a malware file or a benign file. Benign means a good file — one that is safe to run. The class labels are "malware" and "benign."

The file to be scanned is the input, and the output is a verdict. The training set is a large labelled collection of files: known malware samples on one side, known-clean files on the other. Because the model only predicts on a customer's machine and never modifies its own decision rule there, an antivirus deployment is a pure prediction pipeline — this is the same train-build-test-deploy rhythm that section 6.3 walks through in detail.

6.2.3 Cancer Detection

A system takes an image of a cell and predicts whether the cell contains a cancerous, malignant cell or a benign one. The class labels are "malignant" and "benign."

In medicine the cost of the two mistakes is not symmetric: missing a malignant cell is far more dangerous than flagging a benign cell for a second look. That asymmetry is one reason medical classifiers are judged with recall (section 6.7) rather than plain accuracy — the system must not let positive cases slip through. The input here is not a row of numbers but an image, which gets converted into a feature representation before classification.

6.2.4 What Unifies These Problems

All three are classification problems because none of them predicts a continuous value. Each predicts a class label: spam/non-spam, malware/benign, malignant/benign. That pattern is the test for whether something is classification: the answer is a label from a small set, not a number on a scale.

The three problems share the same skeleton even though the domains differ completely — email, executables, cells. Each has:

  • Inputs — a message, a file, an image, converted into a feature vector;
  • A small fixed set of labels — exactly two classes in all three examples;
  • A labelled training set — past messages, past files, past cells with confirmed diagnoses.

If you can write the answer column as two or more named categories, you are doing classification.

Pitfalls. Three traps appear regularly. (1) Confusing the label with a number: "malware = 1, benign = 0" is still classification, because the encoding is just bookkeeping — the values are categories, not measurements. (2) Assuming every classification problem has two classes: the same logic extends to three, five, or fifty labels (see the confusion matrix in section 6.6). (3) Judging a classifier only by accuracy when the classes are unbalanced — in malware and cancer detection the rare class is usually the one that matters most.

Recap + bridge. Spam, malware, and cancer detection are three faces of the same problem: predict a class label from a small fixed set. Now we take one of these problems — the antivirus — and run the full project: table, train-test split, tree model, testing, and deployment.

6.3 Training and Testing a Classifier

Hook. Suppose a company asks you to build an antivirus. Where does the very first training example come from, how do you know the model is any good, and when are you allowed to let it loose on real machines?

6.3.1 The Data Table: Features and Class Labels

Suppose you want to build an antivirus with a data mining algorithm. You start by gathering a tabular data set. The rows represent files: file 1, file 2, file 3, and so on. The columns hold features: attribute 1, attribute 2, attribute 3. The last column is the class label.

A domain expert built this table by hand: for file 1 he looked at the attributes, marked attribute 1 as 1 when present and 0 when missing, wrote numeric values such as 50 or 10 where they applied, and supplied the class label for the file. One means malware, zero means benign, a good file. Attribute engineering and label assignment are done by the domain expert, and the table is gathered over time.

file attribute 1 (present = 1) attribute 2 ... class label (1 = malware, 0 = benign)
file 1 1 50 ... 1
file 2 0 10 ... 0
... ... ... ... ...

Three roles are already visible in this table. The domain expert decides which attributes exist and what each file's label truly is. The features are the columns the model is allowed to look at. The class label is the answer column the model will learn to predict. Notice what the domain expert does not do: he does not decide how the features combine into a decision — that is the learning algorithm's job.

Q: If the file size attribute is zero, do we neglect the file based on the size attribute?

A: It depends on your feature vector. If you believe file size tells you whether a file is malicious, you include it as an attribute, and a file size of zero is not a problem. A lot of malware-detection attributes can be derived by looking at the file header, so even a file that contains no data still yields information from its header. Whether to include file size at all is your choice, guided by how useful the attribute is.

The confusion behind the question is easy to see: a zero in a feature column looks like "missing data", but it is not — it is a legitimate value, exactly the same as an age of zero months in a paediatric data set. The attribute only earns its place by predictive usefulness, not by being nonzero.

6.3.2 Splitting into Training and Test Data

As a data mining expert your first move is to take the table and divide it into two parts: train data, also called training data, and test data. You can do a random sampling over the rows, and each row lands in one part or the other. Train and test are mutually exclusive sets — a sample cannot appear in both. The proportion is chosen by convention, which we come back to when we discuss splits.

The split exists to enforce a basic honesty rule: the model must never be evaluated on data it has already seen. If you measured a model on its training rows, it would look brilliant even when it had merely memorized them. The test rows are held out precisely so that every row the model is scored on is a row it has never met.

6.3.3 Building the Model on the Training Data

The training data builds the model. Suppose you pick the decision tree classification algorithm and train it on the training data. In the classic table used here there are four columns: refund, marital status, taxable income, and cheat. Cheat is the class label; the other three are candidate attributes for building the tree.

By magic of this example, refund is the attribute that best tells you whether the case cheats, so refund sits at the top. The rule to remember: the attribute carrying the highest information goes at the top of the tree, and attributes carrying less information move toward the lower end. The leaves of the tree are always class labels.

A decision tree is a sequence of questions: at each internal node, split the training rows by one attribute, and keep splitting until the rows in a branch are (nearly) all of one class. The "information" the professor refers to is made precise by measures such as entropy or the Gini index — an attribute that separates the classes cleanly is information-rich and earns the top position. The leaves are class labels because a tree's final answer must be a verdict, not a split.

6.3.4 Testing the Tree and Deploying It

Once the tree is built, you test it with the data you held out.

Worked example — walking a test record through the tree.

Take a test record and start at the root.

  1. The root asks: refund? The record's answer is no, so we take the right branch.
  2. The next node asks: marital status? The record's answer is married, so we take the right branch again.
  3. We reach a leaf, and the tree says the class label is no — the person does not cheat.
  4. Check against truth: the test data already carries its class label, and it is also no, so this prediction is perfect — a correct prediction, one true negative.

Sense-check: the record followed the "married" path, and the tree has learned from training that married filers rarely cheat, so predicting "no" is consistent with the learned pattern.

This is the whole training-and-testing rhythm: train data builds the model, test data checks whether the model is good. If the accuracy is 50 percent, you modify or redraw the tree. If the accuracy is 95 percent, the tree is good enough and you can deploy it at the customer end for real-world use.

Real-world & domain connection. This train-build-test-deploy loop is how antivirus vendors ship signature-free detection: the model is trained on labelled malware collections and then runs on customer machines where it only predicts — it never learns, updates, or changes its own rules in the field. The same loop, with the same honesty rule about held-out data, appears in credit scoring, medical screening, and every other deployed classifier.

Pitfalls. (1) The classic fatal mistake: training on all the data and "testing" on part of it — the accuracy you get is fiction, because the model has seen the test rows. (2) Judging the model on a single test record: one perfect prediction proves nothing; you need the whole test set averaged (section 6.4). (3) Letting the domain expert's labels drift over time: if the table is gathered over months, the meaning of "malware" may change while you collect, and the last column stops being trustworthy. (4) Forgetting the tree splits training rows only — when the deployed model meets data with attribute values it has never seen, you need a plan for how the tree handles them.

Recap + bridge. A classifier project is a loop: domain expert builds a labelled table, you split it into train and test, the training rows grow the model, and the held-out rows tell you whether it is good enough to deploy. We still need a number that says "good enough" — that is the subject of the next sections on performance measures.

6.4 Performance Measures for Regression

Hook. You have built two candidate regression models for the same problem — say a decision tree and a linear regression. Both produce numbers. Which one is better? You cannot answer by staring at the models; you need a ruler to measure them. This section builds that ruler.

6.4.1 The Model and the Per-Sample Error

In a regression problem you are given and , where is continuous: with , and you want to build a function that takes an and predicts . Here is the feature vector of test sample , is the actual continuous value, and is the predicted value.

Many candidate functions may be available — one could come from a decision tree, another from linear regression — so you need a way to judge them. On the test data you know both the attributes and the true . You pass into the model; it predicts . If equals , the prediction was perfect and the error is zero. The per-sample error is the difference between prediction and truth:

The professor's words: "the error would be Y dash minus Y. Y dash is essentially what your model is predicting; Y is the actual class value." If the error is zero, the model is good and the journey can stop here. If the error is huge, you must rethink the model.

Notation: some texts write the error the other way round, . The sign convention is a choice — the professor uses predicted minus actual. Never mix the two in one calculation; and note that every squared or absolute version used below is identical under either convention, because .

Intuition. The error is a misfit — how far the dart (the prediction) landed from the bullseye (the true value). A single dart tells you little; what you want is a summary over the whole throw.

6.4.2 Average Error over the Test Set

You do not judge the model on one sample. You pass all test samples through the model one by one and average the results. With the number of samples in the test set, the average error is:

The verbal description: "average error would be one by N — the number of samples in your test set — and you iterate over all the samples in your test set." In words, this is: build the model on the training set, walk every test sample through it, subtract the predicted value from the original value, and average over all test samples. The result is a single number that tells you how far the model's predictions sit from the truth on average.

Worked example — average error on four test houses. Suppose the test set holds four houses with actual prices (thousands of dollars) and a model predicts .

Per-sample errors, :

Average error:

The average error is thousand dollars — the model under-predicts by 5 on average. Sense-check: three errors are small (0 to 20) and they nearly cancel, which is exactly the weakness of this measure — a large negative and a large positive error can cancel into a small-looking average. That is why the next measure squares the differences first.

6.4.3 Sum of Square Errors

There is another famous quantity in regression problems: the sum of square errors, SSE. It squares the same difference you already have:

Math reconciliation. The professor described this formula verbally as "one by n y dash minus y square". That spoken form — squared difference averaged over the samples — matches the average squared error as written in the reference text (Sharda et al., Eq. 5.4: ). The name "sum of square errors" usually refers to the same quantity without the : (Tan et al., Eq. D.4). The two differ only by the factor : . We keep the professor's averaged form here — it is the form he stated and the one the exam follows — and note that when textbooks write "SSE" without , they mean the plain sum, which is the same quantity scaled by .

Why square? Two reasons.

Reason 1 — make large errors stand out. As the error grows, its absolute value should grow so that large errors are highlighted. A linear, absolute-value function keeps a linear relationship, so a big error and a medium error look similar in size. Squaring changes that: think of one squared, ten squared, and hundred squared. One squared stays one, ten squared jumps to a hundred, and hundred squared explodes to ten thousand — the largest errors dominate, exactly what you want to spot.

Reason 2 — remove the sign. Squaring handles negative values, since a negative difference becomes positive. Recall the worked example above: errors of and cancelled in the plain average. After squaring, contributes 400 and contributes 100 — both push the total up, so "wrong is wrong" regardless of direction. This is the "sign bias" the reference text calls out: without squaring, positive and negative errors can hide each other.

The root mean square, RMSE, is the same idea with a root added:

Math reconciliation. The professor described the root mean square in words — "square function or under root function" — without writing a formula. The standard form, confirmed in the reference texts, is exactly the square root of the averaged squared error above. RMSE answers in the same units as : if prices are measured in thousands of dollars, RMSE is in thousands of dollars too, which makes it the easiest number to interpret.

Both the square and the root serve the same purpose: they make bigger errors carry bigger values so the model's behaviour is visible. This is how you measure the performance of any regression model.

Worked example continued — SSE and RMSE on the four houses. With the same errors :

SSE = 150; RMSE ≈ 12.2 thousand dollars. Sense-check: the errors were 0–20 in size, and RMSE ≈ 12 sits inside that range but is pulled up by the largest error (20), exactly as squaring intends — the big miss dominates.

Visual intuition. Picture the errors as a number line with zero in the middle: errors on the left are under-predictions, on the right over-predictions. The plain average error is the balance point of those signed distances — a beautiful balance can hide terrible misses. Squaring folds the negative side onto the positive side, so the picture becomes a "distance from zero" scale, and RMSE is the typical distance after weighting big distances more heavily. One-sentence takeaway: the average error tells you the direction of the bias, SSE/RMSE tell you the size of the misses.

Where do these measures sit in the bigger evaluation picture? RMSE and SSE give a score for continuous targets only; the scope rule below marks the boundary, and section 6.5 handles the label case with a completely different ruler.

Scope. These measures assume the error makes sense as a numeric difference, which is only true for continuous . They are undefined in spirit for labels: "spam minus not-spam" is meaningless (section 6.5). They also assume your test set is a fair sample — measure on data the model has already seen and any error value is fiction. RMSE is sensitive to outliers by design (squaring); if you want misses to count equally, use mean absolute error instead.

Where students most often go wrong:

Pitfalls. (1) Reporting the plain average error alone — it can hide huge cancelling errors. (2) Mixing units: a model for prices in dollars and a model for prices in thousands give different SSEs for the same quality. (3) Comparing RMSE across data sets of different scales — 12.2 on prices near 300 is excellent, on temperatures near 20 it is a disaster. (4) Forgetting the : the professor's SSE is averaged; the plain-sum textbook version differs by a factor of .

Recap + bridge. Regression models are scored with the per-sample error , the average error , the squared error SSE, and RMSE. Squaring exists to amplify big errors and kill sign cancellation. This ruler does not transfer to classification — labels cannot be subtracted — so the next section builds a separate ruler for classifiers.

Real-world & domain connection. SSE and RMSE are the workhorses of continuous forecasting: energy traders score day-ahead electricity price forecasts with RMSE, central banks measure forecast error of inflation and GDP, and house-price models are judged in the same currency as the target (RMSE in dollars). When a vendor claims "our forecast is off by 12 dollars", that number is almost always an RMSE.

6.5 Performance Measures for Classification

Hook. Can you reuse the regression ruler for classification? Try to subtract "spam" minus "not spam" and the question answers itself. Classification needs its own ruler — and it turns out to be a counting problem, not a measuring problem.

6.5.1 The Error Function

In a classification problem, holds class labels instead of continuous values. In a binary classification problem there are two classes, say 0 and 1, so the class-label column contains a mix of zeros and ones, with attribute columns before it and one row per file. You split into train and test by random sampling, build a model , and predicts a class label .

To measure performance you build a helper function that takes the prediction and the true label:

The verbal description: "F will return one when H of X is equal to Y — whatever class label you are predicting is the same as the original class label. It will return zero when you are predicting a class label that is not matching."

Math reconciliation. As spoken, returns 1 on a correct match — so is a correctness indicator: averaging over the test set gives accuracy. The error, however, must count the wrong predictions, so the error uses the complementary indicator that returns 1 on a mismatch. Both readings are needed, and the next subsection shows the mismatch version explicitly. Keeping the professor's as stated, we have when the prediction is right (this is the accuracy indicator), and the error indicator — the two are complementary, so error and accuracy always sum to 1 over the same test set.

6.5.2 Average Classification Error

The error of the classification model is the average of the indicator over all test samples:

where the indicator is 1 when the prediction disagrees with the true label and 0 when they agree, and is the number of test samples. In classification there is exact equality, never approximation: two labels either match or they do not. The professor's phrasing: "error of your classification model would be one by N — the sum over all the test samples, giving H of X and Y."

The professor's mental model of the sum: if you pass one test sample and the result is 1, that one prediction was wrong; with a large test set you sum the ones and divide by to get the average error — in other words, the error is simply the fraction of test samples the model misclassified.

Worked example — classification error on 500 test files. The test set holds 500 files, each already labelled. Run the model over all 500.

  1. For each file, compute the indicator: 1 if the predicted label differs from the true label, 0 otherwise.
  2. Suppose the model produced 40 disagreements — 40 ones.
  3. The error is the sum divided by :

Error = 0.08, meaning the model is wrong on 8% of the test files. Sense-check: the remaining 460 files were predicted correctly, which gives accuracy , and indeed — error and accuracy split the whole test set between them.

6.5.3 Why SSE Does Not Apply to Classification

Q: Why would you calculate the error this way instead of subtracting values like in regression? Why not use SSE?

A: In regression you are subtracting absolute values because the values are continuous. In classification the class labels are nominal attributes, where the only thing you can check is whether the predicted label equals the original label. There is no meaning in computing SSE for a classification problem — you cannot subtract "spam" minus "not spam." You can of course modify the formula, but the equality check is the natural error for labels.

The professor's terminology contrast: regression errors are measured (how far apart are two numbers), classification errors are counted (how many labels disagree). Squaring is a scaling operation on a numeric distance; if no numeric distance exists between labels, there is nothing to square. Even when labels are encoded as numbers (0 and 1), the encoding is arbitrary bookkeeping — subtracting 1 minus 0 produces a number that carries no information about how wrong the model was.

Scope. This indicator-based error assumes a single correct label per sample and a hard prediction from the model. It breaks down when the model outputs probabilities instead of labels (then you must threshold first), when a sample can genuinely belong to several classes, and when the classes are severely imbalanced — on 99% benign data, a model that always predicts "benign" scores a tiny error of 0.01 yet is useless; that is precisely the situation where accuracy, precision, and recall (sections 6.6–6.7) must be examined separately rather than folded into one number.

Pitfalls. (1) Reaching for the regression formulas on a label problem — subtract "spam" minus "not spam" and the computation has no meaning. (2) Forgetting the complementary relationship: error and accuracy sum to 1, so a 0.08 error means 92% accuracy on the same test set. (3) Scoring the model on the training set — the error is only honest on held-out data. (4) Treating the indicator sum as a "distance": it is a count of disagreements, and two wrong predictions can be wrong in completely different ways while both contributing exactly 1.

Recap + bridge. Classification error counts mismatched labels and divides by the test-set size: it is the fraction of wrong predictions. Exact equality replaces numeric difference, which is why SSE cannot be transplanted here. Counting gives us only a single number, though — to understand where the mistakes are, we need the confusion matrix next.

Real-world & domain connection. The indicator error (equivalently, accuracy) is what vendor benchmarks quote for deployed classifiers — a spam filter that is wrong 1% of the time, a face-recognition system with 99.9% match rate. In high-stakes domains the count is usually broken down further: a cancer-screening model can be "98% accurate" and still fail badly on the rare malignant class, which is why sections 6.6–6.7 split the count into the four cells of the confusion matrix.

6.6 Confusion Matrix and Accuracy

Hook. The error count from section 6.5 says how many predictions were wrong, but not how they were wrong. Did the model raise false alarms, or did it let malware through? The confusion matrix answers both questions at once.

6.6.1 Building the Confusion Matrix

The confusion matrix is a performance measure heavily used in the field, and it is built for the test data. Take the antivirus example with two classes: malware is the positive class and benign is the negative class. On the y-axis you write the true labels — what the correct label of each sample actually is, already available in the test data. On the x-axis you write the predicted labels — what the model produced.

The matrix then has four cells:

Predicted positive (malware) Predicted negative (benign)
True positive (malware) True positive (TP) False negative (FN)
True negative (benign) False positive (FP) True negative (TN)
  • True positive (TP): the model predicted positive, and the true label was positive. Correct prediction.
  • True negative (TN): the model predicted negative, and the true label was negative. Correct prediction.
  • False positive (FP): the model predicted positive — it flagged the file as malware — but the true label was negative, a benign sample. Wrong prediction.
  • False negative (FN): the model predicted negative, but the true label was positive, an actual malware file. Wrong prediction.

True positive and true negative are the correct predictions of the model; false positive and false negative are the incorrect predictions.

Vocabulary check. False here does not mean "fake" — it means wrongly: a false positive is a prediction of positive that was false (the sample was not positive), and a false negative is a prediction of negative that was false (the sample was not negative). A true positive is a positive prediction that was true.

Visual intuition. Draw the matrix as a square table: the row labels are the true labels (the professor's y-axis), the column labels are the predicted labels (the x-axis). The top-left to bottom-right diagonal holds TP and TN — the correct predictions — and the opposite diagonal holds FP and FN — the mistakes. When you are asked about the confusion matrix later, this is the axis structure to draw first: true labels on one axis, predicted labels on the other. A good classifier puts almost all the mass on the diagonal; a confused one spills mass into the off-diagonal cells.

Worked example — a 10,000-file confusion matrix. An antivirus model is tested on 10,000 labelled files. The counts land as follows: TP = 6954 (malware flagged as malware), TN = 2588 (benign cleared as benign), FP = 412 (benign files flagged as malware — false alarms), FN = 46 (malware files let through — misses).

Predicted malware Predicted benign
Actually malware 6954 (TP) 46 (FN)
Actually benign 412 (FP) 2588 (TN)

Sense-check: 6954 + 46 = 7000 actual malware files and 412 + 2588 = 3000 actual benign files, so the table is consistent; the diagonal (6954 + 2588 = 9542) dominates, which is what a decent model looks like.

6.6.2 Accuracy

Q: How do you calculate accuracy?

A: Accuracy is the number of correct predictions divided by the total number of predictions. In this antivirus setting, malware is the positive class and benign is the negative class — benign is a good file; the two words are synonyms. The correct predictions are TP plus TN, and the total number of predictions is TP plus TN plus FP plus FN.

So accuracy answers: of everything the model predicted, what fraction was right? Applied to the worked example above:

Accuracy = 95.42% — 9542 of every 10,000 decisions were correct. Notice this matches the complementary relationship from section 6.5: the 46 + 412 = 458 mistakes give error , and .

6.6.3 Extending the Matrix to More Classes

Q: Can the confusion matrix be built for three classes, or five classes, or fifty classes?

A: Yes, it can. This example used a binary problem with two classes, but the matrix extends to N classes. Searching the web for a five-class confusion matrix shows the expanded version — the same idea, with more cells.

For classes the matrix becomes : one row per true class, one column per predicted class, and cells on the diagonal — the correct predictions — with off-diagonal cells for the different ways to be wrong. In a five-class matrix, cell counts the samples of true class that the model predicted as class . The diagonal stays the good news; the off-diagonal cells now tell you which pairs of classes get confused with each other — for example, "malignant" being frequently predicted for "benign" cells is a different and more dangerous confusion than the reverse.

Scope. Accuracy is only a fair summary when the classes are roughly balanced. On 97% benign data, a model that never looks at the file and always answers "benign" scores 97% accuracy — while detecting zero malware. Accuracy's one-number summary hides that failure completely; precision, recall, and the per-class rows of the matrix (sections 6.7) exist precisely for this situation.

Pitfalls. (1) Swapping the axes — true labels go on one axis, predicted labels on the other, and the two diagonals are not interchangeable: TP and TN are on the main diagonal, FP and FN on the other. (2) Thinking "false positive = a fake sample": it is a wrongly positive prediction. (3) Calling a model 95% accurate without checking the class balance — the number can be true and the model useless. (4) Summing the four cells wrong: the total is always the test-set size, .

Recap + bridge. The confusion matrix arranges the test-set verdicts into four cells — TP, TN, FP, FN — with true labels on one axis and predicted labels on the other; accuracy is the diagonal divided by the total. Accuracy compresses the matrix into one number, but it hides which kind of mistake dominates. Next, precision and recall look inside the matrix column by column and row by row.

Real-world & domain connection. Confusion-matrix reasoning runs through every deployed classifier: antivirus vendors tune their products between false alarms (FP) and missed malware (FN), medical screening regulators report both the missed-cancer rate (FN) and the false-positive rate (FP), and credit-card fraud teams balance blocking fraud (TP) against annoying customers with declined cards (FP). The four cells are also the input to cost-benefit analysis — in medicine an FN typically costs far more than an FP, a fact that single-number accuracy cannot express.

6.8 Train-Test Splits and Cross-Validation

Hook. Every performance measure from the last three sections is only as honest as the test set. A single random split can quietly hand you a test set with a different distribution from your training data — and then every number you compute is a lie. How do you make the evaluation trustworthy?

6.8.1 Acceptable Split Ratios

There is no thumb rule for the train-test ratio, but the community accepts three values: a 60/40 split, a 70/30 split, and an 80/20 split, where the first number is the training share. 70/30 is the most accepted value. The choice depends on your use case: if you want more testing, use 60/40; if you want less testing, use 80/20.

The trade-off behind the numbers: more training data gives the model more to learn from, while more test data gives a more reliable performance estimate. 70/30 is the community's default because it balances both. With 60/40 you accept a slightly weaker model to get a sharper verdict on it; with 80/20 you prioritise learning over measuring.

6.8.2 Train-Validate-Test

A second version divides the data into three parts: train, validate, and test.

  • Train trains the model.
  • Validate is part of the training process: it helps you improve the model. If your tree looks like it is chasing noise, the validation set tells you to delete a branch, increase the height of the tree, add a node, or remove a node.
  • Test then checks the fine-tuned model.

The key distinction: the validation set participates in model selection and tuning — you look at it, decide to prune a branch or add a node, and re-train — while the test set stays untouched until the very end. If you tune until the validation accuracy is high, the validation set has leaked its information into the model; the test set is the only measurement that is still unbiased. Both the two-way split and the train-validate-test split exist in the literature.

6.8.3 Cross-Validation

The single random split has a hidden assumption: that the distribution of data in the train set and the test set stays the same. Random sampling usually preserves the distribution, but sometimes it does not — sometimes the distribution between the train and test sets ends up different. When that happens, the model was built on a train set with a different distribution than the test set, and the test set no longer gives proper performance measures. Cross-validation solves this.

Take three-fold cross-validation. Divide the data set into three parts:

  • Iteration 1: parts one and two are the train set and part three is the test set; measure the accuracy.
  • Iteration 2: parts two and three train and part one tests; measure accuracy.
  • Iteration 3: parts one and three train and part two tests; measure accuracy.

Finally average the three accuracies:

Math reconciliation. The professor described the averaging verbally — "average the accuracy here, all the three divided by three" — and the fold-indexed formula above is the direct reconstruction of that description. The reference texts agree on the averaging for this kind of estimation (the accuracy estimate is taken as the average of the accuracies from each iteration); some texts compute the pooled alternative — total correct predictions across all folds divided by the total number of samples — which differs slightly but is the same idea. We keep the professor's averaged form, the one his exam follows.

Worked example — three-fold cross-validation on 900 files. Divide the data set into three parts of 300 files each: .

Iteration Train on Test on Accuracy
1 0.91
2 0.94
3 0.88

Cross-validation accuracy = 0.91. Sense-check: each of the three parts served as the test set exactly once, so no part ever appeared in the same role twice, and the single number 0.91 is the honest average of three independent verdicts — more trustworthy than one random split's score.

Visual intuition. Picture the data set as a strip of 900 cells sliced into three equal bands. In each iteration one band is shaded (test) and the other two are training; the shading slides across the strip one band at a time. After three iterations every cell has been shaded exactly once — the "each part gets tested once" property is the whole point of the picture. One-sentence takeaway: cross-validation rotates the test role through the whole data set, so no subset is ever over-represented in training or in testing.

The idea is to make the distribution of the train and test sets uniform. Even if the data is not uniformly distributed, every part gets used as the test set exactly once, and each iteration has a different train-test combination. In general, n-fold cross-validation divides the data into n parts, uses n minus one parts for training and one part for testing, repeats the exercise n times, and averages the values. Five-fold means five parts and five iterations with a different test set each time; seven-fold means seven parts and seven iterations.

Q: How does the order affect performance?

A: It is not about the order, it is about the set. In the first iteration these parts were your train data; in the second, other parts; in the third, yet others. Every iteration has a different test set, and that is how you get a uniform distribution of train and test across all the iterations. The order does not matter; your train-test split should simply be different again and again.

Q: So do you mean to say the best results come from randomizing the data?

A: Yes. You want to properly randomize the data. A single random sampling can still leave the distribution non-uniform between train and test. With cross-validation, each iteration shifts which parts train and which parts test, and averaging over the iterations balances out any distribution difference.

The misconception behind the first question: students picture the folds as a sequence and suspect the ordering matters. It does not — the folds are sets, and what matters is which combination is used for training and which single part for testing in each iteration. The second question tightens the same point: the fix for distribution drift is not clever ordering but rotation plus averaging.

Scope. Cross-validation fixes distribution drift across samples, not across time or sources. If your data was collected in one period and the deployed world is another (new malware families, new email styles), no rotation of the historical table can guarantee the future looks like the folds. Cross-validation also costs compute: k-fold trains the model k times, so for very large data sets a single stratified split is often chosen instead, and for tiny data sets leave-one-out (k = number of samples) is the limit case.

Pitfalls. (1) Forgetting to randomize before splitting — sorted data (all old files in train, all new files in test) produces a test set with a different distribution by construction. (2) Leaking test information during tuning: adjusting the model on the validation set is fine, adjusting it on the test set is cheating. (3) Using the averaged cross-validation score as a guarantee for the future — it estimates performance on the data family you have, not on any distribution you might meet. (4) Mixing up the three roles: train builds, validate tunes, test verifies.

Recap + bridge. One split is a gamble: a lucky or unlucky partition can skew the distribution between train and test. Accepted ratios are 60/40, 70/30 (most used), and 80/20; a validation set tunes the model in between; and cross-validation rotates the test role through every part, averaging the verdicts: . With honest data and honest splits in place, the measures from sections 6.4–6.7 finally mean something. Next we look at the practical issues that decide which classifier you actually pick.

Real-world & domain connection. k-fold cross-validation is the standard protocol in model selection pipelines: scikit-learn-style workflows grid-search hyperparameters inside k-fold loops precisely so that the reported score is not an artifact of one random split. In industry the same idea appears as "time-series aware" variants for fraud and churn models, where folds must respect time ordering, and in academic papers the phrase "10-fold cross-validation" is the default claim of evaluation honesty.

6.9 Issues in Classification Methods

Hook. Two models can have identical accuracy and still be completely different tools: one trains in a second and predicts slowly, the other trains for hours and predicts instantly; one explains every decision, the other is a black box. Which do you buy? The answer depends on the issues in this section.

6.9.1 Accuracy and Speed

When you judge a classification method, accuracy is the headline: how many correct predictions you make. Precision and recall are more measures you can use on top. Speed is a second issue, measured in two directions:

  • Training time — how quickly you build the model.
  • Test time — how quickly you predict.

The k-nearest neighbor classifier has absolutely zero training time but very high test time: it stores the training data and does nothing at build time, then at prediction time it must scan and compare against (a large fraction of) the stored samples for every new input. Decision tree and naive Bayes sit on the other side: high training time and comparatively low test time — building the tree or estimating the probabilities is the expensive step, after which each prediction is a short walk down the tree or a small product of probabilities.

In the antivirus context the trade-off is concrete — how quickly can you build the model and deploy it on a machine (train time), and how quickly can the deployed model scan an entire computer (test time)? A classifier that scans a 100 GB disk by comparing every file to every training sample is unusable at the customer end, however accurate; a classifier that cost a day of training to build is fine, because training happens once in the lab.

6.9.2 Robustness

Robustness means how well your model handles noise and missing values in the data. Noise can enter by mistake, or it can be added deliberately with bad intentions: an attacker deliberately injects noise into a system to reduce the performance of a classification model. Defending against that kind of adversarial noise is an active research area. If a model folds when 5 percent of its inputs are corrupted, it cannot handle noise.

Real-world & domain connection. Adversarial noise is not theory: image classifiers can be fooled by imperceptible pixel perturbations, spam filters are probed with obfuscated text, and malware detectors face attackers who deliberately pad or mutate files so the feature values shift. Robustness research — training with corrupted inputs, adversarial training, anomaly-aware pipelines — is one of the professor's flagged thesis directions.

6.9.3 Scalability

Scalability asks how the solution behaves as the data grows. A method may build a decision tree quickly and effectively on a small data set; the question is whether it still builds a good tree quickly when you hand it a huge data set.

A method that is fine for 10,000 rows can become infeasible at 10 million rows if its training cost grows quadratically with the sample count, and a method that produces good trees on tidy data may degrade as the volume forces approximations. The scaling question is separate from accuracy: a method can be both accurate and unscalable, or scalable and weak.

6.9.4 Interpretability and Explainability

Interpretability means how well you can explain your results. The model is a function that outputs , but in most places where these models are applied — malware detection, medical decisions, spam detection — you must be able to explain why the decision was reached. If the process is a black box, nobody will buy your model or your solution. Explainability research — making models that can justify their decisions — is currently a hot topic.

The distinction inside this issue: a decision tree is interpretable by construction — every prediction is a readable chain of questions (refund = no, married → "does not cheat") — while deep or ensemble models explain little about why they fired. When a doctor asks "why did the system flag this cell?", "because a 0.93 score exceeded a threshold" is not an answer; explainability research exists to produce the missing justification.

6.9.5 Fairness and Goodness of Rules

Fairness asks how fair your model is: whether it treats groups evenly or quietly discriminates. Other measures include the goodness of rules, the size of the tree, and the compactness of the tree, which we will revisit when we study the models in detail. These issues — robustness, interpretability, explainability, fairness — are the current research buzzwords. If you want to work on a thesis in this area, that is the direction to pick; building a classification model itself is considered routine these days.

Pitfalls. (1) Optimizing accuracy alone and ignoring the other issues — a fast, accurate black box can still be unsellable in medicine or law. (2) Treating train time and test time as the same number — k-NN is the extreme case: zero and slow. (3) Testing robustness only on clean data — a model that never saw noise cannot claim to handle it. (4) Mistaking "the model works on my data" for "the model scales to production data" — scalability is a separate verdict.

Recap + bridge. Choosing a classifier means balancing accuracy, training time, test time, robustness, scalability, interpretability, explainability, and fairness. The professor's warning for the exam: remembering the recall formula will not help; understanding what each measure means is what counts. And for a thesis: the open frontier is robustness, interpretability, explainability, and fairness — building a classifier is routine. We close the lecture with the two failure modes that every choice of classifier must survive: underfitting and overfitting.

Real-world & domain connection. These issues map to regulatory reality: European and other AI regulations require explainability for high-risk decisions, banks must show fair treatment across demographic groups in credit models, and antivirus vendors publish not just detection rates but false-alarm trade-offs. "Goodness of rules" and tree size, as the professor notes, return when the course studies the models themselves — they are the compactness criteria that make a learned rule set auditable.

6.10 Overfitting and Underfitting

Hook. A model that learns nothing is useless. A model that learns everything is also useless. Where is the line, and how do you find it? This section is the most-repeated graph in machine learning, so it is worth understanding once, deeply.

6.10.1 Underfitting: The Straight-Line Limit

Take a binary classification problem with two classes drawn in a plane — say a blue class and a red class. Your classifier is restricted to drawing a straight line, not even a curve: the you build can only separate the plane with a line.

Any straight line leaves many red samples on the blue side and many blue samples on the red side, so the model's performance is poor. This is underfitting.

Underfitting means the classification algorithm was not good enough to learn the complete data. The data set is complex and spread out, and the limited hypothesis space could not divide it properly, which produces a lot of error. The model is not learning the data; there is too much error left over.

The professor's analogy. The straight line is the defining image: the data forms interlocking clusters, and no single line — wherever you draw it — can separate them. The model is not making a subtle mistake; it was never able to represent the pattern, like trying to draw the coastline with a ruler. The professor's line: in one direction you learn nothing (underfitting).

Intuition. Underfitting is the student who never studied: the answer sheet is handed back covered in errors, but the errors are not the student's fault in a deep sense — the student's study method was too weak for the material. Add a stronger hypothesis space (a curve, a deeper tree) and the same data becomes learnable.

6.10.2 Overfitting: Learning the Noise

Now build a very complex classification boundary that winds around every point, separating the two classes exactly. This is overfitting: the model learns all the minute details of the data set — and that includes noise.

The classic tell is an isolated red point sitting deep in the blue zone. It is very different from the rest of the data points, and it is probably a noisy point, a measurement that was not gathered correctly. The ideal model should not learn such points.

Overfitting means over-learning: you gather as much information as you can, including the minute details that are actually noise. The professor's summary: in one direction you learn nothing (underfitting); in the other you learn everything, details and noise alike (overfitting). What you want is a model in the middle that learns the general statistics of the data, not the accidental details.

Analogy from daily life. Overfitting is the student who memorizes the textbook's example answers instead of learning the method: they ace the examples they have seen and fail every unseen question, because what they stored was the accidents of the examples, not the pattern. The isolated red point is exactly such an accident — it belongs to the blue region in general, and a well-generalizing model treats it as a fluke.

Real-world & domain connection. Overfitting is the plague of real deployments: a credit model trained until it recognizes every historical applicant will collapse on new applicants, an antivirus that memorizes its training samples misses every novel malware variant, and medical models that chase noise in imaging data fail in the clinic. The generalization problem — separating signal from accident — is the core reason train-test splits and cross-validation (section 6.8) exist at all.

6.10.3 The Error-Complexity Tradeoff

This graph appears again and again in machine learning, so it is worth understanding once, deeply.

  • On the x axis is model complexity — a simple straight line on the left, then curves, then very complex boundaries on the right.
  • On the y axis is error.

For the train set: when the model is very simple, train error is high; as complexity grows, train error falls steadily and eventually becomes zero, because a complex model memorizes the training data.

For the test set: when the model is very simple, test error is high; as complexity grows, test error falls to a minimum in the middle; beyond that it climbs again.

Underfitting is the left region, where both train and test errors are high. Overfitting is the right region, where train error is very low but test error is very high. The right place for the model is the middle, where test error bottoms out.

error
  |
  |        train error ______
  |                        \  (falls to ~0 on the right)
  |     test error  ___..--''''''--..__
  |                 /  falls to a       \  (climbs again: overfitting)
  |  underfitting  /   minimum here      \
  |  (both high)  +________________________\______  model complexity
  |                                     ^
  |                           sweet spot (lowest test error)

Reading the graph: the train curve is a monotone descent — complexity always helps the training score, so train error can never tell you that you overfit. The test curve is the honest one: it falls, bottoms out at the sweet spot, then rises. The gap between the train and test curves is the signature of overfitting — at the far right the model scores zero on training data while the test error climbs.

The same story in decision-tree terms: a tree with only one node — depth one, just a root — cannot learn anything, so train error is high. As you add nodes, train error drops, and a tree of depth 500 can reach zero train error. The test set follows the same curve as before: it starts high, improves, then worsens as the tree keeps growing. You want to stop in the middle.

Worked example — depth 1 versus depth 500. A classifier is trained on 10,000 labelled records.

  • Depth 1 (one node, the root only): the tree answers every record with the majority class. Train error ≈ 0.35, test error ≈ 0.35. It underfits: there is nothing in the tree but a single split, so both curves sit at their high starting values.
  • Depth 500 (maximal tree): the tree grows until every training leaf is pure, so train error = 0 — it has memorized all 10,000 training records, noise included. Test error, however, is ≈ 0.38, worse than the depth-1 tree and far worse than the sweet spot, because the memorized accidents do not repeat in the test set.
  • Sweet spot (say depth 12): train error ≈ 0.12, test error ≈ 0.08 — the test curve's minimum.

The takeaway: the depth-1 tree learned nothing and the depth-500 tree memorized everything; the depth-12 tree learned the general statistics and scored best on data it had never seen. Sense-check: accuracy is the mirror of error, so the sweet spot is also where test accuracy is highest — which is the number section 6.3 told you to watch before deploying.

Pitfalls. (1) Using train error to judge a model — it always falls as complexity grows, so it cannot detect overfitting; only the test curve can. (2) Mistaking an isolated point deep inside the other class for a real pattern — the professor's flag: it is probably noise and should not be learned. (3) Assuming "more complex = better" because the training score improves — the test curve rises on the right. (4) Labelling the regions wrong on the graph: left = underfitting (both errors high), right = overfitting (train low, test high), middle = the sweet spot where test error bottoms out.

Scope. The tradeoff graph assumes a single smooth axis of "complexity" (more nodes, more degrees of freedom). Real model selection has knobs beyond complexity — regularization, ensembling, feature selection — but every one of them moves the model along the same underlying curve; the error-complexity picture is the map for all of them.

Recap + bridge. Underfitting = too little model (both errors high); overfitting = too much model (train error near zero, test error high); the sweet spot is where the test curve bottoms out. When you see the error-complexity plot on an exam or in a paper, label the left side underfitting, the right side overfitting, and the dip in the test curve the sweet spot. With that, the lecture's full arc is complete: taxonomy, project, measures, splits, practical issues, and the two failure modes — the tools you need to build and judge any classifier.

Exam Guidance Summary

  • The performance-measures block is extremely important. A common interview and exam probe is "what is the recall value?" — be ready to give the number and, more importantly, to explain the significance of that number. Remembering the formula will not help; understanding what each measure means is what counts.
  • Be ready to contrast precision and recall with the axis intuition: precision looks at the x axis (predicted labels), recall at the y axis (true labels). Expect questions on accuracy, the four confusion-matrix cells, precision, recall, the true negative rate, and F1.
  • For F1, be ready to justify the harmonic-style combination: the harmonic mean collapses toward zero when either precision or recall is low, so a model strong on one side cannot mask weakness on the other — a plain average can.
  • The error-versus-model-complexity graph will appear again and again. Know the underfitting region (train and test error both high), the overfitting region (train error low, test error high), and where the model should sit (the sweet spot where test error bottoms out).
  • Expect the train-test split conventions (60/40, 70/30, 80/20), the role of the validation set, and the mechanics of cross-validation: n folds, n minus one parts train, one part tests, accuracies averaged.
  • Remember the classification-versus-regression test (discrete Y versus continuous Y) and the supervised-versus-unsupervised test (labels known versus unknown) — both are frequent short questions.
  • For a thesis or project, the current research directions are robustness, interpretability, explainability, and fairness; building a classifier is considered routine.

Key Industry Applications

  • Weather prediction, tsunami detection, and credit card fraud detection are supervised prediction systems in production.
  • Petrol, oil, and gold price prediction are regression deployments in finance and energy.
  • Spam filtering is classification running inside every email inbox.
  • Antivirus and malware detection are classification systems: models trained on labelled malware collections, deployed to scan machines, with file-header attributes used even for empty files.
  • Cancer detection from cell images is classification in medicine, predicting malignant versus benign cells — where recall (catching every malignant cell) matters more than avoiding false alarms.
  • In industry, k-nearest neighbor is chosen when training time must be zero; decision trees and naive Bayes are chosen when fast prediction matters.
  • The F1 score is the standard performance measure in text-based analysis.
  • RMSE is the standard forecast-error currency in continuous domains: energy markets, economics, and pricing models all report error in the units of the target.
  • Cross-validation is the standard evaluation protocol in model-selection pipelines, with time-aware variants in fraud and churn modelling.
  • Adversarial robustness — noise added deliberately to break classifiers — is an active research field, as are explainable models, because customers will not buy a black box.

DM Lecture 6 notes · Classification, Performance Measures, and Overfitting

Data Mining· postgraduate· 2026-08-05

Sections Breakdown

1Supervised and Unsupervised Learning

The two families of data mining methods and the split between classification and regression

2Classification Problems in the Wild

Spam, malware, and cancer detection as three faces of the same classification problem

3Training and Testing a Classifier

The labelled data table, the train-test split, building a decision tree, and deploying it

4Performance Measures for Regression

Per-sample error, average error, SSE, and RMSE for continuous targets

5Performance Measures for Classification

The indicator-based error function and why SSE does not apply to labels

6Confusion Matrix and Accuracy

The four cells TP, TN, FP, FN, the accuracy formula, and the multi-class extension

7Precision, Recall, and Related Measures

PPV, NPV, recall, TNR, and the F1 score as the harmonic mean of precision and recall

8Train-Test Splits and Cross-Validation

Accepted split ratios, the validation set, and k-fold cross-validation

9Issues in Classification Methods

Accuracy, speed, robustness, scalability, interpretability, explainability, and fairness

10Overfitting and Underfitting

The error-complexity tradeoff and where the model should sit

Postgraduate students in Data Mining

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

Supervised and Unsupervised Learning

Must-know: Supervised = data + labels + prediction; unsupervised = data only + pattern finding. Classification predicts discrete class labels; regression predicts a continuous value.

⚠️ Top pitfall: Calling clustering (or any label-free pattern finding) prediction; confusing ordinal numbers written as digits with continuous regression targets.

Self-check: Is 'predict tomorrow's gold price' classification or regression?

Classification Problems in the Wild

Must-know: The classification test: the answer is a label from a small set, not a number on a scale.

⚠️ Top pitfall: Treating a 0/1 encoding of labels as a numeric regression target; assuming classification is always binary.

Self-check: Is 'predict tomorrow's temperature' classification?

Connects to: Supervised and Unsupervised Learning; Training and Testing a Classifier

Training and Testing a Classifier

Must-know: Train data builds the model; test data checks it; the attribute carrying the highest information goes at the top of a decision tree; leaves are always class labels.

⚠️ Top pitfall: Training on all the data and then 'testing' on part of it — the estimate is fiction.

Self-check: In the refund / marital status / taxable income / cheat tree, a test record with refund = no and marital status = married lands in which leaf?

Connects to: Performance Measures for Regression; Train-Test Splits and Cross-Validation

Performance Measures for Regression

Must-know: Average error = (1/N) sum of (y-hat - y); SSE = (1/n) sum of squared differences (professor's form; standard SSE drops the 1/n); RMSE = sqrt(SSE). Squaring amplifies large errors and removes sign cancellation.

⚠️ Top pitfall: Reporting only the plain average error — positive and negative errors can cancel and hide huge misses.

Self-check: Errors of -20, +10, -10, 0: what are the average error, SSE, and RMSE?

Connects to: Performance Measures for Classification

Performance Measures for Classification

Must-know: Error = (1/N) sum of indicator[H(x_i) != y_i]; error + accuracy = 1; SSE is meaningless for nominal labels because labels cannot be subtracted.

⚠️ Top pitfall: Applying SSE to a label problem; forgetting error and accuracy sum to 1.

Self-check: 40 of 500 test files misclassified: what is the error, and what is the accuracy?

Connects to: Performance Measures for Regression; Confusion Matrix and Accuracy

Confusion Matrix and Accuracy

Must-know: Draw true labels on one axis, predicted labels on the other; Accuracy = (TP + TN) / (TP + TN + FP + FN); the matrix extends to N classes with the diagonal as correct predictions.

⚠️ Top pitfall: Swapping the axes or the diagonals; treating 'false positive' as a fake sample; trusting accuracy on imbalanced classes.

Self-check: TP=6954, TN=2588, FP=412, FN=46 on 10,000 files: what is the accuracy?

Connects to: Performance Measures for Classification; Precision, Recall, and Related Measures

Precision, Recall, and Related Measures

Must-know: Precision = TP/(TP+FP) (x-axis, predicted column); recall = TP/(TP+FN) (y-axis, true rows); F1 = 2PR/(P+R) is the harmonic mean, used because it collapses to zero when either measure is zero.

⚠️ Top pitfall: Answering 'precision = how many correct predictions' (that mixes both classes); swapping the denominators of precision and recall.

Self-check: Predicted 100 malicious, 80 correct; 500 malware files present, 80 caught: what are precision, recall, and F1?

Connects to: Confusion Matrix and Accuracy; Train-Test Splits and Cross-Validation

Train-Test Splits and Cross-Validation

Must-know: 60/40, 70/30, 80/20 splits (70/30 most accepted); validation tunes, test verifies; n-fold CV: n parts, n-1 train, 1 test, repeated n times, accuracies averaged: A_cv = (1/k) sum A_j.

⚠️ Top pitfall: Believing the fold order matters (it is the set, not the order); forgetting to randomize before splitting.

Self-check: Three-fold accuracies 0.91, 0.94, 0.88: what is A_cv?

Connects to: Training and Testing a Classifier; Precision, Recall, and Related Measures

Issues in Classification Methods

Must-know: k-NN: zero training time, high test time; decision trees and naive Bayes: high training time, low test time. The frontier for theses: robustness, interpretability, explainability, fairness. Understanding the meaning of a measure beats memorizing its formula.

⚠️ Top pitfall: Judging a classifier by accuracy alone; treating train time and test time as the same number.

Self-check: Which classifier has zero training time but very high test time?

Connects to: Overfitting and Underfitting; Training and Testing a Classifier

Overfitting and Underfitting

Must-know: Label the error-complexity graph: left = underfitting (train and test both high), right = overfitting (train ~0, test high), middle = sweet spot where test error is minimal; a depth-500 tree reaches zero train error by memorizing noise.

⚠️ Top pitfall: Judging a model by train error, which always falls with complexity and hides overfitting; treating an isolated noise point as a pattern.

Self-check: In the error-complexity graph, what distinguishes the overfitting region from the underfitting region?

Connects to: Train-Test Splits and Cross-Validation; Training and Testing a Classifier

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.