Confusion matrix calculator: precision, recall and F1
A confusion matrix counts, for each actual class, how often a model predicted each class. Precision asks "of the items I called class k, how many were k?" (diagonal ÷ column total); recall asks "of the real class k items, how many did I find?" (diagonal ÷ row total). Report macro F1 when every class matters, and always next to the majority-class baseline.
Type a matrix of up to 10 classes, paste y_true and y_pred, or fill TP, FP, FN, TN. You get every per-class metric, macro, micro and weighted averages, Cohen's kappa and MCC exactly as scikit-learn computes them, plus a check of the numbers in your report. Free, runs in your browser.
scikit-learn 1.9.1 docs and code · UCI Steel Plates Faults (CC BY 4.0) · Chicco and Jurman 2020 · checked against an independent solution (20,620 checks at build, 8,713 scikit-learn cross-checks) · Updated 24 Nov 2026
Rows are the actual classes and columns the predicted classes, as in scikit-learn's confusion_matrix. Tick "transposed" if your matrix has predictions in rows (R caret, some textbooks).
| Class | Precision | Recall | Specificity | F1 | Support |
|---|
| Average | Precision | Recall | F1 |
|---|
Click any number in the two tables to see it worked out.
KNN on two real features of 739 steel plates (Pastry, Z_Scratch, K_Scatch), 70/30 stratified split. The shading is the class KNN would predict at each point. Untick "standardise" to see what raw distances do.
● Pastry ■ Z_Scratch ▲ K_Scatch · small faint marks: training plates · large marks: test plates · ✕: a test plate KNN gets wrong.
Implemented in the page: Euclidean distance, uniform weights; equal distances are taken in row order and a tied vote goes to the class that sorts first, which is what scikit-learn does with its sorted classes_. It matches scikit-learn's KNeighborsClassifier on 2,428 of 2,428 test predictions checked; 236 more have two plates at exactly the k-th distance with different classes, where scikit-learn's kd-tree picks by its own order (its documentation warns about this).
Paste the matrix and the numbers you reported (or sklearn's classification_report). The tool says which match and, for the rest, the likely cause.
- Paste a matrix and at least one number, or fill the example.
The exact script that produced every Steel Plates Faults number on this page. Download the data from the UCI page, then run: python steel_faults_sklearn.py faults.csv
"""Steel Plates Faults: KNN and SVM with and without StandardScaler, confusion matrices, a k sweep.
Produces the numbers on skill-lync.com/tools/confusion-matrix-calculator (src/data/confusion-matrix-steel.json).
Data: UCI Machine Learning Repository, Steel Plates Faults (id 198), Buscema, Terzi and Tastle (2010),
doi:10.24432/C5J88N, CC BY 4.0. Pass either the UCI file Faults.NNA (no header) or a faults.csv with the
27 feature columns and the 7 one-hot fault columns as its header.
Run: python steel_faults_sklearn.py faults.csv [out.json] (needs numpy and scikit-learn)
"""
import json, sys, platform
import numpy as np
import sklearn
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_validate
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score
FEATURES = ["X_Minimum", "X_Maximum", "Y_Minimum", "Y_Maximum", "Pixels_Areas", "X_Perimeter", "Y_Perimeter",
"Sum_of_Luminosity", "Minimum_of_Luminosity", "Maximum_of_Luminosity", "Length_of_Conveyer",
"TypeOfSteel_A300", "TypeOfSteel_A400", "Steel_Plate_Thickness", "Edges_Index", "Empty_Index",
"Square_Index", "Outside_X_Index", "Edges_X_Index", "Edges_Y_Index", "Outside_Global_Index", "LogOfAreas",
"Log_X_Index", "Log_Y_Index", "Orientation_Index", "Luminosity_Index", "SigmoidOfAreas"]
FAULTS = ["Pastry", "Z_Scratch", "K_Scatch", "Stains", "Dirtiness", "Bumps", "Other_Faults"]
SEED, TEST = 42, 0.3
def load(path):
with open(path) as f:
first = f.readline()
sep = "," if "," in first else None
if any(c.isalpha() for c in first): # header row: pick the columns by name
head = [h.strip().strip('"') for h in first.split(sep)]
D = np.loadtxt(path, delimiter=sep, skiprows=1)
X = D[:, [head.index(c) for c in FEATURES]]
Y1 = D[:, [head.index(c) for c in FAULTS]]
else:
D = np.loadtxt(path, delimiter=sep)
X, Y1 = D[:, :27], D[:, 27:34]
assert (Y1.sum(axis=1) == 1).all(), "each plate should carry exactly one fault"
return X, Y1.argmax(axis=1) # class index 0..6 in the order of FAULTS
def models():
return {
"knn_raw": KNeighborsClassifier(n_neighbors=5),
"knn_scaled": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)),
"svc_raw": SVC(), # RBF kernel, C = 1, gamma = "scale"
"svc_scaled": make_pipeline(StandardScaler(), SVC()),
}
def main(path, out):
X, y = load(path)
labels = list(range(7))
res = {"source": "UCI Machine Learning Repository, Steel Plates Faults (id 198), doi:10.24432/C5J88N, CC BY 4.0",
"versions": {"python": platform.python_version(), "numpy": np.__version__, "sklearn": sklearn.__version__},
"n": int(len(y)), "classes": FAULTS, "counts": np.bincount(y, minlength=7).tolist(),
"split": {"test_size": TEST, "random_state": SEED, "stratify": True},
"features": [{"name": c, "min": float(X[:, j].min()), "max": float(X[:, j].max()),
"mean": float(X[:, j].mean()), "std": float(X[:, j].std())} for j, c in enumerate(FEATURES)]}
# 1. one stratified 70/30 split: four confusion matrices (rows = actual, columns = predicted)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=TEST, random_state=SEED, stratify=y)
res["one_split"] = {}
for name, m in models().items():
p = m.fit(Xtr, ytr).predict(Xte)
res["one_split"][name] = {"cm": confusion_matrix(yte, p, labels=labels).tolist(),
"accuracy": accuracy_score(yte, p), "macro_f1": f1_score(yte, p, average="macro")}
# 2. the same split with 10 seeds, and 5-fold stratified cross-validation, so one lucky split is not the story
res["ten_seeds"] = {name: {"accuracy": [], "macro_f1": []} for name in models()}
for s in range(10):
a, b, c, d = train_test_split(X, y, test_size=TEST, random_state=s, stratify=y)
for name, m in models().items():
p = m.fit(a, c).predict(b)
res["ten_seeds"][name]["accuracy"].append(accuracy_score(d, p))
res["ten_seeds"][name]["macro_f1"].append(f1_score(d, p, average="macro"))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)
res["cv5"] = {}
for name, m in models().items():
r = cross_validate(m, X, y, cv=cv, scoring=["accuracy", "f1_macro"])
res["cv5"][name] = {"accuracy": r["test_accuracy"].tolist(), "macro_f1": r["test_f1_macro"].tolist()}
# 3. k sweep for scaled KNN (k = 1, 3, ..., 25), same 5 folds
res["k_sweep"] = []
for k in range(1, 26, 2):
r = cross_validate(make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k)), X, y, cv=cv,
scoring=["accuracy", "f1_macro"])
res["k_sweep"].append({"k": k, "accuracy": float(r["test_accuracy"].mean()), "macro_f1": float(r["test_f1_macro"].mean())})
# 4. two features, three classes (Pastry, Z_Scratch, K_Scatch) for the live KNN demo on the page
keep = np.isin(y, [0, 1, 2])
idx = np.flatnonzero(keep)
tr, te = train_test_split(idx, test_size=TEST, random_state=SEED, stratify=y[idx])
demo = {"rows": idx.tolist(), "train": sorted(tr.tolist()), "test": sorted(te.tolist()), "pairs": []}
for f1, f2 in [("Minimum_of_Luminosity", "Edges_Y_Index"), ("Steel_Plate_Thickness", "LogOfAreas")]:
j = [FEATURES.index(f1), FEATURES.index(f2)]
pair = {"features": [f1, f2], "x": X[idx][:, j].tolist(), "pred": {}}
trs, tes = sorted(tr.tolist()), sorted(te.tolist())
for k in (1, 5, 15):
for sc in (False, True):
m = KNeighborsClassifier(n_neighbors=k)
if sc:
m = make_pipeline(StandardScaler(), m)
p = m.fit(X[trs][:, j], y[trs]).predict(X[tes][:, j])
pair["pred"][f"k{k}_{'scaled' if sc else 'raw'}"] = p.tolist()
demo["pairs"].append(pair)
demo["y"] = y[idx].tolist()
res["demo2d"] = demo
with open(out, "w") as f:
json.dump(res, f, separators=(",", ":"))
for name, r in res["one_split"].items():
cvm = np.mean(res["cv5"][name]["accuracy"])
print(f"{name:11s} split accuracy {r['accuracy']:.4f} macro-F1 {r['macro_f1']:.4f} 5-fold CV accuracy {cvm:.4f}")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "faults.csv", sys.argv[2] if len(sys.argv) > 2 else "steel_results.json")
Run with Python 3.12.8, NumPy 2.5.5 and scikit-learn 1.9.1 on the UCI file (1,941 rows), it prints split accuracies of 0.4460, 0.7376, 0.5111, 0.7530 for the four models in the order above. It reads the UCI Faults.NNA file or a faults.csv with the column names as its header. Another scikit-learn version can move a plate or two where KNN distances tie.
How do you calculate precision, recall and F1 from a confusion matrix?
Read the four counts of each class off its row and column. scikit-learn defines the matrix so that Cij "is equal to the number of observations known to be in group i and predicted to be in group j": the row is the truth, the column the prediction.
scikit-learn's documentation: "The precision is the ratio tp / (tp + fp)" and "The recall is the ratio tp / (tp + fn)". Specificity is recall of the negatives; scikit-learn has no function for it, so the tool computes it from the same counts.
Worked example: the K_Scatch class of the scaled KNN model on the Steel Plates Faults test split below. Its column holds 121 predictions, of which 113 are right; its row holds 117 real K_Scatch plates.
Macro vs micro vs weighted F1: which should you report?
With more than two classes, a single precision, recall or F1 needs an average. scikit-learn: macro "Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account"; weighted finds "their average weighted by support (the number of true instances for each label)"; micro counts "the total true positives, false negatives and false positives".
The user guide adds: "If all labels are included, 'micro'-averaging in a multiclass setting will produce precision, recall and F that are all identical to accuracy." So micro F1 tells you nothing that accuracy did not. Weighted F1 leans toward the big classes. Macro F1 is the one that drops when a small class is missed, so report it (or the per-class table) whenever the small classes matter, as faults on steel plates do. Name the average every time: a "precision of 0.75" means nothing without it.
Two more numbers are worth a line. Balanced accuracy is "the macro-average of recall scores per class". Cohen's kappa and the Matthews correlation coefficient (MCC) compare the matrix with what chance would give. In scikit-learn's form, tk is how often class k occurred, pk how often it was predicted, c the correct count and s the total:
For two classes MCC runs from −1 to +1. With more classes, scikit-learn notes, "the minimum value will be somewhere between -1 and 0" while "The maximum value is always +1". Chicco and Jurman (2020) argue that MCC "produces a high score only if the prediction obtained good results in all of the four confusion matrix categories".
Why is accuracy misleading on imbalanced data?
Because the biggest class can carry it. Take 10,000 people of whom 1 % are sick, and a model that calls everyone healthy:
99 % accurate, and it never finds a sick person. Chicco and Jurman warn that accuracy and F1 "can dangerously show overoptimistic inflated results, especially on imbalanced datasets". The same happens with several classes. These two models both score 80 % accuracy on the same 100 items:
Accuracy cannot tell them apart; macro F1, balanced accuracy and MCC all prefer model 2, which finds 8 of the 10 C items. Always print the majority-class baseline next to accuracy: here it is 60 %.
Steel Plates Faults: KNN and SVM with and without feature scaling
The UCI Steel Plates Faults dataset (Buscema, Terzi and Tastle, 2010; doi:10.24432/C5J88N; CC BY 4.0) has 1,941 plates, 27 features and 7 fault classes. We downloaded it on 24 Nov 2026 and counted Pastry 158, Z_Scratch 190, K_Scatch 391, Stains 72, Dirtiness 55, Bumps 402, Other_Faults 673. Always predicting Other_Faults gives 34.7 %, the baseline every model must beat.
The features sit on wildly different scales. Pixels_Areas runs from 2 to 1,52,655, Sum_of_Luminosity up to 1,15,91,414 and Y_Minimum up to 1,29,87,661, while Edges_Index stays between 0 and 0.995. On raw features a Euclidean distance is almost entirely Y_Maximum (standard deviation 17,74,133) and Y_Minimum (standard deviation 17,74,121): they record where the fault sits on the plate, not what it looks like. With scikit-learn 1.9.1, a stratified 70/30 split (random_state = 42, 583 test plates) and default settings:
| Model | Accuracy (this split) | Macro F1 | Accuracy, 10 seeds (mean ± sd) | 5-fold CV accuracy / macro F1 |
|---|---|---|---|---|
| KNN, k = 5, raw features | 0.4460 | 0.3334 | 0.457 ± 0.017 (0.441 to 0.489) | 0.441 / 0.349 |
| KNN, k = 5, StandardScaler | 0.7376 | 0.7538 | 0.723 ± 0.015 (0.698 to 0.750) | 0.733 / 0.749 |
| SVC (RBF), raw features | 0.5111 | 0.2511 | 0.511 ± 0.011 (0.499 to 0.533) | 0.507 / 0.245 |
| SVC (RBF), StandardScaler | 0.7530 | 0.7484 | 0.750 ± 0.018 (0.726 to 0.791) | 0.749 / 0.767 |
Scaling is the whole story. StandardScaler (fitted on the training split inside a Pipeline) lifts KNN from 44.6 % to 73.8 % and SVC from 51.1 % to 75.3 %, and ten different splits and 5-fold cross-validation agree, so this is not one lucky split. Unscaled SVC is the accuracy trap in real data: 51.1 % looks better than the 34.7 % baseline, but it predicts Other_Faults for 420 of the 583 test plates and finds none of the Z_Scratch, Stains or Dirtiness plates (recall 0), so its macro F1 is 0.251.
The small classes gain most. For KNN, recall on Dirtiness (55 plates in all) goes from 0.412 to 0.824 and on Stains (72) from 0.000 to 0.909. What stays hard after scaling is Bumps against Other_Faults: scaled KNN puts 42 Other_Faults plates in Bumps and 24 Bumps plates in Other_Faults, the two largest errors in its matrix. Per class, scaled KNN:
| Class | Plates (test) | Precision / recall / F1, raw | Precision / recall / F1, scaled |
|---|---|---|---|
| Pastry | 47 | 0.053 / 0.043 / 0.047 | 0.532 / 0.532 / 0.532 |
| Z_Scratch | 57 | 0.224 / 0.193 / 0.208 | 0.750 / 0.895 / 0.816 |
| K_Scatch | 117 | 0.828 / 0.821 / 0.824 | 0.934 / 0.966 / 0.950 |
| Stains | 22 | 0.000 / 0.000 / 0.000 | 0.870 / 0.909 / 0.889 |
| Dirtiness | 17 | 0.438 / 0.412 / 0.424 | 0.737 / 0.824 / 0.778 |
| Bumps | 121 | 0.348 / 0.405 / 0.374 | 0.592 / 0.694 / 0.639 |
| Other_Faults | 202 | 0.444 / 0.470 / 0.457 | 0.755 / 0.609 / 0.674 |
How many neighbours? For scaled KNN, 5-fold CV accuracy is highest at k = 5 (0.733) and macro F1 at k = 7 (0.750); by k = 25 they fall to 0.701 and 0.692, because a wide neighbourhood outvotes the small classes. The default k = 5 is as good as any here.
The live demo in tab 2 shows the same effect on two features you can see. With Minimum_of_Luminosity (0 to 203) against Edges_Y_Index (0 to 1) and k = 5, test accuracy is 73.4 % on raw values and 86.9 % standardised: raw, the shading is vertical bands, because only the luminosity counts. Scaling does not always help, though. With Steel_Plate_Thickness against LogOfAreas, raw gives 91.4 % and standardised 90.5 %: thickness alone happens to separate these three faults well, and scaling gives the weaker feature an equal say.
What the 124 public classification challenge reports do (as of 24 Nov 2026)
We read the 124 public Skill-Lync reports titled "Supervised Learning - Classification Week 7 Challenge" (SVM, 55) and "Week 8 Challenge" (KNN, 69), as of 24 Nov 2026, n = 124. None is image-only, but many show their code and results only in screenshots, so every count is a floor. A row's second number is the reports where the question could be checked. The links are examples.
- 124 / 124Answer the pros and cons question in text. Both weeks ask for pros and cons; most of the text in these reports is this answer (2 list them without the words pros/cons). report 1report 2
- 42 / 124Show the modelling part (code or a result) in text. The rest put the model in screenshots or an attached notebook, so every count below is a floor. report 1report 2
- 35 / 124Python model code visible in text. report 1report 2
- 40 / 124Work on the Steel Plates Faults data (faults.csv or its fault columns in text). 69 name the dataset in text (the question itself names it). report 1report 2
- 26 / 35Fold the 7 one-hot fault columns into one 7-class label. Out of the 35 reports with model code in text. idxmax over the last 7 columns, or a loop that writes the fault name. Two of these carry a bug in that line (==-1, iloc[:,7:]). report 1report 2
- 18 / 35Scale features in code (StandardScaler, MinMaxScaler or z-score). Out of the 35 reports with model code in text. report 1report 2
- 14 / 35Fit the scaler on all rows before the train/test split. Out of the 35 reports with model code in text. The test rows then shape the scaling (a small leak). Fitting on the training split only: 4. report 1report 2
- 28 / 35Fix random_state in train_test_split. Out of the 35 reports with model code in text. stratify= used: 0. Cross-validation in code: 2. report 1report 2
- 28 / 124Print or plot a confusion matrix. classification_report or precision/recall/F1 in text: 7; ROC/AUC: 3; macro/weighted averages shown: 2. report 1report 2
- 24 / 124State a test accuracy in text. Values read by hand; 20 are on the 7-class steel data (2 more on a binary steel framing, 1 iris, 1 not named). See values.accuracy. report 1report 2
- 66 / 69KNN pros/cons: Simple, easy to understand and implement. report 1report 2
- 57 / 69KNN pros/cons: Sensitive to noise, outliers or missing values. report 1report 2
- 56 / 69KNN pros/cons: Slow or memory-hungry on large datasets. report 1report 2
- 53 / 69KNN pros/cons: "No training step" (lazy, instance-based learner). report 1report 2
- 40 / 69KNN pros/cons: Needs feature scaling (normalise or standardise). report 1report 2
- 46 / 69KNN pros/cons: Struggles in high dimensions (curse of dimensionality). report 1report 2
- 40 / 69KNN pros/cons: Choosing k is hard; k must be tuned. report 1report 2
- 51 / 69KNN pros/cons: Handles multi-class problems (and regression too). report 1report 2
- 26 / 69KNN pros/cons: Struggles with imbalanced classes. report 1report 2
- 44 / 69KNN pros/cons: Names distance measures (Euclidean, Manhattan, Minkowski...). report 1report 2
- 47 / 55SVM pros/cons: Works well in high-dimensional spaces. report 1report 2
- 52 / 55SVM pros/cons: Slow or unsuitable for large datasets. report 1report 2
- 41 / 55SVM pros/cons: Weak with noise or overlapping classes. report 1report 2
- 33 / 55SVM pros/cons: Mentions kernels (non-linear boundaries, kernel choice). report 1report 2
- 30 / 55SVM pros/cons: Memory efficient (uses only support vectors). report 1report 2
- 31 / 55SVM pros/cons: Works when features outnumber samples (or fails then). report 1report 2
- 26 / 55SVM pros/cons: Works well with a clear margin of separation. report 1report 2
- 15 / 55SVM pros/cons: Less prone to overfitting. report 1report 2
- 19 / 55SVM pros/cons: No direct probability estimates. report 1report 2
- 16 / 55SVM pros/cons: Hard to interpret. report 1report 2
What stands out for this calculator: 28 of 124 print or plot a confusion matrix, only 7 show precision, recall or F1 in text and 2 name an average. Of the 35 with model code in text, 18 scale the features and 14 fit the scaler on all rows before splitting; 0 use stratify and 2 cross-validate. 40 of the 69 KNN reports list "needs feature scaling" as a con, 17 KNN reports set k in code: k = 19 (5), k = 7 (4), k = 40 (3), k = 5 (2), k = 10 (2), k = 3 (1), k = 4 (1); 5 sweep k. These are first-party counts, a starting point rather than a measure of anyone's ability.
The test accuracies reported in text on the 7-class steel data match the table above. Unscaled KNN: 0.4832 (3 reports, the same value: they run the same code with the same split and seed). Scaled KNN: 0.6587 to 0.7378 (4). SVM: median 0.7341 (11 reports, 0.710 to 0.770). Two reports frame the task as binary (faulty or not) and print a classification report; from its supports, precision, recall and F1 the confusion matrix can be rebuilt, and it is unique: SVM [[222,24],[60,83]], accuracy 0.784, recall of class 1 0.580; KNN [[217,29],[57,86]], accuracy 0.779, recall of class 1 0.601. Paste either into tab 3 to check the rest of the report.
We re-ran three reports' code on the UCI file. A KNN report (k = 7, z-scores on all rows, 20 % test, random_state 0) prints 0.7378: we get the same 0.7377892, and with ten other seeds it ranges 0.702 to 0.779. Another KNN report (k = 40) and an SVM report (linear kernel) also reproduce exactly (0.6587 and 0.7341), but only with their own label strings: both spell the Z_Scratch class "X_Scratch". With the label spelt "Z_Scratch" the same KNN code gives 0.6569, one test plate fewer, because a tied vote goes to the label that sorts first.
Common confusion matrix slips and how to fix them
- Reading the matrix the wrong way round. In scikit-learn rows are actual; caret prints predictions in rows, and Wikipedia's article says the layout varies. Read the wrong way, precision and recall trade places. Fix: label the axes, as in plt.xlabel("Predicted"). Tab 3 tests your numbers against the transposed matrix.
- Quoting an average without naming it. classification_report prints both "macro avg" and "weighted avg". Copying the wrong line is the commonest mismatch tab 3 finds.
- Letting zero_division pass silently. "If set to 'warn', this acts like 0, but a warning is also raised." A class that is never predicted then drags macro precision down. That is fair, but say so.
- Fitting the scaler on all rows before the split. The test rows then shape the scaling. On this dataset the effect is small (the first re-run above gives 0.7378 either way), but it is a leak. Put StandardScaler in a Pipeline so it is fitted on the training rows only.
- Accuracy on one split, no baseline. Ten seeds move scaled KNN between 0.698 and 0.750. Use stratify=y, report a cross-validated mean, and print the 34.7 % majority baseline.
- Calling 0.51 "good" for unscaled SVC. It is barely above always guessing Other_Faults. Look at the per-class recall before you compare models.
How we checked the calculator
An independent Python script, scripts/verify/confusion_matrix.py, recomputes the numbers with its own code. It expands each matrix into y_true and y_pred pairs, counts TP, FP, FN and TN per sample, and computes every metric with exact fractions. This page refuses to build if the browser code differs from it in any of 20,620 numbers, labels, causes or predictions (2,575 cases including 240 matrices from 2×2 to 10×10, with empty rows, empty columns, absent classes, all-correct, all-wrong and one-sample matrices; 1,710 more assertions run inside the script). Run with scikit-learn 1.9.1, it also compared 8,713 values with precision_recall_fscore_support (every average), accuracy_score, balanced_accuracy_score, cohen_kappa_score, matthews_corrcoef, classification_report and KNeighborsClassifier: 0 mismatches. Two deliberate bugs, macro F1 computed as the F1 of macro precision and macro recall, and a tied KNN vote given to the last class, each make the build fail. The Steel Plates numbers come from the script in tab 4; the page recomputes their accuracy and macro F1 from the stored matrices.
What this calculator does not cover
- Thresholds, ROC and precision-recall curves. The tool works on hard predictions; it does not take scores or probabilities.
- Multilabel data (several labels per item, "samples" averaging) and sample weights.
- Confidence intervals for the metrics. With 583 test plates, one plate moves accuracy by 0.17 points.
- Regression. For R², RMSE and gradient descent, use the gradient descent calculator.
SVM, KNN and how to judge a classifier are the classification weeks of Skill-Lync's PG program in data analytics and data science, after the regression week and before clustering.
Frequently asked questions
How do you calculate precision and recall from a confusion matrix?
With actual classes in rows and predictions in columns (scikit-learn's layout), precision for a class is its diagonal count divided by its column total, and recall is the diagonal count divided by its row total. For a binary matrix [[TN, FP], [FN, TP]], precision = TP/(TP+FP) and recall = TP/(TP+FN).
Macro vs micro vs weighted F1: which should I report?
Macro F1 averages the per-class F1 scores equally, so a small class that the model misses pulls it down: report it when every class matters. Weighted F1 weights each class by its support and drifts toward accuracy. Micro F1 equals accuracy for single-label multiclass data, so it adds nothing beyond accuracy.
Why does KNN need feature scaling?
KNN compares Euclidean distances, so a feature measured in large numbers swamps the rest. In the Steel Plates Faults data, Pixels_Areas runs from 2 to 1,52,655 while Edges_Index stays between 0 and 1. On our 70/30 split, KNN with k = 5 scored 44.6 % on raw features and 73.8 % after StandardScaler.
What is a good MCC?
For two classes MCC runs from −1 to +1: +1 is a perfect prediction, 0 is no better than chance and −1 is total disagreement. It is high only when all four cells of the matrix are good. There is no universal cut-off; a model that always predicts the majority class scores 0, so compare against that.
Why is my accuracy high but recall low?
The data is imbalanced and the model favours the big class. If 1 % of 10,000 people are sick, a model that calls everyone healthy is 99 % accurate with recall 0 for the sick class. Check the per-class recall, balanced accuracy or MCC, and compare accuracy with the share of the largest class.
Rows or columns: which is actual in sklearn?
In scikit-learn's confusion_matrix, rows are the actual (true) classes and columns are the predicted classes, in sorted label order; for binary labels ravel() gives tn, fp, fn, tp. R's caret prints predictions in rows instead, and Wikipedia notes that both layouts are used, so check before reading off precision.
What does zero_division mean in scikit-learn?
When a class is never predicted its precision is 0/0, and when it has no true samples its recall is 0/0. scikit-learn then returns 0 by default, with an UndefinedMetricWarning, or the value you pass as zero_division. The choice changes the macro average, so say which one you used.
Related on Skill-Lync
- Gradient descent calculator (the regression week of the same program: learning rate, loss functions, R²)
- K-means clustering calculator (the clustering week that follows: every k-means step, the elbow, the silhouette and scaling)
- Sample vs population variance calculator (n vs n − 1: why StandardScaler's ddof = 0 is fine)
- Curve fitting calculator (least squares for curves)
- All free engineering tools
Sources
- scikit-learn 1.9.1 documentation: confusion_matrix; precision_recall_fscore_support (average options, zero_division); user guide 3.4 (micro average = accuracy, balanced accuracy, Cohen's kappa, multiclass MCC); KNeighborsClassifier (defaults, the warning on equal distances); StandardScaler (ddof = 0, zero variance). Source code of KNeighborsClassifier.predict and cohen_kappa_score in scikit-learn 1.9.1.
- Buscema, M., Terzi, S. and Tastle, W. (2010). Steel Plates Faults [Dataset]. UCI Machine Learning Repository, doi:10.24432/C5J88N, CC BY 4.0.
- Chicco, D. and Jurman, G. (2020). The advantages of the Matthews correlation coefficient (MCC) over F1 score and accuracy in binary classification evaluation. BMC Genomics 21, 6.
- caret documentation (Kuhn), "Measuring performance": confusionMatrix output with Prediction in rows and Reference in columns. Wikipedia, "Confusion matrix": both orientations are used.
- Skill-Lync, the 124 public classification challenge reports (weeks 7 and 8), read 24 Nov 2026.