Data Stream Mining, Imbalanced Learning, Algorithmic Fairness

We first process an oil-price stream under memory constraints, then study online learning, imbalanced classification, synthetic data, and fairness.

Data:

Setup and dataset access

Install dependencies once.

%pip install -q \
    "numpy==2.2.6" \
    "numba>=0.61,<0.62" \
    river \
    scikit-learn \
    imbalanced-learn \
    fairlearn \
    aif360 \
    sdv \
    ctgan \
    bitarray

Download the oil-price dataset from HERE, remove missing prices, and parse dates. The same cleaned observations are used for subsequent stream experiments.

Check: Are dates sorted, and how many rows were excluded?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path

# If already downloaded, use the local file. Otherwise, use KaggleHub.
oil_file = Path('oil.csv')
if not oil_file.exists():
    import kagglehub
    try:
        oil_file = Path(kagglehub.competition_download(
            'store-sales-time-series-forecasting', path='oil.csv'))
    except Exception as exc:
        print('Kaggle access requires authentication and accepted competition rules.')
        print('Run kagglehub.login() and retry, or upload oil.csv to Colab.')
        raise

df_oil = pd.read_csv(oil_file).dropna(subset=['dcoilwtico']).reset_index(drop=True)
df_oil['date'] = pd.to_datetime(df_oil['date'])
print(f'{len(df_oil)} valid oil-price observations')
display(df_oil.head())

Data Streams

Simulating a data stream

A stream is consumed incrementally; the entire history need not be retained. Here we use oil.csv as an ordered source of observations.

Exercise: Read the file one record at a time, skip missing dcoilwtico, and build a DataFrame. Compare the result with pd.read_csv(...).dropna(...).

What this does: csv.DictReader consumes one row at a time, mimicking a stream. The example still accumulates accepted rows to make later comparisons easy. A true bounded-memory processor would not retain records.

import csv

records = []
with open(oil_file, newline='') as stream:
    for row in csv.DictReader(stream):
        if row['dcoilwtico']:
            records.append(row)

df_stream = pd.DataFrame(records)
df_stream['dcoilwtico'] = pd.to_numeric(df_stream['dcoilwtico'])
print(f'Read {len(df_stream)} records incrementally')
display(df_stream.head())

The time-series view reveals changes in the level and variability of oil prices. These changes motivate recent-history windows, but do not alone prove concept drift.

fig, ax = plt.subplots(figsize=(10, 3))
ax.plot(df_oil['date'], df_oil['dcoilwtico'], lw=1)
ax.set(title='Oil price observations over time', xlabel='Date', ylabel='Oil price')
plt.tight_layout(); plt.show()

Interpretation: Look for periods of change. The time ordering motivates window-based monitoring.

This plot alone does not establish concept drift.

Reservoir Sampling

Reservoir sampling is a randomized algorithm for selecting $k$ samples from a list of $n$ items.

The number of selected values $k$ is usually much smaller than the total number of elements in the list $n$.

In data streams, the total number of elements is unknow.

Typically, $n$ is large enough such that the data cannot fit into active memory.

We will assume the oil price as a stream of $n$ records, and we need to to select $k$ records where $1 \le k \le n$. We will also read the records from the csv file one-by-one and ignore the lines with no value for the dcoilwtico attribute.

[TODO] Implement reservoir sampling

Keep exactly $k=10$ observations while scanning the stream. Inspect the reservoir after every 100 valid observations.

Question: Does a reservoir represent the entire history or mainly recent records?

What this does: Reservoir sampling keeps at most k records. At each new observation, a randomly selected previous entry may be replaced, giving all seen observations equal inclusion probability.

import random

rng = random.Random(42)

# ------------------- #
# YOUR CODE
# ------------------- #

How to interpret the plot: Compare the shape of the reservoir histogram with the full-history histogram. Large differences are plausible for k=10.

They are sampling variability, not necessarily a bug.

