惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

腾讯CDC
Hacker News: Ask HN
Hacker News: Ask HN
S
Securelist
Security Latest
Security Latest
S
Schneier on Security
T
Threat Research - Cisco Blogs
Latest news
Latest news
Cyberwarzone
Cyberwarzone
A
Arctic Wolf
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
T
The Exploit Database - CXSecurity.com
N
News and Events Feed by Topic
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
Blog — PlanetScale
Blog — PlanetScale
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CERT Recently Published Vulnerability Notes
The Hacker News
The Hacker News
月光博客
月光博客
WordPress大学
WordPress大学
博客园 - 叶小钗
Hugging Face - Blog
Hugging Face - Blog
美团技术团队
量子位
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cisco Blogs
博客园 - 三生石上(FineUI控件)
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
Webroot Blog
Webroot Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Application and Cybersecurity Blog
Application and Cybersecurity Blog
云风的 BLOG
云风的 BLOG
L
LINUX DO - 最新话题
Schneier on Security
Schneier on Security
Engineering at Meta
Engineering at Meta
www.infosecurity-magazine.com
www.infosecurity-magazine.com
aimingoo的专栏
aimingoo的专栏
D
Docker
有赞技术团队
有赞技术团队
Google DeepMind News
Google DeepMind News
宝玉的分享
宝玉的分享
T
Troy Hunt's Blog
L
Lohrmann on Cybersecurity
T
The Blog of Author Tim Ferriss
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
LangChain Blog

MarkTechPost

A Coding Implementation of End-to-End Brain Decoding from MEG Signals Using NeuralSet and Deep Learning for Predicting Linguistic Features Meta Introduces Autodata: An Agentic Framework That Turns AI Models into Autonomous Data Scientists for High-Quality Training Data Creation Qwen AI Releases Qwen-Scope: An Open-Source Sparse AutoEncoders (SAE) Suite That Turns LLM Internal Features into Practical Development Tools A Coding Deep Dive into Agentic UI, Generative UI, State Synchronization, and Interrupt-Driven Approval Flows Moonshot AI Open-Sources FlashKDA: CUTLASS Kernels for Kimi Delta Attention with Variable-Length Batching and H20 Benchmarks Microsoft Research’s World-R1 Uses Flow-GRPO and 3D-Aware Rewards to Inject Geometric Consistency Into Wan 2.1 Without Architectural Changes A Coding Implementation on Pyright Type Checking Covering Generics, Protocols, Strict Mode, Type Narrowing, and Modern Python Typing IBM Releases Two Granite Speech 4.1 2B Models: Autoregressive ASR with Translation and Non-Autoregressive Editing for Fast Inference Top 10 KV Cache Compression Techniques for LLM Inference: Reducing Memory Overhead Across Eviction, Quantization, and Low-Rank Methods Qwen Team Releases FlashQLA: a High-Performance Linear Attention Kernel Library That Achieves Up to 3× Speedup on NVIDIA Hopper GPUs Step by Step Guide to Build a Complete PII Detection and Redaction Pipeline with OpenAI Privacy Filter Meta FAIR Releases NeuralSet: A Python Package for Neuro-AI That Supports fMRI, M/EEG, Spikes, and HuggingFace Embeddings smol-audio: A Colab-Friendly Notebook Collection for Fine-Tuning Whisper, Parakeet, Voxtral, Granite Speech, and Audio Flamingo 3 A Coding Implementation on Document Parsing Benchmarking with LlamaIndex ParseBench Using Python, Hugging Face, and Evaluation Metrics Poolside AI Introduces Laguna XS.2 and M.1: Agentic Coding Models Reaching 68.2% and 72.5% on SWE-bench Verified How to Build Traceable and Evaluated LLM Workflows Using Promptflow, Prompty, and OpenAI OpenAI Releases Privacy Filter: A 1.5B-Parameter Open-Source PII Redaction Model with 50M Active Parameters Top 10 Physical AI Models Powering Real-World Robots in 2026 How to Build a Lightweight Vision-Language-Action-Inspired Embodied Agent with Latent World Modeling and Model Predictive Control Meet Talkie-1930: A 13B Open-Weight LLM Trained on Pre-1931 English Text for Historical Reasoning and Generalization Research Build a Reinforcement Learning Powered Agent that Learns to Retrieve Relevant Long-Term Memories for Accurate LLM Question Answering OpenMOSS Releases MOSS-Audio: An Open-Source Foundation Model for Speech, Sound, Music, and Time-Aware Audio Reasoning Meta AI Releases Sapiens2: A High-Resolution Human-Centric Vision Model for Pose, Segmentation, Normals, Pointmap, and Albedo The LoRA Assumption That Breaks in Production How to Build a Fully Searchable AI Knowledge Base with OpenKB, OpenRouter, and Llama How to Build Smarter Multilingual Text Wrapping with BudouX Through Parsing, HTML Rendering, Model Introspection, and Toy Training Top 7 Benchmarks That Actually Matter for Agentic Reasoning in Large Language Models RAG Without Vectors: How PageIndex Retrieves by Reasoning A Coding Tutorial on Datashader on Rendering Massive Datasets with High-Performance Python Visual Analytics xAI Launches grok-voice-think-fast-1.0: Topping τ-voice Bench at 67.3%, Outperforming Gemini, GPT Realtime, and More A Coding Implementation on kvcached for Elastic KV Cache Memory, Bursty LLM Serving, and Multi-Model GPU Sharing Google DeepMind Introduces Vision Banana: An Instruction-Tuned Image Generator That Beats SAM 3 on Segmentation and Depth Anything V3 on Metric Depth Estimation Meet GitNexus: An Open-Source MCP-Native Knowledge Graph Engine That Gives Claude Code and Cursor Full Codebase Structural Awareness A Coding Implementation on Deepgram Python SDK for Transcription, Text-to-Speech, Async Audio Processing, and Text Intelligence A Coding Implementation on Microsoft’s OpenMementos with Trace Structure Analysis, Context Compression, and Fine-Tuning Data Preparation DeepSeek AI Releases DeepSeek-V4: Compressed Sparse Attention and Heavily Compressed Attention Enable One-Million-Token Contexts Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Training Architecture Achieving 88% Goodput Under High Hardware Failure Rates Mend Releases AI Security Governance Framework: Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model Mend.io Releases AI Security Governance Framework Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model OpenAI Releases GPT-5.5, a Fully Retrained Agentic Model That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval A Coding Tutorial on OpenMythos on Recurrent-Depth Transformers with Depth Extrapolation, Adaptive Computation, and Mixture-of-Experts Routing Google Cloud AI Research Introduces ReasoningBank: A Memory Framework that Distills Reasoning Strategies from Agent Successes and Failures Xiaomi Releases MiMo-V2.5-Pro and MiMo-V2.5: Matching Frontier Model Benchmarks at Significantly Lower Token Cost How to Design a Production-Grade CAMEL Multi-Agent System with Planning, Tool Use, Self-Consistency, and Critique-Driven Refinement Alibaba Qwen Team Releases Qwen3.6-27B: A Dense Open-Weight Model Outperforming 397B MoE on Agentic Coding Benchmarks A Detailed Implementation on Equinox with JAX Native Modules, Filtered Transforms, Stateful Layers, and End-to-End Training Workflows Next Leap to Harness Engineering: JiuwenClaw Pioneers ‘Coordination Engineering’ Photon Releases Spectrum: An Open-Source TypeScript Framework that Deploys AI Agents Directly to iMessage, WhatsApp, and Telegram OpenAI Open-Sources Euphony: A Browser-Based Visualization Tool for Harmony Chat Data and Codex Session Logs Hugging Face Releases ml-intern: An Open-Source AI Agent that Automates the LLM Post-Training Workflow A Coding Implementation to Build a Conditional Bayesian Hyperparameter Optimization Pipeline with Hyperopt, TPE, and Early Stopping Google Introduces Simula: A Reasoning-First Framework for Generating Controllable, Scalable Synthetic Datasets Across Specialized AI Domains A Coding Implementation on Qwen 3.6-35B-A3B Covering Multimodal Inference, Thinking Control, Tool Calling, MoE Routing, RAG, and Session Persistence Moonshot AI Releases Kimi K2.6 with Long-Horizon Coding, Agent Swarm Scaling to 300 Sub-Agents and 4,000 Coordinated Steps A Coding Implementation on Microsoft’s Phi-4-Mini for Quantized Inference Reasoning Tool Use RAG and LoRA Fine-Tuning OpenAI Scales Trusted Access for Cyber Defense With GPT-5.4-Cyber: a Fine-Tuned Model Built for Verified Security Defenders Moonshot AI and Tsinghua Researchers Propose PrfaaS: A Cross-Datacenter KVCache Architecture that Rethinks How LLMs are Served at Scale Meet OpenMythos: An Open-Source PyTorch Reconstruction of Claude Mythos Where 770M Parameters Match a 1.3B Transformer How TabPFN Leverages In-Context Learning to Achieve Superior Accuracy on Tabular Datasets Compared to Random Forest and CatBoost A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI NVIDIA Releases Ising: the First Open Quantum AI Model Family for Hybrid Quantum-Classical Systems xAI Launches Standalone Grok Speech-to-Text and Text-to-Speech APIs, Targeting Enterprise Voice Developers A Coding Tutorial for Running PrismML Bonsai 1-Bit LLM on CUDA with GGUF, Benchmarking, Chat, JSON, and RAG A Coding Guide for Property-Based Testing Using Hypothesis with Stateful, Differential, and Metamorphic Test Design Anthropic Releases Claude Opus 4.7: A Major Upgrade for Agentic Coding, High-Resolution Vision, and Long-Horizon Autonomous Tasks Google AI Releases Auto-Diagnose: An Large Language Model LLM-Based System to Diagnose Integration Test Failures at Scale A End-to-End Coding Guide to Running OpenAI GPT-OSS Open-Weight Models with Advanced Inference Workflows Top 19 AI Red Teaming Tools (2026): Secure Your ML Models A Coding Guide to Build a Production-Grade Background Task Processing System Using Huey with SQLite, Scheduling, Retries, Pipelines, and Concurrency Control Qwen Team Open-Sources Qwen3.6-35B-A3B: A Sparse MoE Vision-Language Model with 3B Active Parameters and Agentic Coding Capabilities OpenAI Launches GPT-Rosalind: Its First Life Sciences AI Model Built to Accelerate Drug Discovery and Genomics Research Building Transformer-Based NQS for Frustrated Spin Systems with NetKet UCSD and Together AI Research Introduces Parcae: A Stable Architecture for Looped Language Models That Achieves the Quality of a Transformer Twice the Size How to Build a Universal Long-Term Memory Layer for AI Agents Using Mem0 and OpenAI A Coding Implementation to Build Multi-Agent AI Systems with SmolAgents Using Code Execution, Tool Calling, and Dynamic Orchestration A Technical Deep Dive into the Essential Stages of Modern Large Language Model Training, Alignment, and Deployment Google AI Launches Gemini 3.1 Flash TTS: A New Benchmark in Expressive and Controllable AI Voice Google DeepMind Releases Gemini Robotics-ER 1.6: Bringing Enhanced Embodied Reasoning and Instrument Reading to Physical AI Google Launches ‘Skills’ in Chrome: Turning Reusable AI Prompts into One-Click Browser Workflows A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction TinyFish AI Releases Full Web Infrastructure Platform for AI Agents: Search, Fetch, Browser, and Agent Under One API Key NVIDIA and the University of Maryland Researchers Released Audio Flamingo Next (AF-Next): A Super Powerful and Open Large Audio-Language Model A Hands-On Coding Tutorial for Microsoft VibeVoice Covering Speaker-Aware ASR, Real-Time TTS, and Speech-to-Speech Pipelines Meta AI and KAUST Researchers Propose Neural Computers That Fold Computation, Memory, and I/O Into One Learned Model A Coding Implementation of MolmoAct for Depth-Aware Spatial Reasoning, Visual Trajectory Tracing, and Robotic Action Prediction MiniMax Just Open Sourced MiniMax M2.7: A Self-Evolving Agent Model that Scores 56.22% on SWE-Pro and 57.0% on Terminal Bench 2 Liquid AI Releases LFM2.5-VL-450M: a 450M-Parameter Vision-Language Model with Bounding Box Prediction, Multilingual Support, and Sub-250ms Edge Inference Researchers from MIT, NVIDIA, and Zhejiang University Propose TriAttention: A KV Cache Compression Method That Matches Full Attention at 2.5× Higher Throughput How to Build a Secure Local-First Agent Runtime with OpenClaw Gateway, Skills, and Controlled Tool Execution How Knowledge Distillation Compresses Ensemble Intelligence into a Single Deployable AI Model Alibaba’s Tongyi Lab Releases VimRAG: a Multimodal RAG Framework that Uses a Memory Graph to Navigate Massive Visual Contexts A Coding Guide to Markerless 3D Human Kinematics with Pose2Sim, RTMPose, and OpenSim NVIDIA Releases AITune: An Open-Source Inference Toolkit That Automatically Finds the Fastest Inference Backend for Any PyTorch Model Five AI Compute Architectures Every Engineer Should Know: CPUs, GPUs, TPUs, NPUs, and LPUs Compared An End-to-End Coding Guide to NVIDIA KVPress for Long-Context LLM Inference, KV Cache Compression, and Memory-Efficient Generation Meta Superintelligence Lab Releases Muse Spark: A Multimodal Reasoning Model With Thought Compression and Parallel Agents Sigmoid vs ReLU Activation Functions: The Inference Cost of Losing Geometric Context A Coding Guide to Build Advanced Document Intelligence Pipelines with Google LangExtract, OpenAI Models, Structured Extraction, and Interactive Visualization Google AI Research Introduces PaperOrchestra: A Multi-Agent Framework for Automated AI Research Paper Writing A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export
A Coding Implementation on Spatial Graph Neural Networks for Urban Function Inference Using city2graph, OSMnx, and PyTorch Geometric
Sana Hassan · 2026-06-13 · via MarkTechPost

In this tutorial, we build an end-to-end spatial graph learning pipeline using city2graph. We start by collecting real urban POI data and street network information from OpenStreetMap, with a synthetic fallback to ensure the workflow remains reliable. We then engineer spatial features, construct multiple proximity graph families, and compare how different graph-building strategies represent the same urban environment. After that, we create both heterogeneous and homogeneous graph structures, convert them into PyTorch Geometric format, and train a GraphSAGE model to predict POI categories from spatial structure. Through this process, we integrate geospatial data processing, graph construction, and GNN-based urban function inference into a single practical workflow.

Installing city2graph and Importing Geospatial and Graph Learning Libraries

!pip -q install "city2graph[cpu]" osmnx contextily scikit-learn 2>/dev/null
import warnings, numpy as np, pandas as pd, geopandas as gpd
warnings.filterwarnings("ignore")
from shapely.geometry import Point
import matplotlib.pyplot as plt
import city2graph as c2g
print("city2graph version:", getattr(c2g, "__version__", "unknown"))
print("PyTorch / PyG available:", c2g.is_torch_available())
import torch
import torch.nn.functional as F
from torch_geometric.nn import SAGEConv, to_hetero
from torch_geometric.utils import to_undirected
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import accuracy_score, f1_score
from sklearn.decomposition import PCA
SEED = 42
np.random.seed(SEED); torch.manual_seed(SEED)

We begin by installing the required libraries and importing the geospatial, graph learning, and machine learning tools used throughout the tutorial. We verify that city2graph and PyTorch Geometric are available so the rest of the workflow can run properly. We also set a fixed random seed to make the graph construction, training split, and model results more reproducible.

Collecting OpenStreetMap POI Data with a Synthetic Fallback

CENTER = (35.6595, 139.7005)
DIST_M = 1100
TAG_QUERIES = {
   "food":      {"amenity": ["restaurant", "cafe", "fast_food", "bar", "pub"]},
   "retail":    {"shop": True},
   "education": {"amenity": ["school", "university", "college", "kindergarten", "library"]},
   "health":    {"amenity": ["hospital", "clinic", "pharmacy", "doctors", "dentist"]},
}
def to_points(gdf):
   g = gdf.copy()
   g["geometry"] = g.geometry.representative_point()
   return g
poi_gdf, segments_gdf = None, None
try:
   import osmnx as ox
   ox.settings.use_cache = True
   ox.settings.log_console = False
   frames = []
   for label, tags in TAG_QUERIES.items():
       try:
           f = ox.features_from_point(CENTER, tags=tags, dist=DIST_M)
           f = f[f.geometry.notna()]
           if len(f):
               f = to_points(f)[["geometry"]].copy()
               f["category"] = label
               frames.append(f)
       except Exception as e:
           print(f"  (skip {label}: {e})")
   if not frames:
       raise RuntimeError("No POIs returned from Overpass.")
   poi_gdf = gpd.GeoDataFrame(pd.concat(frames, ignore_index=True), crs="EPSG:4326")
   G = ox.graph_from_point(CENTER, dist=DIST_M, network_type="walk")
   segments_gdf = ox.graph_to_gdfs(G, nodes=False, edges=True).reset_index(drop=True)[["geometry"]]
   print(f"OSM acquisition OK -> {len(poi_gdf)} POIs, {len(segments_gdf)} street segments")
except Exception as e:
   print(f"OSM unavailable ({e}) -> generating synthetic clustered POIs.")
   rng = np.random.default_rng(SEED)
   cats = list(TAG_QUERIES.keys())
   centers = rng.uniform(-0.01, 0.01, size=(8, 2)) + np.array(CENTER[::-1])
   rows = []
   for ci, c in enumerate(centers):
       dom = cats[ci % len(cats)]
       n = rng.integers(40, 90)
       pts = c + rng.normal(0, 0.0016, size=(n, 2))
       for (lon, lat) in pts:
           cat = dom if rng.random() < 0.75 else rng.choice(cats)
           rows.append({"geometry": Point(lon, lat), "category": cat})
   poi_gdf = gpd.GeoDataFrame(rows, crs="EPSG:4326")
   segments_gdf = None
   print(f"Synthetic dataset -> {len(poi_gdf)} POIs")
if len(poi_gdf) > 700:
   poi_gdf = poi_gdf.sample(700, random_state=SEED).reset_index(drop=True)
metric_crs = poi_gdf.estimate_utm_crs()
poi_gdf = poi_gdf.to_crs(metric_crs).reset_index(drop=True)
if segments_gdf is not None:
   segments_gdf = segments_gdf.to_crs(metric_crs)
print("Class balance:\n", poi_gdf["category"].value_counts())

We collect real POI data from OpenStreetMap around Shibuya, Tokyo, and group the locations into broad urban function categories such as food, retail, education, and health. We also download the walkable street network so that the POIs can later be connected with urban-form features. If the OSM request fails, we generate a synthetic clustered dataset, which keeps the tutorial runnable even when online data access is unavailable.

Engineering Spatial Features and Building Proximity Graph Families

poi_gdf["cx"] = poi_gdf.geometry.x
poi_gdf["cy"] = poi_gdf.geometry.y
coords = poi_gdf[["cx", "cy"]].to_numpy()
nn = NearestNeighbors(radius=150.0).fit(coords)
poi_gdf["local_density"] = [len(idx) - 1 for idx in nn.radius_neighbors(coords, return_distance=False)]
if segments_gdf is not None and len(segments_gdf):
   try:
       joined = gpd.sjoin_nearest(poi_gdf[["geometry"]], segments_gdf[["geometry"]],
                                  distance_col="dist_street")
       poi_gdf["dist_street"] = joined.groupby(level=0)["dist_street"].min().reindex(poi_gdf.index).fillna(0.0)
   except Exception:
       poi_gdf["dist_street"] = 0.0
else:
   poi_gdf["dist_street"] = 0.0
poi_gdf["category"] = poi_gdf["category"].astype("category")
poi_gdf["label"] = poi_gdf["category"].cat.codes.astype(int)
CLASS_NAMES = list(poi_gdf["category"].cat.categories)
print("Classes:", CLASS_NAMES)
def graph_stats(name, builder):
   try:
       nodes, edges = builder()
       deg = pd.Series(np.r_[edges.index.get_level_values(0),
                             edges.index.get_level_values(1)]).value_counts()
       return name, len(edges), round(deg.mean(), 2), (nodes, edges)
   except Exception as e:
       return name, f"ERR: {e}", None, None
builders = {
   "KNN (k=8)":  lambda: c2g.knn_graph(poi_gdf, distance_metric="euclidean", k=8, as_nx=False),
   "Delaunay":   lambda: c2g.delaunay_graph(poi_gdf, as_nx=False),
   "Gabriel":    lambda: c2g.gabriel_graph(poi_gdf, as_nx=False),
   "RNG":        lambda: c2g.relative_neighborhood_graph(poi_gdf, as_nx=False),
   "EMST":       lambda: c2g.euclidean_minimum_spanning_tree(poi_gdf, as_nx=False),
   "Waxman":     lambda: c2g.waxman_graph(poi_gdf, distance_metric="euclidean", r0=150, beta=0.6),
}
print("\n--- Proximity graph comparison ---")
print(f"{'graph':<14}{'#edges':>10}{'avg_degree':>12}")
built = {}
for nm, b in builders.items():
   name, ne, avgdeg, payload = graph_stats(nm, b)
   print(f"{name:<14}{str(ne):>10}{str(avgdeg):>12}")
   if payload: built[nm] = payload
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
for ax, key in zip(axes, ["KNN (k=8)", "Delaunay", "EMST"]):
   if key in built:
       n_, e_ = built[key]
       e_.plot(ax=ax, linewidth=0.4, color="#3b7dd8", alpha=0.6)
       poi_gdf.plot(ax=ax, markersize=4, color="#d83b5c")
       ax.set_title(key); ax.set_axis_off()
plt.suptitle("Spatial graph topologies on the same POI set", y=1.02)
plt.tight_layout(); plt.show()

We engineer spatial features for each POI by extracting its projected coordinates, calculating local density, and estimating distance to the nearest street segment. We then assign category labels and build several families of proximity graphs, including KNN, Delaunay, Gabriel, RNG, EMST, and Waxman. We compare their edge counts and average degrees, then visualize selected graph topologies to see how differently they connect the same set of POIs.

Constructing Heterogeneous and Homogeneous Graphs in PyTorch Geometric

nodes_dict = {}
for cat in CLASS_NAMES:
   sub = poi_gdf[poi_gdf["category"] == cat].copy().reset_index(drop=True)
   nodes_dict[cat] = sub[["geometry", "cx", "cy", "local_density"]]
try:
   _, bridge_edges = c2g.bridge_nodes(nodes_dict, proximity_method="knn", k=3,
                                      distance_metric="euclidean")
   hetero = c2g.gdf_to_pyg(
       nodes_dict, bridge_edges,
       node_feature_cols={cat: ["cx", "cy", "local_density"] for cat in CLASS_NAMES},
   )
   print("\nHeteroData node types:", hetero.node_types)
   print("HeteroData edge types:")
   for et in hetero.edge_types:
       print(f"   {et}: {hetero[et].edge_index.shape[1]} edges")
except Exception as e:
   hetero = None
   print("Heterogeneous build skipped:", e)
nodes, edges = c2g.knn_graph(poi_gdf, distance_metric="euclidean", k=8, as_nx=False)
deg = pd.Series(np.r_[edges.index.get_level_values(0),
                     edges.index.get_level_values(1)]).value_counts()
nodes["degree"] = deg.reindex(nodes.index).fillna(0).astype(float)
for col in ["cx", "cy", "local_density", "dist_street", "label"]:
   if col not in nodes.columns:
       nodes[col] = poi_gdf.loc[nodes.index, col].values
FEATS = ["cx", "cy", "local_density", "dist_street", "degree"]
nodes[FEATS] = StandardScaler().fit_transform(nodes[FEATS].astype(float))
data = c2g.gdf_to_pyg(nodes, edges, node_feature_cols=FEATS, node_label_cols=["label"])
data.edge_index = to_undirected(data.edge_index)
data.x = data.x.float()
y = data.y.long().view(-1)
N, num_classes = data.num_nodes, int(y.max()) + 1
print(f"\nHomogeneous Data: {N} nodes, {data.edge_index.shape[1]} directed-edges, "
     f"{data.x.shape[1]} features, {num_classes} classes")

We construct a heterogeneous multi-layer graph by separating POIs into node types based on their urban function categories. We then use bridge edges to connect nearby nodes across different layers and convert the result into PyTorch Geometric HeteroData format. After that, we build a homogeneous KNN graph, attach degree and engineered features, standardize them, and prepare the final PyG Data object for GraphSAGE training.

Defining and Training a GraphSAGE Model for POI Classification

perm = torch.randperm(N, generator=torch.Generator().manual_seed(SEED))
n_tr, n_va = int(0.6 * N), int(0.2 * N)
train_mask = torch.zeros(N, dtype=torch.bool); train_mask[perm[:n_tr]] = True
val_mask   = torch.zeros(N, dtype=torch.bool); val_mask[perm[n_tr:n_tr + n_va]] = True
test_mask  = torch.zeros(N, dtype=torch.bool); test_mask[perm[n_tr + n_va:]] = True
class GraphSAGE(torch.nn.Module):
   def __init__(self, in_dim, hidden, out_dim, p=0.3):
       super().__init__()
       self.c1 = SAGEConv(in_dim, hidden)
       self.c2 = SAGEConv(hidden, hidden)
       self.lin = torch.nn.Linear(hidden, out_dim)
       self.p = p
   def forward(self, x, ei, return_emb=False):
       h = F.relu(self.c1(x, ei))
       h = F.dropout(h, p=self.p, training=self.training)
       h = F.relu(self.c2(h, ei))
       out = self.lin(h)
       return (out, h) if return_emb else out
model = GraphSAGE(data.x.shape[1], 64, num_classes)
opt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
def evaluate(mask):
   model.eval()
   with torch.no_grad():
       pred = model(data.x, data.edge_index).argmax(1)
   yt, yp = y[mask].numpy(), pred[mask].numpy()
   return accuracy_score(yt, yp), f1_score(yt, yp, average="macro")
print("\n--- Training GraphSAGE ---")
best_val, best_state = 0.0, None
for epoch in range(1, 201):
   model.train(); opt.zero_grad()
   out = model(data.x, data.edge_index)
   loss = F.cross_entropy(out[train_mask], y[train_mask])
   loss.backward(); opt.step()
   if epoch % 20 == 0:
       va_acc, va_f1 = evaluate(val_mask)
       if va_acc > best_val:
           best_val, best_state = va_acc, {k: v.clone() for k, v in model.state_dict().items()}
       print(f"epoch {epoch:3d} | loss {loss.item():.3f} | val_acc {va_acc:.3f} | val_f1 {va_f1:.3f}")
if best_state: model.load_state_dict(best_state)
te_acc, te_f1 = evaluate(test_mask)
print(f"\nTEST  accuracy={te_acc:.3f}  macro-F1={te_f1:.3f}")

We split the graph nodes into training, validation, and test masks so the model can learn and be evaluated properly. We define a two-layer GraphSAGE model that learns node representations from both node features and graph structure. We train the model for 200 epochs, monitor validation accuracy and macro-F1, save the best model state, and finally report test performance.

Visualizing Embeddings and Running a Heterogeneous GNN Forward Pass

model.eval()
with torch.no_grad():
   logits, emb = model(data.x, data.edge_index, return_emb=True)
   pred = logits.argmax(1).numpy()
emb2d = PCA(n_components=2).fit_transform(emb.numpy())
fig, axes = plt.subplots(1, 2, figsize=(15, 6))
for cls in range(num_classes):
   m = y.numpy() == cls
   axes[0].scatter(emb2d[m, 0], emb2d[m, 1], s=10, label=CLASS_NAMES[cls], alpha=0.7)
axes[0].set_title("GraphSAGE node embeddings (PCA), coloured by TRUE class")
axes[0].legend(fontsize=8); axes[0].set_xticks([]); axes[0].set_yticks([])
plot_gdf = nodes.copy(); plot_gdf["pred"] = pred
plot_gdf["pred_name"] = [CLASS_NAMES[p] for p in pred]
plot_gdf.plot(ax=axes[1], column="pred_name", legend=True, markersize=12, cmap="tab10")
axes[1].set_title("Predicted urban function (mapped back to geography)")
axes[1].set_axis_off()
try:
   import contextily as ctx
   ctx.add_basemap(axes[1], crs=plot_gdf.crs, source=ctx.providers.CartoDB.Positron)
except Exception:
   pass
plt.tight_layout(); plt.show()
if hetero is not None:
   try:
       for nt in hetero.node_types:
           hetero[nt].x = hetero[nt].x.float()
       class HGNN(torch.nn.Module):
           def __init__(self, hid, out):
               super().__init__()
               self.c1 = SAGEConv((-1, -1), hid)
               self.c2 = SAGEConv((-1, -1), out)
           def forward(self, x, ei):
               x = {k: F.relu(v) for k, v in self.c1(x, ei).items()}
               return self.c2(x, ei)
       hmodel = to_hetero(HGNN(32, 16), hetero.metadata(), aggr="sum")
       out_dict = hmodel(hetero.x_dict, hetero.edge_index_dict)
       print("\nHeterogeneous GNN output embedding shapes:")
       for nt, t in out_dict.items():
           print(f"   {nt}: {tuple(t.shape)}")
   except Exception as e:
       print("Hetero GNN forward skipped:", e)
print("\n✅ Done — proximity comparison, hetero construction, and a trained spatial GNN.")

We use the trained GraphSAGE model to extract node embeddings and predictions from the homogeneous graph. We reduce the learned embeddings with PCA and visualize them alongside a geographic prediction map to understand how the model separates urban functions. We also run a heterogeneous GNN forward pass with to_hetero, showing that the tutorial supports both homogeneous training and heterogeneous graph experimentation.

Key Takeaways

  • city2graph turns raw OpenStreetMap POI and street data into spatial graphs.
  • Six proximity graph families (KNN, Delaunay, Gabriel, RNG, EMST, Waxman) connect the same POIs differently.
  • A synthetic clustered fallback keeps the workflow runnable without OSM access.
  • A two-layer GraphSAGE model predicts urban function categories from spatial structure.
  • The pipeline supports both homogeneous training and heterogeneous graph experimentation via to_hetero.

Conclusion

In conclusion, we completed a full spatial GNN pipeline that transforms raw city data into graph-based learning and visualization. We compared several proximity graph methods, built a heterogeneous multi-layer graph, trained a homogeneous GraphSAGE classifier, and inspected the learned embeddings and geographic predictions. It gives us a practical understanding of how spatial relationships among POIs can be represented as graph structures and used to predict urban functions. It also shows how city2graph, GeoPandas, OSMnx, and PyTorch Geometric work together to support advanced geospatial machine learning experiments in a Colab-friendly setup.


Check out the Full Codes with Notebook hereAlso, feel free to follow us on Twitter and don’t forget to join our 150k+ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us

Sana Hassan

Sana Hassan, a consulting intern at Marktechpost and dual-degree student at IIT Madras, is passionate about applying technology and AI to address real-world challenges. With a keen interest in solving practical problems, he brings a fresh perspective to the intersection of AI and real-life solutions.