Skip to main content







Understanding and applying the F1 score
Where the F1 score came from, the math behind it, when to use it and when not to, plus a hands-on tutorial calculating, tuning, and logging F1 with scikit-learn and W&B.
Last updated: September 14, 2026
F1 score is one of the oldest classification metrics still used daily. Over forty-five years after it was first written down, it is still the default number people quote when they talk about a fraud detector, a content moderation classifier, an entity recognizer, or a medical screening tool. Newer metrics have come and gone. F1 has not.
This article covers where F1 came from, the math that makes it work, when it is the right metric and when it is the wrong one, and then walks through a hands-on tutorial that calculates F1 by hand, reproduces the numbers in scikit-learn, sweeps decision thresholds while logging every step to Weights & Biases.
Table of Contents
Table of ContentsThe intuition of F1 scoringWhere the F1 score came fromThe math behind F1When F1 is the right metric and when it is notWhy F1 is still the default in 2026Set up the environmentCalculate F1 by handVerify the formula with scikit-learnF1 vs accuracy on imbalanced dataTrain a model and watch F1 moveTune the decision threshold and log to Weights & BiasesFβ when precision and recall matter unequallyMicro, macro, and weighted F1 for multiclassThings to remember about F1What to do next
The intuition of F1 scoring
Here is the intuition F1 is built to answer: How good is my model at finding the positives while also avoiding false alarms? Precision is about false alarms: of the items the model flagged as positive, how many were truly positive. Recall is about missed cases: of all the true positives that existed, how many did the model find. Example: a fraud model flags 12 transactions and is right on 8 of them; precision is 8/12 = 0.67. If there were 10 total frauds in the batch and it caught 8, recall is 8/10 = 0.80. A different model might be pickier and flag only 5, all correct; precision is 1.00 but recall drops to 0.50 if there were 10 frauds total. F1 is a single number that prefers models that balance both, rather than excelling at one while failing at the other; the next section shows the math.
Where the F1 score came from
In 1979, well before machine learning was even called machine learning, Dutch computer scientist Cornelis Joost van Rijsbergen worked on information retrieval at the University of Glasgow. He had a problem that anyone building a modern search engine or RAG system would recognize. His retrieval algorithms returned ranked lists of documents from corpora where the vast majority were irrelevant to any given query. Accuracy was useless as a quality measure. A system could hit 99.9% accuracy by returning nothing at all, because nearly every document was correctly labeled irrelevant by default.
What van Rijsbergen needed was a metric that captured two competing concerns at once. Of the documents the system returned, how many were actually relevant (precision). Of all the relevant documents in the corpus, how many did the system find (recall). The two pull in opposite directions. Return everything and recall is perfect, but precision collapses. Return only the single most confident result and precision is high, but recall is terrible.
In his 1979 book Information Retrieval, van Rijsbergen defined an Effectiveness function, E, parameterized by a knob that controlled how much the user cared about recall versus precision. Most practitioners today use the F-measure as 1 minus E. The F1 score is the special case where precision and recall are weighted equally.
Van Rijsbergen never actually called it the F-measure. That name appeared at the Fourth Message Understanding Conference in 1992, a US government evaluation of information extraction systems, and it stuck. Where the F came from is itself a small historical mystery. The leading theory is that it was borrowed from a different F function in van Rijsbergen's book, but no one is entirely sure. By the late 1990s, between the TREC information retrieval competitions and the boom in text classification work, F1 had become the default single-number metric for binary classification with imbalanced classes. It never left.
The math behind F1
Start with precision and recall, which are simple ratios over a confusion matrix:
precision = TP / (TP + FP)recall = TP / (TP + FN)
TP = true positives (correct positive predictions),
FP = false positives (incorrect positive predictions), and
FN = false negatives (missed positives).
💡
Precision answers the question, of the items the model flagged as positive, how many actually were positive. Recall answers the complementary question, of all the actual positives in the data, how many did the model catch. The two depend on entirely different denominators, so they can move independently.
F1 is the harmonic mean of these two numbers:
F1 = 2 * (precision * recall) / (precision + recall)
The choice of harmonic mean is the part that earns its keep. An arithmetic mean would let a model paper over weakness in one metric with strength in the other. A model with precision 1.0 and recall 0.0 would get an arithmetic mean of 0.5, which looks acceptable but describes a model that never finds any positives. The harmonic mean punishes that asymmetry. Plug the same numbers in and the harmonic mean comes out at 0.0. The score only rises when both precision and recall are good.
An equivalent formulation, useful when working directly from a confusion matrix, is:
F1 = 2*TP / (2*TP + FP + FN)
The two forms produce the same number. Notice what both miss: true negatives. F1 says nothing about how many genuine negatives the model correctly ignored. This is by design. In information retrieval, the negatives are the millions of irrelevant documents in the corpus, and counting them as wins would let any reasonable system claim near-perfect performance.
The generalization van Rijsbergen actually defined is Fβ, with a tunable weight, which lets you control how much precision versus recall matters::
Fβ = (1 + β²) * (precision * recall) / (β² * precision + recall)
Setting β = 1 recovers F1. Setting β > 1 makes recall count more (good for screening tasks where missing a positive is the expensive failure mode). Setting β < 1 makes precision count more (good for filtering tasks where false alarms are the worse problem). The "F1" naming is just shorthand for Fβ at β=1.
💡
F1 ranges from 0 to 1. Higher is better. A perfect classifier scores 1.0. A classifier that catches none of the positives scores 0.0, regardless of how many true negatives it gets right.
When F1 is the right metric and when it is not
F1 can be particularly useful when classes are imbalanced, and the positive class is the main focus of the task. Fraud detection, spam filtering, defect detection in manufacturing, rare disease screening, abuse and content moderation, named entity recognition, RAG retrieval relevance, and toxicity classification on LLM outputs all fit this shape. In each case, there is a small population of interesting items inside a large population of uninteresting ones, and the cost of missing an interesting item is not the same as the cost of misfiling a routine one.
F1 is the wrong metric in a few specific situations. When classes are balanced and true negatives matter as much as true positives, F1 throws away half the information. Accuracy or Matthews correlation coefficient (MCC) is a better fit. When the downstream system uses the model's probability outputs to rank rather than classify, the relevant question is not "what F1 does this threshold give" but "how well-ordered are the scores," which is what ROC-AUC and PR-AUC measure. When the costs of false positives and false negatives are highly asymmetric and known, expected cost is more informative than any F-measure.
The single biggest pitfall with F1 is that it depends on a decision threshold. Any classifier that outputs probabilities can produce wildly different F1 scores depending on where the threshold is drawn. Reporting F1 without saying which threshold produced it is a common mistake. Tuning the threshold to maximize F1 on the test set is also a common mistake, and a more dangerous one, because it overfits the operating point to the evaluation data.
Why F1 is still the default in 2026
A reasonable question at this point is why a 45-year-old metric, designed for a problem (information retrieval) that dense embeddings and vector search have transformed beyond recognition, is still the headline number on classification leaderboards in 2026.
A few reasons:
- First, F1 is a single number that captures both precision and recall, which makes it cheap to compare across models, datasets, and time.
- Second, the imbalanced classification problem that motivated van Rijsbergen has not gone away. If anything, it has multiplied. Every LLM guardrail, spam filter, fraud system, and clinical decision support tool faces the same skew.
- Third, F1 is so deeply embedded in the literature, the libraries, and the muscle memory of practitioners that newer alternatives like MCC or balanced accuracy have struggled to displace it even where they are arguably better.
For LLM evaluation specifically, F1 has found a second life. When you build a classifier on top of a language model (a content safety classifier, an intent router, a retrieval relevance grader), the standard evaluation harness reports per-class precision, recall, and F1, often with macro and weighted averages. The vocabulary has not changed since the 1990s.
Now with the concept established, the rest of this tutorial is hands-on.
Set up the environment
Any CPU machine works. There is no GPU step.
pip install numpy pandas scikit-learn matplotlib wandb
Authenticate to Weights & Biases once so your runs and the final Report can sync.
wandb login
Pick a project name to reuse below. The examples use f1-score-tutorial.
Calculate F1 by hand
Start from a tiny example so every count is checkable. Two of the eight predictions are correct positives, one is a false alarm, and two positives were missed.
import numpy as np# Eight predictions on a tiny binary problemy_true = np.array([1, 1, 1, 0, 0, 0, 0, 1])y_pred = np.array([1, 0, 1, 0, 0, 1, 0, 0])TP = int(np.sum((y_true == 1) & (y_pred == 1)))FP = int(np.sum((y_true == 0) & (y_pred == 1)))FN = int(np.sum((y_true == 1) & (y_pred == 0)))TN = int(np.sum((y_true == 0) & (y_pred == 0)))precision = TP / (TP + FP) if (TP + FP) else 0.0recall = TP / (TP + FN) if (TP + FN) else 0.0f1_harmonic = 2 * (precision * recall) / (precision + recall) if (precision + recall) else 0.0f1_counts = 2 * TP / (2 * TP + FP + FN) if (2 * TP + FP + FN) else 0.0print("TP=", TP)print("FP=", FP)print("FN=", FN)print("TN=", TN)print("precision=", f"{precision:.4f}")print("recall=", f"{recall:.4f}")print("f1_harmonic=", f"{f1_harmonic:.4f}")print("f1_counts=", f"{f1_counts:.4f}")
Output :