fig, ax = plt.subplots(figsize=(8, 3))
ax.hist(df_oil['dcoilwtico'], bins=25, density=True, alpha=.5, label='All observations')
ax.hist([float(r[1]) for r in reservoir], bins=10, density=True, alpha=.5, label='Reservoir (k=10)')
ax.set(title='Historical distribution vs small reservoir', xlabel='Oil price', ylabel='Density')
ax.legend(); plt.tight_layout(); plt.show()

Interpretation: A reservoir is a uniform sample of previously seen records; with only 10 observations, its histogram may be noisy. Try $k=50$ and $k=100$.

Windowing Models

Another approach for processing data streams is to look at a fixed length (Window) of the last $k$ elements from the stream. We will combine the windowing model with estimating the probability density function of the values to learn the data distribution. We will use the kernel density estimation to estimate the density of the oil price. For more information about using the kernel density estimator can be found in the scikit learn documentation about 1D Kernel Density Estimation

[TODO] Compare sliding, hopping and tumbling windows

Compare sliding, hopping, and tumbling windows by changing step relative to window_size: sliding (step=1), hopping (1 < step < window_size), and tumbling (step=window_size).

How does window size change responsiveness versus stability? Plot only a manageable number of windows.

What this does: Compare the empirical oil-price distributions in successive fixed-length windows. Each curve uses the same histogram bins so changes in the distribution can be compared fairly. Unlike KDE, this version avoids a scikit-learn import.

# ------------------- #
# YOUR CODE
# ------------------- #

Question: How does a shorter window affect responsiveness and statistical stability? Compare step=1, 100, and window_size (reduce plotting frequency for small steps).

Creating Hashtable for the Data Stream

Hashing is an important technique for filtering data streams. In this exercise, we will work on simple techniques for hasing the data streams. Again, we will not use pd.read_csv to read the csv file of the oil dataset. Instead, we will read it line-by-line and parse each line, convert the values of dcoilwtico from strings to float and process the records one-by-one. We will ignore the records that have empty string in the dcoilwtico attribute.

First, we will create a numpy array of size (array_size = 4096) and type boolean to hash the values in the column dcoilwtico. We will initialize the boolean array to false (each element will be initializzed to False). When an element is hashed to an index $i$, we store True at that index of the array.

Second, we will use the hashing function $h(x) = int(x*100) \%\ array\_size$ to hash the elements of dcoilwtico, where the $\%$ represents the modulus function in Python.

Finally, we will keep track of the number of collisions, which represent the cases when as element is hashed to the an index that has been already set to True. Compute the ratio of the number of collisions to the total number of elements in the attribute dcoilwtico.

Why do we have a large ratio of collisions?

[TODO] Hash collisions

For array sizes 1,024 and 4,096, hash each oil price using int(price * 100) % array_size. Count occupied slots, repeated-slot encounters, and elapsed time. Distinguish hash collisions (different values sharing a slot) from repeated observations (the same value returning).

What this does: Hash each price into a fixed-size table and count repeated slot encounters. A repeated slot can be caused by the same price or by a collision between different prices; the bucket inspection separates the two.

# ------------------- #
# YOUR CODE
# ------------------- #

Read the chart: Compare repeated-slot encounter rates across table sizes. Increasing the table size can reduce collisions, but repeated identical observations still revisit the same slot.

ax = hash_summary.plot.bar(x='array_size', y='slot_ratio', legend=False, figsize=(6, 3))
ax.set(title='Repeated-slot encounter rate', xlabel='Hash array size', ylabel='Fraction of observations')
plt.tight_layout(); plt.show()
[TODO] Find a collision

Find a bucket containing different prices and verify that they map to the same hash key.

What this does: Find two distinct oil prices assigned to the same hash bucket. This demonstrates why a hash slot is not an exact identifier.

# ------------------- #
# YOUR CODE
# ------------------- #

Insight: Hashing can map distinct inputs to the same slot. A Boolean hash array alone cannot identify which original value was seen.

[TODO] Exact distinct values

Use a Python set to track exact distinct oil prices and compare runtime with the hash approach. Unlike a fixed-size Boolean array, a set can grow with the number of distinct values.

What this does: A Python set records exact distinct values. Compare its exactness and memory behavior with a fixed-size hashed occupancy structure.

