Balance precision and recall for the positive class
Binary classification
Scikit-Learn · Function
Compute the F1 score, the harmonic mean of precision and recall. It ranges from 0 to 1 and supports binary, multiclass, and multilabel classification through averaging options.
The function compares true and predicted classification labels, counts the resulting true positives, false positives, and false negatives, and combines precision and recall through their harmonic mean. With multiclass or multilabel data, the average option controls whether it returns one class-specific score or an aggregate.
sklearn.metrics.f1_score(y_true, y_pred, *, labels=None, pos_label=1, average='binary', sample_weight=None, zero_division='warn')| Name | Type | Description |
|---|---|---|
y_true | 1d array-like | Ground-truth target labels. |
y_pred | 1d array-like | Estimated target labels. |
labels | array-like, default=None | Labels included in the score calculation. |
pos_label | int, float, bool or str, default=1 | Positive class label for binary classification. |
average | {‘micro’, ‘macro’, ‘samples’, ‘weighted’, ‘binary’} or None, default='binary' | Averaging strategy for multiclass or multilabel targets. |
sample_weight | array-like of shape (n_samples,), default=None | Per-sample weights. |
zero_division | {‘warn’, 0.0, 1.0}, default='warn' | Controls the behavior when division by zero occurs. |
float or array of float, shape = [n_unique_labels]: F1 score of the positive class in binary classification or weighted average of the F1 scores of each class for the multiclass task.
from sklearn.metrics import f1_score
y_true = [0, 1, 1, 0]
y_pred = [0, 1, 0, 0]
score = f1_score(y_true, y_pred)
print(score)Computes the binary F1 score for the positive class (1) from true and predicted labels.
Binary classification
Multiclass evaluation
Imbalanced classification
Cost-sensitive evaluation
F1 is the harmonic mean of precision and recall, so it balances both types of classification error. Its range is 0 to 1, with 1 representing the best score.
Follow-up: Why can F1 be preferable to accuracy? It emphasizes precision and recall, making it more informative when errors in the positive class matter or classes are imbalanced.
With the default average='binary', the function returns the F1 score for the positive class in binary classification. For multiclass or multilabel data, average determines whether scores are aggregated or returned per label.
Follow-up: How would you obtain separate scores? Set average=None, which returns an array containing one score for each label.
The function accepts sample_weight to assign different importance to individual samples. It also accepts labels to define the labels included in the calculation.
Follow-up: What happens when a class is absent from the data? Explicit labels can include it, and zero_division controls the behavior for undefined divisions.
precision_scorerecall_scorefbeta_scoreclassification_report