Applied review: graphs as data, learning tasks and network models
A machine-learning-oriented review of graph theory, graph storage formats, graph variants, node, edge and graph tasks, network statistics and random graph models.
After this lesson you can
- Convert between edge lists, edge_index, CSR and sparse matrices and select a format for each operation.
- Classify real problems by prediction level and by transductive or inductive setting.
- Calculate network statistics and compare them with a null model.
- Generate Erdős-Rényi, Watts-Strogatz and Barabási-Albert graphs and explain their properties.
- Represent code as a graph with syntax, control-flow and data-flow edges and identify graph-based security tasks.
Before you start
Relationships are data too
A molecule contains atoms and bonds; a program contains expressions and dependencies between values. A transaction connects two accounts. In each case, a row per object can store its attributes, but does not by itself say which objects are related. A graph adds that structure. A learning question can concern an atom, a bond or the whole molecule; before choosing a model, specify what is predicted and what information will be available at prediction time.
The graph has nodes. We use the convention for a directed edge from to , where is the adjacency matrix. In an unweighted simple graph, each entry is 0 or 1, the out-degree is and the in-degree is . With weights, these sums are weighted strengths, while degree counts edges. For loop-free simple undirected graphs, is symmetric and : each edge contributes one endpoint to each of its two nodes.
A walk of length is a sequence of compatible edges and can repeat nodes. For binary adjacency, counts walks of length from to : multiplication sums over each possible choice of intermediate node. A simple path does not repeat nodes. Connectivity and distance are defined in terms of paths, not the magnitude of a single entry of .
From edges to memory
An edge list stores pairs , or triples . Among graph data structures used in learning, edge_index is an integer tensor of shape : the first row contains sources and the second destinations. An undirected edge is normally encoded as two arcs when messages are expected in both directions. Indices in the text start at 1 and those in Python at 0.
COO stores coordinates and values; CSR groups entries by row in indptr, indices and data. Row occupies indices[indptr[i]:indptr[i+1]], so retrieving its outgoing neighbors costs plus locating the boundaries. Scanning an unindexed COO list costs in the worst case. CSR uses space and a dense matrix , although sparse multiplication also depends on feature dimension. See sparse formats and gather and scatter operations.
If stores one feature row per node, under our convention sums destination features for each source. If each edge sends messages from source to destination, the weighted sum of incoming messages is . Keep the indexing convention distinct from the actual aggregation direction.
For example, with edges , and , the entry : the two-step walk passes through node 2. The direct edge contributes to , not to that walk of length two. If the entries are weights, sums products of weights along walks and is no longer simply a count unless the weights are one.
An unsorted COO index is convenient for building and concatenating batches of edges and for sending messages with scatter operations by destination. Row-oriented CSR gives fast access to outgoing neighbors; incoming neighbors benefit from a transposed representation or inverse index. For a small subgraph, allocating a dense matrix can be reasonable. At scale, memory cost depends not only on the number of structural entries but also on index width, attributes and intermediate arrays.
A multigraph can have parallel edges. COO can retain one entry per edge, while a conventional sparse matrix may sum duplicates, losing individual edge identity during conversion. A zero weight can also be confused with absence unless the edge pattern is retained explicitly.
What nodes and edges can contain
Attributed graphs and their variants can have a feature matrix , node labels, and edge features or types. Direction and weighting are independent choices. A multigraph allows several relationships between the same pair. A bipartite graph separates nodes into two sets and only allows edges across the sets, such as people and items. A hypergraph allows a relationship with more than two participants: turning a hyperedge into a clique introduces pairs and can change the original meaning.
Graph learning tasks differ in the unit being predicted. Classifying an account is a node task; predicting a link between an account and a product is an edge task; predicting toxicity from a molecule is a graph task. Generating a graph additionally requires a distribution over sizes, attributes and connections. Completing a knowledge-graph relation predicts a typed link rather than classifying a whole graph.
The transductive and inductive settings differ in which objects are available during fitting. In a transductive protocol, the graph and test-node features may be known while their labels remain hidden; an inductive protocol requires generalization to nodes or graphs unavailable during training. State the exact split, visible edges, features and when they were obtained. A transductive result does not establish generalization to new nodes.
Consider a network of accounts. If all accounts and transactions are known but only some fraud labels are available, a method can propagate information throughout the structure and be evaluated on hidden labels. If the operational goal is to analyze accounts appearing tomorrow, that evaluation does not mirror deployment. In recommendation, an absent edge can indicate an unobserved item rather than rejection: negative sampling changes the question and the metrics. For a collection of functions, a function-level split can place nearly identical versions from the same project on both sides; splitting by project or time asks a different generalization question.
Measure before modeling
Network statistics depend on the object and on how weights, direction and disconnected nodes are handled. In a simple undirected graph, for local clustering is , where is the number of triangles containing . For , zero is commonly assigned when averaging. Global transitivity is , with triangles and centered triplets; it is not generally equal to the mean of the .
The degree distribution shows heterogeneity, although an apparently heavy tail alone does not establish a power law. Mean path length and effective diameter, defined as a chosen quantile of finite pairwise distances, require a stated treatment of disconnected pairs. Degree assortativity is the correlation of degrees at edge endpoints; it may be undefined if there is no variation. Comparing a network with a null model requires deciding which properties are preserved.
The distinction between mean clustering and transitivity helps frame a question. The former weights every node equally, according to the chosen convention for low degrees. The latter weights each center by its number of neighbor pairs: a high-degree node contributes many triplets. Consequently, the two summaries can change in different directions when a hub is added. Assortativity describes whether edge endpoints tend to have similar degrees; it does not by itself identify the cause of that correlation.
A useful comparison examines the observed network against many realizations. In , one can choose to approximately match the mean degree, but individual degrees are not fixed. To ask whether clustering is greater than expected given each degree, use a null that preserves the degree sequence and describe its constraints. A result that is extreme under a null indicates incompatibility with that model; it does not establish a unique causal mechanism.
Three models, three hypotheses
Random network models are explicit distributions rather than automatic descriptions of real networks. In Erdős-Rényi each unordered pair appears independently with probability . Its expected degree is . If for constant , the giant component undergoes a scaling transition around ; connectivity of the whole graph requires a different scale, . These thresholds differ.
The probability of each triangle is . By linearity of expectation, . For a node conditioned on having at least two neighbors, each pair of those neighbors is connected with probability , so . If lower-degree nodes are assigned zero, the unconditional expected average includes the factor .
The Watts and Strogatz model starts with a regular ring and rewires edges with probability . For certain parameters it can combine high clustering with short paths; verify this across realizations. The Barabási and Albert model adds nodes and favors links to high-degree nodes. The mechanism produces heterogeneity, but preferential attachment does not explain every heterogeneous network.
The interactive Barabási-Albert model starts with a clique of nodes and selects destinations without replacement, with probability proportional to the previous degree. The Watts-Strogatz model starts with a ring of even degree and rewires each oriented ring edge once, avoiding self-loops and duplicates. A small sample and a single seed do not establish asymptotic behavior.
Code as a graph
A code representation can combine an abstract syntax tree (AST), control-flow edges and data dependencies. Yamaguchi and colleagues combine syntax, control and dependency views in a code property graph and propose traversals to find patterns. Consider a C function receiving a length and using it in a buffer copy: a dependency path from that length to the size argument identifies a relationship worth auditing. The path alone does not demonstrate a vulnerability: bounds checks, preconditions and control flow matter. Classifying functions, locating suspicious nodes and predicting relations are distinct tasks. These defensive representations make relationships explicit for review and do not replace a complete semantic analysis.
Lab: formats and traversals
The following example retains parallel arcs in CSR. The comparison with SciPy uses an aggregated matrix and therefore sums duplicates. Isolated nodes are retained through n, even when they do not occur in the list.
import numpy as np
from scipy.sparse import coo_matrix
edges = [(0, 1, 2.0), (0, 1, 3.0), (1, 2, 1.0), (2, 0, 4.0)]
n = 4
ordered = sorted(edges, key=lambda e: (e[0], e[1]))
counts = np.bincount([u for u, v, w in ordered], minlength=n)
indptr = np.r_[0, np.cumsum(counts)]
indices = np.array([v for u, v, w in ordered], dtype=int)
data = np.array([w for u, v, w in ordered])
edge_index = np.array([[u for u, v, w in edges], [v for u, v, w in edges]])
A = coo_matrix(([w for u, v, w in edges], edge_index), shape=(n, n)).tocsr()
print('edge_index:', edge_index.tolist())
print('CSR con identidad de arista:', indptr.tolist(), indices.tolist(), data.tolist())
print('vecinos de 0:', indices[indptr[0]:indptr[1]].tolist())
print('matriz agregada:', A.toarray().tolist())To compare operations fairly, sum duplicates in both paths. The following check times construction rather than neighbor traversal; it keeps the size moderate so it can run in the browser. Measure again before applying its timings to another machine or to PyTorch.
from time import perf_counter
gen = np.random.default_rng(19)
n_bench, m_bench = 400, 2000
src = gen.integers(0, n_bench, m_bench)
dst = gen.integers(0, n_bench, m_bench)
start = perf_counter()
keys, multiplicities = np.unique(src * n_bench + dst, return_counts=True)
rows, idx = keys // n_bench, keys % n_bench
ptr = np.r_[0, np.cumsum(np.bincount(rows, minlength=n_bench))]
own_time = perf_counter() - start
start = perf_counter()
scipy_matrix = coo_matrix((np.ones(m_bench), (src, dst)), shape=(n_bench, n_bench)).tocsr()
scipy_time = perf_counter() - start
assert np.array_equal(ptr, scipy_matrix.indptr)
assert np.array_equal(idx, scipy_matrix.indices)
assert np.array_equal(multiplicities, scipy_matrix.data)
print('aristas de entrada:', m_bench, 'entradas tras sumar duplicados:', len(idx))
print('segundos, ordenar/CSR:', round(own_time, 5), 'SciPy COO a CSR:', round(scipy_time, 5))from collections import deque
import networkx as nx
adj = [{1, 2}, {0, 2}, {0, 1, 3}, {2}, set()]
def distances(adj, source):
dist = {source: 0}
q = deque([source])
while q:
u = q.popleft()
for v in adj[u]:
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
return dist
def clustering(adj, u):
ns = adj[u]
d = len(ns)
if d < 2:
return 0.0
twice = sum(len(adj[v] & ns) for v in ns)
return twice / (d * (d - 1))
G = nx.Graph()
G.add_nodes_from(range(len(adj)))
G.add_edges_from((u, v) for u, ns in enumerate(adj) for v in ns if u < v)
assert all(distances(adj, u) == dict(nx.single_source_shortest_path_length(G, u)) for u in G)
assert all(abs(clustering(adj, u) - nx.clustering(G, u)) < 1e-12 for u in G)
print('grados:', [len(ns) for ns in adj])
print('clustering:', [round(clustering(adj, u), 3) for u in G])
print('distancias desde 3:', distances(adj, 3))Transitivity and mean distance are now calculated directly. Pairs are counted once and unreachable pairs are excluded; the denominator is also reported so the result does not hide disconnections. Effective diameter is the 90th percentile of these finite distances under NumPy’s percentile convention.
wedges = sum(len(ns) * (len(ns) - 1) // 2 for ns in adj)
triangles = sum(len(adj[u] & adj[v]) for u in range(len(adj)) for v in adj[u] if u < v) // 3
transitivity = 3 * triangles / wedges if wedges else 0.0
finite = [d for u in range(len(adj)) for v, d in distances(adj, u).items() if v > u]
print('triángulos:', triangles, 'tríadas centradas:', wedges)
print('transitividad:', transitivity, 'media local:', sum(clustering(adj, u) for u in range(len(adj))) / len(adj))
print('pares finitos:', len(finite), 'media:', np.mean(finite), 'percentil 90:', np.quantile(finite, 0.9))
print('asortatividad de grado:', nx.degree_assortativity_coefficient(G))
assert abs(transitivity - nx.transitivity(G)) < 1e-12If a network has several components, mean distance calculated only in the largest can improve even when many nodes have become isolated. Report its size and the proportion of covered pairs. Similarly, in a temporal network, constructing the graph with transactions after prediction time leaks future information even when test labels are hidden. Separating label rows is insufficient to prevent that leakage.
The next lab implements edge sampling and uses NetworkX to store edges and calculate metrics. Mean path length is restricted to the largest component. Repeat with different seeds and sizes: one realization does not characterize the distribution.
import numpy as np
import networkx as nx
def er_graph(n, p, rng):
G = nx.empty_graph(n)
for u in range(n):
for v in range(u + 1, n):
if rng.random() < p:
G.add_edge(u, v)
return G
def ws_graph(n, k, beta, rng):
assert 0 < k < n and k % 2 == 0
G = nx.empty_graph(n)
original = [(u, (u + d) % n) for d in range(1, k // 2 + 1) for u in range(n)]
G.add_edges_from(original)
for u, v in original:
if rng.random() < beta:
choices = [x for x in range(n) if x != u and not G.has_edge(u, x)]
if choices:
G.remove_edge(u, v)
G.add_edge(u, int(rng.choice(choices)))
return G
def ba_graph(n, m, rng):
assert 1 <= m < n
G = nx.complete_graph(m + 1)
for u in range(m + 1, n):
weights = np.array([G.degree(v) for v in range(u)], dtype=float)
chosen = []
for _ in range(m):
v = int(rng.choice(u, p=weights / weights.sum()))
chosen.append(v)
weights[v] = 0
G.add_edges_from((u, v) for v in chosen)
return G
for name, graph in [
('ER', er_graph(80, 0.05, np.random.default_rng(4))),
('WS', ws_graph(80, 4, 0.1, np.random.default_rng(4))),
('BA', ba_graph(80, 2, np.random.default_rng(4))),
]:
component = graph.subgraph(max(nx.connected_components(graph), key=len))
print(name, 'aristas', graph.number_of_edges(), 'componente', len(component),
'clustering', round(nx.average_clustering(graph), 3),
'distancia en componente', round(nx.average_shortest_path_length(component), 3),
'grado máximo', max(dict(graph.degree()).values()))The previous cell implements sampling mechanisms and delegates the data structure and statistics to NetworkX. In particular, the BA generator uses an initial clique, which should be fixed when comparing variants; seeds from different libraries need not produce the same sample. To measure performance, use your own data and repeated timings in the target environment: equivalent formulas do not imply identical runtimes.
In the next comparison, NetworkX uses its own pseudorandom numbers. A difference between two samples is not an implementation error. Structural invariants must still hold: no self-loops or duplicate edges, a fixed number of edges in WS and BA, and the requested size. The NetworkX BA generator starts with a star by default; here it receives the same initial clique so the starting conditions match.
start = perf_counter()
ours = [er_graph(80, 0.05, np.random.default_rng(7)),
ws_graph(80, 4, 0.1, np.random.default_rng(7)),
ba_graph(80, 2, np.random.default_rng(7))]
own_time = perf_counter() - start
start = perf_counter()
library = [nx.gnp_random_graph(80, 0.05, seed=7),
nx.watts_strogatz_graph(80, 4, 0.1, seed=7),
nx.barabasi_albert_graph(80, 2, seed=7, initial_graph=nx.complete_graph(3))]
library_time = perf_counter() - start
for name, a, b in zip(['ER', 'WS', 'BA'], ours, library):
assert len(a) == len(b) == 80
assert nx.number_of_selfloops(a) == nx.number_of_selfloops(b) == 0
if name != 'ER':
assert a.number_of_edges() == b.number_of_edges()
print(name, 'aristas propias/biblioteca:', a.number_of_edges(), b.number_of_edges(),
'clustering:', round(nx.average_clustering(a), 3), round(nx.average_clustering(b), 3))
print('segundos propios/biblioteca:', round(own_time, 5), round(library_time, 5))Local lab: PyG and an AST
PyTorch Geometric represents connectivity in edge_index, with node features in x and edge features in edge_attr. The Data documentation recommends setting num_nodes when there are no attributes and isolated nodes exist. The following local cells download Cora and MUTAG on first use; they require a connection and PyTorch Geometric installed. Data are stored in your system’s temporary directory. Each printed result corresponds to the installation running the cell.
from pathlib import Path
from tempfile import gettempdir
from torch_geometric.datasets import Planetoid, TUDataset
from torch_geometric.data import Batch
root = Path(gettempdir()) / 'oryon-graph-datasets'
cora = Planetoid(str(root / 'cora'), 'Cora')[0]
mutag = TUDataset(str(root / 'mutag'), name='MUTAG')
batch = Batch.from_data_list([mutag[0], mutag[1]])
print('Cora:', cora, 'x:', tuple(cora.x.shape), 'edge_index:', tuple(cora.edge_index.shape))
print('MUTAG primer grafo:', mutag[0])
print('lote:', batch, 'asignaciones:', tuple(batch.batch.shape))
assert batch.num_graphs == 2
assert batch.num_nodes == mutag[0].num_nodes + mutag[1].num_nodesnpm run lab and open the connection link.Now compare the Cora citation network with a single null having the same number of nodes and expected mean degree. We convert to a simple undirected graph and remove self-loops, changing both the question and statistics. To limit computation, the percentile and mean distance use finite distances from 128 sources chosen uniformly without replacement. These are source-based estimates, not the exact diameter or a conclusive statistical comparison.
import numpy as np
import networkx as nx
from torch_geometric.utils import to_networkx
real = to_networkx(cora, to_undirected=True, remove_self_loops=True)
n_real, m_real = real.number_of_nodes(), real.number_of_edges()
p_real = 2 * m_real / (n_real * (n_real - 1))
null = nx.fast_gnp_random_graph(n_real, p_real, seed=11)
def describe(graph, seed):
generator = np.random.default_rng(seed)
sources = generator.choice(list(graph.nodes), size=min(128, len(graph)), replace=False)
values = [d for source in sources for target, d in nx.single_source_shortest_path_length(graph, int(source)).items() if target != source]
return {
'n': len(graph), 'm': graph.number_of_edges(),
'mayor componente': len(max(nx.connected_components(graph), key=len)),
'grado máximo': max(dict(graph.degree()).values()),
'clustering medio': round(nx.average_clustering(graph), 4),
'asortatividad': round(nx.degree_assortativity_coefficient(graph), 4),
'distancia media muestreada': round(float(np.mean(values)), 4),
'percentil 90 muestreado': float(np.quantile(values, 0.9)),
'distancias finitas muestreadas': len(values),
}
print('Cora:', describe(real, 3))
print('ER:', describe(null, 3))npm run lab and open the connection link.In one execution of this cell, Cora had 2,708 nodes and 5,278 edges after conversion; mean clustering was 0.2407, compared with 0.0014 in the null generated with the stated seed. The 90th percentile of sampled distances was 9 for Cora and 7 for the null. These are results from this execution, not a confidence interval. The null matches mean degree only in expectation and does not preserve the observed sequence. Sound inference requires repeating the null and estimating uncertainty in the statistics; the comparison does not by itself identify a formation mechanism.
The following analysis uses Python’s ast, not a C parser. It adds a lexical data relation from the last write to the next use of a name. This teaching example is limited to a function without branches or aliases: it does not resolve scope, calls, control flow or complete dependency analysis.
import ast
import torch
from torch_geometric.data import Data
source = 'def f(x):\n y = x + 1\n return y\n'
tree = ast.parse(source)
nodes = list(ast.walk(tree))
ids = {id(node): i for i, node in enumerate(nodes)}
edges, kinds = [], []
for parent in nodes:
for child in ast.iter_child_nodes(parent):
edges.append((ids[id(parent)], ids[id(child)]))
kinds.append(0) # AST
last_write = {node.arg: ids[id(node)] for node in nodes if isinstance(node, ast.arg)}
for node in sorted((n for n in nodes if isinstance(n, ast.Name)), key=lambda n: (n.lineno, n.col_offset)):
if isinstance(node.ctx, ast.Load) and node.id in last_write:
edges.append((last_write[node.id], ids[id(node)]))
kinds.append(1) # última escritura léxica
elif isinstance(node.ctx, ast.Store):
last_write[node.id] = ids[id(node)]
edge_index = torch.tensor(edges, dtype=torch.long).t().contiguous()
data = Data(edge_index=edge_index, edge_type=torch.tensor(kinds), num_nodes=len(nodes))
print('nodos:', data.num_nodes, 'aristas AST:', kinds.count(0), 'aristas de datos:', kinds.count(1))
assert data.edge_index.shape[1] == data.edge_type.numel()
assert data.edge_index.max().item() < data.num_nodesnpm run lab and open the connection link.Exercises
to_csr(edge_index, num_nodes) and neighbors(csr, v). edge_index has two rows, source and destination. Return (indptr, indices) sorted by source and, within each row, by destination; retain duplicates and empty rows. Indices are zero-based integers.import numpy as np
def to_csr(edge_index, num_nodes):
pass
def neighbors(csr, v):
passStep 1 of 2. What is the expectation of I_S?
Key ideas
The evaluation protocol determines what can be claimed about generalization. Statistics summarize different aspects of a network, and random models provide null hypotheses to compare with the data.