# ------------------- #
# YOUR CODE
# ------------------- #

We can see that the time for using the set structure is faster than using the Boolean array. Moreover, for the set we do not have the collision problem. However, the set might be extremely large, which makes it an impractical solution. We can use bitarray to speed up the hashing process and reduce the required space. Instead of using one byte for each Boolean value, we will use only one bit in this case. You will need to install bitarray library. Check this website for more information about using bitarray.

[TODO] Compact bit arrays

Repeat hashing using bitarray and compare memory use. The bit array stores occupancy only; the optional bucket dictionary still consumes memory.

What this does: A bit array uses one bit per slot and is memory-efficient for occupancy tracking. It does not reconstruct the original price or resolve collisions.

# ------------------- #
# YOUR CODE
# ------------------- #
Classifying Data Streams

Online processing of data streams is important as the data cannot be stored in the memory so we need to process one element at a time. Moreover, we need to process each element only once. In the case of machine learning, we need to train the models using one sample at a time. This is completely opposite to the traditional way of training the ML models where the models are trained on a whole training set at the same time.

An online model is therefore a stateful, dynamic object. It keeps learning and doesn't have to revisit past data. For this exercise, you may use the river libray and run some of the online examples such as Binary classification and HoeffdingTreeClassifier. You may check a set performance measures that they defined and use them (e.g. ROCAUC, Accuracy).

Online learning: A Hoeffding tree updates incrementally, one observation at a time. Progressive evaluation predicts first and then learns, avoiding evaluation on the same observation after training.

What this does: The Hoeffding tree predicts each incoming observation and then updates using its true label (prequential evaluation). The learning curve shows how predictive performance evolves.

%pip install numpy
from river.datasets import synth
from river import metrics, tree

stream = synth.Agrawal(classification_function=0, seed=42).take(1000)
model = tree.HoeffdingTreeClassifier(grace_period=100, delta=1e-5,
                                    nominal_attributes=['elevel', 'car', 'zipcode'])
acc, balanced, precision, auc = metrics.Accuracy(), metrics.BalancedAccuracy(), metrics.Precision(), metrics.ROCAUC()
steps, accuracy_history, balanced_history = [], [], []
for i, (x, y) in enumerate(stream, start=1):
    pred = model.predict_one(x)
    proba = model.predict_proba_one(x)
    if pred is not None:
        for metric in (acc, balanced, precision): metric.update(y, pred)
        if proba: auc.update(y, proba)
    model.learn_one(x, y)
    if i % 25 == 0:
        steps.append(i); accuracy_history.append(acc.get()); balanced_history.append(balanced.get())
print(acc, '\n', balanced, '\n', precision, '\n', auc)
plt.figure(figsize=(8, 3))
plt.plot(steps, accuracy_history, label='Accuracy')
plt.plot(steps, balanced_history, label='Balanced accuracy')
plt.xlabel('Observations processed'); plt.ylabel('Progressive metric')
plt.title('Online model quality over the stream'); plt.legend(); plt.tight_layout(); plt.show()

Question: Does performance stabilize as more examples arrive? Why might accuracy conceal errors on a rare class?

SMOTE for Balancing Data
from collections import Counter
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import (accuracy_score, balanced_accuracy_score, f1_score,
                             confusion_matrix, ConfusionMatrixDisplay, classification_report)
from aif360.datasets import GermanDataset
from aif360.metrics import BinaryLabelDatasetMetric
from aif360.algorithms.preprocessing.lfr import LFR

Why start with this plot? The synthetic dataset has a heavily underrepresented positive class. Visualize the original imbalance before changing the training distribution.

# Oversample and plot imbalanced dataset with SMOTE
from collections import Counter
from sklearn.datasets import make_classification
from imblearn.over_sampling import SMOTE
from matplotlib import pyplot as plt
from numpy import where

# define dataset
X_org, y_org = make_classification(n_samples=10000, n_features=2, n_redundant=0,
	n_clusters_per_class=1, weights=[0.99], flip_y=0, random_state=1)

