Accuracy is the share of predictions a classification model gets right. It is the simplest metric and a good starting point – but it can be misleading when classes are imbalanced.
What You Will Learn
- The accuracy formula
- Compute accuracy and a confusion matrix with scikit-learn
- Read TN, FP, FN and TP
- When accuracy is not enough
Prerequisites
Formula
Accuracy = correct predictions ÷ total predictions = (TP + TN) / (TP + TN + FP + FN)

Example: KNN on Social Network Ads
The dataset has users’ Age and Estimated Salary and whether they Purchased a product after seeing an ad (0/1).
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, accuracy_score
data = pd.read_csv("Social_Network_Ads.csv")
X = data.iloc[:, [2, 3]].values # Age, EstimatedSalary
y = data.iloc[:, 4].values # Purchased
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
model = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
y_pred = model.predict(X_test)
print(confusion_matrix(y_test, y_pred))
print("Accuracy:", accuracy_score(y_test, y_pred))
[[64 4] [ 3 29]] Accuracy: 0.93
Explanation: scikit-learn’s confusion matrix is laid out as [[TN, FP], [FN, TP]]. Here 64 + 29 = 93 of 100 test users are classified correctly, so accuracy = 0.93.

Decision Boundary

Explanation: Each colour is the region where KNN predicts that class; points are the test users. Misclassified points sit on the wrong side of the boundary.
When Accuracy Misleads
If only 1% of transactions are fraud, a model that always says “not fraud” is 99% accurate yet useless. For imbalanced data use precision, recall and F1.
Metrics Series
Overview · Precision · Recall · F1 Score
Interview Questions
Q: When is accuracy a poor metric?
With imbalanced classes or when different errors have different costs.
Q: What does the confusion matrix show?
Counts of true negatives, false positives, false negatives and true positives.
Practice Exercises
- Change n_neighbors to 1 and 15 and compare accuracy.
- Calculate accuracy by hand from the confusion matrix.
Summary
Accuracy = correct ÷ total. Compute it with accuracy_score and always look at the confusion matrix, especially when classes are imbalanced.
Next: Precision
Machine Learning Tutorials, Courses and Certifications