Precision is 0.67, recall is 0.50, and F1 lands at 0.57 from either formula. Both forms agree, which is what the algebra promises.
Verify the formula with scikit-learn
Now reproduce the same numbers with the library most practitioners actually use day to day.
import numpy as npfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_scorey_true = np.array([1, 1, 1, 0, 0, 0, 0, 1])y_pred = np.array([1, 0, 1, 0, 0, 1, 0, 0])cm = confusion_matrix(y_true, y_pred, labels=[0, 1])p = precision_score(y_true, y_pred, pos_label=1, zero_division=0)r = recall_score(y_true, y_pred, pos_label=1, zero_division=0)f1 = f1_score(y_true, y_pred, pos_label=1, zero_division=0)print("Confusion_matrix")print(cm)print("Precision", f"{p:.4f}")print("Recall", f"{r:.4f}")print("F1", f"{f1:.4f}")
Output :

Same precision, same recall, same F1. If you ever get a different number from scikit-learn than from a hand calculation, the usual culprits are pos_label (defaults to 1 for binary) and average (defaults to 'binary'). Both are explicit in the snippet above.
F1 vs accuracy on imbalanced data
This is the case that motivated the metric in the first place. Imagine 200 transactions where 10 are fraud. A useless model that flags nothing still gets 95% accuracy.
import numpy as npfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix# We are taking 190 negatives, 10 positives which is usually a common shape for fraud or abuse detection.y_true = np.array([0] * 190 + [1] * 10)y_pred = np.zeros_like(y_true) # always predict the majority classcm = confusion_matrix(y_true, y_pred, labels=[0, 1])acc = accuracy_score(y_true, y_pred)p = precision_score(y_true, y_pred, pos_label=1, zero_division=0)r = recall_score(y_true, y_pred, pos_label=1, zero_division=0)f1 = f1_score(y_true, y_pred, pos_label=1, zero_division=0)print("Confusion_matrix", cm.tolist())print("Accuracy", f"{acc:.4f}")print("Precision", f"{p:.4f}")print("Recall", f"{r:.4f}")print("F1", f"{f1:.4f}")print("Positives_in_test", int(np.sum(y_true == 1)))
Output :