# summarize class distribution
counter = Counter(y_org)
print("Before Running SMOTE: ", counter)
for label, _ in counter.items():
	row_ix = where(y_org == label)[0]
	plt.scatter(X_org[row_ix, 0], X_org[row_ix, 1], label=str(label))
plt.legend()
plt.show()

What this does: Split into training and test sets before resampling. The untouched test set estimates performance on the original class distribution.

X_train, X_test, y_train, y_test = train_test_split(
    X_org, y_org, test_size=0.3, random_state=42, stratify=y_org)
print('Train:', Counter(y_train), 'Test:', Counter(y_test))

What this does: Fit a baseline logistic regression and inspect its confusion matrix. Accuracy alone may conceal poor minority-class recall.

baseline = LogisticRegression(max_iter=1000, random_state=42).fit(X_train, y_train)
result = baseline.predict(X_test)
ConfusionMatrixDisplay.from_predictions(y_test, result, labels=[0, 1]); plt.title('Baseline'); plt.show()
def evaluate_predictions(name, truth, pred):
    return {'method': name, 'accuracy': accuracy_score(truth, pred),
            'balanced_accuracy': balanced_accuracy_score(truth, pred),
            'minority_f1': f1_score(truth, pred, pos_label=1, zero_division=0),
            'minority_recall': (pred[truth == 1] == 1).mean()}

results = [evaluate_predictions('Baseline', y_test, result)]
display(pd.DataFrame(results))

What this does: SMOTE synthesizes minority-class examples using neighbors from the training split only. The test data must remain unchanged.

from imblearn.over_sampling import SMOTE

X_OS, y_OS = SMOTE(random_state=42).fit_resample(X_train, y_train)
print('Before:', Counter(y_train), '| After SMOTE:', Counter(y_OS))

What this does: Train the same classifier on the SMOTE-balanced training data. Comparing with the baseline isolates the effect of the training-data intervention.

smote_model = LogisticRegression(max_iter=1000, random_state=42).fit(X_OS, y_OS)
result_smote = smote_model.predict(X_test)
ConfusionMatrixDisplay.from_predictions(y_test, result_smote, labels=[0, 1]); plt.title('SMOTE'); plt.show()

Compare: Look beyond accuracy: did minority recall improve, and what happened to precision and balanced accuracy?

results.append(evaluate_predictions('SMOTE', y_test, result_smote))
display(pd.DataFrame(results))

Interpretation: Compare minority recall and precision-related metrics. More positive predictions do not automatically mean better decisions. The test set must remain untouched by SMOTE.

The classifier tend to classify more examples as negative than before so it is predicting more samples from the minority class. Keep this in mind so you can apply it for the fairness

Note That: SMOTE treats all the variables as numerical values from a continuous random variable. If you have categorical data, then you can use SMOTENC for mixed set of features (continuous, categorical) from the imblearn.over_sampling package.

Synthetic data generation

C-GAN: Generate Synthetic Data

CTGAN model is based on the GAN-based Deep Learning data synthesizer.

The main idea here is to generate a tabular data, the ctgan can be used to generate any number of data set (All types). After training the ctgan on the fitted dataset, the model will be ready to generate samples and take care about:

  1. Primary_key

  2. Non-redundant values of special features e.x. the addresses.

CTGAN model is based on the GAN-based Deep Learning data synthesizer

The architecture is comprised of a generator and a discriminator model. The generator model is responsible for generating new plausible examples that ideally are indistinguishable from real examples in the dataset. The discriminator model is responsible for classifying a given image as either real (drawn from the dataset) or fake (generated).

The models are trained together in a zero-sum or adversarial manner, such that improvements in the discriminator come at the cost of a reduced capability of the generator, and vice versa.

CTGAN experiment: Train the generator on the training split only, condition on the minority label by learning from minority-class rows, and compare against SMOTE on the original test set. The standalone ctgan.CTGAN does not support sample(..., conditions=...).

What this does: Fit a standalone CTGAN on minority-class training records, generate additional minority examples, and retrain the classifier. Synthetic quality and downstream utility are separate questions.

from ctgan import CTGAN

