TExcelTAD

Class Distribution

How many samples does each class have? The question is simple, and its answer changes how you split, train and evaluate. Many real problems are imbalanced: fraud is a fraction of a percent of payments, a rare disease a few cases per thousand patients, defective parts a handful per production run. A model trained on such data can look excellent by a careless measure while being useless for the one class that matters.

Counting classes

The basic numbers are the count and share of each class, and the imbalance ratio between the largest and the smallest class:

IR=nmax⁡nmin⁡\text{IR} = \frac{n_{\max}}{n_{\min}}

A ratio of 1 is perfectly balanced. Up to about 3 rarely causes trouble; beyond 10 it needs attention; fraud and fault detection often reach 100 to 1000.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer, make_classification

def class_table(y, names=None):
    counts = pd.Series(y).value_counts().sort_index()
    if names is not None:
        counts.index = [names[i] for i in counts.index]
    table = pd.DataFrame({"count": counts, "share": (counts / counts.sum()).round(3)})
    return table, counts.max() / counts.min()

bc = load_breast_cancer()
table, ir = class_table(bc.target, bc.target_names)
print(table)
print(f"imbalance ratio {ir:.2f}\n")

X, y = make_classification(n_samples=5000, weights=[0.98, 0.02], flip_y=0, random_state=0)
table, ir = class_table(y, ["legit", "fraud"])
print(table)
print(f"imbalance ratio {ir:.1f}")
           count  share
malignant    212  0.373
benign       357  0.627
imbalance ratio 1.68

       count  share
legit   4900   0.98
fraud    100   0.02
imbalance ratio 49.0

The breast cancer data is mildly imbalanced (1.68 benign cases per malignant one). The synthetic fraud data, with an imbalance ratio of 49, is strongly imbalanced, like real fraud data.

Why accuracy misleads

On data with 98% "legit", a model that always says "legit" is 98% accurate and catches no fraud at all. Every evaluation of an imbalanced problem should start by computing this majority baseline, and should report per-class measures such as recall (the share of real frauds that are caught) and precision (the share of alarms that are real frauds):

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, recall_score, precision_score
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=5000, n_features=10, n_informative=4, weights=[0.98, 0.02],
                           flip_y=0, class_sep=1.5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

for name, model in [("always 'legit'", DummyClassifier(strategy="most_frequent")),
                    ("logistic regression", LogisticRegression(max_iter=1000))]:
    pred = model.fit(X_tr, y_tr).predict(X_te)
    print(f"{name:20} accuracy {accuracy_score(y_te, pred):.3f}  "
          f"fraud recall {recall_score(y_te, pred):.3f}  "
          f"fraud precision {precision_score(y_te, pred, zero_division=0):.3f}")
print("frauds in the test set:", int(y_te.sum()), "of", len(y_te))
always 'legit'       accuracy 0.980  fraud recall 0.000  fraud precision 0.000
logistic regression  accuracy 0.983  fraud recall 0.133  fraud precision 1.000
frauds in the test set: 30 of 1500

The do-nothing baseline reaches 0.980 accuracy without catching a single fraud. The logistic regression is barely more accurate (0.983) and catches 4 of the 30 frauds in the test set, a recall of 0.133. Every alarm it raises is a real fraud (precision 1.000), but 26 frauds slip through. Accuracy alone shows none of this. The Training & Evaluation course covers the right metrics (precision, recall, F1, PR curves) in depth.

The imbalance lab

The lab below has 200 points of class A (blue) and a variable number of class B (orange), and fits a logistic regression with the usual threshold of 0.5. It scores the model on a separate test set with the same imbalance. Start with the default, 15 minority points (an imbalance ratio of about 13) and no remedy:

−2024−2024x₁x₂Remedy: noneplain logistic regressionA (200)B (15)p(B) = 0.5Test set: 1000 A, 75 Bpred. Bpred. Aactual Bactual A39TP36FN8FP992TNRecall of B0.520Precision for B0.830Accuracy0.959

With 15 minority points, the model reaches an accuracy of 0.959 on the 1,075 test points but finds only 39 of the 75 test points of class B, a recall of 0.520: the boundary sits close to the minority cloud, because errors on the 200 majority points dominate the training loss. Move nMin down to 5 and accuracy goes up to 0.976 while the recall collapses to 0.120 (3 of 25): the rarer the class, the more the plain model ignores it, and the better its accuracy looks.

Now switch Remedy to class weights, which make both classes count equally in training. At 15 minority points, recall rises to 0.867 (65 of 75), precision drops from 0.830 to 0.464 and accuracy to 0.921: more frauds caught, more false alarms. Which balance is right depends on the cost of each kind of error, a business decision. The remedies themselves (weights, oversampling, SMOTE, undersampling, threshold moving) are taught in Data Preparation; what matters here is to measure the imbalance and to evaluate with per-class metrics.

