The user wants a program that performs graph-based semi-supervised learning.
-
Identify the Core Concepts:
- Semi-supervised learning (SSL): Using both labeled and unlabeled data to train a model.
- Graph-based SSL: Constructing a graph where nodes represent data points (both labeled and unlabeled) and edges represent similarities. The goal is to propagate labels from labeled nodes to unlabeled nodes based on the graph structure.
- Key Algorithms: Label Propagation (LP) and Label Spreading are the standard techniques for this.
-
Determine the Scope and Tools:
- Language: Python is the standard for machine learning.
- Libraries:
scikit-learn is the go-to library for classical ML algorithms, including graph-based SSL. networkx could be used for visualization, but scikit-learn is better for the actual algorithm implementation. numpy for data generation.
- Specific Algorithm: Label Spreading is often preferred over Label Propagation because it allows for clamping (hard constraints) on the original labels, which usually leads to better results, but Label Propagation is conceptually simpler. I will implement a class that demonstrates the workflow using
sklearn.semi_supervised.LabelSpreading or LabelPropagation.
-
Structure the Program:
- Data Generation: Need a synthetic dataset with "clusters" to make the graph structure meaningful.
make_circles or make_moons are good because they are non-linear, showing the power of graph methods over linear methods. I need to mask some labels to simulate the "unlabeled" scenario.
- Graph Construction (Implicit): Most libraries (like scikit-learn) handle the graph construction (K-NN or RBF kernel) internally when you call
.fit(). I should mention this, but I don't need to write the adjacency matrix construction code from scratch unless requested (custom implementation is good for understanding, but library usage is better for production). Self-correction: To provide a complete answer, I should probably show how to do it using a library (robust, easy) and perhaps a brief explanation or a from-scratch snippet if the user wants "under the hood" details. However, usually, a request like this implies "give me working code to solve this problem." I will stick to scikit-learn for the main solution but explain the math briefly.
- Visualization: It's crucial to see the results. A plot showing the true labels vs. the predicted labels on the unlabeled data will make the program verifiable.
-
Drafting the Code Steps:
- Import
numpy, matplotlib, sklearn.
- Generate data (e.g., two interleaving moons).
- Split into labeled (small subset) and unlabeled (large subset). In
sklearn, unlabeled data is usually represented by -1 in the target array.
- Instantiate the model (e.g.,
LabelSpreading).
- Fit the model.
- Predict.
- Visualize.
-
Refining the Implementation (Mental Sandbox):
- Scenario: I have 500 points. I label 10. I want to predict the other 490.
- Code:
X, y = make_moons(n_samples=500, noise=0.1, random_state=42)
# Mask labels
rng = np.random.RandomState(42)
random_unlabeled_points = rng.rand(len(y)) < 0.8 # 80% unlabeled
y_masked = np.copy(y)
y_masked[random_unlabeled_points] = -1
# Model
lp_model = LabelSpreading(kernel='knn', n_neighbors=5) # or rbf
lp_model.fit(X, y_masked)
-
Adding a "From Scratch" Implementation (Optional but Educational):
- While
sklearn is practical, "Write a program" sometimes implies "Show me how the algorithm works." The Harmony algorithm or basic Label Propagation iterates:
Y(t+1)=αSY(t)
Where is the normalized adjacency matrix.
-
Finalizing the Output Structure:
- Introduction: Brief explanation of Graph-based SSL.
- Approach 1: Scikit-Learn (Recommended): Standard, optimized, easy to use.
- Approach 2: From Scratch (NumPy): Demonstrates the iterative matrix calculation logic (Label Propagation).
- Visuals: Use Matplotlib to show the "before" (few labels) and "after" (filled clusters).
-
Writing the Code (Mental Check of the "From Scratch" Logic):
- Construct Adjacency matrix W (e.g., RBF kernel).
- Compute Degree matrix D.
- Compute Normalized Laplacian/Propagation matrix S=D−1W.
- Init (one-hot encoded labels).
-
Review against Constraints:
- "Graph-based": Yes.
- "Semi-supervised": Yes.
- "Program": Yes, executable Python code.
-
Refining the explanations: Ensure clear comments explaining why we use -1 for unlabeled data in sklearn, and what the kernel does.
(Self-Correction during drafting): Make sure to handle the random seed so the results are reproducible. Ensure the "From Scratch" version handles the label clamping correctly; otherwise, the labels might drift too far.
Let's write the solution. I will prioritize the scikit-learn version as the primary answer because it's the "correct" engineering approach, but include the custom class for depth.
Plan:
- Imports.
- Data generation (make_moons).
- Label masking.
scikit-learn implementation with visualization.
- Custom NumPy implementation (Label Propagation) with visualization.
Let's stick to one combined script that offers both, or just the sklearn one if it gets too long? No, distinct sections are better. I will provide the Scikit-Learn version first, as it is the standard way to solve this problem. Then I will add a "Custom Implementation" section for understanding the math.
Code Check - Scikit-Learn:
LabelSpreading is generally better than LabelPropagation because it deals with noise better by not clamping the original labels strictly but weighting them. I'll use LabelSpreading.
Code Check - Custom:
Yt+1=αTYt+(1 where is the normalized weight matrix.
This is the classic formulation.
Let's proceed.
Here is a complete solution. I have provided two approaches:
- The Practical Approach (using Scikit-Learn): This is how you would do it in a production environment using the robust
LabelSpreading algorithm.
- The "From Scratch" Approach (using NumPy): This demonstrates the actual mathematics behind graph-based SSL (Label Propagation) so you understand how the graph is built and how labels flow between nodes.
Approach 1: Using Scikit-Learn (Recommended)
This method uses the built-in LabelSpreading module. This is efficient and handles edge cases (like numerical stability) automatically.
Key Concept: We construct a graph where nodes are data points. We connect them based on distance (similarity). The algorithm then "spreads" the known labels to the unlabeled nodes across the edges.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.semi_supervised import LabelSpreading
from sklearn.metrics import accuracy_score
def run_sklearn_example():
# 1. Generate a synthetic dataset (Two interleaving half circles)
X, y = make_moons(n_samples=200, noise=0.1, random_state=42)
# 2. Simulate 'Semi-Supervised' scenario
# We 'lose' the labels for 80% of the data
rng = np.random.RandomState(42)
random_unlabeled_points = rng.rand(len(y)) < 0.8
# Copy original labels to a new array
y_train = np.copy(y)
# Set unknown labels to -1 (Scikit-Learn convention for unlabeled)
y_train[random_unlabeled_points] = -1
# 3. Initialize the Graph-based model
# kernel='knn': Connects each point to its k nearest neighbors
# n_neighbors=7: Size of the neighborhood
# alpha=0.2: Clamping factor (how much we trust original labels vs graph structure)
# 0 = trust graph structure completely, 1 = never change original labels
label_prop_model = LabelSpreading(kernel='knn', n_neighbors=7, alpha=0.2)
# 4. Fit the model
label_prop_model.fit(X, y_train)
# 5. Retrieve the predicted labels for the unlabeled data
predicted_labels = label_prop_model.transduction_
# ---------------------------------------------------------
# Visualization
# ---------------------------------------------------------
plt.figure(figsize=(12, 5))
# Plot 1: The Input (Labeled vs Unlabeled)
plt.subplot(1, 2, 1)
plt.title("Input: Labeled (Colored) vs Unlabeled (Grey)")
# Plot unlabeled points
plt.scatter(X[random_unlabeled_points, 0], X[random_unlabeled_points, 1],
c='gray', s=10, label='Unlabeled', alpha=0.5)
# Plot the few labeled points we have
plt.scatter(X[~random_unlabeled_points, 0], X[~random_unlabeled_points, 1],
c=y[~random_unlabeled_points], s=50, cmap='viridis',
edgecolors='k', label='Labeled')
plt.legend()
# Plot 2: The Result (Learned Manifold)
plt.subplot(1, 2, 2)
plt.title("Output: Learned Labels (Graph Propagation)")
plt.scatter(X[:, 0], X[:, 1], c=predicted_labels, cmap='viridis', s=10)
# Highlight the originally labeled points
plt.scatter(X[~random_unlabeled_points, 0], X[~random_unlabeled_points, 1],
c=y[~random_unlabeled_points], s=50, cmap='viridis', edgecolors='r')
acc = accuracy_score(y, predicted_labels)
plt.suptitle(f"Graph-Based Semi-Supervised Learning (Accuracy: {acc:.2f})", fontsize=14)
plt.show()
if __name__ == "__main__":
run_sklearn_example()
Approach 2: From Scratch (Using NumPy)
This implementation demonstrates the Label Propagation Algorithm explicitly. It builds an adjacency matrix using a Radial Basis Function (RBF) kernel and iteratively updates the label probabilities.
The Algorithm steps:
- Build an Adjacency Matrix (W) based on distances between points.
- Normalize the matrix to create a Transition Matrix (T).
- Iteratively multiply the Label Matrix (Y) by T, but clamp the originally labeled data back to their true values at every step.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.metrics.pairwise import rbf_kernel
import matplotlib.pyplot as plt
class LabelPropagationScratch:
def __init__(self, X, y_masked, n_neighbors=7, gamma=20, max_iter=30):
self.X = X
self.y_masked = y_masked
self.n_samples = X.shape[0]
self.classes = np.unique(y_masked[y_masked != -1])
self.n_classes = len(self.classes)
self.gamma = gamma # Parameter for RBF kernel
self.max_iter = max_iter
# Initialize label matrix (One-hot encoding)
# If label is -1 (unknown), initial probability is uniform or zero
self.Y_init = np.zeros((self.n_samples, self.n_classes))
# Store indices of labeled and unlabeled data
self.labeled_indices = np.where(y_masked != -1)[0]
self.unlabeled_indices = np.where(y_masked == -1)[0]
# Set the known labels (One-hot)
for idx in self.labeled_indices:
class_idx = np.where(self.classes == y_masked[idx])[0][0]
self.Y_init[idx, class_idx] = 1
def _build_graph(self):
"""
Construct the adjacency matrix using RBF Kernel.
W_ij = exp(-gamma * ||x_i - x_j||^2)
"""
# Compute full similarity matrix
W = rbf_kernel(self.X, gamma=self.gamma)
# Sparsify: Keep only K-Nearest Neighbors (symmetrized)
# This makes the graph local rather than fully connected
n_neighbors = 7
for i in range(self.n_samples):
# Find indices of neighbors
neighbors = np.argsort(W[i, :])[-(n_neighbors + 1):] # +1 because self is included
# Create a mask
mask = np.zeros(self.n_samples, dtype=bool)
mask[neighbors] = True
# Zero out non-neighbors
W[i, ~mask] = 0
# Symmetrize the graph (If A is neighbor of B, B is neighbor of A)
W = np.maximum(W, W.T)
return W
def fit(self):
# 1. Build Graph
W = self._build_graph()
# 2. Normalize the Graph (Create Transition Matrix T)
# T = D^-1 * W, where D is the diagonal degree matrix
D = np.sum(W, axis=1)
D_inv = np.diag(1.0 / D)
T = D_inv @ W
# 3. Propagate Labels Iteratively
Y = np.copy(self.Y_init)
for i in range(self.max_iter):
# Step A: Spread labels: Y_new = T @ Y_old
Y_new = T @ Y
# Step B: Clamp (Reset) the originally labeled nodes
# This is crucial. It forces the source of truth to remain constant
Y_new[self.labeled_indices] = self.Y_init[self.labeled_indices]
Y = Y_new
# Optional: Check for convergence (changes are very small)
self.Y_final = Y
return self
def predict(self):
# Convert probabilities to discrete class labels
return self.classes[np.argmax(self.Y_final, axis=1)]
# --- Usage ---
if __name__ == "__main__":
# Generate Data
X, y = make_moons(n_samples=200, noise=0.1, random_state=42)
# Mask 80% of labels
y_masked = np.copy(y)
rng = np.random.RandomState(42)
y_masked[rng.rand(len(y)) < 0.8] = -1
# Run Scratch Model
model = LabelPropagationScratch(X, y_masked, gamma=20)
model.fit()
predictions = model.predict()
# Plot
plt.figure(figsize=(6, 6))
plt.title("From Scratch Label Propagation")
plt.scatter(X[:, 0], X[:, 1], c=predictions, cmap='viridis', s=10)
# Overlay the original labeled points in Red
labeled_idx = np.where(y_masked != -1)[0]
plt.scatter(X[labeled_idx, 0], X[labeled_idx, 1], c='red', s=50, label='Original Labeled', edgecolors='k')
plt.legend()
plt.show()
How it works
- The Graph: We treat every data point as a node. We draw edges between points that are close to each other (using K-Nearest Neighbors).
- The Weights: Edges have weights. If point A and point B are close, the weight is high. If they are far, the weight is low (or zero). This weight matrix represents the "smoothness" assumption: nearby points likely have the same label.
- Propagation: In the "From Scratch" example, we calculate a transition probability. A point "looks" at its neighbors, averages their current label scores, and adopts that average.
- Clamping: We prevent the originally labeled points from changing their minds. They act as anchors (sources) that pour "label energy" into the graph, which flows to the unlabeled points until the system stabilizes.