Machine Learning-Classification: Core Concepts and Operations

1. Classification: Basic concepts of classification

The classification model learns a mapping between input features XX and discrete target variables yy:

y^=f(X;θ)\hat y=f(X;\theta)

Main differences from Regression:

  • Regression: Predict continuous values, such as house prices.
  • Classification: Predict discrete categories, such as whether a user churns.

Classification task type

TypemeaningExample
Binary ClassificationTwo categoriesSpam / Not Spam
Multiclass ClassificationMultiple categories, mutually exclusive categoriesCat / Dog / Bird
Multilabel ClassificationMulti-label, each sample can have multiple labelsNews belongs to both technology and economics

For binary classification, it is usually defined:

  • Positive Class: Positive type, usually recorded as 1.
  • Negative Class: negative class, usually recorded as 0.

For example, in fraud detection, the fraudulent transaction can be defined as Positive Class.

Predict and Predict Probability

Classification models often output predicted labels, and some models can also output predicted probabilities or decision scores.

y_pred = model.predict(X_test)

y_proba = model.predict_proba(X_test)

In the second classification:

positive_proba = y_proba[:, 1]

The category order of model.classes_ needs to be confirmed, and it cannot be assumed that the second column corresponds to the required positive category under any label encoding.

Predicted categories are different from predicted probabilities, and the classification threshold affects the final label and corresponding evaluation metrics.

2. Logistic Regression: Logistic regression

Logistic Regression, although it contains Regression, is actually one of the most commonly used linear classification models.

For binary classification, first calculate the linear function:

z=wTX+bz=w^TX+b

Then map the result to 0~1 through Sigmoid Function:

P(y=1∣X)=σ(z)=11+e−zP(y=1|X)=\sigma(z)=\frac{1}{1+e^{-z}}

Core principles

Logistic Regression essentially learns a linear decision boundary.

For example:

w1x1+w2x2+b=0w_1x_1+w_2x_2+b=0

When the predicted probability exceeds the classification threshold, the sample is predicted as a positive class.

Log Loss (also called Binary Cross-Entropy) is usually minimized during training:

L=−1n∑i[yilog⁡pi+(1−yi)log⁡(1−pi)]L=-\frac{1}{n}\sum_i \left[ y_i\log p_i+(1-y_i)\log(1-p_i) \right]

scikit-learn implementation

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

model = make_pipeline(
    StandardScaler(),
    LogisticRegression(
        C=1.0,
        max_iter=1000,
    ),
)

model.fit(X_train, y_train)

y_pred = model.predict(X_test)
y_proba = model.predict_proba(X_test)

Key hyperparameters

parametersfunction
CThe inverse of the regularization strength
l1_ratioThe ratio of L1 to L2 regularization for the corresponding version and Solver
solverParameter optimization algorithm
class_weightCategory weight
max_iterMaximum number of iterations

The smaller C, the stronger the regularization is generally, which is the opposite direction of alpha in Ridge, Lasso.

Logistic Regression is usually suitable for:

  • Create classification Baseline.
  • Tasks that require better explanations.
  • High-dimensional sparse features, such as text classification.
  • Approximately linearly separable data.

Its limitation is that it cannot directly learn complex nonlinear decision boundaries, but it can be extended by combining polynomial features and other methods.

Multiple categories

Logistic Regression also supports multiple categories.

In the case of multi-classification, you can use Softmax to calculate the predicted probability of each category:

P(y=k∣X)=ezk∑jezjP(y=k|X)= \frac{e^{z_k}}{\sum_j e^{z_j}}

The sum of the predicted probabilities for all classes is 1.

3. Naive Bayes: Naive Bayes

Naive Bayes is a probabilistic classification algorithm based on Bayes' theorem.

Core formula:

P(y∣X)=P(X∣y)P(y)P(X)P(y|X)=\frac{P(X|y)P(y)}{P(X)}

Among them:

  • P(y)P(y): Prior, prior probability.
  • P(X∣y)P(X|y): Likelihood, the likelihood of observing a feature given the class.
  • P(y∣X)P(y|X): Posterior, posterior probability.

Naive Assumption

The key assumptions of Naive Bayes are:

When a category label is given, each input feature is conditionally independent.

Therefore:

P(X∣y)=∏_j=1pP(xj∣y)P(X|y)=\prod\_{j=1}^{p}P(x_j|y)

This assumption is often not strictly true in real data, but the algorithm may still achieve good classification results.

Common Naive Bayes algorithm

algorithmApplicable data
GaussianNBContinuous features, approximately Gaussian distribution within categories
MultinomialNBNon-negative counting features, word frequency
BernoulliNBBinary features, whether words appear
ComplementNBCommonly used for imbalanced text classification

Gaussian Naive Bayes

from sklearn.naive_bayes import GaussianNB

model = GaussianNB()

model.fit(X_train, y_train)

y_pred = model.predict(X_test)

GaussianNB Assume that under each category, each continuous feature obeys Gaussian distribution.

Multinomial Naive Bayes

Often used in text classification:

from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import make_pipeline

model = make_pipeline(
    CountVectorizer(),
    MultinomialNB(alpha=1.0),
)

model.fit(texts_train, labels_train)

y_pred = model.predict(texts_test)

Among them:

  • CountVectorizer: Convert text into word frequency features.
  • alpha: Additive smoothing parameter to avoid zero probability problem.

Advantages and Disadvantages

Advantages:

  • Training speed is fast.
  • It is more friendly to high-dimensional sparse data.
  • Effective baselines can also be established when the amount of data is small.
  • It is widely used in text classification.

Limitations:

  • The conditional independence assumption may be too strong.
  • The correlation between different features is difficult to model directly.
  • The output probabilities are not necessarily well calibrated.

4. KNN:K-Nearest Neighbors

KNN (K nearest neighbor) is an instance- and distance-based classification algorithm.

Basic steps:

  1. Calculate the distance between the sample to be predicted and the training sample.
  2. Find the nearest K samples.
  3. Vote based on neighbor category.
  4. Output the final predicted category.

For example, when K=5, 4 of the latest 5 samples belong to the A class, then the A class is usually predicted.

distance measure

Common distances:

Euclidean Distance:

d(x,y)=∑i(xi−yi)2d(x,y)=\sqrt{\sum_i(x_i-y_i)^2}

Manhattan Distance:

d(x,y)=∑i∣xi−yi∣d(x,y)=\sum_i|x_i-y_i|

The distance metric directly affects the selection of neighbors.

scikit-learn implementation

from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

model = make_pipeline(
    StandardScaler(),
    KNeighborsClassifier(
        n_neighbors=5,
        weights="distance",
        metric="minkowski",
        p=2,
    ),
)

model.fit(X_train, y_train)

y_pred = model.predict(X_test)

Key hyperparameters

parametersfunction
n_neighborsNumber of neighbors K
weightsvoting weight
metricdistance measure
pMinkowski distance parameter
algorithmnearest neighbor search algorithm

weights:

  • uniform: Neighbors vote equally.
  • distance: Neighbors who are closer have higher weight.

K selection

  • K is too small: sensitive to noise and easy to overfit.
  • K is too large: the decision boundary is too smooth and may be underfitting.

Usually K is selected via Cross-validation.

Features of KNN

Advantages:

  • The principle is intuitive.
  • There is no need to assume linear decision boundaries.
  • Can handle more complex local classification relationships.

Limitations:

  • Neighboring sample search is required when predicting.
  • Feature scale has a large impact and usually requires standardization.
  • The ability to distinguish distances in high-dimensional space may decrease, that is, the curse of dimensionality (Curse of Dimensionality).
  • Prediction costs for large-scale data can be high.

fit() of KNN mainly saves and organizes training samples, and does not learn a set of linear coefficients like Logistic Regression.

5. SVM:Support Vector Machine

SVM (Support Vector Machine) distinguishes different categories by finding classification hyperplanes.

Maximum Margin

For a linearly separable binary classification problem, SVM hopes to find a hyperplane:

wTX+b=0w^TX+b=0

And maximize the Margin (margin) between different categories and the decision boundary.

The training sample closest to the decision boundary and the position of the decision boundary is called Support Vectors (support vector).

Soft Margin

Real data often cannot be completely linearly separated.

SVM allows some samples to violate the spacing requirement, and controls the penalty through parameter C.

  • C Larger: Pay more attention to classification errors or margin violations of training samples.
  • C is smaller: allows larger margin violations, stronger regularization.

Kernel Trick

For non-linear classification, you can use Kernel Function to compute similarities in the implicit feature space.

Common Kernel:

KernelFeatures
linearlinear decision boundary
polypolynomial kernel
rbfRadial basis kernel, common nonlinear choice
sigmoidSigmoid Kernel

RBF Kernel:

K(xi,xj)=exp⁡(−γ∥xi−xj∥2)K(x_i,x_j)=\exp(-\gamma\|x_i-x_j\|^2)

gamma controls the scope of influence of a single sample.

scikit-learn implementation

from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

model = make_pipeline(
    StandardScaler(),
    SVC(
        kernel="rbf",
        C=1.0,
        gamma="scale",
    ),
)

model.fit(X_train, y_train)

y_pred = model.predict(X_test)

Key hyperparameters

parametersfunction
CRegularization and margin violation penalties
kernelkernel function
gammaThe influence range of kernel functions such as RBF
class_weightCategory weight
probabilityWhether to additionally fit probability estimates

Note: SVC does not enable predict_proba() by default.

If you only need sorting indicators such as ROC-AUC, you can use:

scores = model.decision_function(X_test)

If probabilistic output is required, SVC(probability=True) can be used, but this will increase the training cost, and the probability estimation still requires attention to calibration quality.

Advantages and Disadvantages of SVM

Advantages:

  • Nonlinear problems can be handled via Kernel.
  • It performs well in some small and medium-sized, high-dimensional data sets.
  • Margin and regularization provide mechanisms to control model complexity.

Limitations:

  • Sensitive to feature scale.
  • Kernel SVM is expensive to train on large datasets.
  • Parameter adjustment may be complicated.
  • Compared with the simple linear model, the explanatory power is weaker.

If it is large-scale high-dimensional sparse data, LinearSVC usually deserves priority.

6. Decision Tree: Decision tree

Decision Tree is classified by recursively dividing the feature space.

For example:

Age >= 30?
├── Yes → Income >= 8000?
│         ├── Yes → Class A
│         └── No  → Class B
└── No  → Class B

The decision tree selects features and division conditions at each node to make the categories of child nodes as pure as possible.

Gini Impurity

Gini Impurity:

Gini=1−∑_k=1Kpk2Gini=1-\sum\_{k=1}^{K}p_k^2

Among them, pkp_k is the proportion of K class in the current node.

If all samples of a node belong to the same category:

Gini=0Gini=0

Indicates that the node is completely pure.

Entropy

Entropy is also a common splitting criterion:

H=−∑_k=1Kpklog⁡2pkH=-\sum\_{k=1}^{K}p_k\log_2p_k

The lower the entropy, the more concentrated the distribution of node categories.

scikit-learn implementation

from sklearn.tree import DecisionTreeClassifier

model = DecisionTreeClassifier(
    criterion="gini",
    max_depth=5,
    min_samples_leaf=5,
    random_state=42,
)

model.fit(X_train, y_train)

y_pred = model.predict(X_test)

Key hyperparameters

parametersfunction
criterionNode partitioning criteria
max_depthmaximum tree depth
min_samples_splitThe minimum number of samples for the node to continue splitting
min_samples_leafMinimum number of samples for leaf nodes
max_leaf_nodesMaximum number of leaf nodes
ccp_alphaPruning strength

Overfitting

If the decision tree is not restricted, it is easy to form an overly deep structure and overfit the training data.

Common control methods:

  • Limit max_depth.
  • Raise min_samples_leaf.
  • Limit max_leaf_nodes.
  • Use Cost Complexity Pruning.

Feature Importance

model.feature_importances_

Decision trees can output feature importance based on impurity reduction calculations.

However, this importance may be biased toward features with more values and does not represent causality.

Visual decision tree

from sklearn.tree import plot_tree
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(12, 7))

plot_tree(
    model,
    filled=True,
    feature_names=feature_names,
    ax=ax,
)

plt.show()

Advantages and Disadvantages

Advantages:

  • Intuitive and easy to explain.
  • No feature standardization is required.
  • Can express non-linear relationships and feature interactions.
  • Suitable for a variety of tabular data.

Limitations:

  • Easy to overfit.
  • May be sensitive to training data perturbations.
  • The predictive performance of a single tree is often inferior to that of a tuned ensemble tree model.

Random Forest and Gradient Boosting can be discussed in detail in the subsequent Ensemble Learning article.

7. Classification Metrics: Classification evaluation index

The evaluation of classification models is more dependent on specific business objectives than regression.

Especially for binary classification tasks, you cannot just focus on Accuracy.

Confusion Matrix: confusion matrix

Take fraud detection as an example:

Prediction NormalPrediction Fraud
Actual NormalTNFP
Actual FraudFNTP
  • TP (True Positive): real example.
  • TN (True Negative): True negative example.
  • FP (False Positive): False positives, false positives.
  • FN (False Negative): False negative examples, missed negatives.
from sklearn.metrics import confusion_matrix

cm = confusion_matrix(y_test, y_pred)

Accuracy: Accuracy

Accuracy=TP+TNTP+TN+FP+FNAccuracy=\frac{TP+TN}{TP+TN+FP+FN}

It is suitable for tasks with relatively balanced categories and similar error costs.

If fraud samples only account for 1%, the model can still get 99% Accuracy if all predictions are normal, so you cannot just look at this indicator.

Precision: accuracy rate

Precision=TPTP+FPPrecision=\frac{TP}{TP+FP}

The proportion of samples predicted to be positive class that actually belong to the positive class.

Suitable for tasks that focus on false positive cost.

For example, misjudgment will result in higher manual review or business processing costs.

Recall: recall rate

Recall=TPTP+FNRecall=\frac{TP}{TP+FN}

The proportion of successful identifications among all true positive classes.

Suitable for tasks that focus on missed reporting cost.

For example, fraud detection, risk screening.

Specificity: Specificity

Specificity=TNTN+FPSpecificity=\frac{TN}{TN+FP}

Measures the proportion of true negative classes that are correctly identified.

Its relationship to False Positive Rate:

FPR=1−SpecificityFPR=1-Specificity

F1 Score

F1 is the harmonic mean of Precision and Recall:

F1=2Precision⋅RecallPrecision+RecallF1=2\frac{Precision\cdot Recall}{Precision+Recall}

Suitable for scenarios where you want to consider Precision and Recall comprehensively.

But if the costs of false positives and false negatives are significantly different, F1 may not necessarily be the most reasonable optimization target.

F-beta Score

F-beta allows adjusting the weights of Precision and Recall based on business goals:

F_β=(1+β2)Precision⋅Recallβ2Precision+RecallF\_\beta=(1+\beta^2) \frac{Precision\cdot Recall}{\beta^2Precision+Recall}
  • β>1\beta>1: Pay more attention to Recall.
  • β<1\beta<1: Pay more attention to Precision.
  • β=1\beta=1:F1。

Commonly used Metrics API

from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score,
    fbeta_score,
    classification_report,
)

accuracy_score(y_test, y_pred)
precision_score(y_test, y_pred)
recall_score(y_test, y_pred)
f1_score(y_test, y_pred)

fbeta_score(y_test, y_pred, beta=2)

print(classification_report(y_test, y_pred))

The default positive label for the above two categories is 1. When using multiple categories, it is usually necessary to explicitly specify parameters such as average.

8. ROC-AUC and PR-AUC

Accuracy, Precision, Recall, and F1 all rely on specific classification results or thresholds.

ROC and PR Curve are used to analyze the performance of the model under different thresholds.

ROC Curve

ROC Curve:

  • X Axis:False Positive Rate。
  • Y Axis:True Positive Rate(Recall)。

ROC-AUC measures the model’s overall ability to distinguish between positive and negative samples.

from sklearn.metrics import roc_auc_score, roc_curve

auc = roc_auc_score(y_test, y_score)

fpr, tpr, thresholds = roc_curve(
    y_test,
    y_score,
)

Here y_score can be the positive class prediction probability or the appropriate decision score.

ROC-AUC does not require a pre-fixed classification threshold.

Precision-Recall Curve

PR Curve:

  • X Axis:Recall。
  • Y Axis:Precision。
from sklearn.metrics import (
    precision_recall_curve,
    average_precision_score,
)

precision, recall, thresholds = precision_recall_curve(
    y_test,
    y_score,
)

ap = average_precision_score(y_test, y_score)

average_precision_score() calculates Average Precision (AP), which is not PR-AUC obtained through trapezoidal integration, and the two values may be different.

ROC-AUC vs PR-AUC

indicatorFeatures
ROC-AUCMeasure the overall sorting ability of positive and negative categories
PR-AUC / APPrecision and Recall, which are more directly concerned with positive class prediction
F1Evaluate the Precision / Recall equilibrium at a specific threshold
AccuracyMeasure the overall proportion of correct classifications

For tasks with highly imbalanced categories, PR Curve and AP tend to be more analytically valuable.

9. Classification Threshold: Classification threshold

For binary classification, the model usually makes a classification based on probabilities or decision scores.

For example:

y_proba = model.predict_proba(X_test)[:, 1]

y_pred = (y_proba >= 0.5).astype(int)

The threshold does not necessarily have to be 0.5.

Effect of threshold changes

Typically:

  • Lower the threshold: predicting more positive classes, Recall tends to increase, and FP may increase at the same time.
  • Raising the threshold: predicting fewer positive classes, FP tends to decrease, while FN may increase.

But Precision is not guaranteed to be strictly monotonic as the threshold changes.

Select threshold

Thresholds should be chosen based on business costs or validation set results.

For example:

threshold = 0.3

y_pred_custom = (y_proba >= threshold).astype(int)

Note:

  • The test set should not be used repeatedly to pick the best threshold.
  • The probabilities output by the model are not necessarily well calibrated.
  • High ROC-AUC does not mean that the classification effect under the 0.5 threshold is necessarily good.

If the business requires reliable probability estimates, Probability Calibration can be further considered, such as CalibratedClassifierCV.

10. Multiclass Evaluation: Multi-class evaluation

In multi-classification problems, you need to pay attention to the averaging method.

Macro Average

Calculate the indicators for each category separately and then do a simple average.

Each category is equally weighted.

Suitable for scenarios where you want equal attention to each category.

Weighted Average

Weighted average based on the number of true samples in each category.

Categories with more samples have greater impact.

Micro Average

First summarize the TP, FP, FN of each category, and then calculate the overall indicator.

For ordinary single-label multi-classification, Micro Precision, Micro Recall, Micro F1 are all equal to Accuracy.

scikit-learn example

from sklearn.metrics import f1_score

f1_score(y_test, y_pred, average="macro")
f1_score(y_test, y_pred, average="weighted")
f1_score(y_test, y_pred, average="micro")
AverageFeatures
MacroEach category is equally important
WeightedWeighted by category sample size
MicroAggregate decision results across all categories

For class-imbalanced multi-classification tasks, it is recommended to look at Precision, Recall, F1 and the number of samples for each class simultaneously, rather than just the average.

11. Class Imbalance: Category imbalance

Assume that in the second category:

Normal: 99%
Fraud:   1%

Common processing methods:

Class Weight

Some algorithms support:

LogisticRegression(class_weight="balanced")
SVC(class_weight="balanced")
DecisionTreeClassifier(class_weight="balanced")

balanced typically adjusts class weights based on the inverse of the class frequency in the training data.

But not all classification algorithms provide the class_weight parameter. For example, the basic KNeighborsClassifier and GaussianNB do not have this parameter.

Resampling

  • Random Oversampling: Add minority class samples.
  • Random Undersampling: Reduce majority class samples.
  • SMOTE: Synthesize minority class samples based on neighboring samples.

Methods such as SMOTE typically use imbalanced-learn.

Resampling must be performed within the training set. For cross-validation, it should be performed within each training Fold to avoid data leakage.

Threshold Adjustment

Choose an appropriate threshold based on business costs.

Metric Selection

Prioritize attention:

  • Precision。
  • Recall。
  • F1 / F-beta。
  • PR-AUC / Average Precision。
  • Confusion Matrix。

Don't simply assume that resampling is necessarily better than class weighting, and don't just choose a model with Accuracy.

12. Cross-validation and model selection

It is generally recommended to use Stratified Split for classification models to keep the proportion of categories in each Fold as close as possible to the original data.

from sklearn.model_selection import StratifiedKFold, cross_val_score

cv = StratifiedKFold(
    n_splits=5,
    shuffle=True,
    random_state=42,
)

scores = cross_val_score(
    model,
    X_train,
    y_train,
    cv=cv,
    scoring="f1",
)

print(scores.mean())
print(scores.std())

Hyperparameter Tuning

For example, perform parameter search for SVM:

from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

pipeline = Pipeline([
    ("scaler", StandardScaler()),
    ("classifier", SVC()),
])

param_grid = {
    "classifier__C": [0.1, 1, 10],
    "classifier__gamma": ["scale", 0.01, 0.1],
    "classifier__kernel": ["rbf"],
}

search = GridSearchCV(
    pipeline,
    param_grid,
    scoring="f1",
    cv=5,
    n_jobs=-1,
)

search.fit(X_train, y_train)

print(search.best_params_)

Important reasons to use Pipeline are:

cross-validates each Fold to fit StandardScaler using only the training data of that Fold.

Otherwise Data Leakage is likely to occur.

For multiple records from the same user, time series data, etc., you should also use Group-based or Time-based Split instead of just relying on stratified random splitting.

13. Complete Example: Comparing Classification Algorithms

Below, we compare Logistic Regression, Naive Bayes, KNN, SVM, and Decision Tree using sample classification data for scikit-learn.

import pandas as pd

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier

from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score,
    roc_auc_score,
)

# 1. Load sample data
dataset = load_breast_cancer()

X = dataset.data
y = dataset.target

# 2. Divide training set and test set
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    stratify=y,
    random_state=42,
)

# 3. Define model
models = {
    "Logistic Regression": make_pipeline(
        StandardScaler(),
        LogisticRegression(max_iter=1000),
    ),

    "Naive Bayes": GaussianNB(),

    "KNN": make_pipeline(
        StandardScaler(),
        KNeighborsClassifier(n_neighbors=5),
    ),

    "SVM": make_pipeline(
        StandardScaler(),
        SVC(kernel="rbf", C=1.0),
    ),

    "Decision Tree": DecisionTreeClassifier(
        max_depth=5,
        random_state=42,
    ),
}

# 4. training and evaluation
results = []

for name, model in models.items():
    model.fit(X_train, y_train)

    y_pred = model.predict(X_test)

    # All these models are available decision_function
    # or at least one of predict_proba
    if hasattr(model, "decision_function"):
        y_score = model.decision_function(X_test)
    else:
        y_score = model.predict_proba(X_test)[:, 1]

    results.append({
        "Model": name,
        "Accuracy": accuracy_score(y_test, y_pred),
        "Precision": precision_score(y_test, y_pred),
        "Recall": recall_score(y_test, y_pred),
        "F1": f1_score(y_test, y_pred),
        "ROC-AUC": roc_auc_score(y_test, y_score),
    })

