CodeBlanks Logo Icon CodeBlanks

Accuracy

Accuracy is the most common classification metric.

Accuracy and error rate

Accuracy = (TP + TN) / total. Its opposite is the error rate: 1 - accuracy. It is computed directly from the confusion matrix:

cm = confusion_matrix(y_true, y_pred)
dogruluk = np.trace(cm) / cm.sum()   # diagonal / total

np.trace is the sum of the diagonal elements; in a multi-class matrix it also gives the number of correct predictions.

Balanced accuracy

On imbalanced data balanced accuracy is the mean of each class's accuracy within itself; a model predicting the majority class gets 0.5:

from sklearn.metrics import balanced_accuracy_score
y_true = [0] * 9 + [1]
y_pred = [0] * 10
print(accuracy_score(y_true, y_pred))           # 0.9
print(balanced_accuracy_score(y_true, y_pred))  # 0.5

If imbalanced data must be summarised with a single number, it is more honest than plain accuracy.

Practice Two accuracies

For the given labels, print accuracy_score and balanced_accuracy_score with round(..., 3) on separate lines.

Starter code

model.py
from sklearn.metrics import accuracy_score, balanced_accuracy_score

y_true = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]
y_pred = [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]

# buraya yaz

Sample solution

model.py
from sklearn.metrics import accuracy_score, balanced_accuracy_score

y_true = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]
y_pred = [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]

print(round(accuracy_score(y_true, y_pred), 3))
print(round(balanced_accuracy_score(y_true, y_pred), 3))

Expected output

0.9
0.75

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If TP=40, TN=45, FP=5, FN=10, what is the accuracy?

  • 0.45
  • 0.85 Correct answer
  • 0.80
  • 0.90

Explanation: (40 + 45) / 100 = 0.85.

2 Take the diagonal sum of the matrix.

Question
dogru = np.____(cm)
Answer
dogru = np.trace(cm)

Explanation: trace adds up the diagonal elements.

3 Match the metrics.

Term Meaning
accuracy (TP+TN)/total
error rate 1 - accuracy
balanced accuracy Mean of class accuracies
np.trace(cm) Number of correct predictions

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation