> ## Documentation Index
> Fetch the complete documentation index at: https://khaos-ml.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Graph

> Networks: fraud rings, link recommendations, similar nodes.

## Find fraud rings in transactions

**Problem:** spot groups of accounts that move money among themselves. **Uses:**
Khaos and networkx.

```python theme={null}
import khaos
import networkx as nx

g = nx.DiGraph()
for src, dst, amount in transactions:
    g.add_edge(src, dst, amount=amount)

result = khaos.load("graph_fraud_rings")(g)
for ring, score in sorted(zip(result.rings, result.scores), key=lambda p: -p[1]):
    flow = sum(d["amount"] for _, _, d in g.subgraph(ring).edges(data=True))
    print(ring, round(score, 2), f"${flow:,.0f} circulating")
# [4, 17, 52, 88] 0.94 $182,400 circulating
# [9, 31, 76] 0.81 $47,900 circulating
```

## Recommend links

**Problem:** suggest likely missing connections in a citation or social graph.
**Uses:** Khaos and networkx.

```python theme={null}
import khaos
import networkx as nx

g = nx.read_edgelist("citations.edgelist", nodetype=int)
links = khaos.load("graph_link_prediction")(g)

new = [(u, v, p) for u, v, p in links.edges if not g.has_edge(u, v)]
for u, v, p in sorted(new, key=lambda e: -e[2])[:3]:
    print(f"{u} -> {v}  p={p:.2f}")
# 3 -> 41  p=0.97
# 12 -> 8  p=0.93
# 5 -> 60  p=0.88
```

## Search for similar nodes

**Problem:** find the accounts that look most like a known bad actor. **Uses:** Khaos
and scikit-learn.

```python theme={null}
import khaos
from sklearn.neighbors import NearestNeighbors

emb = khaos.load("graph_node_embedding")(graph).vector     # (num_nodes, dim)

nn = NearestNeighbors(n_neighbors=6, metric="cosine").fit(emb)
_, idx = nn.kneighbors(emb[known_bad_node][None])
print(idx[0][1:])
# [211 874 40 502 17]
```

## Compare communities

**Problem:** measure how similar two neighborhoods are. **Uses:** Khaos alone.

```python theme={null}
embed = khaos.load("graph_subgraph_embedding")
a = embed(community_a).vector
b = embed(community_b).vector
print(round(float(a @ b / ((a @ a) ** 0.5 * (b @ b) ** 0.5)), 3))
# 0.874
```

## Inputs and outputs for each model

These are real outputs of the v1 models, run through their exported ONNX files on held-out examples. The shapes listed are the exact ONNX inputs and outputs; `batch` and other named sizes are dynamic.

### `graph_node_embedding`

A subgraph in (node features and a dense adjacency matrix), one 128-dimensional embedding per node out.

**Model inputs:** `x float32 [nodes, 64]; adj float32 [nodes, nodes]`\
**Model outputs:** `embeddings float32 [nodes, 128]`

**Input**

```python theme={null}
x.shape = (64, 64)   # wikipedia_crocodile subgraph: nodes x 64 features
adj.shape = (64, 64)   # edges: 163
```

**Output**

```json theme={null}
{
  "embeddings_shape": [
    64,
    128
  ],
  "node_0_embedding": [
    -0.386,
    -0.024,
    -0.701,
    0.14,
    1.06,
    -0.787,
    "..."
  ]
}
```

### `graph_subgraph_embedding`

A subgraph in, one 128-dimensional vector for the whole subgraph out (plus the per-node embeddings).

**Model inputs:** `x float32 [nodes, 64]; adj float32 [nodes, nodes]`\
**Model outputs:** `vector float32 [128]; embeddings float32 [nodes, 128]`

**Input**

```python theme={null}
x.shape = (64, 64)   # wikipedia_crocodile subgraph: nodes x 64 features
adj.shape = (64, 64)   # edges: 145
```

**Output**

```json theme={null}
{
  "vector": [
    -0.348,
    0.219,
    -1.083,
    -0.585,
    0.514,
    -0.779,
    "..."
  ],
  "vector_shape": [
    128
  ],
  "node_embeddings_shape": [
    64,
    128
  ],
  "source_domain": "page_links"
}
```

### `graph_fraud_rings`

A subgraph in, a suspicion score between 0 and 1 for every node out. Nodes with high scores that are connected to each other are candidate fraud rings. `injected_anomaly` is the dataset's label.

**Model inputs:** `x float32 [nodes, 64]; adj float32 [nodes, nodes]`\
**Model outputs:** `scores float32 [nodes]`

**Input**

```python theme={null}
x.shape = (64, 64)   # cora_injected subgraph: nodes x 64 features
adj.shape = (64, 64)   # edges: 90
```

**Output**

```json theme={null}
{
  "top_5_nodes": [
    {
      "node": 36,
      "score": 0.973,
      "injected_anomaly": 1,
      "ring_id": 0
    },
    {
      "node": 58,
      "score": 0.959,
      "injected_anomaly": 1,
      "ring_id": 0
    },
    {
      "node": 27,
      "score": 0.017,
      "injected_anomaly": 0,
      "ring_id": -1
    },
    {
      "node": 61,
      "score": 0.01,
      "injected_anomaly": 0,
      "ring_id": -1
    },
    {
      "node": 37,
      "score": 0.009,
      "injected_anomaly": 0,
      "ring_id": -1
    }
  ]
}
```

### `graph_link_prediction`

A subgraph and a list of candidate node pairs in, the probability that each pair is an edge out. The first three pairs are real edges hidden from the input graph, the next three are non-edges.

**Model inputs:** `x float32 [nodes, 64]; adj float32 [nodes, nodes]; pairs int64 [pairs, 2]`\
**Model outputs:** `probs float32 [pairs]`

**Input**

```python theme={null}
x.shape = (64, 64)   # wikipedia_crocodile subgraph: nodes x 64 features
adj.shape = (64, 64)   # edges: 110
pairs.shape = (38, 2)
```

**Output**

```json theme={null}
{
  "hidden_real_edges": [
    {
      "pair": [
        0,
        3
      ],
      "probability": 0.875
    },
    {
      "pair": [
        0,
        8
      ],
      "probability": 0.912
    },
    {
      "pair": [
        2,
        56
      ],
      "probability": 0.919
    }
  ],
  "non_edges": [
    {
      "pair": [
        0,
        42
      ],
      "probability": 0.05
    },
    {
      "pair": [
        21,
        50
      ],
      "probability": 0.016
    },
    {
      "pair": [
        20,
        46
      ],
      "probability": 0.319
    }
  ]
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.