minority_train = pd.DataFrame(X_train[y_train == 1], columns=['x1', 'x2'])
needed = int((y_train == 0).sum() - (y_train == 1).sum())
generator = CTGAN(epochs=50, verbose=False)
generator.fit(minority_train)
synthetic_minority = generator.sample(needed)

X_train_GAN = np.vstack([X_train, synthetic_minority[['x1', 'x2']].to_numpy()])
y_train_GAN = np.r_[y_train, np.ones(needed, dtype=int)]
gan_model = LogisticRegression(max_iter=1000, random_state=42).fit(X_train_GAN, y_train_GAN)
result_GAN = gan_model.predict(X_test)
results.append(evaluate_predictions('CTGAN', y_test, result_GAN))
display(pd.DataFrame(results))

Interpretation: Overlaying real and generated minority examples can reveal implausible regions or missing modes, but visual similarity is not sufficient to establish synthetic-data quality.

fig, ax = plt.subplots(figsize=(7, 4))
ax.scatter(minority_train['x1'], minority_train['x2'], s=10, alpha=.3, label='Real minority')
ax.scatter(synthetic_minority['x1'], synthetic_minority['x2'], s=10, alpha=.2, label='Synthetic minority')
ax.set(title='CTGAN: real vs synthetic minority observations', xlabel='x1', ylabel='x2')
ax.legend(); plt.tight_layout(); plt.show()

Question: Do synthetic observations cover plausible regions? A similar scatter plot is not proof of statistical fidelity or improved downstream performance.

Cost sensitive classification

What this does: Assign a larger training penalty to errors on the positive class. Class weights change the fitted decision boundary.

They are not the same as choosing a deployment threshold.

cost_model = LogisticRegression(class_weight={0: 0.1, 1: 9.9}, max_iter=1000, random_state=42)
cost_model.fit(X_train, y_train)
result_CS = cost_model.predict(X_test)
ConfusionMatrixDisplay.from_predictions(y_test, result_CS, labels=[0, 1]); plt.title('Cost-sensitive model'); plt.show()

Question: The original example computes 120/200 and 480/700. What do these ratios represent, and are they comparable? For classification, use a defined confusion-matrix denominator and an explicit error-cost assumption.

Decision point: Compare all methods on the same held-out test set. Choose based on the relevant false-negative/false-positive trade-off, not just a single score.

results.append(evaluate_predictions('Cost-sensitive', y_test, result_CS))
comparison = pd.DataFrame(results).set_index('method')
display(comparison)
comparison[['balanced_accuracy', 'minority_recall', 'minority_f1']].plot.bar(figsize=(8, 3), rot=20)
plt.ylim(0, 1); plt.title('Methods on the same untouched test set'); plt.tight_layout(); plt.show()

Interpretation: A higher minority recall can come at the expense of more false positives. The preferred model depends on the application's error costs.

Algorithmic Fairness

In this Exercise, we will learn about measuring the fairness metrics and applying fairness mitigation algorithms.

First, we read the German dataset and replace the class label 2 by 0.

Dataset access: AIF360 expects the German Credit raw files in its package data directory. This cell downloads the original public files when absent.

What this does: Retrieve the German Credit raw files required by AIF360. The original dataset is a separate fairness case study rather than part of the oil-price stream.

import os
import urllib.request
import aif360

# Locate AIF360 installation
aif360_path = os.path.dirname(aif360.__file__)

# Create dataset directory
data_dir = os.path.join(aif360_path, "data", "raw", "german")
os.makedirs(data_dir, exist_ok=True)

# Download required files
base_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/"

for filename in ["german.data", "german.doc"]:
    destination = os.path.join(data_dir, filename)

    if not os.path.exists(destination):
        urllib.request.urlretrieve(
            base_url + filename,
            destination
        )
        print(f"Downloaded: {filename}")

print("German Credit dataset ready!")
german_data = GermanDataset()
german_df = german_data.convert_to_dataframe()
german_df = german_df[0]
german_df

What this does: Inspect the German Credit records and outcome distribution before computing fairness metrics. Keep the label coding consistent with AIF360.

german_data = GermanDataset()
german_df = german_data.convert_to_dataframe()[0].copy()
german_df['credit'] = german_df['credit'].replace({2.0: 0})
display(german_df.head())

Fairness setup: The original exercise defines the privileged group as sex=1 AND age=1 and the unprivileged group as sex=0 AND age=0.

These are intersectional groups, not all records, other combinations are excluded from the two-group comparison.

privileged_groups = [{'sex': 1, 'age': 1}]
unprivileged_groups = [{'sex': 0, 'age': 0}]

What this does: Compute dataset-level group-rate fairness metrics using the privileged/unprivileged definitions above. These metrics describe labels in the dataset, not the errors of a trained classifier.

metric_orig = BinaryLabelDatasetMetric(german_data,
                                              unprivileged_groups=unprivileged_groups,
                                              privileged_groups=privileged_groups)
print("Disparate impact (of original labels) between unprivileged and privileged groups = %f" % metric_orig.disparate_impact())
print("Difference in statistical parity (of original labels) between unprivileged and privileged groups = %f" % metric_orig.statistical_parity_difference())
print("Individual fairness metric that measures how similar the labels are for similar instances = %f" % metric_orig.consistency())

Read the chart: Group sample sizes matter when interpreting differences in observed positive-label rates. Small groups yield less stable estimates.

group_rates = (german_df.groupby(['sex', 'age'])['credit']
               .agg(['mean', 'count']).reset_index())
group_rates['group'] = group_rates[['sex', 'age']].astype(str).agg(' / '.join, axis=1)
ax = group_rates.plot.bar(x='group', y='mean', legend=False, figsize=(7, 3))
ax.set(title='Observed favorable-label rate by intersectional group', xlabel='Sex / age', ylabel='Positive-label rate')
plt.tight_layout(); plt.show()

Interpretation: Statistical parity and disparate impact describe group label rates; they do not by themselves establish whether a model is discriminatory. Consider base rates and sample sizes.

What this does: Prepare a supervised learning split for the German Credit case study. All comparisons should use the same held-out test data.

X_ger = german_df.drop(columns='credit')
y_ger = german_df['credit'].astype(int)
X_train_g, X_test_g, y_train_g, y_test_g = train_test_split(
    X_ger, y_ger, test_size=0.3, random_state=42, stratify=y_ger)

What this does: Fit a baseline credit classifier and inspect classification errors. This is a predictive-performance baseline, not a fairness-mitigation result.

german_model = LogisticRegression(max_iter=2000).fit(X_train_g, y_train_g)
result_LR = german_model.predict(X_test_g)
ConfusionMatrixDisplay.from_predictions(y_test_g, result_LR, labels=[0, 1]); plt.title('German Credit baseline'); plt.show()
print(classification_report(y_test_g, result_LR, zero_division=0))

Fairness mitigation - Learning Fair Representations (LFR): LFR learns a transformed representation balancing reconstruction, prediction, and group-fairness objectives. Compare the transformed labels with the original labels; transformation alone does not guarantee improved downstream decisions.

What this does: Learn a transformed representation with LFR. This experiment evaluates a preprocessing intervention; downstream fairness should be assessed separately on predictions.

dataset_orig_train, dataset_orig_test = german_data.split([0.7], shuffle=True, seed=42)
scale_orig = StandardScaler()
dataset_orig_train.features = scale_orig.fit_transform(dataset_orig_train.features)
dataset_orig_test.features = scale_orig.transform(dataset_orig_test.features)
lfr_model = LFR(unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups,
                k=5, Ax=0.1, Ay=1.0, Az=100.0, verbose=0)
lfr_model.fit(dataset_orig_train, maxiter=1000, maxfun=1000)
dataset_transf_train = lfr_model.transform(dataset_orig_train)
changed = np.count_nonzero(dataset_transf_train.labels != dataset_orig_train.labels)
print(f'Labels changed after LFR: {changed} / {len(dataset_orig_train.labels)}')

What this does: Measure statistical parity, disparate impact, and consistency on the transformed training data. Interpret these as descriptive metrics, not proof of fair decisions.

