Skip to content

CDiscover · discover.graph_embed

Node embeddings (DeepWalk, node2vec, LINE, spectral, GNN)

Which nodes of this network play similar parts, and which missing links are likely?

Gives every node of a network a short vector so that nodes close in the network get close vectors. DeepWalk and node2vec learn from random walks with the skip-gram model of Word vectors; LINE samples edges directly; Laplacian eigenmaps, HOPE and NetMF are exact matrix factorizations; the graph neural network option trains GCN, GraphSAGE, GAT or GIN layers to predict links. A share of the edges can be held out first to check how well the vectors predict links nobody showed them (AUC and average precision). Walks, edge samples and starting weights come from the shared random stream, so Python and R agree.

Experimental Python and R agree to 6 decimals Seeded Also called graph embedding, network embedding, node embedding…

A real result

Example “Netmf blocks”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

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

Plots

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

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

View data
NodeEdgesComponent 1Component 2
p0140.50830.0437
p0260.4652−0.2390
p0350.8700−0.2937
p0430.77740.0396
p0570.6350−0.1573
p0640.8572−0.0789
p0750.1442−0.0612
p0850.5226−0.1690
p0970.7354−0.2552
p1010.7990−0.3033
p1160.75780.1561
p1230.4343−0.1194
p1320.2942−0.1215
p1470.4611−0.0850
p1550.7114−0.2101
p165−0.2423−0.3931
p175−0.2520−0.4304
p184−0.2204−0.3638
p196−0.5023−0.5707
p202−0.5205−0.3657
p214−0.4061−0.5364
p227−0.4514−0.5861
p236−0.5164−0.6148
p245−0.5556−0.3586
p259−0.5039−0.3606
p266−0.2965−0.3275
p274−0.4469−0.4991
p284−0.3043−0.1892
p299−0.3684−0.4175
p307−0.3304−0.3762
p314−0.47570.3231
p3230.33780.6864
p332−0.24140.5799
p346−0.29670.5699
p356−0.27840.5721
p365−0.23690.5895
p373−0.39720.5818
p385−0.25810.5515
p395−0.35510.6076
p405−0.16680.5187
p415−0.23020.2575
p423−0.19690.4359
p436−0.17280.8795
p444−0.41650.3858
p4510.32940.7048
Held-out edges against random non-edgesHow well does a score separate positives from negatives at every cutoff?
View data
MethodFalse-positive rateTrue-positive rate
NetMF00
NetMF00.0909
NetMF00.1818
NetMF00.2727
NetMF00.3636
NetMF00.4545
NetMF00.5455
NetMF00.6364
NetMF00.7273
NetMF0.09090.7273
NetMF0.09090.8182
NetMF0.18180.8182
NetMF0.27270.8182
NetMF0.36360.8182
NetMF0.36360.9091
NetMF0.45450.9091
NetMF0.54550.9091
NetMF0.54551
NetMF0.63641
NetMF0.72731
NetMF0.81821
NetMF0.90911
NetMF11
Most similar nodesWhich words or phrases appear most in a text column, overall or by group?
View data
Cosine similarityNodeNeighbor
0.9667p25p24
0.9566p25p20
0.8778p25p19
0.8113p25p23
0.7576p25p27
0.9605p29p30
0.9572p29p16
0.9402p29p17
0.9080p29p27
0.8963p29p18
0.9542p05p09
0.9016p05p03
0.9007p05p15
0.8637p05p02
0.8302p05p14
0.9672p09p15
0.9542p09p05
0.8736p09p14
0.8647p09p03
0.8554p09p02
0.9304p14p15
0.8736p14p09
0.8302p14p05
0.8197p14p06
0.8030p14p01

Assumptions

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

Most similar nodes

NodeRankSimilar nodeCosine similarity
p251p240.9667
p252p200.9566
p253p190.8778
p254p230.8113
p255p270.7576
p291p300.9605
p292p160.9572
p293p170.9402
p294p270.9080
p295p180.8963
p051p090.9542
p052p030.9016
p053p150.9007
p054p020.8637
p055p140.8302
p091p150.9672
p092p050.9542
p093p140.8736
p094p030.8647
p095p020.8554
p141p150.9304
p142p090.8736
p143p050.8302
p144p060.8197
p145p010.8030
Python

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

NodeRankSimilar nodeCosine similarity
p251p240.9667
p252p200.9566
p253p190.8778
p254p230.8113
p255p270.7576
p291p300.9605
p292p160.9572
p293p170.9402
p294p270.9080
p295p180.8963
p051p090.9542
p052p030.9016
p053p150.9007
p054p020.8637
p055p140.8302
p091p150.9672
p092p050.9542
p093p140.8736
p094p030.8647
p095p020.8554
p141p150.9304
p142p090.8736
p143p050.8302
p144p060.8197
p145p010.8030

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Netmf blocksgrf3_blocks_edges · source: from · target: to
  • Deepwalk blocks weightedgrf3_blocks_edges · source: from · target: to · weight: strength
  • Node2vec blocks nodesgrf3_blocks_edges · source: from · target: to
  • Line both blocksgrf3_blocks_edges · source: from · target: to · weight: strength
  • Laplacian blocksgrf3_blocks_edges · source: from · target: to · weight: strength
  • Hope directedgrf3_directed_edges · source: src · target: dst
  • Deepwalk directedgrf3_directed_edges · source: src · target: dst
  • Gnn gcn attributesgrf3_blocks_edges · source: from · target: to

