TExcelTAD

Graph Data

Some data is about relationships: who follows whom, which papers cite which, which bank accounts send money to which, which atoms are bonded in a molecule, which roads connect which junctions. Forcing such data into one row per thing loses the connections, which are often the most informative part. A graph keeps them: it is a set of nodes (also called vertices) joined by edges (links).

The vocabulary

Term Meaning Example
node one entity a user, an account, an atom
edge a relationship between two nodes "follows", "paid", "bonded to"
directed / undirected edges with or without a direction a payment goes from A to B; a friendship is mutual
weighted edge an edge with a number amount paid, road length
node / edge attributes features stored on nodes or edges account age, transaction time
degree number of edges at a node how many friends someone has
neighbourhood the nodes one edge away a user's direct contacts

Typical ML tasks on graphs are node classification (is this account fraudulent?), link prediction (will these two users connect? which product will this customer buy?) and graph classification (is this molecule toxic?).

Three ways to store a graph

The same small payment network, stored three ways:

python · try it yourself
import numpy as np
import pandas as pd

# 1. Edge list: one row per edge, the usual file format (CSV, database table)
edges = pd.DataFrame({
    "src":    ["ana", "ana", "ben", "cai", "cai", "dev", "eve"],
    "dst":    ["ben", "cai", "cai", "dev", "eve", "eve", "ana"],
    "amount": [120, 40, 75, 300, 60, 25, 90],
})
print(edges)

# 2. Adjacency matrix: n x n, entry (i, j) = weight of the edge i -> j
nodes = sorted(set(edges["src"]) | set(edges["dst"]))
idx = {n: i for i, n in enumerate(nodes)}
A = np.zeros((len(nodes), len(nodes)), dtype=int)
for s, d, w in edges.itertuples(index=False):
    A[idx[s], idx[d]] = w
print()
print(pd.DataFrame(A, index=nodes, columns=nodes))

# 3. Adjacency list: each node with its outgoing neighbours
print()
print(edges.groupby("src")["dst"].apply(list).to_dict())
   src  dst  amount
0  ana  ben     120
1  ana  cai      40
2  ben  cai      75
3  cai  dev     300
4  cai  eve      60
5  dev  eve      25
6  eve  ana      90

     ana  ben  cai  dev  eve
ana    0  120   40    0    0
ben    0    0   75    0    0
cai    0    0    0  300   60
dev    0    0    0    0   25
eve   90    0    0    0    0

{'ana': ['ben', 'cai'], 'ben': ['cai'], 'cai': ['dev', 'eve'], 'dev': ['eve'], 'eve': ['ana']}

The edge list is compact and is how graphs are usually exchanged. The adjacency matrix is convenient for maths (graph neural networks multiply by it) but has n2n^2 entries, almost all zero for a large network: a million users would need a trillion cells. The adjacency list is what graph algorithms use internally.

Working with graphs in NetworkX

NetworkX is the standard Python library for graphs. It reads an edge list from pandas and computes graph features that a model can use as ordinary columns:

python · try it yourself
import networkx as nx
import pandas as pd
import scipy  # NetworkX computes PageRank with SciPy

edges = pd.DataFrame({
    "src":    ["ana", "ana", "ben", "cai", "cai", "dev", "eve"],
    "dst":    ["ben", "cai", "cai", "dev", "eve", "eve", "ana"],
    "amount": [120, 40, 75, 300, 60, 25, 90],
})
G = nx.from_pandas_edgelist(edges, "src", "dst", edge_attr="amount", create_using=nx.DiGraph)
print("nodes:", G.number_of_nodes(), "| edges:", G.number_of_edges(), "| directed:", G.is_directed())

features = pd.DataFrame({
    "out_degree": dict(G.out_degree()),
    "in_degree": dict(G.in_degree()),
    "sent": dict(G.out_degree(weight="amount")),
    "received": dict(G.in_degree(weight="amount")),
    "pagerank": {n: round(v, 3) for n, v in nx.pagerank(G).items()},
})
print(features)
print("cycle back to ana:", nx.find_cycle(G, source="ana"))
nodes: 5 | edges: 7 | directed: True
     out_degree  in_degree  sent  received  pagerank
ana           2          1   160        90     0.241
ben           1          1    75       120     0.132
cai           2          2   360       115     0.245
dev           1          1    25       300     0.134
eve           1          2    90        85     0.248
cycle back to ana: [('ana', 'ben'), ('ben', 'cai'), ('cai', 'dev'), ('dev', 'eve'), ('eve', 'ana')]

The table at the end is ordinary tabular data, one row per node, built from the graph. That is the simplest way to use graph data in a classic model: compute node features (degree, money in and out, PageRank importance, cycles) and feed them to, say, a gradient-boosted tree. Graph neural networks, covered in Deep Learning, learn such features directly.

Pitfalls

  • Leaking through edges. If you split nodes randomly into train and test, test nodes are still connected to training nodes, and their labels can leak through neighbour features. Split by time or by connected component when possible.
  • Direction matters. "A paid B" and "B paid A" are different facts. Store directed graphs as directed.
  • Duplicate nodes. The same person under two ids ("Ana Li" and "ana.li") splits one node into two and hides real connections. Entity resolution is part of graph data quality.
  • Size. Real graphs are sparse and huge; never build the dense adjacency matrix for them.

Practice

  1. A social network has 2 million users and 50 million friendships (undirected). How many cells does the dense adjacency matrix have, and how many of them are non-zero?
Answer

(2×106)2=4×1012(2 \times 10^6)^2 = 4 \times 10^{12} cells. Each undirected friendship fills two symmetric cells, so 10810^8 are non-zero, a share of 2.5×10−52.5 \times 10^{-5}. An edge list with 50 million rows is the sensible storage.

  1. Which ML task is "predict which two products will be bought together next month"?
Answer

Link prediction: products are nodes, past co-purchases are edges, and the task is to predict new edges.

Test yourself

In an edge list, one row describes…

  1. One node and all its attributes
  2. One relationship between two nodes
  3. The whole graph
  4. One column of the adjacency matrix

Why is a dense adjacency matrix a bad idea for a graph with millions of nodes?

  1. It cannot store weights
  2. It has n squared cells, almost all zero
  3. NetworkX cannot read it
  4. It loses edge direction

Predicting whether a molecule is toxic from its atoms and bonds is…

  1. Node classification
  2. Link prediction
  3. Graph classification
  4. Time series forecasting