Graphs¶
kenon.graphs.build_semantic_graph(embedder, corpus, similarity_threshold=0.4, k_neighbors=None, stopwords=None)
¶
Build a semantic similarity graph from corpus-internal embeddings.
Nodes are vocabulary tokens. An edge (u, v) exists when the cosine
similarity between u and v exceeds similarity_threshold. Edge weight
is the cosine similarity value.
If k_neighbors is set, a k-NN graph is used to restrict connectivity
before applying the threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
EmbedderProtocol
|
A fitted or unfitted embedder implementing |
required |
corpus
|
list[str]
|
List of document strings. Used both to fit the embedder and to determine the vocabulary. |
required |
similarity_threshold
|
float
|
Minimum cosine similarity for an edge. Must be in [0, 1]. |
0.4
|
k_neighbors
|
int | None
|
If not |
None
|
stopwords
|
frozenset[str] | None
|
Tokens to exclude from the graph nodes. |
None
|
Returns:
| Type | Description |
|---|---|
SemanticGraph
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Contract
- The graph is undirected.
- No self-loops (diagonal excluded).
- All edge weights are in [0, 1].
- Node labels are vocabulary token strings.
Examples:
>>> from kenon.embeddings import TfidfEmbedder
>>> emb = TfidfEmbedder()
>>> corpus = ["cat mat sat", "dog ran fast", "cat ran fast"] * 5
>>> g = build_semantic_graph(emb, corpus, similarity_threshold=0.1)
>>> isinstance(g.number_of_nodes(), int)
True
Source code in kenon/graphs.py
kenon.graphs.cosine_similarity_matrix(embedder, corpus)
¶
Return the full pairwise cosine similarity matrix for the vocabulary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
EmbedderProtocol
|
A fitted or unfitted embedder. Will be fitted on |
required |
corpus
|
list[str]
|
Corpus used to fit the embedder. |
required |
Returns:
| Type | Description |
|---|---|
Matrix
|
A tuple of |
list[Token]
|
|
tuple[Matrix, list[Token]]
|
token |
Contract
- Diagonal values are 1.0 (self-similarity).
- Matrix is symmetric.
- All values are in [-1, 1].
Examples:
>>> from kenon.embeddings import TfidfEmbedder
>>> emb = TfidfEmbedder()
>>> corpus = ["cat mat", "dog ran"] * 3
>>> sim, vocab = cosine_similarity_matrix(emb, corpus)
>>> sim.shape[0] == sim.shape[1] == len(vocab)
True
Source code in kenon/graphs.py
kenon.graphs.save_graph(graph, path, fmt='graphml')
¶
Persist a graph to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
SemanticGraph
|
The graph to save. |
required |
path
|
str | PathLike[str]
|
Destination file path. |
required |
fmt
|
str
|
Format string. Supported: |
'graphml'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Contract
- The file is written atomically (or as atomically as the format allows).
"graphml"and"gml"produce human-readable output.
Examples:
>>> import tempfile, os, networkx as nx
>>> g = nx.Graph(); g.add_edge("a", "b", weight=0.5)
>>> with tempfile.NamedTemporaryFile(suffix=".graphml", delete=False) as f:
... save_graph(g, f.name)
... os.path.exists(f.name)
True
Source code in kenon/graphs.py
kenon.graphs.load_graph(path, fmt='graphml')
¶
Load a graph from disk.
Warning
The "pickle" format executes arbitrary code on load and must
never be used with files from an untrusted source. Prefer
"graphml" or "gml" for any graph you did not write yourself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Source file path. |
required |
fmt
|
str
|
Format string. Must match the format used when saving. |
'graphml'
|
Returns:
| Type | Description |
|---|---|
SemanticGraph
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Contract
- Loaded graph preserves all node and edge attributes from the original.
"pickle"format is not safe for untrusted files.
Examples:
>>> import tempfile, networkx as nx
>>> g = nx.Graph(); g.add_edge("x", "y", weight=0.9)
>>> with tempfile.NamedTemporaryFile(suffix=".graphml", delete=False) as f:
... save_graph(g, f.name)
... g2 = load_graph(f.name)
>>> g2["x"]["y"]["weight"]
0.9