Skip to content

Neural graph representations: autoencoders and contrastive objectives

A graph network can learn node vectors by rebuilding the links (GAE), by doing so as a probabilistic model (VGAE) or under an adversary (ARGA), or by telling the real graph from a corrupted one (DGI, MVGRL).

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Write the graph autoencoder's GCN encoder and inner-product decoder and evaluate it without edge leakage
  • Explain what the variational and adversarial versions add, and their failure modes
  • Describe Deep Graph Infomax and multi-view contrastive learning, and why their objectives are surrogates

Read first

01

Learned instead of fixed

Read

Walk and matrix embeddings use only the links. Real networks also carry node attributes: a paper's words, a person's age, a protein's sequence. A graph convolutional networkGCNA graph layer that averages a node with its neighbors, each weighted by 1/√(degree × degree). mixes each node's attributes with its neighbors':

H(l+1)=ReLU⁡ ⁣(A^H(l)Wl),A^=D~−1/2(A+I)D~−1/2.H^{(l+1)} = \operatorname{ReLU}\!\big(\hat A H^{(l)} W_l\big), \qquad \hat A = \tilde D^{-1/2}(A + I)\tilde D^{-1/2}.

Without labels, what should it learn? This lesson's five methods each answer with a different self-supervised objective.

02

Propagation, a layer at a time

Explore

DExplorable · Message passing and oversmoothing

Why does a graph network get better with a few layers and worse with many?

Each layer averages over neighbors. At which depth (0–32) will the communities be best separated?

16
How sure?

Graph

2

Normalization

1.2
  • Community separation
  • Mean cosine distance
  • Energy, share of input (dashed)
Aggregating the neighbor multisets {a, b} and {a, a, b, b} (a = 1, b = 2)
Aggregator{a, b}{a, a, b, b}Tells them apart
sum3.006.00yes
mean1.501.50no
max2.002.00no

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Each encoder in this lesson starts from message passing. A few rounds average noise away inside each community; many rounds make every node alike, which is why graph encoders stay shallow.

03

GAE: rebuild the links

Read

A graph autoencoderGraph autoencoderA graph network encodes each node into a vector; a decoder scores every pair, σ(zᵢ·zⱼ), and is trained to rebuild the network's links. encodes with two GCN layers, Z=A^ ReLU⁡(A^XW0) W1Z = \hat A\,\operatorname{ReLU}(\hat A X W_0)\,W_1, and decodes every pair with an inner product:

p(Aij=1∣Z)=σ(zi⊤zj).p(A_{ij} = 1 \mid Z) = \sigma(z_i^\top z_j) .

Training minimizes binary cross-entropy on observed edges and sampled non-edges. The vectors ZZ are the representation; the decoder doubles as a link predictor. A symmetric decoder can't represent direction, and scoring all pairs costs n2n^2.

04

GAE in a run

Read
Node embeddings (DeepWalk, node2vec, LINE, spectral, GNN)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

Graph neural network (link prediction): a 4-number vector for each of 45 nodes from 108 edges. Held-out edges against as many random non-edges: link AUC 0.79 (0.5 is guessing).

Nodes
45
Edges
108
Dimensions
4
Link AUC (held-out edges)
0.7851
Link average precision
0.8501
Loss in the last pass
0.5990

Plots

Map of the nodesWhich levels of a categorical variable does the model treat as alike?

The first two principal components of the node vectors; nodes close together sit in similar places in the network.

