We are going to design a label propagation experiment suite that evaluates:
- Graph-based methods: compare different graph construction methods (e.g., k-NN, epsilon-ball, mutual k-NN) and label propagation algorithms (e.g., standard LP, CLP, CLP with normalisation, etc.)
- Confidence scores: evaluate the quality of confidence scores produced by the methods (e.g., using calibration metrics like ECE, MCE, or reliability diagrams) and also how they correlate with accuracy.
- Lift: evaluate the lift in performance when using the confidence scores to select a subset of the test set (e.g., top-k% most confident predictions) and measure the accuracy on that subset compared to random selection.
Steps:
-
Data: We'll use a set of benchmark datasets (e.g., from UCI, or openML) with both binary and multi-class classification problems. We'll split each dataset into train, validation (if needed) and test.
-
Graph Construction:
- For each dataset, we'll consider multiple graph construction methods:
a. k-NN graph (with k chosen by cross-validation or fixed)
b. epsilon-ball graph (with epsilon chosen by cross-validation or fixed)
c. Mutual k-NN graph (where an edge exists only if both points are in each other's k-NN)
d. Fully connected graph with Gaussian kernel (with bandwidth chosen by cross-validation or fixed)
-
Label Propagation Methods:
- Standard Label Propagation (LP)
- Constrained Label Propagation (CLP) - if we have constraints (but note: in semi-supervised setting we have labeled and unlabeled, so we might not have constraints beyond the initial labels)
- We might also consider variations: with/without normalisation, different weightings (e.g., using the adjacency matrix or a normalized one).
-
Confidence Scores:
- For each method, we can get a confidence score for each test point. In label propagation, the confidence can be the maximum probability in the label distribution (or the difference between the top two, etc.). Alternatively, we can use the normalized graph cut value or other methods.
-
Evaluation:
a. Standard Metrics: Accuracy, Macro-F1 (for multi-class) on the test set.
b. Confidence Evaluation:
- Expected Calibration Error (ECE): bin the predictions by confidence and compute the weighted difference between average confidence and accuracy in each bin.
- Maximum Calibration Error (MCE): the maximum difference over bins.
- reliability diagrams.
- Also, we can compute the correlation (e.g., Spearman) between confidence and correctness (1 if correct, 0 otherwise).
c. Lift Evaluation:
- Sort test points by confidence (descending) and compute the accuracy on the top k% (for k in [1,5,10,...,100]).
- Compare with random selection (which would be the overall accuracy) and compute the lift ratio: (accuracy at top k%) / (random accuracy).
- Plot lift curve (accuracy at top k% vs k) and compute area under the lift curve (AULC).
-
Experimental Setup:
- For each dataset, we'll do multiple random splits (e.g., 10) and average the results.
- We'll use a fixed random seed for reproducibility.
- We'll compare the graph methods and label propagation variants in a factorial design (i.e., all combinations) but note that some graph methods might not be suitable for some datasets (e.g., epsilon-ball might not work well for high-dimensional data). We can also do a grid search for hyperparameters (k, epsilon, bandwidth) on a validation set if we have enough data, or use a fixed set of values.
-
Implementation Details:
- We'll use a library that supports label propagation (e.g., scikit-learn's label_propagation module) and build our own graph construction if needed.
- Alternatively, we can use a graph library (like networkx) to build the graph and then run label propagation.
-
Additional Considerations:
- We should also compare with a baseline (e.g., training a classifier on the labeled data only) to see the benefit of using unlabeled data.
- We might want to vary the amount of labeled data (e.g., 10%, 20%, 50%) to see how the methods perform in low-label regimes.
-
Reporting:
- We'll create tables for accuracy, ECE, MCE, and lift metrics (like AULC) for each method combination.
- We'll also create plots: reliability diagrams for a selected dataset, lift curves for a selected dataset, and maybe boxplots of metrics across datasets.
-
Code Structure:
We can structure the code as follows:
- data_loader.py: loads datasets and does train-test split.
- graph_construction.py: functions to build graphs (knn, epsilon, mutual_knn, fully_connected).
- label_propagation.py: runs label propagation on a given graph and returns labels and confidence scores.
- evaluation.py: computes metrics (accuracy, ECE, MCE, lift, AULC).
- experiment.py: main script that loops over datasets, splits, graph methods, and LP methods, and collects results.
- utils.py: helper functions.
We might also want to have a configuration file (e.g., JSON or YAML) that specifies which datasets, graph methods, LP methods, and hyperparameters to try.
11. Challenges:
- Scalability: label propagation on large graphs can be slow. We might need to use sparse matrices and efficient linear algebra.
- Hyperparameter tuning: we need to avoid overfitting the validation set when choosing k, epsilon, etc. We can use nested cross-validation or a held-out validation set.
12. Extensions:
- We can also evaluate the robustness to noise in the labels (by flipping some labeled points) and see how the methods degrade.
- We can try different ways to compute confidence: e.g., using the entropy of the label distribution, or using the difference between the top two class probabilities.
Given the complexity, we might start with a smaller set of datasets and graph/LP methods.
Let's outline the main steps in the experiment:
For each dataset:
For each random split (e.g., 10):
Split the data into train (with labeled and unlabeled) and test.
For each graph construction method:
Build the graph on the entire training set (labeled+unlabeled) and also include test if we are doing transductive?
But note: in semi-supervised learning, we usually build the graph on all available data (train+test) because we are using the test data as unlabeled during propagation? Actually, in transductive learning we have a fixed set of unlabeled (which includes test). However, in our evaluation we want to simulate the semi-supervised setting where we have a training set (with some labels) and a test set (without labels). But in label propagation, we typically run it on the entire graph that includes both training and test. So we should build the graph on the union of train and test, but we only have labels for the training part.
Steps for one split:
Let X_train_labeled, y_train_labeled, X_train_unlabeled, X_test (with y_test for evaluation only).
Build graph on [X_train_labeled, X_train_unlabeled, X_test] (all available data). Then run label propagation with initial labels only for the training points (and zeros for unlabeled and test?).
After propagation, we get label distributions for every node (including test). Then we assign the test labels as the argmax of the distribution.
We also get confidence scores for the test points (e.g., the maximum probability in the distribution).
Then we evaluate on the test set.
We also want to evaluate the confidence and lift on the test set.
We might also want to run a baseline (supervised) classifier on the labeled training set only and get its confidence scores (e.g., from a RandomForest or LogisticRegression) for comparison.
Then we aggregate over splits and datasets.
However, note that building the graph on the entire dataset (train+test) might leak information because the test points are used in the graph construction. But in transductive settings, this is allowed because we are using all the data (including test) to build the graph. However, if we want to be strict, we could build the graph only on the training set (labeled and unlabeled) and then propagate to the test set by adding them as new nodes (using some method like appending to the graph). But that is more complex and not standard in label propagation. In standard label propagation, we have a fixed graph and we propagate labels on the entire graph. So we'll build the graph on the entire available data (train+test) and then use the known labels for training and predict for test.
Alternatively, we can do:
Step 1: Build graph on training set (labeled+unlabeled) only.
Step 2: Run label propagation on the training graph to get labels for the unlabeled training points.
Step 3: Then we have a fully labeled training set. We can train a supervised classifier on that and predict on test? But that's not the same as label propagation.
The standard transductive setting is: we have a graph on all points (train+test) and we know the labels for some (train). We then propagate and predict for the rest (test). So we'll do that.
But note: when building the graph, we use the features of the test points. So it's not unrealistic because we have the test features. However, if we are in a setting where we get test points one by one, then we cannot use future test points to build the graph. But in batch evaluation, it's acceptable.
We'll stick to the transductive setting: graph built on all available data (train+test) and then propagate with the known training labels.
13. Implementation of Label Propagation:
We can use the following from scikit-learn:
from sklearn.semi_supervised import LabelPropagation
But note: the LabelPropagation in sklearn uses a kernel (rbf or knn) and we might want to use our own graph (adjacency matrix). Alternatively, we can implement our own.
Alternatively, we can use:
from sklearn.semi_supervised import LabelSpreading
which is a variant.
However, we want to use custom graphs. So we might have to implement the propagation ourselves.
The standard label propagation update:
Y^{t+1} = P * Y^t
where P is the transition matrix (column-normalized adjacency matrix). We start with Y^0 having the known labels (one-hot) for labeled nodes and zeros for unlabeled.
We iterate until convergence or for a fixed number of steps.
Then the label for each node is the argmax of the final Y.
The confidence for a node can be the maximum value in its row of Y.
We can also use a normalized version (like the random walk normalized Laplacian).
Steps for our own implementation:
Given an adjacency matrix A (n x n) for all nodes (n = n_train + n_test).
Let D be the diagonal matrix with D[i,i] = sum_j A[i,j].
Then the transition matrix P = D^{-1} A.
We build Y0 (n x C) where C is number of classes. For labeled nodes (indices in train_labeled_indices) we set Y0[i, y_i] = 1, and for others 0.
Then we do:
Y = Y0
for t in range(max_iter):
Y = P @ Y
# but we must keep the labeled nodes fixed: set their rows back to the initial one-hot?
Actually, in standard label propagation, we clamp the labeled nodes at every step? Or do we let them change?
There are two variants:
Variant 1 (Clamped): at every step, we set the labeled nodes back to their initial one-hot encoding.
Variant 2 (Unclamped): we let the labeled nodes change as well.
In sklearn's LabelPropagation, they clamp the labeled nodes at every iteration.
We'll implement the clamped version.
So:
for t in range(max_iter):
Y = P @ Y
Y[train_labeled_indices] = Y0[train_labeled_indices]
We stop when the change is below a tolerance or after max_iter.
Then the predicted label for node i is argmax(Y[i]).
The confidence for node i can be max(Y[i]).
However, note that the transition matrix P might be built from a symmetric normalized adjacency:
Let A_sym = D^{-1/2} A D^{-1/2} and then use that as the transition? But then it's not column-stochastic.
Actually, the standard random walk uses the column-normalized adjacency. So we'll use that.
But note: if we use a k-NN graph, it's usually not symmetric. So we use the directed graph.
Alternatively, we can symmetrize the graph (by A = A + A.T) and then use the symmetric normalized Laplacian? But then the propagation rule becomes:
Y = D^{-1/2} A D^{-1/2} Y
This is the normalized cut version.
We'll implement both? Actually, we can have a parameter for the normalization.
Let's define:
If normalize='random_walk': use P = D^{-1} A (column-normalized)
If normalize='symmetric': use P = D^{-1/2} A D^{-1/2}
But note: in the symmetric case, the propagation might not preserve the sum of each row? Actually, the symmetric normalized adjacency is symmetric and its row sums are not necessarily 1.
Alternatively, we can use the normalized Laplacian L_sym = I - D^{-1/2} A D^{-1/2} and then the update is Y = (I - L_sym) Y? That's not standard.
Actually, the standard label propagation uses the random walk normalized Laplacian: L_rw = I - D^{-1}A, and the update is Y = (I - L_rw) Y = D^{-1}A Y.
So we'll stick to the random walk for now.
However, note that the graph we build might have self-loops? Usually, we add self-loops. So A[i,i] > 0.
We'll build the graph with self-loops (i.e., set the diagonal to a positive value, maybe 1).
14. Graph Construction Methods:
We'll implement:
- knn_graph(X, k, metric='euclidean', self_loop=True): for each point, connect to its k nearest neighbors (including itself if self_loop). We'll use a symmetric version? Actually, we can build a directed graph and then symmetrize if we want. But let's have an option:
If mutual=True: only keep edges that are mutual (i.e., if i is in j's k-NN and j is in i's k-NN). Then we get an undirected graph.
Alternatively, we can build a directed graph and then use it as is (for random walk) or symmetrize.
We'll have:
knn_graph(X, k, metric='euclidean', mutual=False, self_loop=True)
Steps:
Compute pairwise distances.
For each i, find k nearest neighbors (including i if self_loop) and set A[i,j] = 1 (or a weight based on distance?).
If mutual is True, then we only keep an edge (i,j) if i is in the k-NN of j and j is in the k-NN of i.
We can also use a Gaussian kernel on the distances to set weights:
W[i,j] = exp(-d(i,j)^2 / sigma^2) if j is in the k-NN of i (or if mutual condition holds).
We'll have an option to use binary (1/0) or weighted.
- epsilon_graph(X, epsilon, metric='euclidean', self_loop=True): connect points within epsilon distance.
Again, we can do directed or undirected? Usually, it's undirected.
We'll set A[i,j] = 1 (or weight) if d(i,j) <= epsilon.
- fully_connected(X, metric='euclidean', self_loop=True, bandwidth='auto' or a float):
W[i,j] = exp(-d(i,j)^2 / sigma^2) for all i,j.
We can set sigma by the median of the pairwise distances (a common heuristic) or use a fixed value.
We'll build the adjacency matrix as a sparse matrix (using scipy.sparse) for efficiency.
15. Hyperparameters:
For each graph method, we have hyperparameters:
knn: k (and maybe metric, but we'll fix metric to euclidean or use a small set)
epsilon: epsilon
fully_connected: bandwidth (sigma)
We can tune these on a validation set? But note: we are in a semi-supervised setting and we might not have a separate validation set. We can use a part of the labeled data for validation? But then we are reducing the labeled set.
Alternatively, we can use the entire labeled set for training and use a fixed set of hyperparameters (e.g., k=10, epsilon=median of pairwise distances among labeled, etc.). But to be fair, we should tune for each dataset.
We'll do:
We split the labeled data into two parts: one for training (which we use as the initial labeled set in label propagation) and one for validation (to choose hyperparameters). But note: in the transductive setting, we are using all the labeled data as initial labels. So if we split the labeled data, we are reducing the number of initial labels.
Alternatively, we can do nested cross-validation: outer loop for train-test, inner loop for hyperparameter tuning using only the training labeled set? But then we have to build the graph on the training set (without the validation part) and then propagate to the validation? That becomes complicated.
Given the complexity, we might fix the hyperparameters for the graph construction to some standard values (e.g., k=10 for k-NN, epsilon=median distance for epsilon-ball, sigma=median distance for fully connected) and then not tune. But note that the optimal k or epsilon might depend on the dataset.
We can also try multiple values and average? But that would be expensive.
Let's decide:
We'll do a grid of hyperparameters for each graph method and pick the best on a validation set. But we must be cautious not to leak test information.
We'll split the labeled data into 80% for training (which we use as the initial labeled set) and 20% for validation. Then we build the graph on the entire training set (80% labeled + the unlabeled? Wait, we don't have unlabeled in the training set? Actually, in semi-supervised, we have a small labeled set and a large unlabeled set. In our experiment, we are given a dataset with labels for all points? But we simulate semi-supervised by holding out some labels.
So:
We have a dataset with (X, y). We split into train and test (e.g., 70-30). In the train set, we further split the labeled and unlabeled? Actually, we hold out a fraction of the train set as unlabeled. So:
Let L be the set of indices we keep labeled in train, and U the set of indices in train that we treat as unlabeled.
Then we have:
X_train_labeled = X[L], y_train_labeled = y[L]
X_train_unlabeled = X[U] (no labels)
X_test = X[test], y_test = y[test]
We build the graph on [X_train_labeled, X_train_unlabeled, X_test] (all available in the current split).
Then we run label propagation with initial labels for the L indices and zeros for U and test.
Then we evaluate on test.
Now for hyperparameter tuning, we can split the L set (the labeled training set) into two: L_train and L_val. Then we set:
X_train_labeled = X[L_train], y_train_labeled = y[L_train]
X_train_unlabeled = X[U] + X[L_val]? But wait, L_val is labeled but we are going to treat it as unlabeled for the purpose of graph building? That doesn't seem right because we are using the labels of L_val to choose hyperparameters.
Alternatively, we can do:
We have the entire labeled set L. We split L into L_train and L_val. Then we build the graph on [X[L_train], X[U], X[L_val], X_test]? But then we are using L_val in the graph and we are going to evaluate on L_val? That would be using test data (L_val) to tune hyperparameters, which is not allowed.
So we must have a separate validation set that is not used in the graph building? But then we are not using all the data for training.
Given the complexity, I propose:
We do not tune hyperparameters. We use a fixed set of hyperparameters that are reasonable for each dataset? But we don't know the scale of the data.
Alternatively, we can use a fixed value for k (say 10) and for epsilon and sigma, we set them to the median of the pairwise distances among the labeled training points (or all training points?).
Let's do:
For k-NN: k=10 (or maybe try 5,10,20 and average? but that would be 3 times more runs).
For epsilon: set epsilon to the median distance between points in the labeled training set (or the entire training set?).
For fully connected: set sigma to the median distance between points in the labeled training set.
This way, we don't need a validation set.
But note: the median distance might be affected by the number of points. We compute the median of the pairwise distances for the entire set of points we are using (i.e., the training set including unlabeled?).
Actually, we are building the graph on the entire set (train+test). But we don't have labels for unlabeled and test. So we can compute the median distance on the entire training set (labeled and unlabeled) because we have the features for all.
However, we are going to use the same graph for all the label propagation runs? Yes.
So we compute the median distance on the entire training set (X_train_labeled and X_train_unlabeled) and use that for epsilon and sigma.
But note: the test points are not included in the training set? We are building the graph on train+test, so we have the test features. But we shouldn't use the test set to compute the median? Because then we are using test set statistics to build the graph.
So we compute the median only on the training set (labeled and unlabeled).
Steps:
For a given split:
X_train = X[L] + X[U] (all training points, both labeled and unlabeled)
Compute pairwise distances among X_train, take the median, set epsilon and sigma to that.
Then build the graph on [X_train, X_test] using that epsilon/sigma.
For k-NN, we fix k=10.
This way, we don't use the test set to set hyperparameters.
16. Baselines:
We'll compare with:
- Supervised classifier (e.g., Logistic Regression, Random Forest) trained on the labeled training set only.
We can also try multiple classifiers and average? But we are focusing on label propagation.
We'll use the same confidence evaluation for the baseline? We can get probabilities from the classifier (if it supports) and then evaluate calibration and lift.
We'll do this to see the benefit of using unlabeled data.
17. Code Implementation Plan:
We'll write:
- A function to build a graph (adjacency matrix) given a method and hyperparameters.
- A function to run label propagation given an adjacency matrix and initial labels (for the entire graph, with zeros for unlabeled).
- A function to compute confidence scores from the label distribution (e.g., max probability).
- Evaluation functions for accuracy, ECE, MCE, and lift.
We'll loop over:
datasets -> splits -> graph_methods -> (hyperparameters fixed as above) -> label propagation (with fixed max_iter=1000, tol=1e-3) -> evaluate.
We'll store:
For each run (dataset, split, graph_method):
test_accuracy
test_ECE, test_MCE
lift_curve (array of accuracies at different top k%)
AULC (area under lift curve)
And also for the baseline (supervised) on the same split.
Then we aggregate over splits for each dataset and graph method.
We'll also compute the same metrics for the baseline.
We can then do statistical tests (e.g., paired t-test) to see if differences are significant.
18. Output:
We'll produce:
- A table for each dataset: rows = methods (graph methods and baseline), columns: accuracy, ECE, MCE, AULC.
- A summary table across datasets (averaging over datasets) for each method.
We'll also plot:
- Reliability diagrams for one dataset (for each method).
- Lift curves for one dataset (for each method).
19. Time and Resources:
This experiment can be computationally intensive because for each dataset and split we build multiple graphs and run label propagation. We might need to parallelize over splits and graph methods.
We'll use joblib for parallelization.
20. Let's write the code structure:
experiment.py:
import numpy as np
from sklearn.datasets import load_iris, load_digits, ... # or use openml
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import scipy.sparse as sp
from graph_construction import build_graph
from label_propagation import label_propagation
from evaluation import compute_metrics, compute_lift_curve
def run_experiment(dataset_name, n_splits=10, labeled_fraction=0.1, graph_methods=['knn', 'epsilon', 'fully_connected']):
# Load dataset
X, y = load_dataset(dataset_name)
n_samples = X.shape[0]
n_classes = len(np.unique(y))
results = {method: [] for method in graph_methods}
baseline_results = []
for split in range(n_splits):
# Split into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=split)
# Now, from X_train, we take a fraction as labeled and the rest as unlabeled.
n_labeled = int(len(X_train) * labeled_fraction)
# Shuffle the training indices and pick the first n_labeled as labeled.
indices = np.random.permutation(len(X_train))
labeled_indices = indices[:n_labeled]
unlabeled_indices = indices[n_labeled:]
X_train_labeled = X_train[labeled_indices]
y_train_labeled = y_train[labeled_indices]
X_train_unlabeled = X_train[unlabeled_indices]
# Build graph on [X_train_labeled, X_train_unlabeled, X_test]
X_all_train = np.vstack([X_train_labeled, X_train_unlabeled])
# We will build the graph on X_all_train and X_test? Actually, we want to include test in the graph for transductive.
# So let X_graph = np.vstack([X_all_train, X_test])
X_graph = np.vstack([X_all_train, X_test])
n_graph = X_graph.shape[0]
# Compute the median distance on X_all_train for hyperparameters (if needed)
# For simplicity, we compute pairwise distances on X_all_train (labeled and unlabeled) for epsilon and sigma.
from sklearn.metrics.pairwise import pairwise_distances
dists = pairwise_distances(X_all_train, metric='euclidean')
median_dist = np.median(dists)
# For each graph method:
for method in graph_methods:
if method == 'knn':
k = 10
adj = build_graph(X_graph, method='knn', k=k, metric='euclidean', mutual=False, self_loop=True, weighted=False)
elif method == 'epsilon':
epsilon = median_dist
adj = build_graph(X_graph, method='epsilon', epsilon=epsilon, metric='euclidean', self_loop=True, weighted=False)
elif method == 'fully_connected':
sigma = median_dist
adj = build_graph(X_graph, method='fully_connected', sigma=sigma, metric='euclidean', self_loop=True, weighted=False)
# Now run label propagation on the graph.
# We need initial label matrix Y0 for the entire graph (n_graph x n_classes).
# We have n_train_labeled points (the first n_labeled in X_graph) and the rest (n_graph - n_labeled) are unlabeled (including test).
Y0 = np.zeros((n_graph, n_classes))
# The first n_labeled points are labeled.
for i in range(n_labeled):
Y0[i, y_train_labeled[i]] = 1
# Run label propagation
Y = label_propagation(adj, Y0, max_iter=1000, tol=1e-3, clamp_labels=True)
# Predict for test points (the last n_test points in the graph)
n_test = len(X_test)
test_indices = range(n_graph - n_test, n_graph)
y_pred = np.argmax(Y[test_indices], axis=1)
# Confidence scores for test: max probability
confidence = np.max(Y[test_indices], axis=1)
# Evaluate on test
acc = accuracy_score(y_test, y_pred)
ece, mce = compute_ece(y_test, y_pred, confidence, n_bins=10) # we need to write compute_ece
lift_curve, aulc = compute_lift_curve(y_test, y_pred, confidence, n_steps=100)
# Store results
results[method].append({
'accuracy': acc,
'ece': ece,
'mce': mce,
'aulc': aulc,
'lift_curve': lift_curve
})
# Baseline: train a classifier on the labeled training set only.
clf = RandomForestClassifier(n_estimators=100, random_state=split)
clf.fit(X_train_labeled, y_train_labeled)
y_pred_baseline = clf.predict(X_test)
y_proba_baseline = clf.predict_proba(X_test)
confidence_baseline = np.max(y_proba_baseline, axis=1)
acc_baseline = accuracy_score(y_test, y_pred_baseline)
ece_baseline, mce_baseline = compute_ece(y_test, y_pred_baseline, confidence_baseline, n_bins=10)
lift_curve_baseline, aulc_baseline = compute_lift_curve(y_test, y_pred_baseline, confidence_baseline, n_steps=100)
baseline_results.append({
'accuracy': acc_baseline,
'ece': ece_baseline,
'mce': mce_baseline,
'aulc': aulc_baseline,
'lift_curve': lift_curve_baseline
})
# Aggregate results over splits for each method
# For each metric, compute mean and std over splits.
summary = {}
for method in graph_methods:
accs = [r['accuracy'] for r in results[method]]
eces = [r['ece'] for r in results[method]]
mces = [r['mce'] for r in results[method]]
aulcs = [r['aulc'] for r in results[method]]
summary[method] = {
'accuracy_mean': np.mean(accs),
'accuracy_std': np.std(accs),
'ece_mean': np.mean(eces),
'ece_std': np.std(eces),
'mce_mean': np.mean(mces),
'mce_std': np.std(mces),
'aulc_mean': np.mean(aulcs),
'aulc_std': np.std(aulcs)
}
# Baseline summary
accs_baseline = [r['accuracy'] for r in baseline_results]
eces_baseline = [r['ece'] for r in baseline_results]
mces_baseline = [r['mce'] for r in baseline_results]
aulcs_baseline = [r['aulc'] for r in baseline_results]
summary['baseline'] = {
'accuracy_mean': np.mean(accs_baseline),
'accuracy_std': np.std(accs_baseline),
'ece_mean': np.mean(eces_baseline),
'ece_std': np.std(eces_baseline),
'mce_mean': np.mean(mces_baseline),
'mce_std': np.std(mces_baseline),
'aulc_mean': np.mean(aulcs_baseline),
'aulc_std': np.std(aulcs_baseline)
}
return summary, results, baseline_results
Then we run this for multiple datasets and aggregate.
21. Note: We are using the test set in the graph construction. This is transductive. If we want an inductive setting, we would build the graph only on the training set and then find the test points' neighbors in the training graph. But that is more complex and not standard for label propagation.
-
We also need to write the functions:
build_graph: returns a sparse adjacency matrix (n x n). We'll use csr_matrix.
label_propagation:
Input: adj (sparse n x n), Y0 (n x C), max_iter, tol, clamp_labels (bool)
Output: Y (n x C)
Steps:
n, C = Y0.shape
Y = Y0.copy()
# Normalize adj to get transition matrix P (column-normalized)
# But note: if we use a sparse matrix, we can do:
col_sum = np.array(adj.sum(axis=1)).flatten()
# Avoid division by zero: set zeros to 1? but then if a node has no neighbors, we set its column to 1? Actually, we added self-loop so every node has at least itself.
col_sum[col_sum == 0] = 1
D_inv = sp.diags(1/col_sum)
P = D_inv.dot(adj) # This is column-normalized.
for it in range(max_iter):
Y_prev = Y.copy()
Y = P.dot(Y) # (n x n) * (n x C) -> (n x C)
if clamp_labels:
Y[train_labeled_indices] = Y0[train_labeled_indices]
# Check convergence: norm(Y - Y_prev)
if np.linalg.norm(Y - Y_prev) < tol:
break
return Y
But note: the train_labeled_indices are the first n_labeled points in the graph.
We assume that the graph is built in the same order: [X_train_labeled, X_train_unlabeled, X_test].
So the labeled indices are 0 to n_labeled-1.
Alternatively, we can pass the labeled indices as an argument.
Let's change the function to:
label_propagation(adj, labeled_indices, Y0, max_iter=1000, tol=1e-3, clamp_labels=True)
But we already built Y0 with ones at labeled_indices. So we can just clamp at those indices.
However, note that in the clamped version, we set Y[labeled_indices] = Y0[labeled_indices] at every iteration.
So:
def label_propagation(adj, labeled_indices, Y0, max_iter=1000, tol=1e-3, clamp_labels=True):
n, C = Y0.shape
Y = Y0.copy()
col_sum = np.array(adj.sum(axis=1)).flatten()
col_sum[col_sum == 0] = 1
D_inv = sp.diags(1/col_sum)
P = D_inv.dot(adj)
for it in range(max_iter):
Y_prev = Y.copy()
Y = P.dot(Y)
if clamp_labels:
Y[labeled_indices] = Y0[labeled_indices]
if np.linalg.norm(Y - Y_prev) < tol:
break
return Y
But note: we are using the entire Y0 (which has zeros for unlabeled). So we are clamping to the initial one-hot for labeled.
Alternatively, we might want to let the labeled nodes change? Then set clamp_labels=False.
We'll try both? But for now, we'll do clamped (which is standard).
Also, note: we are using the column-normalized adjacency. This assumes the graph is directed? Actually, if we symmetrize the graph, then the column-normalized and row-normalized are the same? Not necessarily.
Given the complexity and time, we might not be able to write the entire code in one response, but we can outline the code structure and key functions.
However, the user asked to "Design a label propagation experiment suite", so we are providing the design and code structure.
Let's write the code for the main parts.
We'll write:
- graph_construction.py
- label_propagation.py
- evaluation.py
- experiment.py
And a main script.
But note: the response length is limited. We'll write the core functions and the main experiment loop.
Let's write the code in a condensed form.
I'll design a comprehensive label propagation experiment suite that systematically evaluates graph-based methods, confidence calibration, and lift metrics. This suite addresses both transductive and inductive semi-supervised learning scenarios.
Experiment Suite Design
1. Experimental Framework
class LabelPropagationExperiment:
"""
Comprehensive evaluation suite for label propagation methods
"""
def __init__(self, config):
self.config = config
self.results = defaultdict(list)
def run(self):
"""Main experimental loop"""
for dataset in self.config['datasets']:
for split in self.config['splits']:
self._run_single_split(dataset, split)
self._aggregate_results()
self._generate_reports()
2. Core Evaluation Dimensions
A. Graph Construction Methods
GRAPH_METHODS = {
'knn': {'k': [5, 10, 20]},
'mutual_knn': {'k': [5, 10]},
'epsilon': {'epsilon_quantiles': [0.1, 0.2, 0.5]},
'fully_connected': {'sigma_strategy': ['median', 'mean', 'knn_radius']},
'rbf_kernel': {'gamma': ['scale', 'auto', 0.1, 1.0]},
'laplacian': {'normalized': [True, False]}
}
B. Label Propagation Algorithms
PROPAGATION_METHODS = {
'standard_lp': {
'alpha': [0.1, 0.2, 0.5, 0.8, 0.9],
'max_iter': [1000],
'tol': [1e-3]
},
'clp': { # Constrained Label Propagation
'constraint_matrix': ['affinity', 'distance'],
'alpha': [0.5, 0.7, 0.9]
},
'absorbing_lp': {
'absorbing_indices': ['labeled', 'high_confidence']
},
'harmonic': {
'use_adjacency': [True, False]
}
}
C. Confidence Scoring Strategies
CONFIDENCE_METHODS = {
'max_prob': 'standard_max',
'margin': 'difference_top2',
'entropy': 'shannon_entropy',
'difference_from_threshold': {
'thresholds': [0.5, 0.6, 0.7, 0.8]
},
'gini_impurity': 'gini_coefficient',
'evidence': 'dempster_shafer' # for evidential deep learning approach
}
3. Evaluation Metrics
A. Predictive Performance
PERFORMANCE_METRICS = [
'accuracy', 'macro_f1', 'micro_f1',
'weighted_f1', 'balanced_accuracy',
'cohen_kappa', 'matthews_corrcoef'
]
B. Confidence Calibration Metrics
CALIBRATION_METRICS = {
'ece': {
'n_bins': [5, 10, 15, 20],
'weighted': [True, False]
},
'mce': 'maximum_calibration_error',
'nll': 'negative_log_likelihood',
'brier_score': 'brier_multi',
'reliability_diagram': {
'plot': True,
'bin_strategy': ['equal_width', 'equal_freq']
}
}
C. Lift Evaluation Framework
LIFT_METRICS = {
'precision_at_k': {
'k_percentages': [0.01, 0.05, 0.1, 0.2, 0.5],
'cumulative': [True, False]
},
'recall_at_k': 'same_as_precision',
'lift_at_k': {
'baseline': ['random', 'majority', 'model_without_ssl'],
'k_values': [1, 5, 10, 20, 50, 100]
},
'auc_lift': 'area_under_lift_curve',
'gain_plot': {
'plot': True,
'normalize': True
},
'cost_benefit_analysis': {
'cost_matrix': 'confusion_matrix_based',
'benefit_fn': 'custom_utility_function'
}
}
4. Experimental Protocol
A. Data Preparation Pipeline
def prepare_data(dataset_name, config):
# 1. Load dataset
X, y = load_dataset(dataset_name)
# 2. Stratified splits
splits = []
for i in range(config['n_splits']):
train_idx, test_idx = train_test_split(
np.arange(len(X)),
test_size=config['test_size'],
stratify=y,
random_state=i
)
# 3. Create partial label scenarios
for labeled_frac in config['labeled_fractions']:
n_labeled = int(len(train_idx) * labeled_frac)
labeled_idx = np.random.choice(
train_idx, n_labeled, replace=False
)
unlabeled_idx = np.setdiff1d(train_idx, labeled_idx)
splits.append({
'train_labeled': X[labeled_idx],
'y_train_labeled': y[labeled_idx],
'train_unlabeled': X[unlabeled_idx],
'test': X[test_idx],
'y_test': y[test_idx]
})
return splits
B. Cross-Validation Strategy
- Outer loop: Dataset splits (5-10 folds)
- Inner loop: Hyperparameter tuning (if applicable)
- Validation approach:
- For graph parameters: Use labeled subset only
- For propagation parameters: Use validation accuracy on held-out labeled points
5. Implementation Architecture
class GraphBuilder:
"""Handles all graph construction methods"""
def build_graph(self, X, method, params):
if method == 'knn':
return self._build_knn(X, params)
elif method == 'epsilon':
return self._build_epsilon(X, params)
# ... other methods
def _compute_sigma(self, X, strategy):
"""Automatic bandwidth selection"""
if strategy == 'median':
return np.median(pairwise_distances(X))
elif strategy == 'knn_radius':
# Use distance to k-th neighbor
pass
class LabelPropagator:
"""Implements various LP algorithms"""
def propagate(self, W, y_labeled, labeled_indices, method, params):
if method == 'standard_lp':
return self._standard_lp(W, y_labeled, labeled_indices, params)
elif method == 'clp':
return self._constrained_lp(W, y_labeled, params)
class ConfidenceEvaluator:
"""Evaluates confidence quality"""
def evaluate(self, y_true, y_pred, confidence_scores):
return {
'ece': self._expected_calibration_error(y_true, y_pred, confidence_scores),
'reliability_diagram': self._plot_reliability_diagram(...),
'sharpness': self._compute_sharpness(confidence_scores)
}
class LiftAnalyzer:
"""Computes lift metrics"""
def compute_lift_curve(self, y_true, confidence_scores, y_pred=None):
sorted_idx = np.argsort(confidence_scores)[::-1]
n = len(y_true)
lift_curve = []
for k in [1, 5, 10, 20, 50, 100]:
n_top = int(n * k / 100)
top_idx = sorted_idx[:n_top]
if y_pred is not None:
acc_top = np.mean(y_true[top_idx] == y_pred[top_idx])
else:
# Use majority baseline
acc_top = np.mean(y_true[top_idx] == np.bincount(y_true[top_idx]).argmax())
lift = acc_top / np.mean(y_true == y_pred) # relative to overall accuracy
lift_curve.append((k, lift))
return lift_curve, self._compute_auc_lift(lift_curve)
6. Statistical Validation
class StatisticalTester:
"""Paired statistical tests across methods"""
def compare_methods(self, results_dict, metric='accuracy'):
"""Conduct Friedman test with Nemenyi post-hoc"""
from scipy.stats import friedmanchisquare
from scikit_posthocs import posthoc_nemenyi_friedman
# Organize results: methods × folds
data = []
methods = list(results_dict.keys())
for method in methods:
data.append(results_dict[method][metric])
# Friedman test
stat, p = friedmanchisquare(*data)
# Post-hoc if significant
if p < 0.05:
posthoc = posthoc_nemenyi_friedman(np.array(data).T)
return {
'friedman_p': p,
'posthoc_matrix': posthoc,
'significant_pairs': self._extract_significant_pairs(posthoc)
}
7. Visualization Suite
class VisualizationSuite:
"""Generate all required plots"""
def plot_all(self, results):
self._plot_lift_curves(results)
self._plot_reliability_diagrams(results)
self._plot_confidence_distributions(results)
self._plot_accuracy_vs_confidence(results)
self._plot_graph_qualities(results) # e.g., clustering coefficient, degree distribution
self._plot_parameter_sensitivity(results)
def _plot_lift_curves(self, results):
"""Multi-panel lift curves for all methods"""
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
for idx, (method, lifts) in enumerate(results['lift_curves'].items()):
ax = axes[idx//3, idx%3]
for dataset, lift in lifts.items():
ax.plot([k for k, _ in lift], [v for _, v in lift],
label=dataset, alpha=0.7)
ax.set_title(f'{method} - Lift Curves')
ax.set_xlabel('Top k%')
ax.set_ylabel('Lift')
ax.legend()
ax.grid(True, alpha=0.3)
8. Configuration Management
# config.yaml
experiment:
name: "lp_comprehensive_evaluation"
n_splits: 10
random_seed: 42
datasets:
- name: "cifar10"
type: "image"
preprocess: ["normalize", "pca50"]
- name: "20newsgroups"
type: "text"
preprocess: ["tfidf", "svd100"]
- name: "ade"
type: "tabular"
graph_methods:
- knn:
k: [5, 10, 20]
metric: ["cosine", "euclidean"]
- epsilon:
epsilon_quantiles: [0.1, 0.2]
propagation:
- standard_lp:
alpha: [0.2, 0.5, 0.8]
max_iter: 1000
- clp:
alpha: [0.5, 0.7, 0.9]
confidence_eval:
calibration_metrics: ["ece", "mce", "nll"]
n_bins: 10
lift_eval:
k_percentages: [0.01, 0.05, 0.1, 0.2, 0.5]
baseline: "random"
baselines:
- "supervised_rf"
- "supervised_mlp"
- "semi_supervised_vat"
- "graph_ssl"
9. Main Execution Flow
def main():
# 1. Load configuration
config = load_config('config.yaml')
# 2. Initialize experiment
exp = LabelPropagationExperiment(config)
# 3. Run all experiments
for dataset in config['datasets']:
print(f"\n{'='*50}")
print(f"Dataset: {dataset['name']}")
print(f"{'='*50}")
# Prepare data splits
splits = prepare_data(dataset, config)
# Iterate over all combinations
for graph_method in config['graph_methods']:
for prop_method in config['propagation']:
for conf_method in config['confidence_eval']:
# Run single experiment
results = run_single_experiment(
splits, graph_method, prop_method, conf_method
)
# Store results
exp.results[dataset['name']][graph_method][prop_method] = results
# 4. Post-processing
exp._aggregate_results()
exp._statistical_tests()
exp._generate_latex_tables()
exp._create_visualizations()
exp._save_results()
# 5. Generate summary report
exp._generate_summary_report()
10. Key Analysis Questions Addressed
-
Graph Sensitivity: How does performance vary with:
- k in k-NN graphs
- ε in ε-balls
- Bandwidth in RBF kernels
-
Algorithm Comparison:
- Standard LP vs Constrained LP vs Harmonic
- Transductive vs Inductive evaluation
-
Confidence Quality:
- Which confidence scoring strategy best correlates with accuracy?
- How well calibrated are different methods?
- Sharpness vs calibration trade-off
-
Lift Analysis:
- Which method gives highest precision in top-1%?
- How does lift degrade as k increases?
- Cost-benefit optimal operating points
-
Data Regime Analysis:
- Performance vs labeled fraction (1%, 5%, 10%, 20%, 50%)
- Performance vs number of classes
- Performance vs graph density
11. Reproducibility Features
- Fixed random seeds for all splits
- Versioned dependencies (requirements.txt with versions)
- Complete configuration logging (YAML files)
- Intermediate results caching to avoid recomputation
- Docker container for environment consistency
12. Output Structure
results/
├── raw/
│ ├── {dataset}_{graph}_{prop}_{conf}_{split}.pkl
├── aggregated/
│ ├── {dataset}_summary.csv
│ ├── lift_curves.json
│ ├── calibration_metrics.json
├── figures/
│ ├── lift_curves/
│ ├── reliability_diagrams/
│ ├── parameter_sensitivity/
├── tables/
│ ├── main_results.tex
│ ├── statistical_tests.tex
│ ├── ablation_studies.tex
└── report/
├── main_report.html
├── dataset_specific_reports/
13. Example Usage
# Quick test on small dataset
config = {
'datasets': ['iris'],
'splits': 3,
'labeled_fractions': [0.1, 0.2],
'graph_methods': ['knn'],
'propagation': ['standard_lp'],
'confidence_eval': ['ece', 'mce'],
'lift_eval': {'k_percentages': [0.1, 0.2, 0.5]}
}
exp = LabelPropagationExperiment(config)
exp.run()
exp.plot_lift_curves()
exp.print_summary_table()
14. Advanced Extensions
- Time-series graphs: Temporal graph construction
- Heterogeneous graphs: Multiple node/edge types
- Active learning integration: Query-by-committee with LP
- Adversarial robustness: Performance under label noise
- Scalability benchmarks: Memory/time vs graph size
15. Validation Checklist
This suite provides:
- Comprehensive: Covers all critical aspects of LP evaluation
- Modular: Easy to extend with new methods
- Rigorous: Proper statistical validation
- Practical: Realistic scenarios with partial labels
- Reproducible: Complete versioning and configuration
The framework enables researchers to answer questions like: "Does constrained LP improve calibration?" or "Which graph construction yields best lift in low-label regimes?" while providing statistical evidence for claims.