Graphs & Machine Learning on Graphs
A graph G = (V, E) is a set of nodes (vertices) V connected by edges E. Graphs are a natural way to represent entities and the relationships between them.
Kinds of graphs
- Undirected — edges have no direction; directed — edges go from one node to another; weighted — each edge carries a weight.
- Adjacency matrix A ∈ ℝ|V|×|V| encodes the edges: A[u][v] tells whether (and how strongly) node u connects to node v. If the graph is undirected, A is symmetric.
- Multi-relational graphs: edges can be of different relation types τ, so the adjacency becomes A ∈ ℝ|V|×|R|×|V| (one slice per relation).
- Heterogeneous graphs: nodes themselves have types, and V is partitioned into disjoint sets of typed nodes.
Node attributes
Nodes can carry features: a feature matrix X ∈ ℝ|V|×m associates an m-dimensional attribute vector with each of the |V| nodes.
Machine-learning tasks on graphs
Node classification
Predict a label for each node.
Link prediction
Predict whether an edge exists between two nodes.
Graph classification / regression
Predict a label or value for a whole graph.
Graph clustering
Group nodes (or graphs) by similarity.
The Permutation Challenge & Graph Isomorphism
Why not just flatten the adjacency matrix into an MLP?
A tempting idea is to flatten the adjacency matrix into a vector and feed it to a standard MLP. This does not work: the ordering of the nodes is arbitrary, so the same graph has many different flattened matrices. An MLP is not permutation-invariant — it would treat each ordering as a different input.
The goal of a GNN is therefore a permutation-independent representation: the nodes are treated as a set, not an ordered list. Whatever order we feed them in, the learned embeddings should be the same.
Message Passing, Self-Loops & GCNs
GNNs learn a per-node embedding through message passing: at each iteration, every node combines information coming from its neighbors and uses it to update its own state.
The two operations
- AGGREGATE — combines the information coming from the neighbors N(u) of the target node.
- UPDATE — updates the representation of the target node using the aggregated message and its own previous state.
Intuition: the initial embedding is the node feature, hu(0) = xu. After K iterations, each node's embedding contains information from its K-hop neighborhood — analogous to how stacking convolutions in a CNN grows the receptive field.
Naive message passing
Separate weight matrices transform the node's own state (Wself) and the summed neighbor states (Wneigh).
Message passing with self-loops
Instead of treating the node separately, we can aggregate over the neighborhood plus the node itself, N(u) ∪ {u}:
Pros
- Simplifies the model and removes the UPDATE step (the node is already part of the aggregation)
- Often alleviates overfitting
Cons
- Limits expressivity: the model can no longer differentiate the neighbors' information from the node's own information
Normalization & GCNs
- Normalization stabilizes aggregation: mean normalization divides by |N(u)|; symmetric normalization divides each neighbor by √(|N(u)|·|N(v)|).
- A Graph Convolutional Network (GCN) combines self-loops with symmetric normalization — and that operation is exactly what the deck calls "Convolution!" on a graph.
Pooling & GNN Tasks Revisited
Aggregation needs a function that maps a set of neighbor embeddings to a single vector. Two families:
Set Pooling
- A permutation-invariant universal set-function approximator: mN(u) = MLPθ( Σ MLPφ(hv) )
- Sum makes it order-independent
Janossy Pooling
- Permutation-sensitive (e.g., an LSTM over the neighbors)
- Made order-independent by averaging over sampled permutations
Graph-level embedding (graph pooling)
To get a single embedding for the whole graph, pool the node embeddings: zG = Σu zu / fn(|V|), optionally with an attention mechanism to weight nodes differently.
Tasks revisited with GNNs
| Task | How a GNN does it |
|---|---|
| Node classification | Loss L = Σu∈Vtrain −log( softmax(zu, yu) ); inductive/test nodes are ignored during training. |
| Link prediction | Cast as metric learning on the node embeddings (do two nodes belong together?). |
| Graph classification | Use the graph-level embedding zG as a single data point and classify it. |
GNNs in Ambient Intelligence
Why GNNs for sensor data?
- CNNs and RNNs can be viewed as GNNs: CNNs work on fixed-size grid graphs, RNNs on line graphs.
- Typical GNNs handle complex graphs with no fixed form, a variable number of unordered nodes, and a variable number of neighbors per node.
- Advantage: they effectively encode complex relationships and interdependencies among devices in IoT sensing systems, and among data instances over time.
Constructing a graph from a multivariate time series
Each node represents a sensor (or a device with several sensors); its features are a time window of sensor data. How to set the edges?
Heuristic-based graphs
- Edges from heuristics like spatial proximity between sensors or pairwise similarity computed on training data
Learning-based graphs
- Edges learned end-to-end (start fully connected); attention derives the most important edges
- More costly, but yields richer structures
Body-sensing & spatio-temporal graphs
- Body-sensing graph: each node is a device at a body position (feature = a time window of that position's data); edges connect adjacent body parts to capture dependencies between close devices.
- Spatio-temporal graphs encode both space and time as a multi-relational graph where layers are time instants. Three edge types: spatial dependency (nodes linked at the same instant), temporal correlation (the same node across instants), and spatial-temporal correlation (different nodes across different instants).
Smart-home graph construction
- Heuristic-based (GNN-XAR): a window of sensor events becomes a graph; each node (a sensor event) is linked to another if they are temporally consecutive in the window.
- Heuristic + learning (Know Thy Neighbors): start fully connected (each node a sensor), compute pairwise similarity from sensor behavior (activation frequency, periodicity, value range), keep only the highest-similarity edges, then weight them with attention (higher weight for sensors often triggered together).
Concrete GNN architectures & applications
GraphConvLSTM
Graph convolution captures spatial properties; temporal convolution (1D-CNN per node) captures temporal properties; a final LSTM captures long-term dependencies before classification.
Load disaggregation
Cluster the aggregate smart-meter signal (each cluster = a node); edges weighted by transition probability (Markov chain); GCN message passing + graph pooling → decoder maps to per-appliance consumption.
Indoor localization
Each node = an Access Point (feature = measured RSSI); weighted edge if two APs are spatially close; after message passing, graph pooling identifies the subject's position.
Advanced GNN Topics
Two questions connect GNNs back to earlier lectures: can GNNs be used for self-supervised learning? and can we employ XAI methods for GNNs?
Self-supervised learning with GNNs
Predictive approach
- Graph reconstruction: an encoder maps the (partially hidden) graph to embeddings, a decoder reconstructs it, and the loss compares reconstruction to the original
Contrastive approach
- Graph augmentation produces two views; a GNN-based feature extractor encodes both; positive/negative sampling + a contrastive loss pull matching views together
Explainability for GNNs — a perturbation-based approach
Given an input graph (features X and adjacency A), a mask-generation algorithm produces a feature mask, an edge mask and a node mask. These masks are multiplied into the GNN's input, and an objective function tied to the prediction optimizes the masks — revealing which features, edges and nodes most influenced the output.
Final Quiz — Exam Style
16 MCQs + 2 open-ended. One is the actual simulation question (Q19) reproduced verbatim; the rest follow the professor's recipe — sibling distractors, one-word swaps, and a FALSE question hiding an absolutizer.
What is the primary goal of adding self-loops for message passing within GNNs?
a) A graph G = (V, E) has nodes and edges; it can be undirected (symmetric adjacency A), directed, or weighted. Multi-relational graphs have typed edges (A ∈ ℝ|V|×|R|×|V|); heterogeneous graphs have typed nodes (V partitioned by type). Nodes may carry features X ∈ ℝ|V|×m. Flattening A into an MLP fails because node ordering is arbitrary: the same graph yields many flattened matrices, and an MLP is not permutation-invariant, so it treats each ordering as a new input. Isomorphic graphs (the same graph relabeled) may have different adjacency matrices, so we need a permutation-independent representation — nodes as a set — so isomorphic graphs are treated identically.
b) A GNN learns node embeddings via message passing: AGGREGATE combines the neighbors' embeddings and UPDATE refreshes the target node — hu(k+1) = UPDATE(hu(k), AGGREGATE({hv(k): v∈N(u)})), starting from hu(0) = xu. After K iterations each node sees its K-hop neighborhood. Self-loops aggregate over N(u)∪{u}: pros — they simplify the model, remove the UPDATE step, and alleviate overfitting; con — they limit expressivity (can't separate the node's own info from its neighbors'). A GCN = self-loops + symmetric normalization (dividing each neighbor by √(|N(u)|·|N(v)|)), which the deck calls graph "Convolution".
a) CNNs/RNNs are special GNNs (grid graphs / line graphs); general GNNs handle variable-size, unordered nodes and encode device interdependencies. From a multivariate time series, each node is a sensor (feature = a time window); edges are set either heuristically (spatial proximity, pairwise similarity on training data; in smart homes, link temporally consecutive events — GNN-XAR) or by learning (start fully connected, use attention to derive important edges; Know Thy Neighbors computes similarity from sensor behavior, keeps top edges, weights them by attention). Body-sensing graphs place a node at each body position and connect adjacent parts; spatio-temporal graphs add spatial, temporal and spatial-temporal edges across time layers. Applications: GraphConvLSTM (graph conv = spatial, temporal conv = temporal, LSTM = long-term), load disaggregation (cluster the aggregate meter signal into nodes, Markov-chain edge weights, GCN + pooling → per-appliance power), and indoor localization (nodes = APs with RSSI features, edges between close APs, pooling → position).
b) Self-supervised learning: the predictive approach uses graph reconstruction (encoder → decoder → reconstruction loss); the contrastive approach uses graph augmentation into two views, GNN feature extractors, positive/negative sampling and a contrastive loss. Explainability: a perturbation-based method generates a feature mask, edge mask and node mask via a mask-generation algorithm, multiplies them into the GNN input, and optimizes an objective tied to the prediction to reveal which features, edges and nodes drove the output.