Accuracy looks fine. F1 says zero. Precision and recall are both 0 because the model never predicted the positive class. This is the exact problem van Rijsbergen was trying to solve. When the positive class is rare, a single accuracy number can hide a model that does nothing useful.
Train a model and watch F1 move
Fit a logistic regression on a reproducible imbalanced dataset and see what happens when there is a real predictor at work.
import numpy as npfrom sklearn.datasets import make_classificationfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score# Reproducible, imbalanced dataset (about 10 percent positives)X, y = make_classification(n_samples=1000,n_features=10,n_informative=5,n_redundant=2,n_clusters_per_class=2,weights=[0.9, 0.1],flip_y=0.01,class_sep=1.5,random_state=7,)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, stratify=y, random_state=7)clf = LogisticRegression(solver="liblinear", class_weight="balanced", random_state=7)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)cm = confusion_matrix(y_test, y_pred, labels=[0, 1])acc = accuracy_score(y_test, y_pred)p = precision_score(y_test, y_pred, pos_label=1, zero_division=0)r = recall_score(y_test, y_pred, pos_label=1, zero_division=0)f1 = f1_score(y_test, y_pred, pos_label=1, zero_division=0)print("Confusion_matrix")print(cm)print("accuracy", f"{acc:.4f}")print("precision", f"{p:.4f}")print("recall", f"{r:.4f}")print("f1", f"{f1:.4f}")
Output :