In the guides

Where it sits in the decision guides

  • Type: structured (tabular), unstructured (text, images, audio, video), time series / sequential, graph / relational · DS & ML Decision Guide · Key data characteristics — what influences method choice
  • Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels

What you need

From (source)categorical / numeric · 1 column
The column with one end of each edge: a person, page or station id.
To (target)categorical / numeric · 1 column
The column with the other end of each edge.
Edge weightnumeric · 0–1 column
Optional strength of each edge (positive numbers). Repeated edges add up; without it every edge counts 1.

Choices you make

model

Methoddefault netmf

NetMF, HOPE and Laplacian eigenmaps are exact and quick on small networks; walks, LINE and the graph neural network learn by sampling.

  • NetMF (exact)(default) — Factorizes the matrix DeepWalk learns implicitly (Qiu et al. 2018): DeepWalk's answer without the random walks.
  • DeepWalk — Random walks read as sentences by the skip-gram model (Perozzi et al. 2014).
  • node2vec — Random walks that you can bend toward staying close (BFS-like) or wandering off (DFS-like) with p and q (Grover & Leskovec 2016).
  • LINE — Samples edges in proportion to their weight and learns from direct neighbors (first order) or shared neighbors (second order) (Tang et al. 2015).
  • Laplacian eigenmaps — The network's smoothest eigenvectors: linked nodes land close together (Belkin & Niyogi 2003). Needs a connected network.
  • HOPE (directed) — Factorizes Katz proximity, which counts paths of every length; keeps the direction of links with separate source and target vectors (Ou et al. 2016).
  • Graph neural network (link prediction) — GCN, GraphSAGE, GAT or GIN layers trained to tell edges from random pairs (a graph autoencoder); reads node attributes when the node table has them.
Dimensionsdefault 16

Length of each node's vector. Capped below the number of nodes for the exact methods.

Edges have a directiondefault off

On: an edge from A to B is not an edge from B to A. Walks, LINE and HOPE follow directions; the other methods treat every edge as two-way.

Walk lengthdefault 20

Nodes in each random walk. Longer walks see more of the network around each node.

Walks per nodedefault 10

Walks started from every node. More walks give steadier vectors and take longer.

Context windowdefault 5

How many steps on each side of a node count as its context. NetMF uses it as the walk window it factorizes.

Return parameter (p)default 1

Below 1 the walk often steps back to the node it came from; above 1 it rarely does.

In–out parameter (q)default 1

Above 1 the walk stays near where it started (communities); below 1 it moves outward (roles like hubs and bridges).

Proximitydefault second

Which kind of closeness LINE keeps.

  • First order — Linked nodes get close vectors.
  • Second order(default) — Nodes with the same neighbors get close vectors, linked or not.
  • Both — Half the dimensions from each, every half scaled to length 1.
Layerdefault gcn

How each node combines its neighbors.

  • GCN(default) — A degree-weighted average of the node and its neighbors (Kipf & Welling 2017).
  • GraphSAGE (mean) — The node's own vector next to the mean of its neighbors' (Hamilton et al. 2017).
  • GAT — Learned attention weights decide how much each neighbor counts (Veličković et al. 2018).
  • GIN — The sum of the neighbors through a small network: tells apart more network shapes (Xu et al. 2019).
Hidden unitsdefault 32

Units in each graph layer.

Graph layersdefault 2

Each layer reaches one step further into the network.

Attention headsdefault 4

GAT only: attention heads side by side; the hidden units must divide evenly by it.

Passesdefault —

Training passes: over all walks, over all edges (LINE) or full-network steps (graph network).

Advanced

Dropoutdefault 0

Share of hidden units dropped while training (masks from the shared random stream).

Noise nodes per pairdefault 5

Random nodes drawn as counterexamples for every training pair.

Learning ratedefault —

Starting step size; walks and LINE decay it linearly to almost zero, the graph network uses Adam.

Katz decay (β)default —

How fast longer paths fade in Katz proximity; must be below 1 over the adjacency matrix's largest eigenvalue.

Negative samples (b)default 1

The skip-gram noise count that NetMF's matrix assumes; larger values shrink the matrix before its logarithm.

Optimizerdefault default

How the weights are updated. The method's own choice is the usual one.

  • Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
  • Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
  • AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
  • SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
Learning-rate scheduledefault none

