1. Home
  2. Explore
  3. Computer Science
  4. Classical Machine Learning Classification

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Classical Machine Learning Classification

Classification in Classical Machine Learning

What classification does

Classification is a supervised machine-learning task in which a model learns from examples with known labels and predicts a category for new examples. For instance, a model can use measurements of a penguin to predict whether it is male or female.

This differs from regression, which predicts a numerical value rather than a category. In both tasks, the model learns patterns from labeled training data and is evaluated on data it has not used for training.

A classification task can have:

  • Two classes, such as male and female. This is binary classification.

  • More than two classes, such as predicting one of three penguin species. This is multiclass classification.


Classification workflow

A typical classification process follows these steps:

  1. Prepare the data: inspect it, handle missing or invalid values, and convert features into forms the model can use.

  2. Separate features and target: the features are the input variables; the target is the category to predict.

  3. Split the data: use one portion to train the model and another to test it.

  4. Transform the features: for example, standardize numerical measurements when appropriate.

  5. Train classifiers: fit one or more algorithms to the training data.

  6. Evaluate predictions: compare predicted labels with known labels using metrics suited to the problem.

  7. Select a model: choose based on appropriate evaluation results and the needs of the application.

A common split uses about 80% of the data for training and 20% for testing. The training set teaches the model; the test set estimates how well it performs on unseen examples. The test set should not be used to fit the model or its preprocessing transformations.


Example data: penguins

The Palmer Penguins dataset contains measurements and categorical information for three penguin species found on Antarctic islands. The dataset includes:

  • Species

  • Island

  • Culmen length

  • Culmen depth

  • Flipper length

  • Body mass

  • Sex

In the example, the goal is to predict sex using the other listed variables. Species and island are used as features, along with the physical measurements.


Preparing and cleaning data

Inspecting the dataset

A dataset should be inspected before modeling to understand its dimensions, column types, and completeness. In pandas, an information summary can show the number of rows, columns, and non-missing values in each column.

The original dataset has 344 rows. Some measurement and sex fields are missing, so the number of available values varies across columns.

Handling missing and invalid values

Missing values can prevent some models from being trained directly. One simple option is to remove rows with missing entries. In the example, dropping rows with missing values reduces the dataset from 344 rows to 334 rows.

The sex column also contains one invalid entry represented by a dot. Since it is not a valid category and there is no additional information to resolve it, that row is removed. The cleaned dataset then contains 333 rows.

Dropping incomplete rows is straightforward, but it is not always the best choice: if many rows are incomplete, removal may discard too much useful data. Depending on the problem, missing values may instead be imputed or handled with methods designed for incomplete data.

Checking category counts

Category counts help reveal how classes and groups are represented. After removing rows with missing values, the example has:

  • Species: Adelie, 146; Gentoo, 120; Chinstrap, 68.

  • Island: Biscoe, 164; Dream, 123; Torgersen, 47.

  • Sex: male, 168; female, 165; plus one invalid entry before it is removed.

Because these groups do not all have equal counts, the dataset is not perfectly balanced. Class balance matters when interpreting evaluation results: a model can appear strong on a dataset dominated by one class while performing poorly on a less common class.


Categorical encoding

Many machine-learning algorithms require numerical input. Encoding converts categorical values, such as species names or island names, into numerical representations.

A label encoder assigns each category an integer. For example:

  • Three species receive codes such as 000, 111, and 222.

  • Three islands receive codes such as 000, 111, and 222.

  • Two sex categories receive codes such as 000 and 111.

The particular integer assigned to a category is an encoding choice, not a meaningful ranking of the categories.

For nominal features such as species or island, integer labels can inadvertently suggest an order or distance that does not exist. One-hot encoding is an alternative: it represents categories with separate indicator columns containing zeros and ones. Label encoding is commonly appropriate for class labels, but one-hot encoding is often more suitable for unordered categorical input features.


Outliers and exploratory visualization

Identifying outliers with the interquartile range

An outlier is a value that lies unusually far from the main body of a distribution. It may reflect a data-entry or measurement error, but it may also be a valid observation. Its cause should be investigated before it is removed.

The interquartile range, or IQR, measures the spread of the middle half of the data:

IQR=Q3−Q1\text{IQR} = Q_3 - Q_1IQR=Q3​−Q1​

Here, Q1Q_1Q1​ is the first quartile and Q3Q_3Q3​ is the third quartile. The inner fences are:

Lower inner fence=Q1−1.5 IQR\text{Lower inner fence} = Q_1 - 1.5\,\text{IQR}Lower inner fence=Q1​−1.5IQR
Upper inner fence=Q3+1.5 IQR\text{Upper inner fence} = Q_3 + 1.5\,\text{IQR}Upper inner fence=Q3​+1.5IQR

Values outside these inner fences are commonly flagged as potential outliers. More distant outer fences can be defined using three times the IQR:

Lower outer fence=Q1−3 IQR\text{Lower outer fence} = Q_1 - 3\,\text{IQR}Lower outer fence=Q1​−3IQR
Upper outer fence=Q3+3 IQR\text{Upper outer fence} = Q_3 + 3\,\text{IQR}Upper outer fence=Q3​+3IQR

These fences are rules for flagging unusual values, not proof that a value is erroneous. In the example, the measured culmen length, culmen depth, flipper length, and body mass show no outliers under the method used.

Visualizing distributions

Histograms show how numerical values are distributed across bins. A kernel density estimate (KDE) overlays a smoothed estimate of the distribution, making its general shape easier to see.

The measurements can be plotted individually and then compared across species. Such visualizations help reveal differences in typical values and spread among species. Bar plots can also show and compare measurement summaries by category, depending on how the plot is constructed.

Visual inspection complements numerical checks: it can expose patterns, unusual values, or group differences that may not be obvious from a table alone.


Defining features and target

For the example sex-prediction task:

  • Features (XXX): culmen length, culmen depth, flipper length, body mass, island, and species.

  • Target (yyy): encoded sex.

The model learns a relationship between the feature values and the target labels. Once trained, it can predict the likely sex for a new penguin described by those features.

The target must be kept separate from the input features. Including the answer itself among the features would allow the model to access information it is supposed to predict.


Splitting and scaling the data

Train–test split

The cleaned data has 333 rows. With an 80/20 split, the example uses:

  • Training set: 266 rows and six feature columns.

  • Test set: 67 rows and six feature columns.

The corresponding target labels are divided in the same way. A fixed random seed, such as 42, makes a randomized split reproducible: repeated runs can use the same partition rather than producing a new one each time.

Standardization

The numerical features have different units and scales. For example, body mass is measured in the thousands, while other measurements are much smaller. Standardization rescales each feature using its training-set mean and standard deviation:

z=x−μσz = \frac{x - \mu}{\sigma}z=σx−μ​

After standardization, a feature has mean approximately 000 and standard deviation approximately 111 on the data used to fit the transformation. This can help algorithms that are sensitive to feature scale, particularly distance-based methods such as kkk-nearest neighbors.

Standardization does not guarantee that a feature follows a Gaussian distribution. It changes the feature’s location and scale; it does not generally change the shape of its distribution.

To avoid data leakage, the scaler should be fitted using the training features only. The fitted training transformation is then applied to both the training features and the test features. The test set must not influence the estimated means or standard deviations.

The target labels are not standardized: they represent categories, not continuous measurements.


Classifiers used in the example

Three scikit-learn classifiers are compared. Different algorithms make predictions in different ways, so their performance should be evaluated rather than assumed.

kkk-nearest neighbors

The kkk-nearest neighbors classifier (KNN) predicts a new example’s class based on the classes of nearby training examples in feature space. The example uses k=3k=3k=3 neighbors.

Because KNN relies on distances between examples, features with large numerical scales can dominate those distances. Standardization is therefore especially important for this method.

Decision tree

A decision tree classifier makes predictions through a sequence of feature-based decisions. Its maximum depth limits how many levels of decisions the tree can make. The example uses a maximum depth of 333.

Limiting tree depth constrains model complexity, which can reduce the risk of fitting the training data too closely, though the most suitable depth depends on the problem.

Support vector classifier

A support vector classifier (SVC) seeks a decision boundary that separates classes. The example uses a linear kernel, which produces a linear decision boundary in the transformed feature space. SVC has parameters that can be adjusted, so model settings should be selected deliberately rather than treated as universally optimal.


Predictions and evaluation

After fitting a classifier on the scaled training features and training labels, the model predicts labels for the scaled test features. These predictions are compared with the actual test labels. The differences indicate misclassifications.

A single list of predictions can show individual errors, but summary metrics are more useful for assessing overall performance.


Confusion matrix

A confusion matrix compares actual classes with predicted classes. For binary classification, it contains four outcomes:

  • True positive (TP): an actual positive example predicted as positive.

  • False negative (FN): an actual positive example predicted as negative.

  • False positive (FP): an actual negative example predicted as positive.

  • True negative (TN): an actual negative example predicted as negative.

A confusion matrix is organized by actual and predicted class; which one appears on rows or columns depends on the display convention. Its diagonal entries represent correct predictions, and its off-diagonal entries represent errors. The labels and orientation must be checked before interpreting individual cells.

The example’s test set has 67 observations. The KNN matrix is described by counts of 32 and 28 correct predictions and 5 and 2 misclassifications. The decision tree and support vector classifier produce different distributions of correct and incorrect predictions. A heatmap can display the matrix more clearly than a plain array of numbers.

Confusion matrices are useful because they distinguish error types. In some applications, a false negative is more costly than a false positive; in others, the reverse is true.


Metrics derived from the confusion matrix

