Classical Machine Learning Classification
A Tutor Lesson on Classification in Classical Machine Learning
1. What Classification Does
Classification is a supervised machine-learning task in which a model learns from examples that already have known labels, then predicts a label for new examples. For instance, a model might use a penguin’s measurements to predict whether it is male or female.
This differs from regression, which predicts a numerical value rather than a category. A regression model might estimate a penguin’s body mass; a classification model might predict its species or sex.
In supervised learning, the known answers in the training data guide the model. The model looks for patterns connecting the input variables—called features—to the answer it is meant to predict, called the target.
Classification predicts a category; regression predicts a numerical quantity.
Think about it: If a model predicts whether an email is spam or not spam, is that classification or regression? What if it predicts how many minutes a person will spend reading the email?
2. Preparing Data for a Classifier
A classifier can only learn from data that has been prepared appropriately. That preparation includes inspecting the data, handling missing or invalid values, converting categories into numeric representations, and checking how the values are distributed.
The penguin example
The Palmer penguins dataset contains measurements and descriptive information for penguins from three species living on three Antarctic islands. Its variables include species, island, bill length, bill depth, flipper length, body mass, and sex.
The dataset contains 344 rows initially. Some rows have missing measurements or missing sex values. A common first step is to inspect the dataset’s structure and count missing values. In the example, dropping rows with missing values leaves 334 rows. A further check finds one invalid sex entry represented by a dot; removing that row leaves 333 rows.
This illustrates an important principle: missing and invalid values should be identified before training. A model may not be able to use an incomplete row, and an invalid category should not accidentally be treated as a meaningful label.
Dropping incomplete rows is one possible strategy, as used here. It is not automatically the best choice for every dataset: if many rows are incomplete, removing them could discard too much useful information. The right treatment depends on the data and the task.
Encoding categorical variables
Many machine-learning algorithms expect numeric inputs. In the penguin dataset, species, island, and sex are categorical variables, so they must be represented numerically before being used by a model.
A label encoder assigns a numeric code to each category. For example, three species could be represented by codes such as 0, 1, and 2, while two sex categories could be represented by 0 and 1. These numbers are identifiers; they do not mean that one species is “greater than” another.
For some algorithms, numeric codes can accidentally suggest an order that does not exist. One-hot encoding is an alternative: it creates a separate indicator variable for each category. For example, a three-category variable becomes three columns, with one column marked as active for each observation. This avoids treating arbitrary category codes as ordered quantities.
Checking distributions and possible outliers
Before building a model, it helps to examine how numerical values are distributed. Histograms show how many observations fall into ranges of values, and a kernel density estimate (KDE) gives a smoothed view of the distribution. Comparing these plots by species can reveal whether measurements differ across groups.
An outlier is an observation that lies unusually far from the rest of the data. An unusual value might be a data-entry error, but it might also be a real and meaningful observation. It should be investigated rather than removed automatically.
One common way to flag possible outliers uses quartiles. The first quartile, Q1, marks the point below which roughly 25% of observations fall; the third quartile, Q3, marks the point below which roughly 75% fall. The interquartile range is
IQR=Q3−Q1.The usual inner fences are
Q1−1.5IQRandQ3+1.5IQR.Values beyond these fences are often flagged as potential outliers. More distant outer fences can be defined using 3IQR instead of 1.5IQR. In the penguin example, this check did not flag outliers in the four physical measurements examined.
Think about it: Why would it be risky to delete every value that falls beyond an outlier fence without checking whether it is a real observation?
3. Splitting the Data and Scaling Features
Once the data is clean and the prediction task is defined, it is divided into separate parts for learning and evaluation.
Features, target, and the train–test split
In the example, the goal is to predict penguin sex. The features are bill length, bill depth, flipper length, body mass, island, and species. The target is the encoded sex label.
The data is divided into a training set and a test set. The model learns patterns from the training set; the test set is held back to estimate how well the model works on examples it did not learn from. A common split is about 80% for training and 20% for testing, as in this example.
With 333 usable observations, this produces 266 training rows and 67 test rows. The exact row counts depend on the split and rounding.
A fixed random seed makes a random split repeatable. In the example, the seed is set to 42. This does not make the model inherently better; it allows the same random split to be generated again, which makes results easier to reproduce.
Why standardize numerical features?
The penguin measurements use different scales. Body mass is in the thousands, while some other measurements are in the tens or hundreds. A feature with much larger numeric values can dominate calculations in certain algorithms, even if it is not more informative.
Standardization rescales a feature using its mean and standard deviation:
z=σx−μ,where x is an observed value, μ is the feature’s mean, and σ is its standard deviation. After standardization, a value is expressed in terms of how far it is from the mean, measured in standard deviations. The transformed feature has mean near 0 and standard deviation near 1 when calculated using the same data used to fit the transformation.
Standardization does not guarantee that a feature becomes normally distributed, nor does it necessarily force every value into a fixed range. It changes the scale, not the underlying shape of the distribution.
To avoid data leakage, the scaler should be fitted using the training features only. The training data is transformed using that fitted scaler, and the test data is transformed using the same scaler. If the test data is included when estimating the mean and standard deviation, information from the evaluation set has influenced the preparation process.
The target labels are not scaled in this example. The scaler is applied to the numerical input features, while the target remains the category the model is learning to predict.
4. Three Classification Algorithms
The example compares three classifiers: k-nearest neighbors, a decision tree, and a support vector classifier. Each learns in a different way.
k-nearest neighbors
The k-nearest neighbors classifier predicts a new example’s category by looking at the categories of nearby training examples. With k=3, it considers the three closest examples and predicts based on their labels.
Because “nearby” is determined using distances between feature values, the scale of the features matters. Standardization can therefore be especially important for this method.
Decision tree
A decision tree makes predictions by applying a sequence of feature-based decisions. Each decision divides the data into smaller groups, and the path through the tree leads to a predicted class.
A maximum depth limits how many decision levels the tree can use. In the example, the tree’s maximum depth is 3. Limiting depth can make the model simpler, though the best depth depends on the data and must be evaluated.
Support vector classifier
A support vector classifier (SVC) seeks a decision boundary that separates classes. A linear kernel specifies a linear decision boundary. The example also enables probability estimates so that the model can provide scores useful for evaluating its ROC curve.
The settings supplied to a model are called parameters or, more precisely in this context, hyperparameters. Different algorithms have different settings. Trying reasonable values and evaluating their results is part of model development; changing settings should be guided by evaluation rather than by assumption.
Each model is fitted using the training features and training labels. It then predicts labels for the test features. Comparing those predictions with the test labels shows where the model succeeds and where it makes mistakes.
Think about it: Why should a model be evaluated on examples that were kept out of training rather than only on the examples it has already seen?
5. Understanding Classification Results
A single score rarely describes every kind of classification error. Evaluation metrics help show what the model gets right, what it misses, and which types of mistakes matter.
The confusion matrix
A confusion matrix compares actual labels with predicted labels. For binary classification, it tracks four outcomes:
- True positive (TP): the actual class is positive, and the model predicts positive.
- False negative (FN): the actual class is positive, but the model predicts negative.
- True negative (TN): the actual class is negative, and the model predicts negative.
- False positive (FP): the actual class is negative, but the model predicts positive.
The matrix’s rows and columns represent actual and predicted classes, although the exact arrangement depends on the software or plotting convention. The labels should always be checked before interpreting the cells. Correct predictions fall on the diagonal; misclassifications appear off the diagonal.
For the nearest-neighbors example, one reported matrix has the counts 32, 5, 2, and 28. Interpreted with positive as the first class, this means 32 actual positives were predicted positive, 5 actual positives were predicted negative, 2 actual negatives were predicted positive, and 28 actual negatives were predicted negative. The two off-diagonal counts represent the two kinds of errors.
A confusion matrix is useful because two models can have similar overall accuracy but different error patterns. In a medical screening task, for example, missing a true positive may be more serious than raising a false alarm. The importance of each type of error depends on the application.
Precision, recall, and accuracy
Precision asks: among the cases the model predicted as positive, how many were actually positive?
Precision=TP+FPTP.Recall, also called the true positive rate, asks: among all actual positives, how many did the model identify?
Recall=TP+FNTP.These measures answer different questions. A model can have high precision by making positive predictions only when it is confident, yet still miss many actual positives. That would give high precision but lower recall.
Accuracy is the proportion of all predictions that are correct:
Accuracy=TP+TN+FP+FNTP+TN.Accuracy is easy to understand, but it can be misleading when the classes are unevenly represented. A model that predicts only the more common class might appear accurate while failing to identify the less common one.
The F1 score combines precision and recall using their harmonic mean:
F1=2Precision+RecallPrecisionRecall.It is useful when both precision and recall matter, but it does not include true negatives in its formula.
The specificity measures how well the classifier identifies actual negatives:
Specificity=TN+FPTN.A classification report can provide precision, recall, F1 score, and support for each class. Support is the number of actual examples belonging to that class in the evaluated data. Reports may also include macro and weighted averages. A macro average gives each class equal weight; a weighted average accounts for how many examples belong to each class.
There is no single metric that is best for every task. The appropriate choice depends on the consequences of different errors and on the conventions of the research or application area.
ROC curves and area under the curve
A receiver operating characteristic (ROC) curve evaluates a binary classifier across different decision thresholds. It plots the true positive rate against the false positive rate:
TPR=TP+FNTP,FPR=FP+TNFP.Changing the threshold changes how readily a model predicts the positive class. A lower threshold may identify more actual positives, but it can also increase false positives. The ROC curve shows this trade-off across thresholds.
The area under the ROC curve, or AUC, summarizes how well the model distinguishes between the two classes across thresholds. An AUC of 0.5 corresponds to chance-level discrimination, while an AUC of 1 represents perfect discrimination. A curve that rises toward the upper-left area of the plot generally indicates better separation between the classes.
In the penguin example, the reported AUC values are approximately:
- 0.94 for k-nearest neighbors
- 0.93 for the decision tree
- 0.91 for the support vector classifier
By AUC, k-nearest neighbors performs best among these three models in this particular comparison. That does not prove it is best for every purpose: other metrics, error costs, or evaluation on different data might lead to a different choice.
Think about it: If missing a positive case is especially costly, which result deserves close attention: accuracy alone, or the model’s recall and false-negative count as well?
6. Binary and Multiclass Classification
The sex-prediction task has two possible labels, so it is a binary classification problem. A task that predicts among the three penguin species is a multiclass classification problem.
For a binary classifier, a confusion matrix has two classes on each axis, producing a 2×2 matrix. For a problem with three classes, such as the three species, it has three classes on each axis, producing a 3×3 matrix. Its diagonal entries count correct predictions for each class; off-diagonal entries show which classes are confused with one another.
The same general idea—comparing predicted and actual labels—applies to both cases, but the metrics and averaging methods must account for multiple classes. Precision, recall, and F1 can be computed for each class and then combined, for example, using macro or weighted averaging.
Comprehensive Review
Classification learns from labeled examples to predict categories for new observations. A sound workflow begins by defining the target and features, inspecting the data, addressing missing or invalid values, and encoding categorical variables. Exploratory plots and outlier checks help reveal the shape and quality of the data.
The data is then divided into training and test sets. Numerical features may be standardized so that differences in measurement scale do not distort algorithms that depend on distances or feature magnitudes. The scaler must be fitted on the training data and then applied to the test data to avoid leakage.
Different classifiers learn different kinds of patterns: nearest-neighbors uses nearby labeled examples, a decision tree applies branching rules, and a support vector classifier learns a separating boundary. Their predictions should be evaluated against held-out labels with metrics suited to the task. Confusion matrices show the kinds of mistakes; precision, recall, accuracy, and F1 summarize different aspects of performance; and ROC curves and AUC compare binary classifiers across thresholds.
The best model is therefore not simply the one with the highest score in isolation. It is the model whose performance, measured on appropriate data and with appropriate metrics, best fits the purpose of the classification task.

Ask anything
We've read this whole study set, so questions about it get the best answers.