# Session 08 — Python demos

Small, self-contained scripts that illustrate ideas from `08_graphs.html`
and the companion slide decks `G1_graph-intro.pptx` (graphs, representations,
ML tasks) and `G2_graph-02-nodeemb.pptx` (node embeddings, DeepWalk).

## Setup

With `uv` (recommended — no venv to manage, deps fetched on the fly):

```bash
uv run --with-requirements requirements.txt --with jupyterlab jupyter lab
```

Or the classic way:

```bash
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
jupyter lab
```

The `d3` notebook additionally needs `scikit-learn`, `ipywidgets` and
`torch-geometric` (all in `requirements.txt`). `torch-geometric` runs fine on
CPU here — no GPU-specific build needed.

## Demos

### `demo_d1_graph_node_embeddings.py`  /  `.ipynb`
A synthetic graph with 3 planted communities (stochastic block model,
60 nodes), shown three ways — picture, adjacency matrix, degree distribution
— and then **DeepWalk-style node embeddings** trained from scratch with
PyTorch (random walks → skip-gram with negative sampling).

The script snapshots the 2-D embeddings during training so the class can
watch random noise turn into three community clusters arranged in a triangle.
Caps off with a 1-NN community-prediction sanity check (typically ~95%+
without ever telling the model which node belongs to which community).

```bash
python demo_d1_graph_node_embeddings.py
# → fig1_graph_representations.png
# → fig2_embeddings_evolution.png
```

The notebook version splits the same code into cells with markdown narration
between sections, plus a longer discussion of why the triangle geometry
emerges, what the boundary-node mistakes mean, and the limits of shallow
embeddings (preview of GNNs in session 10).

### `demo_d2_networkx_playground.ipynb`
Hands-on tour of NetworkX for students to play with. Walks through:

1. Building a graph from an edge list, named-node "friendship network" example.
2. Layouts (spring / circular / kamada-kawai / shell) shown side by side.
3. Basic stats: nodes, edges, density, degrees, degree distribution.
4. **Zachary's Karate Club** (`nx.karate_club_graph()`) — the canonical
   real-world example, with the post-split factions colour-coded.
5. **Four centrality measures** (degree, betweenness, closeness, **PageRank**)
   computed on the Karate Club and visualised as node colours, top-3 nodes
   labelled per metric.
6. **PageRank from scratch** — ten lines of NumPy power iteration, verified
   against `nx.pagerank` to ~1e-6 precision. Demystifies the black box.
7. Tiny directed "web" graph showing PageRank's original setting.
8. Four hands-on exercises (avg shortest-path length, diameter, clustering
   coefficient, Erdős–Rényi comparison) with worked solutions inline.
9. A take-home cheat-sheet of the most-used NetworkX calls.

Notebook-only (interactive exploration). Saves `centralities.png` for use
in slides or class previews.

### `demo_d3_node2vec_and_gnn.ipynb`
Picks up where `d1` ends and runs four "acts" on Zachary's Karate Club:

1. **node2vec** — the biased random walk (`p`, `q` knobs) instead of DeepWalk's
   uniform walk. Same skip-gram backend as `d1`. 2-D embedding, KMeans recovers
   the two factions with no labels.
2. **The `p`/`q` explorer** — an `ipywidgets` slider over a precomputed grid,
   showing how `q < 1` captures **homophily** (communities) and `q > 1` captures
   **structural equivalence** (roles). Includes a static fallback figure.
3. **Link prediction** — hide 20% of edges, retrain, score missing pairs with the
   Hadamard-product operator + logistic regression. ROC/AUC and a top-k
   predicted-links picture.
4. **Shallow vs. GNN** — a 2-layer `GCNConv` (PyTorch Geometric) trained
   semi-supervised from just 4 labelled nodes; watch its hidden embedding
   separate the factions, then a head-to-head accuracy bar vs. node2vec.
   Bridges into the GNN material in session 10.

Notebook-only. Companion to `G2_graph-02-nodeemb.pptx`.

## Exercises

### `exercise_node_embeddings.ipynb`
A hands-on **skeleton notebook** for students. Helper code, the graph, and the
skip-gram model are provided; students fill in six `# TODO` lines that are the
real ideas — the random-walk step, the sliding-window `(target, context)` pairs,
the PyTorch training step, the embedding scatter plot, and the KMeans
sanity-check. Ends with a free-form playground and a few wrap-up questions.

Covers the basic DeepWalk pipeline only (no `p`/`q`, no GNNs) — it's the
"now you build it" companion to demo `d1`. No solutions file; walk through it
live or reuse `d1` as the worked version.
