Nodes known by their neighbors: node embeddings and link prediction
Give every node of a network a vector from the network around it, check the vectors honestly by hiding edges, and see why a random network has nothing to predict.
What runs in CodeSplash
You will be able to
- Explain how walks, edge samples and matrix factorizations turn a network into node vectors
- Read a link-prediction check (held-out edges against random non-edges, AUC and average precision)
- Choose a method for the size and shape of the network you have
From word vectors to node vectors
ReadWord vectors learn from the words around each word. Node embeddingsNode embeddingA short list of numbers per node, learned from the network, so nodes in similar places get similar vectors. do the same for a network: a node is known by the nodes around it. DeepWalk and node2vecRandom-walk embeddingNode vectors from random walks read as sentences by skip-gram: nodes that show up near each other on walks get close vectors. take random walks through the network and feed them to the same skip-gram model as Word vectors, as if each walk were a sentence. NetMFNetMFThe matrix DeepWalk learns without saying so, built exactly from the network and factorized by SVD: no walks, no random start. skips the walks and factorizes the matrix those walks would teach, so it gives the same kind of vectors exactly and quickly.
A network of three communities
ReadNetMF: a 8-number vector for each of 45 nodes from 108 edges. Held-out edges against as many random non-edges: link AUC 0.91 (0.5 is guessing).
- Nodes
- 45
- Edges
- 108
- Dimensions
- 8
- Link AUC (held-out edges)
- 0.9091
- Link average precision
- 0.9328
- Matrix kept by these dimensions
- 0.8410
Plots
The first two principal components of the node vectors; nodes close together sit in similar places in the network.
View data
| Node | Edges | Component 1 | Component 2 |
|---|---|---|---|
| p01 | 4 | 0.5083 | 0.0437 |
| p02 | 6 | 0.4652 | −0.2390 |
| p03 | 5 | 0.8700 | −0.2937 |
| p04 | 3 | 0.7774 | 0.0396 |
| p05 | 7 | 0.6350 | −0.1573 |
| p06 | 4 | 0.8572 | −0.0789 |
| p07 | 5 | 0.1442 | −0.0612 |
| p08 | 5 | 0.5226 | −0.1690 |
| p09 | 7 | 0.7354 | −0.2552 |
| p10 | 1 | 0.7990 | −0.3033 |
| p11 | 6 | 0.7578 | 0.1561 |
| p12 | 3 | 0.4343 | −0.1194 |
| p13 | 2 | 0.2942 | −0.1215 |
| p14 | 7 | 0.4611 | −0.0850 |
| p15 | 5 | 0.7114 | −0.2101 |
| p16 | 5 | −0.2423 | −0.3931 |
| p17 | 5 | −0.2520 | −0.4304 |
| p18 | 4 | −0.2204 | −0.3638 |
| p19 | 6 | −0.5023 | −0.5707 |
| p20 | 2 | −0.5205 | −0.3657 |
| p21 | 4 | −0.4061 | −0.5364 |
| p22 | 7 | −0.4514 | −0.5861 |
| p23 | 6 | −0.5164 | −0.6148 |
| p24 | 5 | −0.5556 | −0.3586 |
| p25 | 9 | −0.5039 | −0.3606 |
| p26 | 6 | −0.2965 | −0.3275 |
| p27 | 4 | −0.4469 | −0.4991 |
| p28 | 4 | −0.3043 | −0.1892 |
| p29 | 9 | −0.3684 | −0.4175 |
| p30 | 7 | −0.3304 | −0.3762 |
| p31 | 4 | −0.4757 | 0.3231 |
| p32 | 3 | 0.3378 | 0.6864 |
| p33 | 2 | −0.2414 | 0.5799 |
| p34 | 6 | −0.2967 | 0.5699 |
| p35 | 6 | −0.2784 | 0.5721 |
| p36 | 5 | −0.2369 | 0.5895 |
| p37 | 3 | −0.3972 | 0.5818 |
| p38 | 5 | −0.2581 | 0.5515 |
| p39 | 5 | −0.3551 | 0.6076 |
| p40 | 5 | −0.1668 | 0.5187 |
| p41 | 5 | −0.2302 | 0.2575 |
| p42 | 3 | −0.1969 | 0.4359 |
| p43 | 6 | −0.1728 | 0.8795 |
| p44 | 4 | −0.4165 | 0.3858 |
| p45 | 1 | 0.3294 | 0.7048 |
View data
| Method | False-positive rate | True-positive rate |
|---|---|---|
| NetMF | 0 | 0 |
| NetMF | 0 | 0.0909 |
| NetMF | 0 | 0.1818 |
| NetMF | 0 | 0.2727 |
| NetMF | 0 | 0.3636 |
| NetMF | 0 | 0.4545 |
| NetMF | 0 | 0.5455 |
| NetMF | 0 | 0.6364 |
| NetMF | 0 | 0.7273 |
| NetMF | 0.0909 | 0.7273 |
| NetMF | 0.0909 | 0.8182 |
| NetMF | 0.1818 | 0.8182 |
| NetMF | 0.2727 | 0.8182 |
| NetMF | 0.3636 | 0.8182 |
| NetMF | 0.3636 | 0.9091 |
| NetMF | 0.4545 | 0.9091 |
| NetMF | 0.5455 | 0.9091 |
| NetMF | 0.5455 | 1 |
| NetMF | 0.6364 | 1 |
| NetMF | 0.7273 | 1 |
| NetMF | 0.8182 | 1 |
| NetMF | 0.9091 | 1 |
| NetMF | 1 | 1 |
View data
| Cosine similarity | Node | Neighbor |
|---|---|---|
| 0.9667 | p25 | p24 |
| 0.9566 | p25 | p20 |
| 0.8778 | p25 | p19 |
| 0.8113 | p25 | p23 |
| 0.7576 | p25 | p27 |
| 0.9605 | p29 | p30 |
| 0.9572 | p29 | p16 |
| 0.9402 | p29 | p17 |
| 0.9080 | p29 | p27 |
| 0.8963 | p29 | p18 |
| 0.9542 | p05 | p09 |
| 0.9016 | p05 | p03 |
| 0.9007 | p05 | p15 |
| 0.8637 | p05 | p02 |
| 0.8302 | p05 | p14 |
| 0.9672 | p09 | p15 |
| 0.9542 | p09 | p05 |
| 0.8736 | p09 | p14 |
| 0.8647 | p09 | p03 |
| 0.8554 | p09 | p02 |
| 0.9304 | p14 | p15 |
| 0.8736 | p14 | p09 |
| 0.8302 | p14 | p05 |
| 0.8197 | p14 | p06 |
| 0.8030 | p14 | p01 |
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
| Node | Rank | Similar node | Cosine similarity |
|---|---|---|---|
| p25 | 1 | p24 | 0.9667 |
| p25 | 2 | p20 | 0.9566 |
| p25 | 3 | p19 | 0.8778 |
| p25 | 4 | p23 | 0.8113 |
| p25 | 5 | p27 | 0.7576 |
| p29 | 1 | p30 | 0.9605 |
| p29 | 2 | p16 | 0.9572 |
| p29 | 3 | p17 | 0.9402 |
| p29 | 4 | p27 | 0.9080 |
| p29 | 5 | p18 | 0.8963 |
| p05 | 1 | p09 | 0.9542 |
| p05 | 2 | p03 | 0.9016 |
| p05 | 3 | p15 | 0.9007 |
| p05 | 4 | p02 | 0.8637 |
| p05 | 5 | p14 | 0.8302 |
| p09 | 1 | p15 | 0.9672 |
| p09 | 2 | p05 | 0.9542 |
| p09 | 3 | p14 | 0.8736 |
| p09 | 4 | p03 | 0.8647 |
| p09 | 5 | p02 | 0.8554 |
| p14 | 1 | p15 | 0.9304 |
| p14 | 2 | p09 | 0.8736 |
| p14 | 3 | p05 | 0.8302 |
| p14 | 4 | p06 | 0.8197 |
| p14 | 5 | p01 | 0.8030 |
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 a4bf5d362245b1aa
# 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/netmf_blocks/out-r")
g <- cs_graph_read(out)
warnings <- as.list(g$warnings)
METHOD <- "netmf"
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 = 8L, walk_length = 20L, walks_per_node = 10L, window = 5L,
p = 1, q = 1, line_order = "second", layer = "gcn",
width = 32L, layers = 2L, heads = 4L, dropout = 0,
epochs = NULL, 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).")
}
# %% 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)
))
NetMF: a 8-number vector for each of 45 nodes from 108 edges. Held-out edges against as many random non-edges: link AUC 0.91 (0.5 is guessing).
- Nodes
- 45
- Edges
- 108
- Dimensions
- 8
- Link AUC (held-out edges)
- 0.9091
- Link average precision
- 0.9328
- Matrix kept by these dimensions
- 0.8410
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
| Node | Rank | Similar node | Cosine similarity |
|---|---|---|---|
| p25 | 1 | p24 | 0.9667 |
| p25 | 2 | p20 | 0.9566 |
| p25 | 3 | p19 | 0.8778 |
| p25 | 4 | p23 | 0.8113 |
| p25 | 5 | p27 | 0.7576 |
| p29 | 1 | p30 | 0.9605 |
| p29 | 2 | p16 | 0.9572 |
| p29 | 3 | p17 | 0.9402 |
| p29 | 4 | p27 | 0.9080 |
| p29 | 5 | p18 | 0.8963 |
| p05 | 1 | p09 | 0.9542 |
| p05 | 2 | p03 | 0.9016 |
| p05 | 3 | p15 | 0.9007 |
| p05 | 4 | p02 | 0.8637 |
| p05 | 5 | p14 | 0.8302 |
| p09 | 1 | p15 | 0.9672 |
| p09 | 2 | p05 | 0.9542 |
| p09 | 3 | p14 | 0.8736 |
| p09 | 4 | p03 | 0.8647 |
| p09 | 5 | p02 | 0.8554 |
| p14 | 1 | p15 | 0.9304 |
| p14 | 2 | p09 | 0.8736 |
| p14 | 3 | p05 | 0.8302 |
| p14 | 4 | p06 | 0.8197 |
| p14 | 5 | p01 | 0.8030 |
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 a4bf5d362245b1aa
# 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/netmf_blocks/out-python")
g = csgraph.read(out)
warnings = list(g.warnings)
METHOD = "netmf"
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": 8, "walk_length": 20, "walks_per_node": 10, "window": 5,
"p": 1, "q": 1, "line_order": "second", "layer": "gcn",
"width": 32, "layers": 2, "heads": 4, "dropout": 0,
"epochs": None, "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).")
# %% 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],
})
The network has 45 people and 108 links, about 4.8 per person. The most similar person to p05 is p09, someone from the same community, without the method ever seeing the communities.
View data
| PC 1 | PC 2 | level | feature | rows |
|---|---|---|---|---|
| −0.8520 | 0.2910 | Mon | weekday | 1,436 |
| −0.6840 | 0.0770 | Tue | weekday | 1,499 |
| −0.6460 | −0.0950 | Wed | weekday | 1,301 |
| −0.5400 | −0.1380 | Thu | weekday | 1,520 |
| −0.2430 | −0.4700 | Fri | weekday | 1,517 |
| 1.366 | 0.1560 | Sat | weekday | 1,424 |
| 1.281 | 0.4470 | Sun | weekday | 1,493 |
| 0.5590 | −0.5520 | urban | store type | 4,200 |
| 0.1730 | −0.7490 | suburban | store type | 3,100 |
| −0.6620 | 0.6650 | rural | store type | 1,600 |
| 0.9010 | 0.8360 | outlet | store type | 900 |
Check the vectors on links they never saw
ReadA map can look convincing either way. The edge holdoutEdge holdoutHiding a share of edges before learning, keeping a spanning forest so the network stays in one piece, then scoring them later. check is harder to fool: before learning, the app hides a share of the edges, learns a second copy of the vectors from the rest, and asks whether the hidden edges score higher than random pairs of nodes that aren't linked. Here 11 hidden edges reach a link AUCLink AUCChance that a hidden edge scores above a random non-edge (ties count half); 0.5 is guessing, 1 is perfect. of 0.91.
View data
| fpr | tpr | marker | cutoff |
|---|---|---|---|
| 0 | 0 | troponin | false |
| 0 | 0.0159 | troponin | false |
| 0 | 0.0317 | troponin | false |
| 0 | 0.0476 | troponin | false |
| 0 | 0.0635 | troponin | false |
| 0.0103 | 0.0635 | troponin | false |
| 0.0103 | 0.0794 | troponin | false |
| 0.0103 | 0.0952 | troponin | false |
| 0.0103 | 0.1111 | troponin | false |
| 0.0103 | 0.1270 | troponin | false |
| 0.0103 | 0.1429 | troponin | false |
| 0.0103 | 0.1587 | troponin | false |
| 0.0103 | 0.1746 | troponin | false |
| 0.0103 | 0.1905 | troponin | false |
| 0.0103 | 0.2063 | troponin | false |
| 0.0103 | 0.2222 | troponin | false |
| 0.0206 | 0.2222 | troponin | false |
| 0.0206 | 0.2381 | troponin | false |
| 0.0206 | 0.2540 | troponin | false |
| 0.0206 | 0.2698 | troponin | false |
| 0.0206 | 0.2857 | troponin | false |
| 0.0206 | 0.3016 | troponin | false |
| 0.0309 | 0.3016 | troponin | false |
| 0.0309 | 0.3175 | troponin | false |
| 0.0412 | 0.3175 | troponin | false |
| 0.0412 | 0.3333 | troponin | false |
| 0.0515 | 0.3333 | troponin | false |
| 0.0619 | 0.3333 | troponin | false |
| 0.0619 | 0.3492 | troponin | false |
| 0.0619 | 0.3651 | troponin | false |
| 0.0619 | 0.3810 | troponin | false |
| 0.0619 | 0.3968 | troponin | false |
| 0.0722 | 0.3968 | troponin | false |
| 0.0722 | 0.4127 | troponin | false |
| 0.0825 | 0.4127 | troponin | false |
| 0.0928 | 0.4127 | troponin | false |
| 0.0928 | 0.4286 | troponin | false |
| 0.0928 | 0.4444 | troponin | false |
| 0.0928 | 0.4603 | troponin | false |
| 0.0928 | 0.4762 | troponin | false |
| 0.1031 | 0.4762 | troponin | false |
| 0.1134 | 0.4762 | troponin | false |
| 0.1237 | 0.4762 | troponin | false |
| 0.1340 | 0.4762 | troponin | false |
| 0.1340 | 0.4921 | troponin | false |
| 0.1340 | 0.5079 | troponin | false |
| 0.1340 | 0.5238 | troponin | false |
| 0.1340 | 0.5397 | troponin | false |
| 0.1443 | 0.5397 | troponin | false |
| 0.1546 | 0.5397 | troponin | false |
| 0.1546 | 0.5556 | troponin | false |
| 0.1649 | 0.5556 | troponin | false |
| 0.1649 | 0.5714 | troponin | false |
| 0.1649 | 0.5873 | troponin | false |
| 0.1753 | 0.5873 | troponin | false |
| 0.1856 | 0.5873 | troponin | false |
| 0.1856 | 0.6032 | troponin | false |
| 0.1959 | 0.6032 | troponin | false |
| 0.2062 | 0.6032 | troponin | false |
| 0.2165 | 0.6032 | troponin | false |
First 60 of 322 rows.
The app never hides an edge that holds the network together: a spanning forest is kept, so every node still has a link and the network keeps its pieces. The vectors saved for each node are learned from every edge.
Check yourself
Why are the held-out edges removed before the check's vectors are learned?
Show the answer
Answer: b
A link the vectors were trained on is easy to "predict". Hiding it first is what makes the AUC an honest score.
Walks need more network than you think
ReadDeepWalk: a 6-number vector for each of 45 nodes from 108 edges. Held-out edges against as many random non-edges: link AUC 0.69 (0.5 is guessing).
- Nodes
- 45
- Edges
- 108
- Dimensions
- 6
- Link AUC (held-out edges)
- 0.6875
- Link average precision
- 0.6754
- Loss in the last pass
- 4.070
Plots
The first two principal components of the node vectors; nodes close together sit in similar places in the network.
View data
| Node | Edges | Component 1 | Component 2 |
|---|---|---|---|
| p01 | 4 | 0.0058 | −0.0256 |
| p02 | 6 | 0.0461 | −0.0300 |
| p03 | 5 | 0.0839 | −0.0591 |
| p04 | 3 | −0.0153 | −0.1005 |
| p05 | 7 | 0.1138 | 0.0566 |
| p06 | 4 | −0.0488 | −0.0888 |
| p07 | 5 | 0.1005 | 0.0320 |
| p08 | 5 | 0.0016 | 0.0136 |
| p09 | 7 | −0.0272 | −0.0209 |
| p10 | 1 | −0.0581 | −0.0163 |
| p11 | 6 | 0.0247 | 0.0250 |
| p12 | 3 | 0.1044 | −0.0628 |
| p13 | 2 | −0.0037 | −0.0395 |
| p14 | 7 | 0.0503 | 0.1407 |
| p15 | 5 | 0.0636 | 0.0418 |
| p16 | 5 | −0.0464 | −0.0337 |
| p17 | 5 | −0.0880 | 0.0934 |
| p18 | 4 | −0.0068 | 0.0444 |
| p19 | 6 | −0.0304 | 0.0072 |
| p20 | 2 | −0.0700 | −0.0471 |
| p21 | 4 | 0.0517 | −0.0194 |
| p22 | 7 | −0.0277 | 0.0695 |
| p23 | 6 | −0.0223 | 0.0695 |
| p24 | 5 | −0.0451 | −0.0414 |
| p25 | 9 | −0.0229 | 0.0078 |
| p26 | 6 | −0.0017 | 0.0666 |
| p27 | 4 | −0.0576 | 0.0004 |
| p28 | 4 | −0.0931 | −0.0691 |
| p29 | 9 | −0.0392 | 0.0275 |
| p30 | 7 | −0.0080 | 0.1011 |
| p31 | 4 | −0.0971 | 0.0044 |
| p32 | 3 | −0.0312 | 0.0804 |
| p33 | 2 | −0.0199 | 0.0155 |
| p34 | 6 | 0.1124 | −0.0778 |
| p35 | 6 | 0.0341 | −0.0437 |
| p36 | 5 | 0.0153 | −0.0012 |
| p37 | 3 | −0.1070 | −0.0012 |
| p38 | 5 | 0.1249 | 0.0444 |
| p39 | 5 | 0.0110 | −0.1163 |
| p40 | 5 | 0.0540 | 0.0378 |
| p41 | 5 | −0.0413 | −0.0820 |
| p42 | 3 | −0.0516 | −0.0152 |
| p43 | 6 | 0.1265 | −0.0329 |
| p44 | 4 | 0.0378 | −0.0049 |
| p45 | 1 | −0.1018 | 0.0497 |
View data
| Method | False-positive rate | True-positive rate |
|---|---|---|
| DeepWalk | 0 | 0 |
| DeepWalk | 0 | 0.0625 |
| DeepWalk | 0 | 0.1250 |
| DeepWalk | 0.0625 | 0.1250 |
| DeepWalk | 0.1250 | 0.1250 |
| DeepWalk | 0.1875 | 0.1250 |
| DeepWalk | 0.1875 | 0.1875 |
| DeepWalk | 0.1875 | 0.2500 |
| DeepWalk | 0.1875 | 0.3125 |
| DeepWalk | 0.1875 | 0.3750 |
| DeepWalk | 0.1875 | 0.4375 |
| DeepWalk | 0.2500 | 0.4375 |
| DeepWalk | 0.2500 | 0.5000 |
| DeepWalk | 0.2500 | 0.5625 |
| DeepWalk | 0.2500 | 0.6250 |
| DeepWalk | 0.3125 | 0.6250 |
| DeepWalk | 0.3750 | 0.6250 |
| DeepWalk | 0.4375 | 0.6250 |
| DeepWalk | 0.4375 | 0.6875 |
| DeepWalk | 0.4375 | 0.7500 |
| DeepWalk | 0.4375 | 0.8125 |
| DeepWalk | 0.4375 | 0.8750 |
| DeepWalk | 0.5000 | 0.8750 |
| DeepWalk | 0.5625 | 0.8750 |
| DeepWalk | 0.6250 | 0.8750 |
| DeepWalk | 0.6875 | 0.8750 |
| DeepWalk | 0.6875 | 0.9375 |
| DeepWalk | 0.7500 | 0.9375 |
| DeepWalk | 0.8125 | 0.9375 |
| DeepWalk | 0.8750 | 0.9375 |
| DeepWalk | 0.8750 | 1 |
| DeepWalk | 0.9375 | 1 |
| DeepWalk | 1 | 1 |
View data
| Cosine similarity | Node | Neighbor |
|---|---|---|
| 0.7103 | p25 | p21 |
| 0.6045 | p25 | p07 |
| 0.5764 | p25 | p26 |
| 0.5651 | p25 | p01 |
| 0.5432 | p25 | p32 |
| 0.8778 | p29 | p27 |
| 0.8720 | p29 | p19 |
| 0.7662 | p29 | p09 |
| 0.7608 | p29 | p08 |
| 0.7387 | p29 | p23 |
| 0.9864 | p05 | p15 |
| 0.8128 | p05 | p07 |
| 0.8031 | p05 | p14 |
| 0.7982 | p05 | p38 |
| 0.7233 | p05 | p23 |
| 0.8041 | p09 | p33 |
| 0.7799 | p09 | p36 |
| 0.7662 | p09 | p29 |
| 0.6886 | p09 | p06 |
| 0.5908 | p09 | p20 |
| 0.8536 | p14 | p23 |
| 0.8484 | p14 | p15 |
| 0.8031 | p14 | p05 |
| 0.7690 | p14 | p38 |
| 0.7467 | p14 | p11 |
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
| Node | Rank | Similar node | Cosine similarity |
|---|---|---|---|
| p25 | 1 | p21 | 0.7103 |
| p25 | 2 | p07 | 0.6045 |
| p25 | 3 | p26 | 0.5764 |
| p25 | 4 | p01 | 0.5651 |
| p25 | 5 | p32 | 0.5432 |
| p29 | 1 | p27 | 0.8778 |
| p29 | 2 | p19 | 0.8720 |
| p29 | 3 | p09 | 0.7662 |
| p29 | 4 | p08 | 0.7608 |
| p29 | 5 | p23 | 0.7387 |
| p05 | 1 | p15 | 0.9864 |
| p05 | 2 | p07 | 0.8128 |
| p05 | 3 | p14 | 0.8031 |
| p05 | 4 | p38 | 0.7982 |
| p05 | 5 | p23 | 0.7233 |
| p09 | 1 | p33 | 0.8041 |
| p09 | 2 | p36 | 0.7799 |
| p09 | 3 | p29 | 0.7662 |
| p09 | 4 | p06 | 0.6886 |
| p09 | 5 | p20 | 0.5908 |
| p14 | 1 | p23 | 0.8536 |
| p14 | 2 | p15 | 0.8484 |
| p14 | 3 | p05 | 0.8031 |
| p14 | 4 | p38 | 0.7690 |
| p14 | 5 | p11 | 0.7467 |
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 9ded890896766a22
# 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/deepwalk_blocks_weighted/out-r")
g <- cs_graph_read(out)
warnings <- as.list(g$warnings)
METHOD <- "deepwalk"
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 = 6L, walk_length = 8L, walks_per_node = 3L, window = 2L,
p = 1, q = 1, line_order = "second", layer = "gcn",
width = 32L, layers = 2L, heads = 4L, dropout = 0,
epochs = NULL, 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).")
}
# %% Link check: hide edges, learn from the rest, score hidden edges against random non-edges
HOLD <- 0.15
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)
))
DeepWalk: a 6-number vector for each of 45 nodes from 108 edges. Held-out edges against as many random non-edges: link AUC 0.69 (0.5 is guessing).
- Nodes
- 45
- Edges
- 108
- Dimensions
- 6
- Link AUC (held-out edges)
- 0.6875
- Link average precision
- 0.6754
- Loss in the last pass
- 4.070
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
| Node | Rank | Similar node | Cosine similarity |
|---|---|---|---|
| p25 | 1 | p21 | 0.7103 |
| p25 | 2 | p07 | 0.6045 |
| p25 | 3 | p26 | 0.5764 |
| p25 | 4 | p01 | 0.5651 |
| p25 | 5 | p32 | 0.5432 |
| p29 | 1 | p27 | 0.8778 |
| p29 | 2 | p19 | 0.8720 |
| p29 | 3 | p09 | 0.7662 |
| p29 | 4 | p08 | 0.7608 |
| p29 | 5 | p23 | 0.7387 |
| p05 | 1 | p15 | 0.9864 |
| p05 | 2 | p07 | 0.8128 |
| p05 | 3 | p14 | 0.8031 |
| p05 | 4 | p38 | 0.7982 |
| p05 | 5 | p23 | 0.7233 |
| p09 | 1 | p33 | 0.8041 |
| p09 | 2 | p36 | 0.7799 |
| p09 | 3 | p29 | 0.7662 |
| p09 | 4 | p06 | 0.6886 |
| p09 | 5 | p20 | 0.5908 |
| p14 | 1 | p23 | 0.8536 |
| p14 | 2 | p15 | 0.8484 |
| p14 | 3 | p05 | 0.8031 |
| p14 | 4 | p38 | 0.7690 |
| p14 | 5 | p11 | 0.7467 |
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 9ded890896766a22
# 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/deepwalk_blocks_weighted/out-python")
g = csgraph.read(out)
warnings = list(g.warnings)
METHOD = "deepwalk"
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": 6, "walk_length": 8, "walks_per_node": 3, "window": 2,
"p": 1, "q": 1, "line_order": "second", "layer": "gcn",
"width": 32, "layers": 2, "heads": 4, "dropout": 0,
"epochs": None, "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).")
# %% Link check: hide edges, learn from the rest, score hidden edges against random non-edges
HOLD = 0.15
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],
})
DeepWalk with short walks on this small network reaches a link AUC of 0.69, below NetMF. Walks are random samples of the network; with a few short walks per node, the vectors are noisy. On small networks start with NetMF, HOPE or Laplacian eigenmaps, which are exact. Use walks when the network is large and you want node2vec's control over where the walks go.
node2vec: a 6-number vector for each of 45 nodes from 108 edges. Held-out edges against as many random non-edges: link AUC 0.77 (0.5 is guessing).
- Nodes
- 45
- Edges
- 108
- Dimensions
- 6
- Link AUC (held-out edges)
- 0.7686
- Link average precision
- 0.7813
- Loss in the last pass
- 4.067
Plots
The first two principal components of the node vectors; nodes close together sit in similar places in the network.
View data
| community | Node | Edges | Component 1 | Component 2 |
|---|---|---|---|---|
| A | p01 | 4 | 0.0429 | −0.0328 |
| A | p02 | 6 | 0.0446 | 0.0101 |
| A | p03 | 5 | 0.1101 | −0.0004 |
| A | p04 | 3 | 0.0361 | 0.0792 |
| A | p05 | 7 | 0.0491 | −0.1058 |
| A | p06 | 4 | 0.0085 | 0.0769 |
| A | p07 | 5 | 0.0690 | −0.0666 |
| A | p08 | 5 | 0.0127 | −0.0350 |
| A | p09 | 7 | −0.0169 | 0.0408 |
| A | p10 | 1 | −0.0289 | −0.0382 |
| A | p11 | 6 | −0.0067 | 0.0169 |
| A | p12 | 3 | 0.1162 | −0.0049 |
| A | p13 | 2 | 0.0251 | 0.0075 |
| A | p14 | 7 | −0.0546 | −0.0919 |
| A | p15 | 5 | 0.0192 | −0.0804 |
| B | p16 | 5 | −0.0163 | 0.0251 |
| B | p17 | 5 | −0.1254 | −0.0191 |
| B | p18 | 4 | −0.0288 | −0.0341 |
| B | p19 | 6 | −0.0299 | −0.0128 |
| B | p20 | 2 | −0.0269 | 0.0337 |
| B | p21 | 4 | 0.0642 | −0.0316 |
| B | p22 | 7 | −0.0472 | −0.1006 |
| B | p23 | 6 | −0.0561 | −0.0545 |
| B | p24 | 5 | −0.0279 | 0.0954 |
| B | p25 | 9 | −0.0137 | 0.0091 |
| B | p26 | 6 | −0.0427 | −0.0182 |
| B | p27 | 4 | −0.0423 | 0.0171 |
| B | p28 | 4 | −0.0410 | 0.1488 |
| B | p29 | 9 | −0.0446 | 0.0212 |
| B | p30 | 7 | −0.0588 | −0.0756 |
| C | p31 | 4 | −0.0761 | 0.0377 |
| C | p32 | 3 | −0.0573 | −0.0196 |
| C | p33 | 2 | −0.0414 | 0.0274 |
| C | p34 | 6 | 0.1291 | 0.0132 |
| C | p35 | 6 | 0.0692 | −0.0036 |
| C | p36 | 5 | −0.0010 | 0.0358 |
| C | p37 | 3 | −0.0808 | 0.0136 |
| C | p38 | 5 | 0.0521 | −0.0270 |
| C | p39 | 5 | 0.0710 | 0.0965 |
| C | p40 | 5 | 0.0189 | −0.0090 |
| C | p41 | 5 | 0.0176 | 0.0749 |
| C | p42 | 3 | −0.0267 | −0.0174 |
| C | p43 | 6 | 0.1222 | −0.0135 |
| C | p44 | 4 | 0.0250 | −0.0010 |
| C | p45 | 1 | −0.1109 | 0.0126 |
View data
| Method | False-positive rate | True-positive rate |
|---|---|---|
| node2vec | 0 | 0 |
| node2vec | 0 | 0.0909 |
| node2vec | 0 | 0.1818 |
| node2vec | 0.0909 | 0.1818 |
| node2vec | 0.0909 | 0.2727 |
| node2vec | 0.0909 | 0.3636 |
| node2vec | 0.0909 | 0.4545 |
| node2vec | 0.1818 | 0.4545 |
| node2vec | 0.1818 | 0.5455 |
| node2vec | 0.1818 | 0.6364 |
| node2vec | 0.1818 | 0.7273 |
| node2vec | 0.2727 | 0.7273 |
| node2vec | 0.3636 | 0.7273 |
| node2vec | 0.3636 | 0.8182 |
| node2vec | 0.4545 | 0.8182 |
| node2vec | 0.4545 | 0.9091 |
| node2vec | 0.5455 | 0.9091 |
| node2vec | 0.6364 | 0.9091 |
| node2vec | 0.7273 | 0.9091 |
| node2vec | 0.8182 | 0.9091 |
| node2vec | 0.9091 | 0.9091 |
| node2vec | 0.9091 | 1 |
| node2vec | 1 | 1 |
View data
| Cosine similarity | Node | Neighbor |
|---|---|---|
| 0.7754 | p01 | p21 |
| 0.7279 | p01 | p07 |
| 0.6293 | p01 | p03 |
| 0.8095 | p20 | p29 |
| 0.7900 | p20 | p27 |
| 0.7432 | p20 | p06 |
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
| Node | Rank | Similar node | Cosine similarity |
|---|---|---|---|
| p01 | 1 | p21 | 0.7754 |
| p01 | 2 | p07 | 0.7279 |
| p01 | 3 | p03 | 0.6293 |
| p20 | 1 | p29 | 0.8095 |
| p20 | 2 | p27 | 0.7900 |
| p20 | 3 | p06 | 0.7432 |
- Not in the network: zz.
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 51bbe5ee3235c0d7
# 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/node2vec_blocks_nodes/out-r")
g <- cs_graph_read(out)
warnings <- as.list(g$warnings)
METHOD <- "node2vec"
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 = 6L, walk_length = 8L, walks_per_node = 3L, window = 2L,
p = 0.5, q = 2, line_order = "second", layer = "gcn",
width = 32L, layers = 2L, heads = 4L, dropout = 0,
epochs = NULL, 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).")
}
# %% 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 <- "p01, p20, zz"
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 <- 3
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)
))
node2vec: a 6-number vector for each of 45 nodes from 108 edges. Held-out edges against as many random non-edges: link AUC 0.77 (0.5 is guessing).
- Nodes
- 45
- Edges
- 108
- Dimensions
- 6
- Link AUC (held-out edges)
- 0.7686
- Link average precision
- 0.7813
- Loss in the last pass
- 4.067
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
| Node | Rank | Similar node | Cosine similarity |
|---|---|---|---|
| p01 | 1 | p21 | 0.7754 |
| p01 | 2 | p07 | 0.7279 |
| p01 | 3 | p03 | 0.6293 |
| p20 | 1 | p29 | 0.8095 |
| p20 | 2 | p27 | 0.7900 |
| p20 | 3 | p06 | 0.7432 |
- Not in the network: zz.
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 51bbe5ee3235c0d7
# 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/node2vec_blocks_nodes/out-python")
g = csgraph.read(out)
warnings = list(g.warnings)
METHOD = "node2vec"
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": 6, "walk_length": 8, "walks_per_node": 3, "window": 2,
"p": 0.5, "q": 2, "line_order": "second", "layer": "gcn",
"width": 32, "layers": 2, "heads": 4, "dropout": 0,
"epochs": None, "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).")
# %% 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 = "p01, p20, zz"
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 = 3
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],
})
node2vec bends the walks: a return parameter p and in–out parameter qRandom-walk embeddingNode vectors from random walks read as sentences by skip-gram: nodes that show up near each other on walks get close vectors. below or above 1 decide whether walks stay near home or wander off. A node table can color the map by community; it never changes the vectors.
Check yourself
You want node2vec vectors that group people by community, not by role (hub or bridge). Which setting fits?
Show the answer
Answer: a
Walks that stay local see the same community over and over, so its members end up close. Walks that move outward see nodes with the same role in different places.
When there is nothing to predict
ReadHOPE: a 6-number vector for each of 25 nodes from 63 edges. Held-out edges against as many random non-edges: link AUC 0.36 (0.5 is guessing).
- Nodes
- 25
- Edges
- 63
- Dimensions
- 6
- Link AUC (held-out edges)
- 0.3611
- Link average precision
- 0.4832
- Matrix kept by these dimensions
- 0.6649
Plots
The first two principal components of the node vectors; nodes close together sit in similar places in the network.
View data
| Node | Edges | Component 1 | Component 2 |
|---|---|---|---|
| 1 | 3 | 0.0488 | −0.0452 |
| 10 | 3 | 0.0204 | 0.0910 |
| 11 | 5 | 0.0271 | 0.1318 |
| 12 | 5 | −0.1332 | −0.2017 |
| 13 | 4 | −0.1725 | 0.0391 |
| 14 | 4 | −0.2059 | 0.0516 |
| 15 | 6 | 0.1433 | −0.0189 |
| 16 | 9 | 0.2481 | 0.4714 |
| 17 | 3 | −0.1568 | 0.0101 |
| 18 | 3 | −0.1213 | 0.1015 |
| 19 | 3 | −0.1843 | −0.1920 |
| 2 | 4 | −0.0673 | 0.0868 |
| 20 | 8 | 0.1696 | 0.1679 |
| 21 | 4 | −0.2301 | 0.0363 |
| 22 | 5 | −0.0845 | −0.2634 |
| 23 | 8 | 0.3719 | 0.0895 |
| 24 | 5 | −0.0456 | −0.0150 |
| 25 | 2 | −0.0298 | −0.0315 |
| 3 | 8 | 0.4016 | −0.2923 |
| 4 | 7 | 0.0196 | −0.1205 |
| 5 | 7 | 0.2607 | −0.1905 |
| 6 | 4 | 0.0245 | −0.0412 |
| 7 | 4 | −0.1783 | 0.1707 |
| 8 | 2 | −0.1822 | 0.0715 |
| 9 | 4 | 0.0561 | −0.1070 |
View data
| Method | False-positive rate | True-positive rate |
|---|---|---|
| HOPE | 0 | 0 |
| HOPE | 0.1667 | 0 |
| HOPE | 0.1667 | 0.1667 |
| HOPE | 0.3333 | 0.1667 |
| HOPE | 0.3333 | 0.3333 |
| HOPE | 0.5000 | 0.3333 |
| HOPE | 0.5000 | 0.5000 |
| HOPE | 0.6667 | 0.5000 |
| HOPE | 0.8333 | 0.5000 |
| HOPE | 0.8333 | 0.6667 |
| HOPE | 1 | 0.6667 |
| HOPE | 1 | 0.8333 |
| HOPE | 1 | 1 |
View data
| Cosine similarity | Node | Neighbor |
|---|---|---|
| 0.7513 | 16 | 20 |
| 0.7187 | 16 | 8 |
| 0.6523 | 16 | 23 |
| 0.6042 | 16 | 10 |
| 0.5977 | 16 | 24 |
| 0.8319 | 20 | 15 |
| 0.7549 | 20 | 23 |
| 0.7513 | 20 | 16 |
| 0.7282 | 20 | 6 |
| 0.6836 | 20 | 5 |
| 0.7984 | 23 | 3 |
| 0.7816 | 23 | 6 |
| 0.7602 | 23 | 11 |
| 0.7549 | 23 | 20 |
| 0.7343 | 23 | 15 |
| 0.9012 | 3 | 5 |
| 0.8340 | 3 | 9 |
| 0.7984 | 3 | 23 |
| 0.7090 | 3 | 1 |
| 0.6851 | 3 | 6 |
| 0.7545 | 4 | 9 |
| 0.7345 | 4 | 6 |
| 0.6910 | 4 | 5 |
| 0.6701 | 4 | 20 |
| 0.6638 | 4 | 14 |
Assumptions
- Enough network — 2.5 edges per node on average; similar nodes and link scores are noisy on so sparse a network.
- 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
| Node | Rank | Similar node | Cosine similarity |
|---|---|---|---|
| 16 | 1 | 20 | 0.7513 |
| 16 | 2 | 8 | 0.7187 |
| 16 | 3 | 23 | 0.6523 |
| 16 | 4 | 10 | 0.6042 |
| 16 | 5 | 24 | 0.5977 |
| 20 | 1 | 15 | 0.8319 |
| 20 | 2 | 23 | 0.7549 |
| 20 | 3 | 16 | 0.7513 |
| 20 | 4 | 6 | 0.7282 |
| 20 | 5 | 5 | 0.6836 |
| 23 | 1 | 3 | 0.7984 |
| 23 | 2 | 6 | 0.7816 |
| 23 | 3 | 11 | 0.7602 |
| 23 | 4 | 20 | 0.7549 |
| 23 | 5 | 15 | 0.7343 |
| 3 | 1 | 5 | 0.9012 |
| 3 | 2 | 9 | 0.8340 |
| 3 | 3 | 23 | 0.7984 |
| 3 | 4 | 1 | 0.7090 |
| 3 | 5 | 6 | 0.6851 |
| 4 | 1 | 9 | 0.7545 |
| 4 | 2 | 6 | 0.7345 |
| 4 | 3 | 5 | 0.6910 |
| 4 | 4 | 20 | 0.6701 |
| 4 | 5 | 14 | 0.6638 |
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 a5b3f0821083fa6d
# Dataset: grf3_directed_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/hope_directed/out-r")
g <- cs_graph_read(out)
warnings <- as.list(g$warnings)
METHOD <- "hope"
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 = 6L, walk_length = 20L, walks_per_node = 10L, window = 5L,
p = 1, q = 1, line_order = "second", layer = "gcn",
width = 32L, layers = 2L, heads = 4L, dropout = 0,
epochs = NULL, 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).")
}
# %% 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)
))
HOPE: a 6-number vector for each of 25 nodes from 63 edges. Held-out edges against as many random non-edges: link AUC 0.36 (0.5 is guessing).
- Nodes
- 25
- Edges
- 63
- Dimensions
- 6
- Link AUC (held-out edges)
- 0.3611
- Link average precision
- 0.4832
- Matrix kept by these dimensions
- 0.6649
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough network — 2.5 edges per node on average; similar nodes and link scores are noisy on so sparse a network.
- 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
| Node | Rank | Similar node | Cosine similarity |
|---|---|---|---|
| 16 | 1 | 20 | 0.7513 |
| 16 | 2 | 8 | 0.7187 |
| 16 | 3 | 23 | 0.6523 |
| 16 | 4 | 10 | 0.6042 |
| 16 | 5 | 24 | 0.5977 |
| 20 | 1 | 15 | 0.8319 |
| 20 | 2 | 23 | 0.7549 |
| 20 | 3 | 16 | 0.7513 |
| 20 | 4 | 6 | 0.7282 |
| 20 | 5 | 5 | 0.6836 |
| 23 | 1 | 3 | 0.7984 |
| 23 | 2 | 6 | 0.7816 |
| 23 | 3 | 11 | 0.7602 |
| 23 | 4 | 20 | 0.7549 |
| 23 | 5 | 15 | 0.7343 |
| 3 | 1 | 5 | 0.9012 |
| 3 | 2 | 9 | 0.8340 |
| 3 | 3 | 23 | 0.7984 |
| 3 | 4 | 1 | 0.7090 |
| 3 | 5 | 6 | 0.6851 |
| 4 | 1 | 9 | 0.7545 |
| 4 | 2 | 6 | 0.7345 |
| 4 | 3 | 5 | 0.6910 |
| 4 | 4 | 20 | 0.6701 |
| 4 | 5 | 14 | 0.6638 |
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 a5b3f0821083fa6d
# Dataset: grf3_directed_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/hope_directed/out-python")
g = csgraph.read(out)
warnings = list(g.warnings)
METHOD = "hope"
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": 6, "walk_length": 20, "walks_per_node": 10, "window": 5,
"p": 1, "q": 1, "line_order": "second", "layer": "gcn",
"width": 32, "layers": 2, "heads": 4, "dropout": 0,
"epochs": None, "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).")
# %% 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],
})
HOPEHOPEFactorizes Katz proximity (paths of every length, longer ones fading by β) into a source and a target vector per node. keeps the direction of each link with a source and a target vector per node. This network was drawn at random: every ordered pair is linked with the same chance. The link AUC is 0.36, no better than guessing on only 6 hidden edges. That is the right answer: when links are random, no vector can predict them.
Check yourself
A link check gives AUC 0.52 on 40 held-out edges. What is the most reasonable reading?
Show the answer
Answer: b
Around 0.5 means guessing. Check edges per node and try an exact method before blaming the method; some networks simply have no pattern in who links to whom.
Some methods need one piece
ReadLaplacian eigenmaps place linked nodes close together using the network's smoothest eigenvectors. A network in two separate parts has no single smoothest picture, so the method stops and says how many parts it found. Filter to the largest part, or choose NetMF, HOPE or walks, which handle separate parts.
Concepts in this lesson