The class-weighted model catches 30 of the 31 positives. That is around 0.97 recall, dramatically better than the silent baseline. The cost is 32 false alarms, which drags precision to 0.48. F1 lands at 0.65 at the default threshold of 0.5.
Quite naturally the next question comes as - is 0.5 actually the right place to draw the line?
Tune the decision threshold and log to Weights & Biases
F1 depends on the threshold that converts predicted probabilities into class labels. The predict method uses 0.5 by default, but you can tune any probabilistic classifier by sweeping the threshold and picking the value that optimizes the metric that matches the cost structure.
The sweep below runs 19 thresholds from 0.05 to 0.95, logs precision, recall, and F1 at each one, and records a confusion matrix at the best operating point.
import numpy as npimport wandbfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix# Reuse clf, X_test, y_test from the previous stepy_proba = clf.predict_proba(X_test)[:, 1]run = wandb.init(project="f1-score-tutorial",job_type="threshold_sweep",config={"dataset": "make_classification", "model": "LogisticRegression"},)thresholds = np.linspace(0.05, 0.95, 19)table = wandb.Table(columns=["threshold", "accuracy", "precision", "recall", "f1", "tp", "fp", "fn", "tn"])best = {"threshold": None, "f1": -1, "preds": None}for t in thresholds:y_hat = (y_proba >= t).astype(int)acc = accuracy_score(y_test, y_hat)p = precision_score(y_test, y_hat, pos_label=1, zero_division=0)r = recall_score(y_test, y_hat, pos_label=1, zero_division=0)f1 = f1_score(y_test, y_hat, pos_label=1, zero_division=0)tn, fp, fn, tp = confusion_matrix(y_test, y_hat, labels=[0, 1]).ravel()table.add_data(float(t), float(acc), float(p), float(r), float(f1),int(tp), int(fp), int(fn), int(tn))wandb.log({"threshold": float(t), "accuracy": acc,"precision": p, "recall": r, "f1": f1})if f1 > best["f1"]:best = {"threshold": float(t), "f1": float(f1), "preds": y_hat}wandb.log({"Threshold_metrics : ": table})cm_plot = wandb.plot.confusion_matrix(y_true=y_test.tolist(), preds=best["preds"].tolist(), class_names=["0", "1"])wandb.log({"Confusion_matrix_at_best_threshold": cm_plot})print("best_threshold =", f"{best['threshold']:.2f}")print("best_f1 =", f"{best['f1']:.4f}")print("run_url =", run.url)run.finish()
Output :

For reference, here is the full sweep:

Three things to notice. Precision climbs monotonically from 0.17 to 1.00 as the threshold rises. Recall stays pinned at 0.97 until about threshold 0.55 and then falls, hitting 0.55 by threshold 0.95. F1 traces an inverted U with a clean peak at 0.85.
The improvement from threshold tuning alone is sizeable.
The default 0.5 threshold gave F1 = 0.65. The tuned threshold of 0.85 gives F1 = 0.86. Same model, same data, same probabilities. The only thing that changed was where the line was drawn.
The Weights & Biases run records every threshold as a logged step, so the linked Run view shows F1, precision, and recall as separate curves you can overlay. The Table panel holds the full sweep for sorting and filtering.
Fβ when precision and recall matter unequally
F1 weights precision and recall equally. In production systems, those weights almost never reflect the actual cost ratio. A medical screening tool that misses cancers is far worse than one that produces a few extra biopsies, so it should be tuned to favor recall. A spam filter that quarantines legitimate email is far worse than one that misses a few promotional messages, so it should be tuned to favor precision.
Fβ encodes this tradeoff.
- β = 1 gives F1.
- β > 1 weights recall more.
- β < 1 weights precision more.
import numpy as npfrom sklearn.metrics import fbeta_scorey_true = np.array([1, 1, 1, 0, 0, 0, 0, 1])y_pred = np.array([1, 0, 1, 0, 0, 1, 0, 0])for beta in [0.5, 1, 2]:val = fbeta_score(y_true, y_pred, beta=beta, pos_label=1, zero_division=0)print(f"F{beta} = {val:.4f}")F0.5 = 0.6250F1 = 0.5714F2 = 0.5263
Same predictions, same labels. The score moves because the weighting changed. Pick β based on the cost ratio in your setting, not on convention.
Micro, macro, and weighted F1 for multiclass
For three or more classes, scikit-learn computes F1 per class with a one-vs-rest view, then aggregates three ways. Micro pools the counts across all classes before computing F1. Macro takes the unweighted mean of per-class F1. Weighted takes a support-weighted mean of per-class F1.
import numpy as npfrom sklearn.metrics import f1_score# Three classes, with class 2 having more support than the othersy_true = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 2])y_pred = np.array([0, 0, 1, 1, 2, 1, 2, 2, 0, 1])per_class = f1_score(y_true, y_pred, average=None, labels=[0, 1, 2], zero_division=0)micro = f1_score(y_true, y_pred, average="micro", zero_division=0)macro = f1_score(y_true, y_pred, average="macro", zero_division=0)weighted = f1_score(y_true, y_pred, average="weighted", zero_division=0)print("per_class_f1", [f"{v:.4f}" for v in per_class])print("micro_f1", f"{micro:.4f}")print("macro_f1", f"{macro:.4f}")print("weighted_f1", f"{weighted:.4f}")
Output :

Macro fits when every class deserves equal weight regardless of rarity. Weighted fits when class support should pull the score. Micro fits when you want a single number that tracks overall correctness. For multiclass single-label problems, micro F1 equals accuracy, which is why the two numbers above are the same.
Things to remember about F1
A few sharp edges that catch people out:
- F1 ranges from 0 to 1, and higher is better. There is no absolute scale for "good." A 0.5 might be strong on a hard problem with few positives and weak on an easy one. Always compare against a baseline on the same data.
- F1 ignores true negatives by design. In a fraud problem that is a feature. In a balanced problem where being right on negatives also matters, complement F1 with specificity, ROC-AUC, PR-AUC, or MCC.
- Default thresholds are not sacred. The 0.5 cutoff that predict returns is convention, not optimization. The sweep above produced an absolute F1 gain of 0.21 from threshold tuning alone.
- Picking a threshold on a single test split overfits the operating point. In production code, choose the threshold via cross-validation or on a held-out validation set, not on the same data used to report final metrics.
- The zero_division argument controls what scikit-learn returns when precision or recall is undefined (no predicted positives, no actual positives, or both):
from sklearn.metrics import f1_score# No actual positives and no predicted positives: precision and recall undefinedval = f1_score([0, 0, 0, 0], [0, 0, 0, 0], zero_division=0)print("f1_no_positives", f"{val:.1f}")

What to do next
F1 is a starting point, not a destination. Two follow-ups that compound on this workflow:
- Pick the threshold by minimizing expected cost at the real class prevalence. F1 implicitly assumes the cost of a false positive equals the cost of a false negative. In a fraud system where investigating a flagged transaction costs five dollars and missing fraud costs five hundred, the right threshold is whichever minimizes expected loss, not whichever maximizes F1.
- Calibrate the predicted probabilities before tuning the threshold. The probability outputs of an uncalibrated classifier are not probabilities in any strict sense. The CalibratedClassifierCV wrapper in scikit-learn fits any base estimator with isotonic or sigmoid calibration on a held-out fold, which makes threshold choices more stable across retrains.
Both moves use the same logging pattern from this tutorial. Swap F1 for expected cost or for Fβ, rerun the sweep, and the Weights & Biases Run view does the rest. The metric van Rijsbergen wrote down in 1979 is the same one driving the dashboard.