Visual Topology Regression via Deep Convolutional Networks
An empirical investigation into whether 2D visual representations of graphs contain sufficient structural signals to recover graph-level topological invariants (vertex & edge counts) without graph-native message passing.
Key Findings • System Architecture • Quickstart • Interactive Web App • Repository Layout • Contributing
Topolens explores a fundamental research question at the boundary of Computer Vision and Graph Learning:
Can a generic 2D Convolutional Neural Network (CNN) estimate topological properties—specifically node count $|V|$ and edge count $|E|$—purely from rendered 2D bitmap representations of graphs, and how does it compare to graph-native GNN architectures?
Graph Neural Networks (GNNs) operate natively on graph adjacency matrices and node features via spatial or spectral message passing. However, in many real-world scenarios—such as legacy scientific diagrams, scanned figures, UI wireframes, and biological pathways—only rendered 2D images are available. Topolens formulates graph counting as a visual regression task over 224×224 RGB images, benchmarking a 4-block CNN (CustomCNNRegressor) against a standard 3-layer Graph Convolutional Network (GraphCountGCN) and a non-learned density heuristic.
Evaluated on 1,676 test and held-out graphs across synthetic generators and real-world biological benchmark datasets (MUTAG & PROTEINS):
| Model | Split | Vertex MAE (N) | Vertex Median | Edge MAE (E) | Edge Median | Key Characteristics |
|---|---|---|---|---|---|---|
| Custom CNN | Synthetic Test | 3.20 | 1.0 | 25.39 | 4.0 | Highly accurate in-distribution |
| GCN Baseline | Synthetic Test | 19.05 | 14.0 | 76.21 | 42.0 | Degree-normalized mean pooling |
| Heuristic | Synthetic Test | 0.00* | 0.0 | 342.10 | 128.0 | *Trivial node lookup; edge formula fails on scale |
| Custom CNN | Held-Out (Real) | 10.62 | 3.0 | 28.03 | 10.0 | Robust on small-to-medium real graphs |
| GCN Baseline | Held-Out (Real) | 21.15 | 16.0 | 32.50 | 18.0 | Stable mean-pooling embedding |
| Heuristic | Held-Out (Real) | 0.00* | 0.0 | 4927.70 | 2841.0 | Catastrophic failure on large graphs |
Controlled intervention probes (
| Tier / Group | Variant | Vertex MAE | Edge MAE | Sample Size (N) | Primary Insight |
|---|---|---|---|---|---|
| Overall | original |
3.43 | 54.18 | 40 | Baseline canonical render (sfdp) |
| Overall | constant_node_size |
10.48 | 39.80 | 40 |
Vertex MAE triples ( |
| Overall | alt_layout |
3.08 | 35.53 | 40 | No significant layout sensitivity ( |
| Large Tier | original |
8.90 | 195.50 | 10 |
|
| Large Tier | constant_node_size |
16.70 | 82.80 | 10 | Vertex error doubles on large graphs |
| Large Tier | alt_layout |
7.10 | 122.40 | 10 | Apparent edge-MAE drop is a mean-distortion artifact from one outlier graph, not a real effect (Wilcoxon p=0.898, no significant layout sensitivity) |
| Medium Tier | constant_node_size |
15.30 | 51.70 | 10 |
|
| Small Tier | constant_node_size |
8.50 | 21.20 | 10 |
|
Figure 1: Mean Absolute Error (MAE) across original, constant node size, and alternative layout probes.
Categorization of model errors into domain-specific failure modes:
| Split | Failure Category | Mean Vertex MAE | Median Vertex MAE | Mean Edge MAE | Median Edge MAE | N |
|---|---|---|---|---|---|---|
| Held-Out | high_density_clutter |
0.43 | 0.0 | 1.13 | 1.0 | 144 |
| Held-Out | in_distribution_normal |
6.67 | 3.0 | 20.79 | 10.0 | 1090 |
| Held-Out | out_of_distribution_size |
96.64 | 71.0 | 203.60 | 155.0 | 67 |
| Test | high_density_clutter |
1.27 | 1.0 | 51.82 | 4.0 | 110 |
| Test | in_distribution_normal |
4.00 | 2.0 | 14.42 | 3.0 | 265 |
Figure 2: Top 15 worst-case prediction errors with true vs. predicted vertex/edge counts and category labels.
Pearson correlation coefficients (
| Split | Metric X | Metric Y | Pearson r | p-value | Interpretation |
|---|---|---|---|---|---|
| Test | ink_fraction |
num_edges |
+0.824 | Ink fraction strongly tracks edge count in synthetic data | |
| Test | ink_fraction |
pred_num_edges |
+0.845 | CNN edge output highly aligned with ink coverage | |
| Test | mean_component_area |
pred_num_vertices |
+0.627 | Connected component size correlates with vertex predictions | |
| Held-Out | ink_fraction |
pred_num_edges |
+0.465 | Ink shortcut degrades significantly on real biological graphs | |
| Held-Out | ink_fraction |
num_edges |
+0.093 | Real graphs violate simple pixel-coverage counting assumptions |
Figure 15: Grad-CAM Activation Maps Across Generators
Layer features[3] spatial attention heatmaps comparing Vertex target attention (left) vs. Edge target attention (right).
Figure 16: Grad-CAM Attention Maps on Failure Cases
Spatial attention patterns on worst-error graph predictions.
Figure 17: Top 15 Worst-Case Error Grid
Ranked top 15 worst-case edge prediction errors with true vs. predicted counts and taxonomy overlay badges.
-
Out-of-distribution size ceiling (
$n > 100$ ): The training set contains no graphs above 100 nodes. On the held-out real-world split ($n = 67$ graphs exceeding this ceiling), held-out vertex MAE is 96.64 and edge MAE is 203.6, compared with vertex MAE 6.67 / edge MAE 20.79 for the 1,090 in-distribution graphs in the same split. Do not use predictions on large graphs without awareness of this gap. -
Node-size shortcut confound: The renderer scales node radius as
$\max(15, 4000/n)$ , so larger nodes signal fewer vertices. A shortcut probe (constant node size) raises vertex MAE from 3.42 to 10.47 overall — strong evidence the model exploits visual node size rather than topology alone to count vertices. - Synthetic training distribution: The model was trained entirely on NetworkX-generated graphs (Erdős–Rényi, Barabási–Albert, Watts–Strogatz, random trees, dense). Graphs with markedly different visual structure — hierarchical, planar, or domain-specific layouts — may fall outside the learned distribution.
-
Single layout algorithm: All training images use Graphviz
sfdp(spring-electrical). An alternative-layout probe (Kamada-Kawai) shows no statistically significant change in either vertex or edge MAE (Wilcoxon p=0.499 vertex, p=0.898 edge) — a reassuring but narrow result that does not establish robustness to layout families with substantially different visual conventions (e.g. hierarchical or circular layouts), none of which were tested.
flowchart LR
subgraph Data Generation
A1[NetworkX Synthetic Generators] --> B[GraphML Raw Graphs]
A2[PyG TUDataset MUTAG/PROTEINS] --> B
end
subgraph Rendering Pipeline
B --> C{Graphviz sfdp Backend}
C -- Success --> D[224x224 RGB PNG]
C -- Fallback --> C2[NetworkX Spring Layout] --> D
end
subgraph Inference & Benchmarking
D --> E1[Custom CNN Regressor]
B --> E2[GraphCount GCN]
B --> E3[Density Heuristic]
end
subgraph Web & Evaluation
E1 --> F[Streamlit Web App]
E2 --> F
E3 --> F
E1 --> G[Grad-CAM Attention Maps]
end
-
Synthetic & Real Dataset Engine (
data/):-
Synthetic: 2,500 graphs across 5 generator families (Erdős–Rényi, Barabási–Albert, Watts–Strogatz, Random Trees, Dense ER) × 4 node tiers (tiny
$\le 10$ , small$10\text{–}25$ , medium$25\text{–}50$ , large$50\text{–}100$ ). - Real-World: MUTAG (188 graphs) & PROTEINS (1,113 graphs), including an out-of-distribution "xlarge" tier up to 620 nodes.
-
Synthetic: 2,500 graphs across 5 generator families (Erdős–Rényi, Barabási–Albert, Watts–Strogatz, Random Trees, Dense ER) × 4 node tiers (tiny
-
Custom CNN Regressor (
models/cnn_model.py):- 4-Block Conv2D stack with BatchNorm, ReLU, and MaxPool2D (
$3 \to 32 \to 64 \to 128 \to 256$ channels). - Adaptive Average Pooling (
$1 \times 1$ )$\to$ Linear MLP head ($256 \to 128 \to 2$ ), dropout 0.2. - Log-transformed targets ($\log(1 + y)$) with MSE loss and Adam optimizer.
- 4-Block Conv2D stack with BatchNorm, ReLU, and MaxPool2D (
-
Graph Neural Network Baseline (
models/gnn_baseline.py):- 3-Layer GCN architecture using PyTorch Geometric.
- Normalized degree node features +
global_mean_poolsize-invariant embeddings.
-
Grad-CAM Interpretation Engine (
models/gradcam.py):- Captures activation maps at
features[3](last spatial convolutional block) for target-specific (vertex vs. edge) visual attention analysis.
- Captures activation maps at
# 1. Clone repository
git clone https://github.com/whozahm3d/topolens.git
cd topolens
# 2. Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txtNote
Optional Backend: Graphviz sfdp rendering requires system-level Graphviz binaries installed on your system PATH (dot/sfdp). If unavailable, render_graphs.py gracefully falls back to NetworkX spring layout with an automated [WARN] notification.
Launch the production Streamlit application locally:
streamlit run app/app.pyOpen http://localhost:8501 in your browser.
The Streamlit web application (app/app.py) provides an interactive interface for model inspection, prediction, and visual interpretability:
-
Multi-Format Ingestion: Upload raw graph structures (
.graphml,.csv,.txt) or rendered visual graph images (.png,.jpg). - Live Multi-Model Comparison: Evaluates uploaded topology simultaneously through the CNN, GCN, and Statistical Heuristic models.
-
Dynamic Warning Banner: Fires context-aware low-confidence alerts when node counts exceed the empirical training distribution (
$|V| > 100$ ) or when density enters the clutter regime ($\text{density} \ge 0.40$ ). - Grad-CAM Heatmap Overlay: Real-time side-by-side rendering of spatial attention for vertex counting vs. edge counting.
- Research Insights Suite: Interactive dashboards covering shortcut probes, layout sensitivity, and ink coverage correlations.
All models support automatic CUDA GPU detection (used for Colab T4 training) and fall back to CPU execution:
# Train CNN Regressor (smoke test: 2 epochs on tiny subset)
python models/train_cnn.py --smoke-test
# Train CNN Regressor (full training)
python models/train_cnn.py
# Train GCN Baseline (smoke test: 2 epochs on tiny subset)
python models/gnn_baseline.py --smoke-test
# Train GCN Baseline (full training)
python models/gnn_baseline.py# Evaluate checkpoints against test and held-out splits
python evaluation/evaluate.py
# Run error analysis & generate scatter plots
python evaluation/error_analysis.py
# Run failure-case taxonomy classification
python evaluation/failure_taxonomy.py
# Execute controlled shortcut and layout probes
python render/render_probe_variants.py
python evaluation/shortcut_probe.py
# Compute ink coverage & component stats
python evaluation/ink_coverage_analysis.pytopolens/
├── app/
│ ├── app.py # Main Streamlit multi-page web application
│ └── .streamlit/config.toml # UI theme styling & configuration
├── data/
│ ├── raw/ # Raw GraphML synthetic & real graph files
│ ├── images/ # Rendered 224x224 graph images
│ ├── images_probe/ # Rendered probe variants (constant node size, alt layouts)
│ ├── novel_images/ # Raw user-uploaded/scanned/handwritten test images (handwritten_graph_*.jpeg)
│ ├── processed/ # Dataset manifests & labels (labels_processed.csv, probe_manifest.csv)
│ ├── splits/ # Train, val, test, and held-out CSV splits
│ ├── gephi_demo/ # Curated diverse graphs exported for manual rendering in Gephi
│ ├── generate_synthetic.py # NetworkX synthetic graph generator
│ ├── load_tu_datasets.py # PyG MUTAG / PROTEINS dataset importer
│ ├── make_splits.py # Stratified dataset split script
│ └── validate_dataset.py # Dataset integrity validator (labels vs. rendered graphs)
├── render/
│ ├── render_graphs.py # Core Graphviz/NetworkX graph rendering engine
│ ├── render_probe_variants.py # Controlled probe variant generator
│ └── novel_uploads/ # User-uploaded application testing images & manifest
├── models/
│ ├── cnn_model.py # Custom 4-block CNN Regressor architecture
│ ├── gnn_baseline.py # PyG 3-layer GraphCountGCN model + self-contained training CLI
│ ├── graph_statistic_baseline.py# Density-based statistical baseline
│ ├── dataset.py # PyTorch TopolensImageDataset & normalization
│ ├── gradcam.py # Grad-CAM attention heatmap generator
│ ├── train_cnn.py # CNN training loop with checkpointing
│ └── checkpoints/ # Trained PyTorch model checkpoints (.pt)
├── evaluation/
│ ├── evaluate.py # Multi-model test & held-out evaluation runner
│ ├── error_analysis.py # Error distribution & faceted scatter plots
│ ├── failure_taxonomy.py # Out-of-distribution & clutter failure classifier
│ ├── shortcut_probe.py # Node-size & layout intervention analyzer
│ ├── ink_coverage_analysis.py # Pixel coverage & connected component analysis
│ ├── image_statistics.py # Ink-fraction & connected-component pixel helpers
│ ├── compute_structural_pixel_features.py # Structural + pixel feature merge for pixel-only baseline
│ ├── interpretation.py # Grad-CAM interpretation orchestration script
│ ├── generate_dual_trigger_testcase.py # Dual OOD-size + dense-clutter warning testcase generator
│ └── results/ # Computed evaluation CSV metrics & summaries
│ ├── baseline_predictions.csv # Predictions from the heuristic baseline
│ ├── cnn_metrics.csv # Error metrics computed for the CNN
│ ├── cnn_training_log.csv # Train and validation loss log for the CNN
│ ├── cnn_worst_edge_errors.csv # List of worst edge errors for the CNN
│ ├── failure_case_categories.csv # Full categorical failure cases classifications
│ ├── failure_case_summary.csv # Failure case category metrics summary
│ ├── gnn_metrics.csv # Error metrics computed for the GNN
│ ├── gnn_training_log.csv # Train and validation loss log for the GNN
│ ├── graph_statistic_metrics.csv # Error metrics computed for the heuristic
│ ├── ink_coverage_correlations.csv # Correlation coefficients for ink/pixel metrics
│ ├── probe_predictions.csv # Variant predictions for the shortcut/layout probes
│ ├── probe_summary.csv # Summary metrics across the probe variants
│ ├── structural_pixel_features.csv # Structural and pixel features computed per graph
│ ├── summary_comparison.csv # Side-by-side metrics comparisons across models
│ ├── topolens_free_analyses_results.csv # Metrics for Wilcoxon and warning validation tests
│ ├── topolens_novelimage_results.csv # Predictions on user-uploaded/novel images
│ ├── topolens_novelimage_results.docx # Word document summary of novel image predictions
│ ├── topolens_pixel_structural_correlations.csv # Correlations between structural attributes and errors
│ ├── topolens_spotcheck_results.csv # Predictions on live spotcheck graphs
│ └── topolens_spotcheck_results.docx # Word document summary of spotcheck predictions
├── notebooks/ # Exploratory analysis & visualization notebooks
├── report/
│ ├── FINAL_REPORT.md # Comprehensive research report & submission
│ ├── log.md # Technical execution log
│ ├── figures/ # Generated figures, Grad-CAM grids, and plots
│ └── latex/ # LaTeX report sources and compiled outputs
│ ├── topolens_report.tex # LaTeX source document for the research report
│ ├── topolens_report.pdf # Compiled PDF of the final research report
│ ├── topolens_report.aux # Auxiliary file containing references/labels
│ ├── topolens_report.log # LaTeX engine compilation log
│ ├── topolens_report.out # Bookmarks/hyperlinks metadata
│ ├── topolens_report.toc # Table of contents auxiliary file
│ ├── topolens_report.lof # List of figures auxiliary file
│ └── topolens_report.lot # List of tables auxiliary file
├── config.py # Central Python environment & path constants
├── config.yaml # Global YAML parameter configuration
├── topolens_utils.py # Shared deterministic path/seed/config helpers
├── test_render.py # Rendering reproducibility/regression test
├── progress_log.md # Narrative project development log
├── requirements.txt # Pinned Python package dependencies
├── CONTRIBUTING.md # Open-source contribution guidelines
└── LICENSE # MIT License
- Deterministic Random Seeds: All stochastic processes (graph generation, split partitioning, weight initialization, probe sampling) are seeded via
config.yaml(project.seed = 42). - Graph ID Hashing: Individual synthetic graph parameters are derived deterministically using SHA-256 hashes of
graph_idstrings. - Checkpoint Compatibility: Model checkpoints saved during GPU training explicitly support CPU execution (
map_location="cpu") and safe dict unpickling (weights_only=False).
Topolens demonstrates that while graph-native message passing architectures (GNNs) remain the theoretical benchmark for structured topology, deep convolutional vision models can extract latent geometric invariants purely from 2D visual layouts. When properly calibrated against visual shortcuts (such as node scaling radii and pixel ink density), 2D visual topology regression provides a practical, non-invasive alternative for counting and analyzing graph structures from legacy diagrams, UI wireframes, and scanned scientific publications where raw adjacency data is unavailable.
- Vision Transformers (ViT): Evaluating self-attention mechanisms (e.g., DINOv2 / ViT-B) to test patch-level scale invariance on complex graph renders.
-
Multi-Layout Visual Ensembles: Training vision backbones on multi-projection renders (
$sfdp$ +$Kamada\text{-}Kawai$ +$Circo$ ) to eliminate layout-specific spatial bias. -
Joint Density-Scale Calibration: Learning continuous joint embeddings of node size and clutter density to extend reliable counting beyond
$|V| > 100$ .
Developed as an intensive 9-day empirical research investigation (13–21 July 2026, weekend included) into visual graph learning.
Special thanks to the open-source maintainers of:
- PyTorch & PyTorch Geometric for neural network and graph learning primitives.
-
NetworkX & Graphviz for graph generation and
$sfdp$ layout algorithms. - Streamlit for interactive model visualization and web application prototyping.
- TU Dortmund Benchmark Collection for the MUTAG and PROTEINS real-world datasets.
Distributed under the MIT License. See LICENSE for details.
If you use Topolens in your research or project, please cite:
@misc{topolens2026,
author = {Whozahm3d},
title = {Topolens: Visual Topology Regression via Deep Convolutional Networks},
year = {2026},
publisher = {GitHub},
url = {https://github.com/whozahm3d/topolens}
}