The user wants a program for graph-based semi-supervised learning (SSL).
This is a broad request. I need to choose a specific, standard algorithm that represents the field well.
Common algorithms include:
Label Propagation (LP)
Label Spreading
Graph Convolutional Networks (GCNs) - Too complex for a simple "write a program" request without specific libraries like PyTorch/TF, and probably overkill if they just want the core logic.
Harmonic Function (Zhu et al.) - Good, but LP is the standard implementation of this idea.
I will stick with Label Propagation because it is intuitive, effective, and easy to implement using standard libraries like numpy and networkx (or just numpy for the matrix math), or scikit-learn which has a built-in implementation.
However, usually, when someone asks for a "program" to do X without specifying a library, they either want:
A from-scratch implementation to understand the math.
A practical usage example using a high-level library (like scikit-learn).
I should probably provide a from-scratch implementation using numpy to show how it works, as that is more educational and meets the "program that performs" criteria better than just calling fit(). I will also provide the scikit-learn version for practical use.
Algorithm Choice: Label Propagation
Input: A graph G=(V,E) and labels for a subset of nodes.
Core Logic:
Build an Adjacency Matrix (or Affinity Matrix).
Build a Transition Matrix (Probabilities of moving from node i to node j).
Initialize label distributions (hard labels for known nodes, zeros/uniform for unknown).
Iterate: Propagate labels via matrix multiplication Ynew=T.
Steps for the Python Code:
Imports: numpy, maybe networkx for visualization (optional, but makes it standalone). Let's stick to numpy and matplotlib (for the plot) to keep dependencies low but visualization high.
Data Generation: Create a synthetic dataset (e.g., two moons or blobs) to make the code runnable immediately.
Refining the Code Structure:
I will create a class LabelPropagation to encapsulate the logic. This makes it look like a proper program/tool.
fit(X, y): X are features, y are labels (-1 for unlabeled).
_build_graph(): RBF kernel or KNN.
_predict(): The propagation loop.
Wait, let's double check. Is Label Propagation better or Label Spreading?
Label Propagation clamps the original labels.
Label Spreading allows original labels to change slightly (normalized Laplacian).
Label Propagation is the "classic" intro algorithm. I'll go with that.
Let's write the mental draft of the core math:
Wij=exp(−∥xi− if are neighbors, else 0.
Alternative: Use the closed-form solution (Harmonic Function Solution).
Yu=(Duu−W.
This involves matrix inversion, which is . Iterative is per step. Iterative is often more intuitive for a "simulation" style program.
Plan:
Provide a From-Scratch Implementation using NumPy. This explains how it works.
Provide a Scikit-Learn Implementation. This is how you do it in production.
From-Scratch Details:
Use sklearn.datasets.make_moons for interesting non-linear data.
Mask some labels as -1.
Run the algorithm.
Plot the decision boundary or color the points.
Let's structure the response clearly.
Introduction: Briefly explain Graph-based SSL (using the manifold assumption).
Method 1: NumPy Implementation (The "How it works" version).
Class LabelPropagation.
RBF Kernel for graph building.
Iterative matrix multiplication.
Visualization.
Method 2: Scikit-Learn Implementation (The "Production" version).
Simple usage of LabelPropagation class from sklearn.
I will focus the code on the NumPy version as the primary answer, as it is a "program that performs" the task rather than a "script that calls a library".
Code specifics for NumPy version:
Handle the "unlabeled" marker (usually -1 or NaN).
One-hot encoding for labels? Yes, Y is usually a matrix N×C.
Convergence check: ∥Ynew.
Let's refine the matrix math.
Y (Label matrix): N×C.
Initialized: Labeled nodes have 1 in the correct class column. Unlabeled have 0 (or uniform).
Update: Y←T×Y.
Clamp: Overwrite rows of Y corresponding to labeled nodes.
This looks solid. I will write the code now.
One edge case: Numerical stability. The matrix D−1 can be tricky if degree is 0. I should add a small epsilon or ensure every node is connected to at least itself or a neighbor. KNN graph ensures connectivity usually.
Let's stick to the RBF kernel on the whole dataset (dense graph) or KNN (sparse). Dense is slow (O(N2)). KNN is better. I'll use KNN (k=5 or 10) to build the adjacency matrix, then RBF to weight edges.
Actually, to keep the code simple and readable, I might use a dense RBF kernel for small datasets, or just a KNN graph with binary weights? No, weighted is better for performance. I'll implement a basic RBF kernel on KNN neighbors.
Wait, a pure NumPy KNN is annoying to write from scratch without sklearn.neighbors.
To make the code dependency-light, maybe I'll just use a dense RBF matrix if N<500. That's the easiest "from scratch" way without writing a KD-Tree.
Let's assume the user has scikit-learn for data generation (make_moons) anyway. I can use sklearn.neighbors.kneighbors_graph for the graph construction part, but implement the propagation math in NumPy.
Okay, the plan is:
Generate data with sklearn.
Build Graph (Affinity Matrix) using RBF.
Normalize to get Transition Matrix.
Iterate.
I will add comments explaining the "Clamping" mechanism, which is key to SSL.
Let's write the description.
Semi-supervised learning (SSL) uses graph structures to propagate known labels to unlabeled data points based on the assumption that connected nodes (similar data points) are likely to share the same label.
The program will:
Generate a synthetic dataset (two interleaving half circles).
Randomly mask most labels (simulate having very little labeled data).
Build a similarity graph.
Run the Label Propagation algorithm.
Visualize the result.
This covers all bases.
Checking constraints: The prompt asks for "a program". It doesn't specify language, but Python is the de facto standard for ML. I will use Python.
Structure of the provided code:
python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.neighbors import kneighbors_graph
# Class definition
class LabelPropagation:
...
# Main execution
if __name__ == "__main__":
# 1. Data
# 2. Mask labels
# 3. Run Algorithm
# 4. Plot
This looks perfect.
One detail: Label Spreading vs Propagation.
Label Propagation (Zhu & Ghahramani) often uses a specific clamping weight α.
F(t+1)=αSF
Where is the initial labels.
This is actually "Label Spreading" in sklearn terminology sometimes, or just a robust version of Propagation.
Standard Zhu & Ghahramani 2002:
.
.
(Hard clamping).
I will stick to Hard Clamping (standard Label Propagation) as it is conceptually simpler.
Final check on graph construction:
We need a symmetric affinity matrix usually.
Wij=exp(−∥xi−.
If using KNN, it's often directed (i is j's neighbor but j might not be i's). It's best to symmetrize it: or .
Then normalize rows to sum to 1.
Let's generate the response.
Here is a complete Python program that demonstrates Graph-Based Semi-Supervised Learning using the Label Propagation algorithm.
This program includes:
Data Generation: Creates a "Two Moons" dataset (non-linearly separable).
Graph Construction: Builds a similarity graph using k-Nearest Neighbors and an RBF (Gaussian) kernel.
The Algorithm: Implements the iterative Label Propagation logic from scratch using numpy.
Visualization: Shows the decision boundary and how labels spread from a few labeled points to the whole dataset.
The Python Program
You will need numpy, matplotlib, and scikit-learn (for data generation only) installed.
python
How It Works
Graph Construction (_build_graph):
We assume that data points close to each other share the same label. The code calculates a Weight Matrix W where the weight between two points i and j is determined by the Radial Basis Function (RBF):
W
To make the graph sparse (faster computation and better local consistency), we only connect the nearest neighbors.
Interpreting the Visualization
Left Plot: Shows the "Soft" probability. You will see a smooth gradient of color between the clusters.
Right Plot: Shows the "Hard" classification. The yellow-ringed points are the only information the algorithm was given; the algorithm successfully colored the rest of the moons based on the graph structure.
×
Yold
Clamp: Reset the known labels to their ground truth (so they don't drift).
Repeat until convergence.
1
W
Loop propagation step.
Visualization: Show the labels changing over time.
x
j
∥2
/2
σ2
)
i,j
Dii=∑jWij.
T=D−1W (Row normalized transition matrix).
Y(t+1)=TY(t).
Clamp labeled nodes.
Repeat.
uu
)−1
Wul
Yl
O(N3)
O(N2)
−
Yold∥<
ϵ
(t)
+
(1−
α)Y
Y
Funlabeled←SF
Flabeled←Ylabeled
xj
∥2
/
σ2
)
W=W+WT
W=max(W,WT)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.neighbors import kneighbors_graph
import warnings
# Suppress rounding warnings during matrix multiplication
warnings.filterwarnings("ignore", category=RuntimeWarning)
class LabelPropagation:
def __init__(self, max_iter=1000, tol=1e-3, k=10, gamma=20):
"""
Label Propagation Classifier.
Parameters:
- max_iter: Maximum number of iterations.
- tol: Convergence tolerance (stop if changes are smaller than this).
- k: Number of neighbors for graph construction.
- gamma: Coefficient for RBF kernel (controls how far influence reaches).
"""
self.max_iter = max_iter
self.tol = tol
self.k = k
self.gamma = gamma
def _build_graph(self, X):
"""
Builds the affinity matrix (Graph) W.
Uses k-Nearest Neighbors with RBF kernel.
"""
# 1. Find k-nearest neighbors (connectivity only)
# mode='connectivity' gives a binary matrix (1 if neighbor, 0 else)
knn_graph = kneighbors_graph(X, self.k, mode='connectivity', include_self=False)
# 2. Convert binary connections to weighted edges using RBF Kernel
# W_ij = exp(-gamma * ||x_i - x_j||^2)
n_samples = X.shape[0]
W = np.zeros((n_samples, n_samples))
# Iterate over rows to compute distances for neighbors only (Sparse approach)
for i in range(n_samples):
# Find indices of neighbors
neighbors = np.where(knn_graph[i].toarray().flatten() == 1)[0]
for j in neighbors:
# Compute RBF distance
dist = np.sum((X[i] - X[j])**2)
W[i, j] = np.exp(-self.gamma * dist)
# Make the matrix symmetric (if i is neighbor of j, j is neighbor of i with same weight)
W = np.maximum(W, W.T)
return W
def fit(self, X, y):
"""
Fits the model to the data.
X: Feature matrix (n_samples, n_features)
y: Labels (-1 for unlabeled samples)
"""
self.X = X
self.classes = np.unique(y[y != -1])
n_classes = len(self.classes)
n_samples = n_features = X.shape[0]
# 1. Build Graph and Transition Matrix
print("Building graph...")
W = self._build_graph(X)
# Normalize W to create Transition Matrix T (Row Stochastic)
# T_ij = W_ij / sum_k(W_ik)
D = np.sum(W, axis=1, keepdims=True)
D[D == 0] = 1e-10 # Avoid division by zero
self.T = W / D
# 2. Initialize Label Distribution Y
# Y is a matrix (n_samples, n_classes)
# Labeled nodes: One-hot encoding
# Unlabeled nodes: Zeros
Y_init = np.zeros((n_samples, n_classes))
for i in range(n_samples):
if y[i] != -1:
class_idx = np.where(self.classes == y[i])[0][0]
Y_init[i, class_idx] = 1
Y = Y_init.copy()
# 3. Propagation Loop
print("Starting propagation...")
for i in range(self.max_iter):
Y_prev = Y.copy()
# a. Propagate: Y = T * Y
Y = self.T @ Y
# b. Clamp: Reset known labeled nodes to their original truth
# This is the "Supervised" constraint
Y[y != -1] = Y_init[y != -1]
# c. Check convergence
if np.linalg.norm(Y - Y_prev, ord=1) < self.tol:
print(f"Converged at iteration {i}")
break
self.Y_final = Y
self.labels = self.classes[np.argmax(Y, axis=1)]
return self
def plot(self, y_true=None):
"""Visualizes the results."""
plt.figure(figsize=(12, 5))
# Plot 1: Label Map (Soft Probability)
plt.subplot(1, 2, 1)
plt.scatter(self.X[:, 0], self.X[:, 1], c=self.Y_final[:, 0], cmap='coolwarm', s=20, edgecolors='k', alpha=0.8)
plt.title("Learned Class Probability (Red=1, Blue=0)")
plt.colorbar()
# Plot 2: Final Hard Predictions
plt.subplot(1, 2, 2)
plt.scatter(self.X[:, 0], self.X[:, 1], c=self.labels, cmap='coolwarm', s=20, edgecolors='k', alpha=0.8)
# Highlight the originally labeled points
labeled_indices = np.where(y_train != -1)[0]
plt.scatter(self.X[labeled_indices, 0], self.X[labeled_indices, 1],
c=y_train[labeled_indices], cmap='coolwarm', s=150,
edgecolors='yellow', linewidth=2, label='Initial Labels')
plt.title("Final Classification")
plt.legend()
plt.show()
# --- Main Execution ---
if __name__ == "__main__":
# 1. Generate synthetic data (Two Moons)
X, y_true = make_moons(n_samples=300, noise=0.1, random_state=42)
# 2. Create "Unlabeled" data
# We mask 95% of the labels (set them to -1)
y_train = np.copy(y_true)
rng = np.random.RandomState(42)
random_unlabeled_points = rng.rand(len(y_train)) < 0.95
y_train[random_unlabeled_points] = -1
print(f"Total samples: {len(y_true)}")
print(f"Labeled samples: {np.sum(y_train != -1)}")
print(f"Unlabeled samples: {np.sum(y_train == -1)}")
# 3. Run Label Propagation
model = LabelPropagation(max_iter=100, k=10, gamma=20)
model.fit(X, y_train)
# 4. Visualize
model.plot()
ij
=
exp(−γ∥xi−
xj∥2)
k
Transition Matrix (T):
We normalize W so that the sum of weights for every node equals 1. This turns W into a stochastic transition matrix T (similar to a Markov Chain). Tij represents the probability of "jumping" from node i to node j.
Propagation Loop:
The algorithm repeats two steps until convergence:
Spread: Multiply the current label distribution by the Transition Matrix (Y=T⋅Y). This diffuses label information to neighbors.
Clamp: Reset the values of the originally labeled nodes back to their true values. This anchors the solution so the labels don't drift into noise.