Precision

Precision asks: among the examples predicted positive, how many were actually positive?

Precision=TPTP+FP\text{Precision} = \frac{TP}{TP + FP}Precision=TP+FPTP​

High precision means that positive predictions are less often false alarms.

Recall

Recall, also called sensitivity or the true positive rate, asks: among all actual positive examples, how many were correctly identified?

Recall=TPTP+FN\text{Recall} = \frac{TP}{TP + FN}Recall=TP+FNTP​

High recall means that fewer actual positives are missed. Precision and recall measure different aspects of performance, so one can be high while the other is lower.

F1 score

The F1 score combines precision and recall using their harmonic mean:

F1=2⋅Precision⋅RecallPrecision+RecallF_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}} {\text{Precision} + \text{Recall}}F1​=2⋅Precision+RecallPrecision⋅Recall​

It is useful when both precision and recall matter. It can be low when either measure is low.

Accuracy

Accuracy is the fraction of all predictions that are correct:

Accuracy=TP+TNTP+TN+FP+FN\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}Accuracy=TP+TN+FP+FNTP+TN​

Accuracy is easy to interpret, but it can be misleading when classes are imbalanced. For instance, predicting only the majority class can yield high accuracy even when the model fails on the minority class.

Specificity and other measures

Specificity measures how often actual negatives are correctly identified:

Specificity=TNTN+FP\text{Specificity} = \frac{TN}{TN + FP}Specificity=TN+FPTN​

Other classification measures include the Jaccard index and rates related to false positives. The most informative metrics depend on the application and on the relative costs of different errors.

Classification reports and averages

A classification report can summarize precision, recall, F1 score, and support for each class. Support is the number of actual test examples belonging to that class.

For multiple classes, results can be combined using different averages:

  • Macro average: computes the metric separately for each class and averages the class results equally.

  • Weighted average: averages class results while weighting each class by its support.

These averaging methods can give different summaries, especially when the classes have unequal numbers of examples. In the example, the KNN model has an accuracy of about 0.900.900.90 on the test set; this result is meaningful only in the context of the test data and the other metrics.


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:

True positive rate=TPTP+FN\text{True positive rate} = \frac{TP}{TP + FN}True positive rate=TP+FNTP​
False positive rate=FPFP+TN\text{False positive rate} = \frac{FP}{FP + TN}False positive rate=FP+TNFP​

The ROC curve shows the trade-off between identifying actual positives and incorrectly labeling negatives as positive. A curve closer to the upper-left corner generally indicates stronger separation between classes.

The area under the ROC curve (AUC) summarizes the curve:

  • An AUC of 111 represents perfect class separation.

  • An AUC of 0.50.50.5 is the level expected from random ranking.

  • Larger AUC values generally indicate better separation for the evaluated task.

A ROC curve is normally calculated from a classifier’s probability estimates or decision scores so that performance can be assessed across thresholds. It is not usually constructed from a single set of hard class predictions alone.

In the example, the reported AUC values are:

  • KNN: 0.940.940.94

  • Decision tree: 0.930.930.93

  • Support vector classifier: 0.910.910.91

By AUC, KNN is the strongest of the three models tested. This does not establish that KNN is always best; the result is specific to the chosen data, split, features, model settings, and evaluation measure.


Binary and multiclass classification

Predicting sex in the example is a binary classification problem. Predicting species would instead involve three classes. A multiclass confusion matrix has one row and one column for each class, giving a 3×33 \times 33×3 matrix for three species.

The evaluation method should match the task. For multiclass classification, class-specific precision, recall, and F1 scores can be reported, along with an appropriate averaging method. ROC analysis can also be extended to multiclass settings, but it requires a strategy for handling multiple classes.


Choosing and improving a model

Model selection should consider more than one number. Useful comparisons include:

  • Whether the model makes errors that are acceptable for the application.

  • Class-specific precision and recall.

  • The F1 score, accuracy, and other relevant metrics.

  • ROC curves and AUC for binary classification when ranking performance matters.

Different research fields and applications prioritize different metrics. A model selected by the highest AUC may not be the best choice if another model better controls a particularly costly error type. Model parameters can also be tuned, but choices should be evaluated with data that has not been used to fit the model.


Dimensionality reduction

Dimensionality reduction aims to simplify a problem with many features by representing the data using fewer dimensions. It can help answer whether all available variables are useful and whether the data can be represented in a smaller feature space.

For example, a penguin dataset may use several dimensions corresponding to physical measurements and categorical features. A dimensionality-reduction method might seek a simpler representation, such as two dimensions, while retaining important structure in the data.

This generally involves transforming the original feature space into a lower-dimensional one, often using ideas from linear algebra. The resulting dimensions may be combinations of original variables rather than individual measurements. A reduced representation can make data easier to explore or use, but the retained dimensions must still be appropriate for the task.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent