Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Classification metrics

Classification metrics

In machine learning, training a classification model is only the first step.

Just as a doctor cannot judge a patient's condition by feeling alone, we also need a set of scientificphysical examination indicatorsto assess the health of a model.

These metrics areClassification metrics, which tell us how accurate the model's predictions are, where it does well, and where it still falls short. This article will systematically study these crucial evaluation tools.


Why do we need classification metrics?

A model that "looks accurate" does not necessarily mean it is useful; we need to quantify its performance from multiple perspectives.

Imagine you train a model to identify whether an email is spam. The model makes predictions for 100 emails, and you might ask:

If we judge only by "how many were correct," it is like evaluating a student solely by their total exam score, which overlooks a lot of important information.

Different business scenarios focus on completely different things:

Business scenario Most feared outcome Priority goal Can be sacrificed to some extent
Disease diagnosis Missing a patient (FN) High recall Some precision
Spam Filtering Deleting important emails by mistake (FP) High precision Some recall

Therefore, we need a whole set of metrics to comprehensively evaluate model performance from different perspectives.


Core concept: The confusion matrix

Almost all classification metrics originate from a powerful tool — Confusion matrix(Confusion Matrix), which is a "panoramic map" for understanding model prediction results.

What is a confusion matrix

It is a table that shows all four possible cases between the model's predicted results and the true labels.

Example

An example of a confusion matrix (taking the binary classification "spam / not spam" as an example)

from

sklearn.

metrics

import

confusion_matrix

1 represents spam (such as promotional emails like "RUNOOB Limited Time Offer"), and 0 represents normal email

y_true

=

[

1

,

0

,

1

,

1

,

0

,

0

,

1

,

0

,

0

,

1

]

 

Ground-truth labels

y_pred

=

[

1

,

0

,

0

,

1

,

0

,

0

,

1

,

1

,

0

,

1

]

 

The model's predicted results

Compute the confusion matrix

In the returned matrix: rows represent the true classes, and columns represent the predicted classes

cm

=

confusion_matrix

(

y_true

,

y_pred

)

print

(

"Confusion matrix:"

)

print

(

cm

)



Confusion matrix:

[[4 1]

 [1 4]]

The four numbers in the matrix correspond to the four cases. To understand them more intuitively, let's visualize it:

Predicted: Spam

Predicted: Normal email

Actual

Spam

4

TP True Positive

Correctly identified spam

1

FN False Negative

Missed spam (Type II Error)

Actual

Normal email

1

FP False Positive

Misclassified normal email (Type I Error)

4

TN True Negative

Correctly allowed normal email

The diagonal (TP and TN) are the correctly predicted samples, while the off-diagonal (FP and FN) are the incorrectly predicted samples.

Let's break down these four core terms:

Term Shorthands Meaning Explanation in the spam email example
True Positive TP The model predictspositive, and the truth is alsopositive。 Correctly identified by the model asSpam。
False Positive FP The model predictspositive, but the truth isnegative。 ModelMisclassified asspamNormal email(Type I Error)。
True Negative TN The model predictsnegative, and the truth is alsonegative。 Correctly identified by the model asNormal email。
False Negative FN The model predictsnegative, but the truth ispositive。 ModelMissed'sSpam(Type II Error)。

Memory tip:True / FalseLooks atwhether the prediction is correct,Positive / NegativeLooks atThe model's predicted results。


Detailed explanation of core classification metrics

With the confusion matrix, all evaluation metrics have a unified computational foundation. Below, we introduce the four most commonly used metrics one by one.

Accuracy - The most intuitive metric

Accuracy(Accuracy) measures the proportion of correctly predicted samples out of all samples.

Example

from

sklearn.

metrics

import

accuracy_score

accuracy

=

accuracy_score

(

y_true

,

y_pred

)

print

(

f

"Accuracy: {accuracy:.2f}"

)



准确率: 0.80

Advantages: Very intuitive and easy to understand.

Common pitfalls:Accuracy can be severely distorted when data is imbalanced. If 99% of emails are normal, a "dumb model" that predicts every email as normal can still achieve 99% accuracy, but it won't catch a single spam email.

Precision - The "better to have none than too many" metric

Precision(Precision) focuses on how many of thepositive casespredicted by the model are truly positive, measuring the precision of the predictionsReliability。

The question it answers: Among the emails we predicted as spam, how many are truly spam?

High precision means: When the model says "this is spam," it is highly trustworthy.

Example

from

sklearn.

metrics

import

precision_score

precision

=

precision_score

(

y_true

,

y_pred

)

print

(

f

"Precision: {precision:.2f}"

)



精确率: 0.80

Recall - The "better to over-kill" metric

Recall(Recall) focuses on how many of all the truepositive casescases are found by the model, measuring the model's ability to discover positive casesCapability。

The question it answers: Among all the truly spam emails, how many did we find?

High recall means: The model rarely misses genuine spam emails.

Example

from

sklearn.

metrics

import

recall_score

recall

=

recall_score

(

y_true

,

y_pred

)

print

(

f

"Recall: {recall:.2f}"

)



召回率: 0.80

F1 Score - The harmonic mean of precision and recall

Precision and recall are usually contradictory; improving one often lowers the other.

F1 scoreis their harmonic mean, aiming to find a balance point.

Characteristics of the harmonic mean: It tends to penalize extreme values more; the F1 score is high only when both precision and recall are high.

Example

from

sklearn.

metrics

import

f1_score

f1

=

f1_score

(

y_true

,

y_pred

)

print

(

f

"F1 score: {f1:.2f}"

)



F1分数: 0.80

Metric comparison and selection guide

The four metrics each have their own focus; choosing the wrong metric can make the model's optimization direction run counter to business goals:

Pointer Formula Focus Example applicable scenarios
Accuracy (TP+TN)/Total Overall prediction accuracy Scenarios with balanced classes and similar costs for FP and FN.
Precision TP/(TP+FP) Predicted positiveaccuracy of samples High FP cost: Such as spam filtering (fear of deleting important emails by mistake) and recommendation systems (fear of recommending poor-quality products).
Recall TP/(TP+FN) Truly positiveproportion of samples found High FN cost: Such as disease screening (fear of missed diagnosis) and fraud detection (fear of missing fraudulent transactions).
F1 score 2PR/(P+R) Balance between precision and recall Scenarios requiring comprehensive consideration with no clear preference; better than accuracy when classes are imbalanced.

Advanced metrics: ROC curve and AUC

When the model's prediction is a probability value (for example, the probability that an email is spam is 0.8), we need to set athreshold(such as 0.5) to decide the final classification.

The ROC curve helps us evaluate the overall performance of the model at different thresholds.

True Positive Rate and False Positive Rate

The two axes of the ROC curve are formed by these two metrics:

ROC curve

The ROC curve uses FPR as the horizontal axis,TPR as the vertical axis, and each point on the curve corresponds to a specific classification threshold.

The figure below plots the ROC curve corresponding to the sample data in this article:

The model ranks all 3 genuine spam emails at the very top, the curve hugs the upper-left corner, and the shaded area is the area under the ROC curve (AUC = 1.00).

AUC value

AUC (Area Under Curve) is the area under the ROC curve, with values ranging from 0 to 1:

AUC value Meaning
AUC = 1 Perfect model.
0.5 < AUC < 1 The model has some predictive ability; the larger the value, the better.
AUC = 0.5 The model has no discriminative ability, equivalent to random guessing.
AUC < 0.5 The model is worse than random guessing, usually meaning the prediction direction is reversed.

The advantage of AUC is that itis insensitive to class imbalance, and it evaluates the model's overall ranking ability (the ability to rank positive samples ahead of negative samples).

Example

from

sklearn.

metrics

import

roc_curve

,

auc

Suppose we have some prediction probabilities (1 represents spam, 0 represents normal email)

y_true

=

[

1

,

0

,

1

,

0

,

1

]

y_scores

=

[

0.9

,

0.4

,

0.6

,

0.3

,

0.8

]

 

The probability that the model predicts as positive

Calculate FPR and TPR at different thresholds

fpr

,

tpr

,

thresholds

=

roc_curve

(

y_true

,

y_scores

)

AUC is the area under the ROC curve

roc_auc

=

auc

(

fpr

,

tpr

)

print

(

f

"AUC value: {roc_auc:.2f}"

)

Plot the ROC curve (optional, requires matplotlib)

import

matplotlib.

pyplot

as

plt

plt.

figure

(

)

plt.

plot

(

fpr

,

tpr

,

color

=

'darkorange'

,

lw

=

2

,

label

=

f

'ROC curve (area = {roc_auc:.2f})'

)

plt.

plot

(

[

0

,

1

]

,

[

0

,

1

]

,

color

=

'navy'

,

lw

=

2

,

linestyle

=

'--'

,

label

=

'Random Guess'

)

plt.

xlim

(

[

0.0

,

1.0

]

)

plt.

ylim

(

[

0.0

,

1.05

]

)

plt.

xlabel

(

'False Positive Rate'

)

plt.

ylabel

(

'True Positive Rate'

)

plt.

title

(

'Receiver Operating Characteristic (ROC) Curve'

)

plt.

legend

(

loc

=

"lower right"

)

plt.

show

(

)

Output:



AUC 值: 1.00


Metrics for multi-class problems

When there are more than two classes (such as recognizing cats, dogs, and rabbits), the above metrics can be extended to multi-class problems through "averaging."

Averaging method Calculation method Feature
Macro average(macro) First calculate the metric for each class (such as precision), then take the arithmetic mean across all classes. Treats each class equally, so the performance of small classes significantly affects the result.
Micro average(micro) First aggregate TP, FP, etc. across all classes, then use the aggregated values to compute a global metric. Treats each sample equally, so it is more influenced by large classes.

In Scikit-learn, you can use average parameter:

Example

from

sklearn.

metrics

import

precision_score

Three-class example: 0 = cat, 1 = dog, 2 = rabbit

y_true

=

[

0

,

1

,

2

,

0

,

1

,

2

,

0

,

1

,

2

]

 

Ground-truth labels

y_pred

=

[

0

,

2

,

2

,

0

,

1

,

1

,

0

,

0

,

2

]

 

The model's predicted results

precision_macro

=

precision_score

(

y_true

,

y_pred

,

average

=

'macro'

)

 

Macro average: calculate each class first, then take the average

precision_micro

=

precision_score

(

y_true

,

y_pred

,

average

=

'micro'

)

 

Micro average: aggregate TP/FP first, then compute the global metric

print

(

f

"Macro-averaged precision: {precision_macro:.2f}"

)

print

(

f

"Micro-averaged precision: {precision_micro:.2f}"

)



宏平均精确率: 0.64

微平均精确率: 0.67

The macro average (0.64) is lower than the micro average (0.67), indicating that the model performs worse on classes with fewer samples — this is exactly the manifestation of macro averaging being more sensitive to classes.


Practical exercise: Comprehensively evaluating a classification model

Now, let's use the famous Iris dataset to fully evaluate a classification model.

Example

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

linear_model

import

LogisticRegression

from

sklearn.

metrics

import

classification_report

,

confusion_matrix

,

accuracy_score

,

roc_auc_score

1. Load the data

iris

=

load_iris

(

)

X

=

iris.

data

y

=

iris.

target

target_names

=

iris.

target_names

2. Split into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

3. Train a simple logistic regression model

model

=

LogisticRegression

(

max_iter

=

200

)

model.

fit

(

X_train

,

y_train

)

4. Make predictions on the test set

y_pred

=

model.

predict

(

X_test

)

y_pred_proba

=

model.

predict_proba

(

X_test

)

 

Obtain prediction probabilities for AUC

5. Calculate and print the various metrics

print

(

"=== Confusion matrix ==="

)

The confusion matrix for multi-class problems is N x N

print

(

confusion_matrix

(

y_test

,

y_pred

)

)

print

(

"\n=== Classification report (including precision, recall, F1) ==="

)

classification_report is a very convenient function that outputs multiple metrics at once

print

(

classification_report

(

y_test

,

y_pred

,

target_names

=

target_names

)

)

print

(

f

"\n=== Accuracy ==="

)

print

(

f

"{accuracy_score(y_test, y_pred):.4f}"

)

6. AUC for multi-class problems, usually computed as the "one-vs-rest" AUC of each class against the others, then averaged

Note: roc_auc_score requires specifying multi_class='ovr' (One-vs-Rest) for multi-class problems

try

:

    auc_ovr

=

roc_auc_score

(

y_test

,

y_pred_proba

,

multi_class

=

'ovr'

,

average

=

'macro'

)

   

print

(

f

"\n=== Macro-averaged AUC (OvR) ==="

)

   

print

(

f

"{auc_ovr:.4f}"

)

except

Exception

as

e:

   

print

(

f

"\nError calculating AUC (possibly some classes did not appear in the test set): {e}"

)



=== 混淆矩阵 ===

[[19  0  0]

 [ 0 13  0]

 [ 0  0 13]]



=== 分类报告(包含精确率、召回率、F1)===

              precision    recall  f1-score   support



      setosa       1.00      1.00      1.00        19

  versicolor       1.00      1.00      1.00        13

   virginica       1.00      1.00      1.00        13



    accuracy                           1.00        45

   macro avg       1.00      1.00      1.00        45

weighted avg       1.00      1.00      1.00        45





=== 准确率 ===

1.0000



=== 宏平均 AUC (OvR) ===

1.0000

Run this code, and you will see a complete model evaluation report.

Try modifying the model parameters or switching to a different model (such as sklearn.tree.DecisionTreeClassifier), and observe how these metrics change.


Notes and common pitfalls

Finally, let's go over a few pitfalls that beginners are most likely to stumble into:

Common misconception Correct approach
Looking only at accuracy when classes are imbalanced Also pay attention to F1 scoreor AUC, which are more robust to imbalanced data.
Evaluating a model's overall ability using precision and recall at a single threshold combined with ROC curve and AUC, to evaluate the model's ranking ability across all thresholds.
Directly calling scoring functions when the positive class label is not 1 Pass pos_label explicitly specify the positive class label via the parameter to avoid computing in the wrong direction.