Stratified splits

With a rare class, a random train/test split can leave the test set with very few minority samples, or a different share than the training set. A stratified split keeps the class shares the same in every part:

python · try it yourself
import numpy as np
from sklearn.model_selection import train_test_split

y = np.array([0] * 485 + [1] * 15)              # 15 minority samples in 500
X = np.arange(len(y)).reshape(-1, 1)

random_counts = [int(train_test_split(X, y, test_size=0.2, random_state=s)[3].sum()) for s in range(10)]
strat_counts = [int(train_test_split(X, y, test_size=0.2, random_state=s, stratify=y)[3].sum()) for s in range(10)]
print("minority samples in a 100-sample test set, 10 random splits:    ", random_counts)
print("minority samples in a 100-sample test set, 10 stratified splits:", strat_counts)
minority samples in a 100-sample test set, 10 random splits:     [3, 4, 2, 2, 3, 2, 3, 3, 1, 5]
minority samples in a 100-sample test set, 10 stratified splits: [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

The random splits put anywhere from 1 to 5 of the 15 minority samples into the test set, so the measured minority recall would jump around from split to split; the stratified splits always put exactly 3 there, the expected 20%. Use stratified splits (and stratified cross-validation) for classification as a default, and always print the class counts of every split.

Many classes: the long tail

With many classes, the distribution often has a long tail: a few classes with many samples and many classes with very few. Product categories, species in camera-trap photos, diagnosis codes and words in a vocabulary all look like this:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

ranks = np.arange(1, 41)
counts = np.round(2000 / ranks ** 1.3).astype(int)           # a Zipf-like tail over 40 classes
s = pd.Series(counts, index=[f"c{r:02}" for r in ranks])
print("total samples:", s.sum(), "| classes:", len(s))
print("share of samples in the top 5 classes:", round(s.head(5).sum() / s.sum(), 3))
print("classes with fewer than 50 samples:", int((s < 50).sum()))
print("imbalance ratio:", round(s.max() / s.min(), 1))

fig, ax = plt.subplots(figsize=(7, 3))
ax.bar(range(len(s)), s.values)
ax.set_yscale("log")
ax.set_xlabel("class (sorted by size)")
ax.set_ylabel("samples (log scale)")
ax.set_title("A long-tailed class distribution")
fig.tight_layout()
plt.show()
total samples: 5667 | classes: 40
share of samples in the top 5 classes: 0.683
classes with fewer than 50 samples: 23
imbalance ratio: 117.6

The top 5 of the 40 classes hold 68.3% of the samples, while 23 classes have fewer than 50 each; the imbalance ratio is 117.6. The tail classes are where models fail first. Report per-class results (at least for the smallest classes), and check whether the tail classes have enough samples in the test set to measure anything at all: a class with 3 test samples gives a recall of 0, 0.33, 0.67 or 1, nothing in between.

Pitfalls

  • Accuracy on imbalanced data: always compare with the majority baseline and look at per-class metrics.
  • Non-stratified splits: the minority class can almost vanish from a test set.
  • Rebalancing before splitting: oversampling must happen on the training part only, or copies of the same minority sample end up in both sets.
  • Different distributions in training and real use: a dataset collected to be balanced (50% fraud) does not reflect production (0.2% fraud); precision measured on it will be far too optimistic.

Practice

  1. A dataset has 9,900 negatives and 100 positives. What is the imbalance ratio, and what accuracy does the majority baseline reach?
Answer

IR=9900/100=99\text{IR} = 9900/100 = 99. Always predicting "negative" is right on 9,900 of 10,000 samples: an accuracy of 0.99, with a recall of 0 for the positives.

  1. In the lab, set nMin to 50 with no remedy, then with class weights. What happens to recall and precision?
Answer

Without a remedy, recall is 0.708 (177 of 250) and precision 0.819. With class weights, recall rises to 0.884 (221 of 250) and precision falls to 0.711. With less imbalance, the plain model already does better, and the remedy changes less.

Test yourself

On data with 99% negatives, a model has 99% accuracy. What do you know about it?

  1. It is excellent
  2. Nothing useful yet: always predicting 'negative' gives the same accuracy
  3. It has high recall
  4. It is overfitting

What does a stratified split guarantee?

  1. The same number of samples in train and test
  2. The same class proportions in every part
  3. No duplicates
  4. Balanced classes

In the lab, adding class weights increased minority recall and lowered precision. Why?

  1. The model got worse in every way
  2. The boundary moved towards the majority class: more minority points are caught, and more majority points are wrongly flagged
  3. Weights change the test set
  4. Precision and recall always move together

What is the imbalance ratio of a dataset with classes of 600, 300 and 50 samples?

  1. 2
  2. 6
  3. 12
  4. 950