View data
communityNodeEdgesComponent 1Component 2
Ap0140.9103−0.0707
Ap0260.93350.0882
Ap0351.746−0.0974
Ap0431.2440.0338
Ap0571.2160.0318
Ap0641.387−0.0148
Ap0750.8120−0.0953
Ap0851.503−0.0100
Ap0971.443−0.0096
Ap1011.563−0.1340
Ap1160.96710.1933
Ap1230.5993−2.916e-5
Ap1321.238−0.0758
Ap1470.8863−0.0099
Ap1551.3500.0436
Bp165−0.4720−0.1735
Bp175−0.5760−0.1651
Bp184−0.3384−0.1049
Bp196−0.7383−0.1240
Bp202−0.4094−0.1067
Bp214−0.4634−0.1766
Bp227−0.7401−0.1330
Bp236−0.6587−0.1741
Bp245−0.6550−0.0531
Bp259−0.8132−0.1224
Bp266−0.6007−0.1795
Bp274−0.7631−0.1640
Bp284−0.8144−0.1705
Bp299−0.9856−0.0861
Bp307−0.87510.0038
Cp314−0.45410.0558
Cp323−0.31520.5961
Cp332−0.4299−0.0241
Cp346−0.34660.1384
Cp356−0.84250.1108
Cp365−0.4259−0.0059
Cp373−0.52950.0493
Cp385−0.30440.0634
Cp395−0.67460.0845
Cp405−0.54870.0983
Cp415−0.44330.0540
Cp423−0.7374−0.0017
Cp436−0.86500.1962
Cp444−0.5453−0.0216
Cp451−0.43320.6636
Held-out edges against random non-edgesHow well does a score separate positives from negatives at every cutoff?
View data
MethodFalse-positive rateTrue-positive rate
Graph neural network (link prediction)00
Graph neural network (link prediction)00.0909
Graph neural network (link prediction)00.1818
Graph neural network (link prediction)00.2727
Graph neural network (link prediction)00.3636
Graph neural network (link prediction)00.4545
Graph neural network (link prediction)00.5455
Graph neural network (link prediction)0.09090.5455
Graph neural network (link prediction)0.09090.6364
Graph neural network (link prediction)0.18180.6364
Graph neural network (link prediction)0.27270.6364
Graph neural network (link prediction)0.27270.7273
Graph neural network (link prediction)0.36360.7273
Graph neural network (link prediction)0.45450.7273
Graph neural network (link prediction)0.54550.7273
Graph neural network (link prediction)0.54550.8182
Graph neural network (link prediction)0.54550.9091
Graph neural network (link prediction)0.63640.9091
Graph neural network (link prediction)0.72730.9091
Graph neural network (link prediction)0.81820.9091
Graph neural network (link prediction)0.90910.9091
Graph neural network (link prediction)0.90911
Graph neural network (link prediction)11
Most similar nodesWhich words or phrases appear most in a text column, overall or by group?
View data
Cosine similarityNodeNeighbor
0.9998p25p19
0.9998p25p22
0.9990p25p28
0.9989p25p29
0.9988p25p27
0.9989p29p25
0.9989p29p24
0.9981p29p19
0.9978p29p22
0.9969p29p30
0.9998p05p15
0.9998p05p04
0.9994p05p14
0.9985p05p09
0.9985p05p08
1.0000p09p08
1.0000p09p06
0.9990p09p14
0.9987p09p04
0.9986p09p15
0.9994p14p05
0.9991p14p06
0.9990p14p08
0.9990p14p04
0.9990p14p09

Assumptions

  • Enough network — 4.8 edges per node on average.
  • Coordinates are arbitrary — Compare similarities and link scores, not single coordinates; another seed or method rotates the vectors.
  • The link check hides edges first — Held-out edges were removed before the check's vectors were learned; the vectors saved per node use every edge.

Most similar nodes

NodeRankSimilar nodeCosine similarity
p251p190.9998
p252p220.9998
p253p280.9990
p254p290.9989
p255p270.9988
p291p250.9989
p292p240.9989
p293p190.9981
p294p220.9978
p295p300.9969
p051p150.9998
p052p040.9998
p053p140.9994
p054p090.9985
p055p080.9985
p091p081.0000
p092p061.0000
p093p140.9990
p094p040.9987
p095p150.9986
p141p050.9994
p142p060.9991
p143p080.9990
p144p040.9990
p145p090.9990
The exact R script · R R version 4.5.1 (2025-06-13)
# Node embeddings (DeepWalk, node2vec, LINE, spectral, GNN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.graph_embed 1.0.0 · spec 041679f95f63c962
# Dataset: grf3_blocks_edges (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% The network the host built (canonical node order, merged edges; cs_graph_read). Nodes are 0-based in the
# host's files and 1-based in the embedding twins (R/graph_embed.R).
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.graph_embed/gnn_gcn_attributes/out-r")
g <- cs_graph_read(out)
warnings <- as.list(g$warnings)
METHOD <- "gnn"
SEED <- 42
LABELS <- cs_graph_embed_labels()
N <- g$n
if (N < 3) cs_error("CS_E_UNDEFINED", what = "Node embeddings", reason = sprintf("the network has %d nodes; at least 3 are needed", N))
DIRECTED <- g$directed
if (DIRECTED && METHOD %in% c("laplacian", "netmf", "gnn")) {
  up <- cs_graph_undirected_pairs(g)  # this method reads every edge both ways
  EI <- up$a + 1L; EJ <- up$b + 1L; EW <- up$w
  DIR <- FALSE
  warnings <- c(warnings, sprintf("%s treats every edge as two-way, so the directions were set aside.", LABELS[[METHOD]]))
} else {
  EI <- g$si + 1L; EJ <- g$sj + 1L; EW <- g$sw
  DIR <- DIRECTED
}
M <- length(EI)
OPTS <- list(
  dim = 4L, walk_length = 20L, walks_per_node = 10L, window = 5L,
  p = 1, q = 1, line_order = "second", layer = "gcn",
  width = 8L, layers = 2L, heads = 4L, dropout = 0,
  epochs = 30, negative = 5L, lr = NULL,
  katz_beta = NULL, netmf_negative = 1
)
lim <- cs_graph_embed_limits(METHOD, OPTS, DIR)
if (N > lim[1] || M > lim[2]) cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = M, max_nodes = lim[1], max_edges = lim[2])
if (METHOD == "laplacian") {
  W <- cs_graph_dense(N, EI, EJ, EW, DIR)
  parts <- cs_graph_pieces(if (DIR) (W + t(W)) / 2 else W)
  if (parts > 1) cs_error("CS_E_GRAPH_DISCONNECTED", what = "Laplacian eigenmaps", components = parts)
}
DIM <- cs_graph_embed_max_dim(METHOD, N, OPTS$dim)
if (DIM < OPTS$dim) {
  warnings <- c(warnings, sprintf("The network has %d nodes, so %s returns %d dimensions instead of %d.", N, LABELS[[METHOD]], DIM, OPTS$dim))
} else if (METHOD == "hope" && DIM != OPTS$dim) {
  warnings <- c(warnings, sprintf("HOPE splits the vector into equal source and target halves, so it has %d dimensions.", DIM))
}
X <- NULL
if (METHOD == "gnn") {
  nf <- cs_graph_node_features(g$nodes, g$attributes)
  X <- nf$X
  if (!length(nf$names)) warnings <- c(warnings, "No node attributes were given, so the graph network starts from one indicator per node (it can't place new nodes).")
}
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.graph_embed/gnn_gcn_attributes/out-r")

# %% Link check: hide edges, learn from the rest, score hidden edges against random non-edges
HOLD <- 0.1
link <- NULL
if (HOLD > 0) {
  link <- cs_graph_embed_link_check(METHOD, N, EI, EJ, EW, DIR, OPTS, SEED, HOLD, X)
  if (link$status == "none") {
    warnings <- c(warnings, "Every edge is needed to keep the network in one piece, so no edge could be held out and the link check was skipped.")
  } else if (link$status == "dense") {
    warnings <- c(warnings, "The network has too few missing links to draw as many non-edges as held-out edges, so the link check was skipped.")
  } else if (link$held < link$wanted) {
    warnings <- c(warnings, sprintf("Only %d of the %d edges asked for could be held out without cutting the network apart.", link$held, link$wanted))
  }
}

# %% Fit on the whole network
fit <- cs_graph_embed_fit(METHOD, N, EI, EJ, EW, DIR, OPTS, SEED, X)
vectors <- fit$vectors
D <- ncol(vectors)

# %% Similar nodes (default: the five best-connected; ties in node order)
deg <- as.integer(diff(cs_graph_csr(g, undirected = TRUE)$indptr))
QUERY <- ""
asked <- trimws(strsplit(QUERY, ",", fixed = TRUE)[[1]])
asked <- unique(asked[nzchar(asked)])
queries <- head(asked[asked %in% g$node_id], 9)
missing <- asked[!(asked %in% g$node_id)]
if (length(missing)) warnings <- c(warnings, paste0("Not in the network: ", paste(missing, collapse = ", "), "."))
if (!length(asked)) queries <- g$node_id[head(order(-deg, seq_len(N), method = "radix"), 5)]
K <- 5
nb_rows <- list()
values_nb <- list()
for (q in queries) {
  near <- cs_graph_neighbors(vectors, match(q, g$node_id), K)
  for (r in seq_along(near$index)) nb_rows[[length(nb_rows) + 1L]] <- list(node = q, rank = r, neighbor = g$node_id[near$index[r]], cosine = near$cosine[r])
  if (length(near$index)) {
    values_nb[[sprintf("nearest[%s]", q)]] <- g$node_id[near$index[1]]
    values_nb[[sprintf("similarity[%s]", q)]] <- near$cosine[1]
  }
}

# %% Node table: one row per node (Save node table as dataset)
cols <- list(degree = deg)
for (k in seq_len(D)) cols[[paste0("emb_", k)]] <- vectors[, k]
nodes_art <- cs_graph_write_nodes(out, g, cols)

# %% Result
per_node <- (if (DIR) M else 2 * M) / N
held <- if (is.null(link) || is.null(link$auc)) 0L else link$held
values <- list(n_nodes = N, n_edges = M, dim = D, method = LABELS[[METHOD]])
values["final_loss"] <- list(fit$loss)
values["link_auc"] <- list(if (is.null(link)) NULL else link$auc)
values["link_ap"] <- list(if (is.null(link)) NULL else link$ap)
values$n_held_out <- held
values$n_isolated <- sum(deg == 0)
values["katz_beta"] <- list(fit$beta)
values["sv_share"] <- list(fit$sv_share)
values$edges_per_node <- per_node
values <- c(values, values_nb)
assumptions <- list(
  list(key = "enough_network", label = "Enough network", status = if (per_node < 3) "warn" else "pass",
       detail = paste0(sprintf("%.1f edges per node on average", per_node), if (per_node < 3) "; similar nodes and link scores are noisy on so sparse a network." else ".")),
  list(key = "coordinates_arbitrary", label = "Coordinates are arbitrary", status = "info",
       detail = "Compare similarities and link scores, not single coordinates; another seed or method rotates the vectors."),
  list(key = "holdout_honest", label = "The link check hides edges first", status = "info",
       detail = if (held > 0) "Held-out edges were removed before the check's vectors were learned; the vectors saved per node use every edge." else "No link check ran (held-out share 0, or no edge could be held out).")
)
xy <- cs_graph_map_2d(vectors)
map_roles <- list(
  x = cs_col("Component 1", xy[, 1], "numeric"),
  y = cs_col("Component 2", xy[, 2], "numeric"),
  label = cs_col("Node", g$node_id, "categorical"),
  size = cs_col("Edges", as.numeric(deg), "numeric")
)
if (!is.null(g$label)) {
  lab <- as.character(g$nodes[[g$label]])
  lab[is.na(lab)] <- "(none)"
  levels <- sort(unique(lab), method = "radix")
  if (length(levels) <= 12) {
    map_roles$group <- cs_col(g$label, lab, "categorical", levels)
  } else {
    warnings <- c(warnings, sprintf("%s has %d groups, more than the map can color (12).", g$label, length(levels)))
  }
}
charts <- list(cs_chart("map", "embedding-map", "Map of the nodes", map_roles,
                        note = "The first two principal components of the node vectors; nodes close together sit in similar places in the network."))
if (!is.null(link) && !is.null(link$roc)) {
  charts[[length(charts) + 1L]] <- cs_chart("link_roc", "roc-curve", "Held-out edges against random non-edges", list(
    fpr = cs_col("False-positive rate", link$roc$fpr, "numeric"),
    tpr = cs_col("True-positive rate", link$roc$tpr, "numeric"),
    curve = cs_col("Method", rep(LABELS[[METHOD]], length(link$roc$tpr)), "categorical")
  ))
}
if (length(nb_rows)) {
  charts[[length(charts) + 1L]] <- cs_chart("neighbors", "ngram-bars", "Most similar nodes", list(
    term = cs_col("Neighbor", vapply(nb_rows, `[[`, "", "neighbor"), "categorical"),
    count = cs_col("Cosine similarity", vapply(nb_rows, `[[`, 0, "cosine"), "numeric"),
    group = cs_col("Node", vapply(nb_rows, `[[`, "", "node"), "categorical", queries)
  ))
}
stats <- list(list(key = "n_nodes", label = "Nodes", value = N), list(key = "n_edges", label = "Edges", value = M),
              list(key = "dim", label = "Dimensions", value = D))
if (!is.null(values$link_auc)) {
  stats <- c(stats, list(list(key = "link_auc", label = "Link AUC (held-out edges)", value = values$link_auc),
                         list(key = "link_ap", label = "Link average precision", value = values$link_ap)))
}
if (!is.null(values$final_loss)) stats <- c(stats, list(list(key = "final_loss", label = "Loss in the last pass", value = values$final_loss)))
if (!is.null(values$sv_share)) stats <- c(stats, list(list(key = "sv_share", label = "Matrix kept by these dimensions", value = values$sv_share)))
summary <- sprintf("%s: a %d-number vector for each of %d nodes from %d edges.", LABELS[[METHOD]], D, N, M)
if (!is.null(values$link_auc)) summary <- paste0(summary, sprintf(" Held-out edges against as many random non-edges: link AUC %.2f (0.5 is guessing).", values$link_auc))
nb_cols <- list(list(key = "node", label = "Node"), list(key = "rank", label = "Rank", type = "number"),
                list(key = "neighbor", label = "Similar node"), list(key = "cosine", label = "Cosine similarity", type = "number"))
cs_publish(list(
  title = "Node embeddings (DeepWalk, node2vec, LINE, spectral, GNN)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = M,
  summary = summary,
  statistics = stats,
  tables = list(list(key = "neighbors", title = "Most similar nodes", columns = nb_cols, rows = nb_rows)),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(nodes_art)
))
Python

Graph neural network (link prediction): a 4-number vector for each of 45 nodes from 108 edges. Held-out edges against as many random non-edges: link AUC 0.79 (0.5 is guessing).

Nodes
45
Edges
108
Dimensions
4
Link AUC (held-out edges)
0.7851
Link average precision
0.8501
Loss in the last pass
0.5990

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Enough network — 4.8 edges per node on average.
  • Coordinates are arbitrary — Compare similarities and link scores, not single coordinates; another seed or method rotates the vectors.
  • The link check hides edges first — Held-out edges were removed before the check's vectors were learned; the vectors saved per node use every edge.

Most similar nodes

NodeRankSimilar nodeCosine similarity
p251p190.9998
p252p220.9998
p253p280.9990
p254p290.9989
p255p270.9988
p291p250.9989
p292p240.9989
p293p190.9981
p294p220.9978
p295p300.9969
p051p150.9998
p052p040.9998
p053p140.9994
p054p090.9985
p055p080.9985
p091p081.0000
p092p061.0000
p093p140.9990
p094p040.9987
p095p150.9986
p141p050.9994
p142p060.9991
p143p080.9990
p144p040.9990
p145p090.9990
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Node embeddings (DeepWalk, node2vec, LINE, spectral, GNN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.graph_embed 1.0.0 · spec 041679f95f63c962
# Dataset: grf3_blocks_edges (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import graph as csgraph
from codesplash import ml as csml
from codesplash.graph import embed as ge  # twin of codesplashr R/graph_embed.R (walks, LINE, spectral, link check)

# %% The network the host built (canonical node order, merged edges; codesplash.graph)
out = csml.out_dir("target/academy-parity/run-8142/discover.graph_embed/gnn_gcn_attributes/out-python")
g = csgraph.read(out)
warnings = list(g.warnings)
METHOD = "gnn"
SEED = 42
N = g.n
if N < 3:
    cs.cs_error("CS_E_UNDEFINED", what="Node embeddings", reason=f"the network has {N} nodes; at least 3 are needed")
DIRECTED = g.directed
if DIRECTED and METHOD in ge.TWO_WAY:
    EI, EJ, EW = csgraph.undirected_pairs(g)  # this method reads every edge both ways
    DIR = False
    warnings.append(f"{ge.LABELS[METHOD]} treats every edge as two-way, so the directions were set aside.")
else:
    EI, EJ, EW = g.si, g.sj, g.sw
    DIR = DIRECTED
M = len(EI)
OPTS = {
    "dim": 4, "walk_length": 20, "walks_per_node": 10, "window": 5,
    "p": 1, "q": 1, "line_order": "second", "layer": "gcn",
    "width": 8, "layers": 2, "heads": 4, "dropout": 0,
    "epochs": 30, "negative": 5, "lr": None,
    "katz_beta": None, "netmf_negative": 1,
}
MAX_NODES, MAX_EDGES = ge.limits(METHOD, OPTS, DIR)
if N > MAX_NODES or M > MAX_EDGES:
    cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=M, max_nodes=MAX_NODES, max_edges=MAX_EDGES)
if METHOD == "laplacian":
    parts = ge.pieces(ge.symmetrized(N, EI, EJ, EW, DIR))
    if parts > 1:
        cs.cs_error("CS_E_GRAPH_DISCONNECTED", what="Laplacian eigenmaps", components=parts)
DIM = ge.max_dim(METHOD, N, OPTS["dim"])
if DIM < OPTS["dim"]:
    warnings.append(f"The network has {N} nodes, so {ge.LABELS[METHOD]} returns {DIM} dimensions instead of {OPTS['dim']}.")
elif METHOD == "hope" and DIM != OPTS["dim"]:
    warnings.append(f"HOPE splits the vector into equal source and target halves, so it has {DIM} dimensions.")
X = None
if METHOD == "gnn":
    X, feature_names = ge.node_features(g.nodes, g.attributes)
    if not feature_names:
        warnings.append("No node attributes were given, so the graph network starts from one indicator per node (it can't place new nodes).")
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/discover.graph_embed/gnn_gcn_attributes/out-python",
)

# %% Link check: hide edges, learn from the rest, score hidden edges against random non-edges
HOLD = 0.1
link = None
if HOLD > 0:
    link = ge.link_check(METHOD, N, EI, EJ, EW, DIR, OPTS, SEED, HOLD, X)
    if link["status"] == "none":
        warnings.append("Every edge is needed to keep the network in one piece, so no edge could be held out and the link check was skipped.")
    elif link["status"] == "dense":
        warnings.append("The network has too few missing links to draw as many non-edges as held-out edges, so the link check was skipped.")
    elif link["held"] < link["wanted"]:
        warnings.append(f"Only {link['held']} of the {link['wanted']} edges asked for could be held out without cutting the network apart.")

# %% Fit on the whole network
fit = ge.fit(METHOD, N, EI, EJ, EW, DIR, OPTS, SEED, X)
vectors = fit["vectors"]
D = vectors.shape[1]

# %% Similar nodes (default: the five best-connected; ties in node order)
deg = np.diff(csgraph.csr(g, undirected=True)[0]).astype(int)
QUERY = ""
asked = [s.strip() for s in QUERY.split(",") if s.strip()]
index = {v: k for k, v in enumerate(g.node_id)}
queries = [q for q in dict.fromkeys(asked) if q in index][:9]
missing = [q for q in dict.fromkeys(asked) if q not in index]
if missing:
    warnings.append("Not in the network: " + ", ".join(missing) + ".")
if not asked:
    queries = [g.node_id[k] for k in sorted(range(N), key=lambda k: (-deg[k], k))[:5]]
K = 5
nb_rows = []
values_nb = {}
for q in queries:
    near = ge.neighbors(vectors, index[q], K)
    for r, (k, c) in enumerate(near, start=1):
        nb_rows.append({"node": q, "rank": r, "neighbor": g.node_id[k], "cosine": c})
    if near:
        values_nb[f"nearest[{q}]"] = g.node_id[near[0][0]]
        values_nb[f"similarity[{q}]"] = near[0][1]

# %% Node table: one row per node (Save node table as dataset)
cols = {"degree": deg}
for k in range(D):
    cols[f"emb_{k + 1}"] = vectors[:, k]
nodes_art = csgraph.write_nodes(out, g, cols)

# %% Result
per_node = (M if DIR else 2 * M) / N
values = {
    "n_nodes": N, "n_edges": M, "dim": D, "method": ge.LABELS[METHOD], "final_loss": fit.get("loss"),
    "link_auc": None if link is None else link["auc"], "link_ap": None if link is None else link["ap"],
    "n_held_out": 0 if link is None or link["auc"] is None else link["held"],
    "n_isolated": int(np.sum(deg == 0)), "katz_beta": fit.get("beta"), "sv_share": fit.get("sv_share"), "edges_per_node": per_node,
}
values.update(values_nb)
assumptions = [
    {"key": "enough_network", "label": "Enough network", "status": "warn" if per_node < 3 else "pass",
     "detail": f"{per_node:.1f} edges per node on average" + ("; similar nodes and link scores are noisy on so sparse a network." if per_node < 3 else ".")},
    {"key": "coordinates_arbitrary", "label": "Coordinates are arbitrary", "status": "info",
     "detail": "Compare similarities and link scores, not single coordinates; another seed or method rotates the vectors."},
    {"key": "holdout_honest", "label": "The link check hides edges first", "status": "info",
     "detail": "Held-out edges were removed before the check's vectors were learned; the vectors saved per node use every edge."
     if values["n_held_out"] else "No link check ran (held-out share 0, or no edge could be held out)."},
]
xy = ge.map_2d(vectors)
map_roles = {
    "x": cs.col("Component 1", [float(v) for v in xy[:, 0]], "numeric"),
    "y": cs.col("Component 2", [float(v) for v in xy[:, 1]], "numeric"),
    "label": cs.col("Node", list(g.node_id), "categorical"),
    "size": cs.col("Edges", [float(v) for v in deg], "numeric"),
}
if g.label:
    lab = ["(none)" if v is None or (isinstance(v, float) and np.isnan(v)) else str(v) for v in g.nodes[g.label].tolist()]
    levels = sorted(set(lab))
    if len(levels) <= 12:
        map_roles["group"] = cs.col(g.label, lab, "categorical", levels)
    else:
        warnings.append(f"{g.label} has {len(levels)} groups, more than the map can color (12).")
charts = [cs.chart("map", "embedding-map", "Map of the nodes", map_roles,
                   note="The first two principal components of the node vectors; nodes close together sit in similar places in the network.")]
if link is not None and link["roc"] is not None:
    charts.append(cs.chart("link_roc", "roc-curve", "Held-out edges against random non-edges", {
        "fpr": cs.col("False-positive rate", [float(v) for v in link["roc"]["fpr"]], "numeric"),
        "tpr": cs.col("True-positive rate", [float(v) for v in link["roc"]["tpr"]], "numeric"),
        "curve": cs.col("Method", [ge.LABELS[METHOD]] * len(link["roc"]["tpr"]), "categorical"),
    }))
if nb_rows:
    charts.append(cs.chart("neighbors", "ngram-bars", "Most similar nodes", {
        "term": cs.col("Neighbor", [r["neighbor"] for r in nb_rows], "categorical"),
        "count": cs.col("Cosine similarity", [r["cosine"] for r in nb_rows], "numeric"),
        "group": cs.col("Node", [r["node"] for r in nb_rows], "categorical", queries),
    }))
stats = [{"key": "n_nodes", "label": "Nodes", "value": N}, {"key": "n_edges", "label": "Edges", "value": M},
         {"key": "dim", "label": "Dimensions", "value": D}]
if values["link_auc"] is not None:
    stats += [{"key": "link_auc", "label": "Link AUC (held-out edges)", "value": values["link_auc"]},
              {"key": "link_ap", "label": "Link average precision", "value": values["link_ap"]}]
if values["final_loss"] is not None:
    stats.append({"key": "final_loss", "label": "Loss in the last pass", "value": values["final_loss"]})
if values["sv_share"] is not None:
    stats.append({"key": "sv_share", "label": "Matrix kept by these dimensions", "value": values["sv_share"]})
summary = f"{ge.LABELS[METHOD]}: a {D}-number vector for each of {N} nodes from {M} edges."
if values["link_auc"] is not None:
    summary += f" Held-out edges against as many random non-edges: link AUC {values['link_auc']:.2f} (0.5 is guessing)."
nb_cols = [{"key": "node", "label": "Node"}, {"key": "rank", "label": "Rank", "type": "number"},
           {"key": "neighbor", "label": "Similar node"}, {"key": "cosine", "label": "Cosine similarity", "type": "number"}]
cs.publish({
    "title": "Node embeddings (DeepWalk, node2vec, LINE, spectral, GNN)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": M,
    "summary": summary,
    "statistics": stats,
    "tables": [{"key": "neighbors", "title": "Most similar nodes", "columns": nb_cols, "rows": nb_rows}],
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [nodes_art],
})

With a GCN encoder that sees three node attributes, held-out edges outscore non-edges with AUC 0.79 and average precision 0.85. A one-layer attention encoder with no attributes reaches AUC 0.60.

The held-out edges were removed before the encoder ever saw the network. Leave them in and the encoder's message passing has already used them, so the test grades links it was taught.

05

VGAE: a probabilistic encoder

Read

The variational graph autoencoder outputs a mean and variance per node and samples zi=μi+σi⊙ϵiz_i = \mu_i + \sigma_i \odot \epsilon_i. It maximizes the ELBOEvidence lower boundThe quantity a VAE maximizes; minus it is the loss — how badly rows are rebuilt plus how far their codes stray from the prior.:

Eq(Z∣X,A)log⁡p(A∣Z)−KL⁡(q(Z∣X,A) ∥ N(0,I)).\mathbb{E}_{q(Z \mid X, A)} \log p(A \mid Z) - \operatorname{KL}\big(q(Z \mid X, A)\,\Vert\, N(0, I)\big).

The KL term pulls posteriors toward the prior; in the reference's example it is 1.552 for a small graph. If the KL term wins, posterior collapsePosterior collapseLatent dimensions that a VAE stops using; their codes equal the prior for every row, so they carry no information. makes the vectors ignore the graph. A node's latent variance is not a calibrated uncertainty about its links.

06

ARGA: an adversary as the regularizer

Read

ARGA keeps the autoencoder's reconstruction loss and adds a discriminator that tries to tell encoded vectors from draws of a prior; the encoder learns to fool it. That pushes the vectors toward the prior's shape without a KL term.

In the reference's example the discriminator's loss is 1.224 and the encoder's adversarial loss 0.772. Like all adversarial training it can be unstable: a dominant discriminator or badly scaled losses can wreck reconstruction.

07

DGI and MVGRL: real or corrupted?

Read

Deep Graph InfomaxDeep Graph InfomaxSelf-supervised node vectors: a discriminator tells real nodes' vectors from a corrupted graph's, each judged against a whole-graph summary. skips reconstruction. It encodes the real graph into node vectors hih_i and a summary ss (the sigmoid of their mean), and encodes a corrupted graph (node features shuffled) into h~i\tilde h_i. A bilinear discriminator D(h,s)=σ(h⊤Ws)D(h, s) = \sigma(h^\top W s) must score real nodes high and corrupted ones low.

MVGRL makes two views, the adjacency and a diffusion of it (such as personalized PageRank), and contrasts each view's node vectors with the other view's summary. The reference's DGI example has loss 1.614.

Both are surrogates for mutual information, not measurements of it. Too-easy corruptions allow shortcuts, and both views can share a nuisance pattern.

08

Readiness

Read
09

Check: neural graph representations

Checkpoint

Check yourself

What does a graph autoencoder's inner-product decoder predict?

Show the answer

Answer: a

The decoder reconstructs the adjacency matrix, so trained vectors score likely links highly.

Check yourself

You train a GAE on the full network, then hide 10% of edges and test link prediction on them. Why is the score too good?

Show the answer

Answer: a

Hide test edges before training, so neither the encoder nor the loss ever sees them.

Check yourself

Why can't the plain GAE decoder model who follows whom on a directed network?

Show the answer

Answer: a

A symmetric score can't separate i→ji \to j from j→ij \to i. Directed decoders use separate source and target vectors, like HOPE.

Check yourself

In a VGAE, what does the KL term do?

Show the answer

Answer: a

The ELBO trades reconstruction against staying close to the prior. Too much KL leads to posterior collapse.

Check yourself

A VGAE gives one node a large latent variance. Can you read that as "we're unsure about this node's links"?

Show the answer

Answer: a

The variance serves the training objective. Calibrated uncertainty about links needs its own check, such as a reliability diagram on held-out edges.

Check yourself

What replaces the VGAE's KL term in ARGA?

Show the answer

Answer: a

Adversarial matching shapes the vector distribution without a closed-form KL.

Check yourself

ARGA's reconstruction gets worse as training goes on, while its discriminator loss falls toward zero. What is happening?

Show the answer

Answer: a

Rebalance the losses or slow the discriminator. Adversarial training needs watching.

Check yourself

Where do Deep Graph Infomax's negative examples come from?

Show the answer

Answer: a

Corruption keeps the network's shape but breaks the link between a node's features and its position, which the discriminator must detect.

Check yourself

DGI is described as maximizing mutual information. What does its loss value actually tell you?

Show the answer

Answer: a

The objective is a lower-bound-style surrogate. Judge the vectors by downstream checks.

Check yourself

What are MVGRL's two views of one graph?

Show the answer

Answer: a

Each view's node vectors are contrasted with the other view's summary.

Check yourself

Both MVGRL views were built from a network with a strong batch effect: nodes collected in one week link densely. What might the vectors encode?

Show the answer

Answer: a

Contrastive agreement keeps shared structure, wanted or not. Check vectors against known nuisance variables.

10

Recap

Recap
  • GAE encodes with a GCN and decodes links by inner products; hide test edges before training.
  • VGAE adds an ELBO (watch for collapse), ARGA an adversary (watch for instability).
  • DGI and MVGRL contrast real with corrupted or cross-view signals; their losses are surrogates. GAE runs in CodeSplash; the rest are explained here.

Concepts in this lesson