#Fairness Performance of Datasets Before Classification

#Constucting two functions to call the desired metrics
metric_transf_train = BinaryLabelDatasetMetric(dataset_transf_train,
                                             unprivileged_groups = unprivileged_groups,
                                             privileged_groups = privileged_groups)

print("Disparate impact ratio (of transformed labels) between unprivileged and privileged groups = %f" % metric_transf_train.disparate_impact())
print("Difference in statistical parity (of transformed labels) between unprivileged and privileged groups = %f" % metric_transf_train.statistical_parity_difference())
print("Individual fairness metric 'consistency' that measures how similar the labels are for similar instances = %f" % metric_transf_train.consistency())
Using C-GAN for Generating Synthetic data from the German Dataset
from ctgan import CTGAN
print('Using standalone CTGAN, fit requires a DataFrame.')

We will generate values such that the number of records that have:

  • 0 in 'sex' & 0 in class label,

  • 0 in 'sex' & 1 in class label,

  • 1 in 'sex' & 0 in class label, AND 1 in 'sex' & 1 in class label will be the same

What this does: Create an intersectional label encoding combinations of sex and credit outcome. This makes it possible to inspect how well each subgroup is represented.

ger_df = german_df.copy()
ger_df['sub_labels'] = (2 * ger_df['sex'].astype(int) + ger_df['credit'].astype(int) + 1)
ger_df = ger_df.drop(columns=['sex', 'credit'])
print('Intersectional categories:', sorted(ger_df['sub_labels'].unique()))
display(ger_df['sub_labels'].value_counts().sort_index())

CTGAN note: To oversample specific sub_labels, the standalone CTGAN API cannot accept a conditions argument to sample(). We fit a separate generator to each group's features instead. Small groups can be difficult to model reliably.

What this does: Count the original intersectional groups and set a target group size. Equal counts are an experimental balancing target, not a guarantee of fairness.

target_attribute = 'sub_labels'
counts_before = ger_df[target_attribute].value_counts().sort_index()
target_rows = int(counts_before.max())
print('Original group sizes:')
display(counts_before)

What this does: Fit a separate CTGAN to each underrepresented group and append generated records. The method may be unreliable for very small groups, so inspect fidelity and evaluate downstream results on real data.

synthetic_groups = []
feature_columns = ger_df.columns.drop(target_attribute).tolist()
for key, count in counts_before.items():
    needed = target_rows - int(count)
    if needed <= 0:
        continue
    group_features = ger_df.loc[ger_df[target_attribute] == key, feature_columns]
    group_generator = CTGAN(epochs=50, verbose=False)
    group_generator.fit(group_features)
    new_rows = group_generator.sample(needed)
    new_rows[target_attribute] = key
    synthetic_groups.append(new_rows[ger_df.columns])

ger2_df = pd.concat([ger_df, *synthetic_groups], ignore_index=True)
ger2_df = ger2_df.sample(frac=1, random_state=42).reset_index(drop=True)
counts_after = ger2_df[target_attribute].value_counts().sort_index()
display(pd.DataFrame({'Before': counts_before, 'After': counts_after}))

Read the plot: Verify that the intended group counts increased. This demonstrates count balancing only; it does not establish predictive improvement or fairness.

pd.DataFrame({'Before': counts_before, 'After': counts_after}).plot.bar(figsize=(7, 3), rot=0)
plt.title('Intersectional group sizes before vs after CTGAN')
plt.xlabel('Combined sex / credit group code'); plt.ylabel('Records')
plt.tight_layout(); plt.show()

Question: Does balancing group counts ensure fairness? No: group sizes, predictive quality, and fairness metrics are different properties. Evaluate any trained model on real held-out data.

Optional persistence: The standalone ctgan.CTGAN class does not expose the old SDV .save() method. Save a fitted generator with pickle only if you trust the source when loading it.

import pickle
'''
Example (uncomment only if you have trained a model you want to retain):
with open('ctgan_group_model.pkl', 'wb') as f:
    pickle.dump(group_generator, f)
'''