How the learning rate changes over training.

  • Constant(default) — The same learning rate every epoch (the method's default).
  • Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
  • Step — Divides the learning rate by 10 after each third of the epochs.
  • One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
  • Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
Warm-up epochsdefault 0

Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.

Gradient clippingdefault 0

Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.

Weight average (EMA)default 0

Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.

Weight average from epoch (SWA)default 0

Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.

Record every stepdefault off

Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.

Compute profiledefault parity

Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.

  • Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
  • Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
  • Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
Checkpoint every (epochs)default —

Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.

options

Held-out edges for the link checkdefault 0.1

Share of edges hidden while a second copy of the vectors is learned, then scored against as many random non-edges (0 skips the check).

Nodes to look updefault —

Node ids whose most similar nodes to list, separated by commas. Empty lists the five best-connected nodes.

Similar nodes per nodedefault 5

How many most-similar nodes to list for each looked-up node.

Node tabledefault —

Optional table with one row per node: a label colors the map; attributes feed the graph neural network.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Enough network

    Node vectors need many edges per node; with fewer than about three edges per node, similar nodes and link scores are noisy.

  • Coordinates are arbitrary

    Vectors can be rotated or flipped without changing their meaning; compare similarities, not single coordinates.

  • The link check hides edges first

    Held-out edges never reach the vectors that score them, and the spanning forest that keeps the network in one piece is never held out.

What it reports

n_nodes
Nodes are the ids at either end of an edge (plus node-table ids); edges are the distinct pairs after repeats are merged.
n_edges
Nodes are the ids at either end of an edge (plus node-table ids); edges are the distinct pairs after repeats are merged.
dim
A short list of numbers per node, learned from the network, so nodes in similar places get similar vectors.
method
A short list of numbers per node, learned from the network, so nodes in similar places get similar vectors.
final_loss
Average training loss in the final pass (walks, LINE, the graph network); compare runs with the same settings only.
link_auc
Chance that a hidden edge scores above a random non-edge (ties count half); 0.5 is guessing, 1 is perfect.
link_ap
Precision averaged over the recall steps when pairs are ranked by score, hidden edges against as many non-edges.
n_held_out
Hiding a share of edges before learning, keeping a spanning forest so the network stays in one piece, then scoring them later.
n_isolated
A node with no edges: the network says nothing about it, so its vector or prediction comes from its own columns or its start.
katz_beta
Counts the paths between two nodes, each length k down-weighted by βᵏ; β must stay below 1 over the largest eigenvalue.
sv_share
Share of the factorized matrix's squared size that the kept singular values hold (NetMF, HOPE).
edges_per_node
The average number of edges at a node (out-edges on a directed network); below about 3, node vectors are noisy.

Per group, level or term: nearest[<node>], similarity[<node>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses numpy, pandas, torch, codesplash; R uses nanoparquet, torch, codesplashr.

Default traps between the two languages

  • Both engines run the same twins (codesplash.graph.embed / linkpred and codesplash.deep.gnn ↔ codesplashr R/graph_embed.R, R/graph_linkpred.R, R/deep_gnn.R) on the host's canonical node order: the same walks, edge samples, held-out edges and non-edges from the shared Wichmann–Hill stream (identical integers), and Word vectors' skip-gram twin unchanged. Dot products and BLAS products sum in a different order, so trained vectors agree to rounding, not bit for bit.
  • Laplacian eigenmaps, HOPE and NetMF use each engine's LAPACK; columns are signed so their largest entry is positive. A network with tied eigenvalues (a ring, a perfectly symmetric graph) has no unique eigenvectors, and the engines may return different vectors in the tied subspace.
  • The graph neural network trains in double precision on LibTorch builds that can differ by one ulp per kernel (as for every torch learner).
Python

The exact script CodeSplash ran for example “Netmf blocks” · 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],
})
R

The exact script CodeSplash ran for example “Netmf blocks” · 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)
))

Sources

  • Perozzi B, Al-Rfou R, Skiena S (2014). DeepWalk: online learning of social representations. KDD 2014, 701–710.
  • Grover A, Leskovec J (2016). node2vec: scalable feature learning for networks. KDD 2016, 855–864.
  • Tang J, Qu M, Wang M, Zhang M, Yan J, Mei Q (2015). LINE: large-scale information network embedding. WWW 2015, 1067–1077.
  • Belkin M, Niyogi P (2003). Laplacian eigenmaps for dimensionality reduction and data representation. Neural Computation 15:1373–1396.
  • Ou M, Cui P, Pei J, Zhang Z, Zhu W (2016). Asymmetric transitivity preserving graph embedding. KDD 2016, 1105–1114.
  • Qiu J, Dong Y, Ma H, Li J, Wang K, Tang J (2018). Network embedding as matrix factorization: unifying DeepWalk, LINE, PTE, and node2vec. WSDM 2018, 459–467.
  • Kipf TN, Welling M (2016). Variational graph auto-encoders. NeurIPS Workshop on Bayesian Deep Learning.
  • Liben-Nowell D, Kleinberg J (2007). The link-prediction problem for social networks. JASIST 58:1019–1031.

From the CodeSplash method registry · discover.graph_embed v1.0.0.