results_df = pd.DataFrame(results)

print(results_df.sort_values("F1", ascending=False))

The hyperparameters of different models here are just demonstration configurations.

Real tasks should:

  1. First divide the independent test set.
  2. Compare models using cross-validation on the training set.
  3. Select evaluation metrics based on your business.
  4. Search for hyperparameters and necessary classification thresholds.
  5. Finally, the final solution is evaluated on the test set.

Another detail to note: the labels 1 in this example dataset represent benign and 0 represent malignant. Therefore, the default two categories Precision and Recall evaluate label 1. If the actual task focus is on malignant identification, the positive class or conversion label should be specified explicitly.

14. How to choose a classification algorithm?

algorithmAdvantageslimitationsCommon scenarios
Logistic RegressionSimple, fast and explainablelinear boundaryBaseline model, sparse features
Naive BayesFast and suitable for high-dimensional sparse dataconditional independence assumptionText classification
KNNIntuitive and supports complex local boundariesHigh-dimensional and large-scale predictions are slowerSmall-scale, meaningful distance data
SVMMargin, Kernel, nonlinear capabilityParameter adjustment and large-scale calculation costsSmall and medium-sized complex classification
Decision TreeClear rules and no need for standardizationEasy to overfit and unstableTable data, rule explanation

Recommended modeling process:

Dataset
   ↓
Logistic Regression Baseline
   ↓
Naive Bayes / KNN / SVM / Decision Tree
   ↓
Cross-validation
   ↓
Hyperparameter Tuning
   ↓
Threshold Selection
   ↓
Confusion Matrix / Metrics
   ↓
Final Test Evaluation

If it is tabular data, integrated models such as Random Forest, XGBoost, LightGBM should also be considered later.

15. FAQ

1. Does classification necessarily need to be standardized?

uncertain.

  • Logistic Regression: It is generally recommended to normalize numerical features.
  • KNN: Usually highly desired due to distance dependence.
  • SVM: Standardization is generally recommended.
  • GaussianNB: Not required.
  • Decision Tree: Usually not required.

2. Does predict_proba mean the probability is accurate?

uncertain.

There may be a Calibration problem with the probability output.

For example, for a sample set with a predicted probability of 0.8, the true positive class proportion may not be close to 80%.

This can be further evaluated by Reliability Diagram, Brier Score and probabilistic calibration methods.

3. The Accuracy of the model is very high, why is it still not good?

There may be:

  • Category imbalance.
  • Some key categories Recall are low.
  • Training and test data leakage.
  • Test data is not representative.
  • In business, the cost difference between FP and FN is huge.

4. What is the relationship between the decision tree and Random Forest?

Decision Tree is a single tree.

Random Forest combines multiple random decision trees through mechanisms such as Bagging to improve prediction stability and generalization capabilities.

The detailed principles can be placed in the Ensemble Learning article.


Summary

Knowledge pointsimportance
Binary / Multiclass / Multilabelcore
Logistic Regression / Sigmoidcore
Naive Bayes / Conditional Independenceimportant
KNN / Distance / Kimportant
SVM / Margin / Kernelcore
Decision Tree / Gini / Entropycore
Confusion Matrixcore
Precision / Recall / F1core
ROC-AUC / PR-AUC / APcore
Classification Thresholdcore
Macro / Micro / Weightedimportant
Class Imbalancecore
Cross-validation / Data Leakagecore
Probability Calibrationimportant

The five most important concepts in classification learning:

  1. Decision Boundary: Different algorithms construct classification boundaries through linear functions, distances, kernel functions or tree rules.
  2. Probability / Decision Score: The classification score of the model is not the same concept as the final classification label.
  3. Precision–Recall Tradeoff: Balancing false positives and false negatives through thresholds and business goals.
  4. Class Imbalance: Category proportions may significantly affect model evaluation, you cannot just look at Accuracy.
  5. Generalization: The model should be evaluated through reasonable data splitting, cross-validation and independent test sets, rather than focusing only on training set performance.

Reference documentation

Back to top