This confusion matrix calculator scores a 2×2 matrix for a binary classifier, or a 3×3 and larger matrix for multiclass models. Get accuracy, precision, recall, F1, MCC, balanced accuracy, Cohen's kappa and per-class scores — with 95% confidence intervals and a heatmap. Everything runs in your browser; no data is uploaded.
Rows are actual labels; columns are predicted labels. Edit any cell, or paste a block of numbers straight into the grid.
Separate values with commas, spaces or new lines. Both lists must have the same length. For multi-word class names, rename the classes in the matrix grid.
All metrics
| Metric | Value |
|---|
Adjust PPV and NPV for a different prevalence
PPV and NPV depend on how common the positive class is. This matrix implies a prevalence of —. Enter another value to see the projected scores.
—
Per-class scores
| Class | Support | Precision | Recall | F1 | 95% CI (P / R) |
|---|
| Average | Precision | Recall | F1 |
|---|
Macro treats every class equally. Weighted weights each class by its support. Micro is the global count-based rate; for single-label multiclass it equals accuracy.
How to use this confusion matrix calculator
The calculator is already loaded with a spam-filter example. To use your own numbers:
- Set the number of classes. The default is a 2×2 binary matrix. Use + Class for 3×3, 4×4 and up to 10×10. The last class can be removed once its row and column are empty.
- Name the classes. Edit the column headers. Rows use the same names and represent the actual labels; columns represent what the model predicted.
- Enter the counts. Put the number of correct predictions on the diagonal. Every other cell is a specific confusion. You can paste a block of numbers directly into the grid, or switch to Paste counts or y_true / y_pred.
- Pick the positive class. Precision, recall, F1, specificity, NPV and Youden's J are one-vs-rest scores. For binary problems the positive class is usually the event you are trying to detect.
- Read the results. The headline tiles show accuracy plus precision, recall and F1 for the selected class. The tables below add MCC, kappa, balanced accuracy, confidence intervals, per-class scores and macro/micro/weighted averages.
The matrix follows the scikit-learn convention: rows are actual, columns are predicted. If your numbers are transposed, recall and precision will swap.
Confusion matrix formulas
For a binary classifier, the four cells are true positives (TP), false positives (FP), false negatives (FN) and true negatives (TN). For multiclass problems, each class is scored one-vs-rest: that class is positive, every other class is negative.
| Metric | Formula | What it tells you |
|---|---|---|
| Accuracy | (TP + TN) / N | Share of all predictions that are correct. |
| Precision (PPV) | TP / (TP + FP) | Of the cases predicted positive, how many really are positive. |
| Recall (sensitivity, TPR) | TP / (TP + FN) | Of the actual positives, how many the model found. |
| Specificity (TNR) | TN / (TN + FP) | Of the actual negatives, how many the model correctly rejected. |
| F1 score | 2 × (P × R) / (P + R) | Harmonic mean of precision and recall; punishes a lopsided trade-off. |
| NPV | TN / (TN + FN) | Of the cases predicted negative, how many really are negative. |
| Balanced accuracy | Mean recall across classes | Accuracy that gives each class equal weight, not each example. |
| MCC | (TP×TN − FP×FN) / √((TP+FP)(TP+FN)(TN+FP)(TN+FN)) | Correlation between actual and predicted labels, from −1 to 1. Uses all four cells. |
| Cohen's κ | (po − pe) / (1 − pe) | Agreement corrected for chance. 0 is chance level; 1 is perfect. |
| Youden's J | Sensitivity + specificity − 1 | How well the classifier separates the two classes; 0 is no better than chance. |
The multiclass MCC uses the standard generalisation based on the full confusion matrix, matching sklearn.metrics.matthews_corrcoef. All rates are shown as percentages by default; switch to 0–1 to compare directly with scikit-learn output. MCC and kappa are always shown on their natural scale.
Worked example: spam filter
Suppose a spam filter labels 1,000 emails. It catches 85 of the 100 spam messages and wrongly flags 8 of the 900 legitimate messages.
| Actual ↓ / Predicted → | Spam | Not spam | Total |
|---|---|---|---|
| Spam | 85 | 15 | 100 |
| Not spam | 8 | 892 | 900 |
| Total | 93 | 907 | 1,000 |
Accuracy is 97.7%, which sounds excellent. Precision is 91.4%: of the 93 emails flagged as spam, 85 really are spam. Recall is 85.0%: the filter misses 15 of the 100 spam messages. F1 is 88.1%, MCC is 0.869 and balanced accuracy is 92.1%.
The gap between precision and recall is the useful part. This filter is conservative: when it flags an email, it is usually right, but it lets some spam through. Lowering the threshold would catch more spam and flag more legitimate mail. The calculator lets you test that trade-off by editing the matrix.
Why accuracy misleads on imbalanced data
Now screen 1,000 people for a rare cancer. The model catches 18 of 20 cancers, misses 2, and flags 40 healthy people.
| Actual ↓ / Predicted → | Cancer | Healthy | Total |
|---|---|---|---|
| Cancer | 18 | 2 | 20 |
| Healthy | 40 | 940 | 980 |
| Total | 58 | 942 | 1,000 |
Accuracy is 95.8%, but a model that predicts “healthy” for everyone would score 98.0%. Accuracy rewards the majority class. Precision is only 31.0%: two out of three positive flags are false alarms. Recall is 90.0%, F1 is 46.2%, MCC is 0.515 and balanced accuracy is 93.0%.
For screening, recall usually matters more than precision because a missed cancer is costly. But the false positives are not free: they create anxiety, follow-up tests and cost. That is why the calculator reports PPV and NPV, and why the optional prevalence control matters. At a lower prevalence, the same sensitivity and specificity produce a much lower PPV.
Read more about the costs of each error in Type I and Type II errors.
How to read a 3×3 confusion matrix
A multiclass matrix has one row and one column per class. The diagonal is still correct; each off-diagonal cell is a specific confusion. Take a 150-flower iris test set:
| Actual ↓ / Predicted → | Setosa | Versicolor | Virginica | Total |
|---|---|---|---|---|
| Setosa | 50 | 0 | 0 | 50 |
| Versicolor | 0 | 47 | 3 | 50 |
| Virginica | 0 | 4 | 46 | 50 |
| Total | 50 | 51 | 49 | 150 |
Accuracy is 95.3% (143 of 150). Setosa is perfectly separated: 50 of 50. Versicolor is confused with Virginica 3 times; Virginica is confused with Versicolor 4 times. The per-class table shows why a single accuracy number hides that:
| Class | Support | Precision | Recall | F1 |
|---|---|---|---|---|
| Setosa | 50 | 100.0% | 100.0% | 100.0% |
| Versicolor | 50 | 92.2% | 94.0% | 93.1% |
| Virginica | 50 | 93.9% | 92.0% | 92.9% |
Macro F1 averages the three class F1 scores and gives Setosa, Versicolor and Virginica equal weight. Weighted F1 weights by support (50, 50, 50 here, so it matches). Micro F1 pools all TP, FP and FN; for single-label multiclass it equals accuracy. When classes are imbalanced, macro and weighted can diverge sharply, and the calculator shows all three so you can see which story the number is telling.
For a full treatment of model evaluation beyond the matrix, see how to evaluate a supervised learning model.
Which metric should you optimize?
There is no universal best metric. The right one depends on which mistake is more expensive and how imbalanced the classes are.
| If… | Optimize | Why |
|---|---|---|
| A false positive is expensive (spam filter, fraud block) | Precision | You want the positive calls to be trustworthy. |
| A false negative is expensive (cancer screening, safety alarm) | Recall | You want to miss as few positives as possible. |
| Both errors matter and you need one number | F1 | Balances precision and recall without using TN. |
| Classes are imbalanced and all four cells matter | MCC | Uses the whole matrix and is high only when all four cells are good. |
| You want each class to count equally | Balanced accuracy | Averages recall across classes, not examples. |
| You need agreement beyond chance | Cohen's κ | Corrects for the agreement expected by chance. |
Report more than one. A precision-only or accuracy-only summary is easy to game. For a model that will be deployed, pair the headline metric with a confusion matrix, a per-class breakdown and a confidence interval.
How to make a confusion matrix in Excel
If your actual labels are in column A and predictions in column B, list the class names across the top and down the side, then use COUNTIFS:
=COUNTIFS($A:$A,$E2,$B:$B,F$1)
Here $E2 is the actual class for the row and F$1 is the predicted class for the column. Copy the formula across the grid. Add totals with SUM, then divide the diagonal by the grand total for accuracy.
The fastest route is to copy the finished block from Excel and paste it into the matrix grid above; the calculator accepts tab-separated values. Size the grid to match first, or use Paste counts to build a new matrix from the block.
Confusion matrix in Python with scikit-learn
If you already have y_true and y_pred, scikit-learn computes the same matrix:
from sklearn.metrics import confusion_matrix, classification_report, matthews_corrcoef
cm = confusion_matrix(y_true, y_pred, labels=labels)
print(cm)
print(classification_report(y_true, y_pred, target_names=labels, digits=4))
print("MCC:", matthews_corrcoef(y_true, y_pred))
Keep the label order consistent. confusion_matrix sorts labels by default; pass labels= when the order matters. For a multiclass problem, classification_report prints per-class precision, recall and F1 plus the macro and weighted averages. The calculator mirrors those definitions.
Two details can make the numbers differ. First, scikit-learn's default zero-division handling reports 0 when a denominator is zero (and may warn); this calculator shows — by default. Switch Zero division to Use 0 (sklearn) for a direct match. Second, the confidence intervals here are Wilson score intervals; scikit-learn does not report them.
If you are building the classifier itself, start with your first supervised learning model in Python, then compare models with k-fold cross-validation.
Common mistakes
- Transposing the matrix. Rows are actual, columns are predicted. Swapping them swaps precision and recall.
- Reporting accuracy alone on imbalanced data. A majority-class predictor can look accurate while finding none of the positives.
- Mixing up macro and weighted averages. Macro gives each class equal weight; weighted follows support. They answer different questions.
- Silently zeroing undefined metrics. A class with no predictions has undefined precision, not zero precision. The default here shows — so the gap is visible.
- Tuning on the test set. Choosing a threshold on the same data you report inflates every metric. Use a validation set or nested cross-validation.
- Forgetting prevalence. PPV and NPV move when the base rate moves, even if sensitivity and specificity stay fixed.
Data leakage is another common reason a matrix looks too good. See data leakage in machine learning for the usual suspects.
Frequently asked questions
How do I calculate a confusion matrix?
Compare each actual label with the corresponding prediction. Count how many times each actual class was predicted as each possible class. Put those counts in a table with actual labels as rows and predicted labels as columns. The diagonal holds correct predictions; every other cell is a specific misclassification.
What is a good F1 score?
It depends on the task and the baseline. In many benchmark problems, 0.7 or higher is usable and 0.9 or higher is strong, but a spam filter and a cancer screen have very different tolerances. Compare against a simple baseline and against the cost of false positives and false negatives rather than a universal cutoff.
Is 0.7 a good F1 score?
It can be. For a balanced, well-studied benchmark, 0.7 may be mediocre; for a noisy real-world task with weak labels, it may be excellent. The number only becomes meaningful next to the majority-class baseline, the per-class scores and the business cost of each error.
How do I read a 3×3 confusion matrix?
Rows are actual classes and columns are predicted classes. The three diagonal cells are correct predictions. An off-diagonal cell tells you which class was confused with which: for example, a count in the Versicolor row and Virginica column is a Versicolor flower predicted as Virginica. Read the per-class precision and recall to see which class is suffering.
What is the difference between precision and recall?
Precision asks: of the cases we predicted positive, how many were actually positive? Recall asks: of the actual positives, how many did we find? Precision is about false alarms; recall is about misses. Raising one usually lowers the other, which is why F1 combines them.
Why is accuracy misleading on imbalanced data?
Accuracy counts every example equally, so the majority class dominates. If 98% of cases are negative, a model that always predicts negative scores 98% while catching zero positives. Balanced accuracy, recall, F1 and MCC expose that failure.
How do I make a confusion matrix in Excel?
Put actual labels in one column and predictions in another. Create a grid of class names and use COUNTIFS with the actual class as the row criterion and the predicted class as the column criterion. The calculator accepts a pasted Excel block, so you can also build the counts in Excel and paste them here.
Can this confusion matrix calculator handle more than two classes?
Yes. Use + Class to build a 3×3, 4×4 or larger matrix, up to 10×10. It reports per-class precision, recall, F1 and support, plus macro, micro and weighted averages and multiclass MCC and kappa.
What is the difference between MCC and F1?
F1 focuses on the positive class and ignores true negatives. MCC uses all four cells of the binary matrix and is high only when the model does well on both positives and negatives. On imbalanced data, MCC is often the more honest single number; F1 is more interpretable when the positive class is the only one you care about.
Does this confusion matrix calculator match scikit-learn?
For non-degenerate matrices, yes: accuracy, precision, recall, F1, specificity, MCC, kappa and the macro/micro/weighted averages use the same definitions. Set Zero division to “Use 0 (sklearn)” to match scikit-learn's default handling of undefined metrics. The 95% confidence intervals are Wilson intervals, which scikit-learn does not provide.
Related guides and tools
- How to evaluate a supervised learning modelThe full evaluation workflow: splits, metrics, curves and error analysis.
- Type I and Type II errorsWhy false positives and false negatives have different costs.
- Machine learning models guideChoose a classifier before you measure it.
- Logistic regression explainedA natural baseline for binary classification.
- Naive Bayes classifierFast text classification and its evaluation.
- K-nearest neighborsDistance-based classification and its failure modes.
- Support vector machinesMargins, kernels and decision boundaries.
- K-fold cross-validationCompare models without leaking test data.
- Classification vs regressionMake sure you are solving the right problem.
- AI token counterEstimate tokens and API cost for LLM inputs.
