leapgraph 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- leapgraph/__init__.py +76 -0
- leapgraph/cli.py +296 -0
- leapgraph/core/__init__.py +4 -0
- leapgraph/core/cycles.py +57 -0
- leapgraph/core/learning.py +95 -0
- leapgraph/core/propagation.py +362 -0
- leapgraph/core/relevance.py +102 -0
- leapgraph/core/walking.py +106 -0
- leapgraph/io/__init__.py +4 -0
- leapgraph/io/corpus.py +74 -0
- leapgraph/io/ingest.py +324 -0
- leapgraph/io/serialize.py +97 -0
- leapgraph/model.py +267 -0
- leapgraph/py.typed +0 -0
- leapgraph/service.py +119 -0
- leapgraph-0.6.0.dist-info/METADATA +587 -0
- leapgraph-0.6.0.dist-info/RECORD +21 -0
- leapgraph-0.6.0.dist-info/WHEEL +5 -0
- leapgraph-0.6.0.dist-info/entry_points.txt +2 -0
- leapgraph-0.6.0.dist-info/licenses/LICENSE +93 -0
- leapgraph-0.6.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""个性化 PageRank 扩散:一次算出全图相关度排序。
|
|
2
|
+
|
|
3
|
+
为什么需要它(v0.4 变更):
|
|
4
|
+
带温度的随机游走只产出"一条路径",路径长度有限、会在局部打转,
|
|
5
|
+
且温度参数对结果的影响不稳定。要回答"跟 X 最相关的是什么",
|
|
6
|
+
系统必须给出全图排序,而不是一次采样的脚印。
|
|
7
|
+
|
|
8
|
+
算法:
|
|
9
|
+
设 s 为种子分布(单种子时 s(seed)=1,其余 0),P 为按列归一化的转移矩阵,
|
|
10
|
+
d 为阻尼系数,则稳态分数满足
|
|
11
|
+
π = (1 - d) · s + d · P π
|
|
12
|
+
用幂迭代求解,直至相邻两轮的一范数差小于 tol。
|
|
13
|
+
悬挂节点(无出边)的质量按 s 重新分配,保证分数总和恒为 1。
|
|
14
|
+
|
|
15
|
+
双后端(v0.5.0):
|
|
16
|
+
安装 `leapgraph[fast]` 且环境可导入 numpy/scipy 时,走 CSR 稀疏矩阵迭代;
|
|
17
|
+
否则退回纯 Python 字典实现。两条路径给出相同排序(归一化后分数差 < 1e-6),
|
|
18
|
+
只是速度差约两个数量级(5,346 节点、7.9 万边的实测:1.5 s → 7.7 ms)。
|
|
19
|
+
|
|
20
|
+
scipy 采用惰性导入:`import leapgraph` 不会因此变慢,只有真正调用
|
|
21
|
+
diffuse() 且未指定纯 Python 后端时才会尝试加载。可用环境变量
|
|
22
|
+
LEAPGRAPH_PPR_BACKEND=python|scipy|auto 强制选择(默认 auto)。
|
|
23
|
+
|
|
24
|
+
设计要点:
|
|
25
|
+
- 纯 Python 路径每轮遍历一次边表,复杂度 O(E),不构造稠密矩阵。
|
|
26
|
+
- 结果按 (分数降序, 名称升序) 排序,同分也稳定,保证可复现。
|
|
27
|
+
- 不依赖随机数,同一输入永远同一输出;与 walking 的采样语义区分开。
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import os
|
|
33
|
+
import threading
|
|
34
|
+
from collections.abc import Iterable
|
|
35
|
+
from functools import lru_cache
|
|
36
|
+
from typing import Any
|
|
37
|
+
from weakref import WeakKeyDictionary
|
|
38
|
+
|
|
39
|
+
from leapgraph.model import (
|
|
40
|
+
DiffusionParams,
|
|
41
|
+
DiffusionResult,
|
|
42
|
+
Graph,
|
|
43
|
+
LeapGraphError,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
BACKEND_ENV = "LEAPGRAPH_PPR_BACKEND"
|
|
47
|
+
|
|
48
|
+
# 稀疏矩阵缓存:键是图对象,值附带构建时的 Graph.version。
|
|
49
|
+
# 用弱引用字典,图被回收时条目自动消失,不会持有内存。
|
|
50
|
+
# 图结构一变(add_edge 递增 version),缓存立即失效并重建。
|
|
51
|
+
_CACHE_LOCK = threading.Lock()
|
|
52
|
+
_MATRIX_CACHE: "WeakKeyDictionary[Graph, tuple[Any, ...]]" = WeakKeyDictionary()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class DiffusionParameterError(ValueError, LeapGraphError):
|
|
56
|
+
"""阻尼系数、种子或迭代参数非法。"""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@lru_cache(maxsize=1)
|
|
60
|
+
def _load_scipy() -> tuple[Any, Any] | None:
|
|
61
|
+
"""惰性导入 numpy 与 scipy.sparse;任一缺失时返回 None。
|
|
62
|
+
|
|
63
|
+
结果被缓存:首次探测后不再重复尝试导入。若运行期间才安装依赖,
|
|
64
|
+
需要重启进程或调用 ``reset_backend_cache()``。
|
|
65
|
+
"""
|
|
66
|
+
try:
|
|
67
|
+
import numpy
|
|
68
|
+
import scipy.sparse
|
|
69
|
+
except ImportError:
|
|
70
|
+
return None
|
|
71
|
+
return numpy, scipy.sparse
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def reset_backend_cache() -> None:
|
|
75
|
+
"""清空后端探测缓存,供测试或运行期动态安装依赖后重新探测。"""
|
|
76
|
+
_load_scipy.cache_clear()
|
|
77
|
+
with _CACHE_LOCK:
|
|
78
|
+
_MATRIX_CACHE.clear()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def resolve_backend(choice: str | None = None) -> str:
|
|
82
|
+
"""决定本次计算使用哪个后端。
|
|
83
|
+
|
|
84
|
+
参数:
|
|
85
|
+
choice: 显式指定 "python" / "scipy" / "auto";None 时读环境变量,
|
|
86
|
+
再缺省为 "auto"。
|
|
87
|
+
|
|
88
|
+
返回:
|
|
89
|
+
"python" 或 "scipy"。
|
|
90
|
+
|
|
91
|
+
异常:
|
|
92
|
+
DiffusionParameterError: 显式要求 scipy 但环境中不可用,或取值非法。
|
|
93
|
+
"""
|
|
94
|
+
if choice is None:
|
|
95
|
+
choice = os.environ.get(BACKEND_ENV, "auto")
|
|
96
|
+
choice = choice.strip().lower()
|
|
97
|
+
if choice not in ("auto", "python", "scipy"):
|
|
98
|
+
raise DiffusionParameterError(
|
|
99
|
+
f"{BACKEND_ENV} 只能取 auto、python 或 scipy,收到: {choice!r}"
|
|
100
|
+
)
|
|
101
|
+
if choice == "python":
|
|
102
|
+
return "python"
|
|
103
|
+
modules = _load_scipy()
|
|
104
|
+
if choice == "scipy":
|
|
105
|
+
if modules is None:
|
|
106
|
+
raise DiffusionParameterError(
|
|
107
|
+
"已指定 scipy 后端,但无法导入 numpy/scipy;"
|
|
108
|
+
"请执行 pip install 'leapgraph[fast]'"
|
|
109
|
+
)
|
|
110
|
+
return "scipy"
|
|
111
|
+
return "scipy" if modules is not None else "python"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _build_seed_distribution(
|
|
115
|
+
graph: Graph, seeds: Iterable[str]
|
|
116
|
+
) -> dict[str, float]:
|
|
117
|
+
"""把种子列表转成归一化的种子分布,并校验其存在性。"""
|
|
118
|
+
unique: list[str] = []
|
|
119
|
+
seen: set[str] = set()
|
|
120
|
+
for node in seeds:
|
|
121
|
+
if node not in seen:
|
|
122
|
+
seen.add(node)
|
|
123
|
+
unique.append(node)
|
|
124
|
+
if not unique:
|
|
125
|
+
raise DiffusionParameterError("seeds 不能为空")
|
|
126
|
+
missing = [n for n in unique if not graph.has_node(n)]
|
|
127
|
+
if missing:
|
|
128
|
+
available = "、".join(sorted(graph.nodes)[:10]) or "(空)"
|
|
129
|
+
raise DiffusionParameterError(
|
|
130
|
+
f"种子不在图中: {'、'.join(missing)};可用节点示例: {available}"
|
|
131
|
+
)
|
|
132
|
+
share = 1.0 / len(unique)
|
|
133
|
+
return {node: share for node in unique}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _transition(graph: Graph) -> dict[str, dict[str, float]]:
|
|
137
|
+
"""按行归一化邻接权重,得到转移概率表;零权重邻居被剔除。"""
|
|
138
|
+
transition: dict[str, dict[str, float]] = {}
|
|
139
|
+
for node in graph.nodes:
|
|
140
|
+
neighbors = graph.neighbors(node)
|
|
141
|
+
total = sum(w for w in neighbors.values() if w > 0.0)
|
|
142
|
+
if total <= 0.0:
|
|
143
|
+
continue
|
|
144
|
+
transition[node] = {
|
|
145
|
+
nbr: w / total for nbr, w in neighbors.items() if w > 0.0
|
|
146
|
+
}
|
|
147
|
+
return transition
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _iterate_python(
|
|
151
|
+
graph: Graph,
|
|
152
|
+
seed_dist: dict[str, float],
|
|
153
|
+
params: DiffusionParams,
|
|
154
|
+
nodes: list[str],
|
|
155
|
+
) -> tuple[dict[str, float], int, bool]:
|
|
156
|
+
"""纯 Python 字典实现:零依赖路径,任何环境都能跑。"""
|
|
157
|
+
transition = _transition(graph)
|
|
158
|
+
pi: dict[str, float] = {node: seed_dist.get(node, 0.0) for node in nodes}
|
|
159
|
+
restart = 1.0 - params.damping
|
|
160
|
+
iterations = 0
|
|
161
|
+
converged = False
|
|
162
|
+
|
|
163
|
+
for _ in range(params.max_iter):
|
|
164
|
+
iterations += 1
|
|
165
|
+
new_pi = {node: restart * seed_dist.get(node, 0.0) for node in nodes}
|
|
166
|
+
dangling_mass = 0.0
|
|
167
|
+
|
|
168
|
+
for node, mass in pi.items():
|
|
169
|
+
if mass <= 0.0:
|
|
170
|
+
continue
|
|
171
|
+
row = transition.get(node)
|
|
172
|
+
if not row:
|
|
173
|
+
dangling_mass += mass
|
|
174
|
+
continue
|
|
175
|
+
spread = params.damping * mass
|
|
176
|
+
for nbr, prob in row.items():
|
|
177
|
+
new_pi[nbr] += spread * prob
|
|
178
|
+
|
|
179
|
+
# 悬挂质量按种子分布回流,维持总质量为 1
|
|
180
|
+
if dangling_mass > 0.0:
|
|
181
|
+
back = params.damping * dangling_mass
|
|
182
|
+
for node, share in seed_dist.items():
|
|
183
|
+
new_pi[node] += back * share
|
|
184
|
+
|
|
185
|
+
delta = sum(abs(new_pi[n] - pi[n]) for n in nodes)
|
|
186
|
+
pi = new_pi
|
|
187
|
+
if delta < params.tol:
|
|
188
|
+
converged = True
|
|
189
|
+
break
|
|
190
|
+
|
|
191
|
+
return pi, iterations, converged
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _sparse_payload(
|
|
195
|
+
graph: Graph, modules: tuple[Any, Any]
|
|
196
|
+
) -> tuple[tuple[str, ...], dict[str, int], Any, Any, bool]:
|
|
197
|
+
"""构建(或复用)列随机转移矩阵,按图版本号做失效判断。
|
|
198
|
+
|
|
199
|
+
矩阵构建占单次查询的大头:5,346 节点的图重建一次约 70 ms,而迭代本身
|
|
200
|
+
只要 8 ms。建图完成后结构不再变化,因此按 ``Graph.version`` 缓存命中后
|
|
201
|
+
可省掉这部分开销,把单次查询从 ~85 ms 降到 ~8 ms。
|
|
202
|
+
"""
|
|
203
|
+
numpy, sparse = modules
|
|
204
|
+
with _CACHE_LOCK:
|
|
205
|
+
cached = _MATRIX_CACHE.get(graph)
|
|
206
|
+
if cached is not None and cached[0] == graph.version:
|
|
207
|
+
return cached[1:]
|
|
208
|
+
|
|
209
|
+
nodes = tuple(sorted(graph.nodes))
|
|
210
|
+
index = {node: position for position, node in enumerate(nodes)}
|
|
211
|
+
size = len(nodes)
|
|
212
|
+
|
|
213
|
+
rows: list[int] = []
|
|
214
|
+
cols: list[int] = []
|
|
215
|
+
data: list[float] = []
|
|
216
|
+
dangling: list[int] = []
|
|
217
|
+
|
|
218
|
+
# 直接读内部邻接表(只读),避免为每个节点复制一次字典
|
|
219
|
+
for node in nodes:
|
|
220
|
+
column = index[node]
|
|
221
|
+
neighbors = graph.adjacency.get(node, {})
|
|
222
|
+
total = 0.0
|
|
223
|
+
for weight in neighbors.values():
|
|
224
|
+
if weight > 0.0:
|
|
225
|
+
total += weight
|
|
226
|
+
if total <= 0.0:
|
|
227
|
+
dangling.append(column)
|
|
228
|
+
continue
|
|
229
|
+
for neighbor, weight in neighbors.items():
|
|
230
|
+
if weight > 0.0:
|
|
231
|
+
rows.append(index[neighbor])
|
|
232
|
+
cols.append(column)
|
|
233
|
+
data.append(weight / total)
|
|
234
|
+
|
|
235
|
+
shape = (size, size)
|
|
236
|
+
if data:
|
|
237
|
+
transition = sparse.csr_matrix(
|
|
238
|
+
(data, (rows, cols)), shape=shape, dtype=numpy.float64
|
|
239
|
+
)
|
|
240
|
+
else:
|
|
241
|
+
transition = sparse.csr_matrix(shape, dtype=numpy.float64)
|
|
242
|
+
|
|
243
|
+
dangling_mask = numpy.zeros(size, dtype=bool)
|
|
244
|
+
for position in dangling:
|
|
245
|
+
dangling_mask[position] = True
|
|
246
|
+
|
|
247
|
+
payload = (nodes, index, transition, dangling_mask, bool(dangling))
|
|
248
|
+
with _CACHE_LOCK:
|
|
249
|
+
_MATRIX_CACHE[graph] = (graph.version, *payload)
|
|
250
|
+
return payload
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _iterate_sparse(
|
|
254
|
+
graph: Graph,
|
|
255
|
+
seed_dist: dict[str, float],
|
|
256
|
+
params: DiffusionParams,
|
|
257
|
+
nodes: list[str],
|
|
258
|
+
modules: tuple[Any, Any],
|
|
259
|
+
) -> tuple[dict[str, float], int, bool]:
|
|
260
|
+
"""scipy 稀疏矩阵实现:与纯 Python 路径数学等价,靠 BLAS 加速。"""
|
|
261
|
+
numpy, _sparse = modules
|
|
262
|
+
cached_nodes, index, transition, dangling_mask, has_dangling = _sparse_payload(
|
|
263
|
+
graph, modules
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
size = len(cached_nodes)
|
|
267
|
+
seed_vector = numpy.zeros(size, dtype=numpy.float64)
|
|
268
|
+
for node, share in seed_dist.items():
|
|
269
|
+
seed_vector[index[node]] = share
|
|
270
|
+
|
|
271
|
+
pi = seed_vector.copy()
|
|
272
|
+
restart = 1.0 - params.damping
|
|
273
|
+
iterations = 0
|
|
274
|
+
converged = False
|
|
275
|
+
|
|
276
|
+
for _ in range(params.max_iter):
|
|
277
|
+
iterations += 1
|
|
278
|
+
new_pi = restart * seed_vector + params.damping * (transition @ pi)
|
|
279
|
+
if has_dangling:
|
|
280
|
+
mass = float(pi[dangling_mask].sum())
|
|
281
|
+
if mass > 0.0:
|
|
282
|
+
new_pi = new_pi + params.damping * mass * seed_vector
|
|
283
|
+
delta = float(numpy.abs(new_pi - pi).sum())
|
|
284
|
+
pi = new_pi
|
|
285
|
+
if delta < params.tol:
|
|
286
|
+
converged = True
|
|
287
|
+
break
|
|
288
|
+
|
|
289
|
+
scores = {node: float(pi[index[node]]) for node in cached_nodes}
|
|
290
|
+
return scores, iterations, converged
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def diffuse(
|
|
294
|
+
graph: Graph,
|
|
295
|
+
seeds: str | Iterable[str],
|
|
296
|
+
params: DiffusionParams | None = None,
|
|
297
|
+
backend: str | None = None,
|
|
298
|
+
) -> DiffusionResult:
|
|
299
|
+
"""从种子节点出发做个性化 PageRank,返回全图相关度排序。
|
|
300
|
+
|
|
301
|
+
参数:
|
|
302
|
+
graph: 无向带权图。
|
|
303
|
+
seeds: 单个种子节点名,或种子节点名序列。
|
|
304
|
+
params: 扩散参数(阻尼、收敛阈值、最大轮数)。
|
|
305
|
+
backend: 计算后端,"python" / "scipy" / "auto";None 时读环境变量
|
|
306
|
+
LEAPGRAPH_PPR_BACKEND,再缺省为自动选择(v0.5.0 新增)。
|
|
307
|
+
|
|
308
|
+
返回:
|
|
309
|
+
DiffusionResult: 分数、排序、迭代轮数、是否收敛与实际后端。
|
|
310
|
+
|
|
311
|
+
异常:
|
|
312
|
+
DiffusionParameterError: seeds 为空、种子不在图中、参数越界,
|
|
313
|
+
或显式要求 scipy 但环境不可用。
|
|
314
|
+
|
|
315
|
+
说明:
|
|
316
|
+
悬空概率质量(无出边节点的分数)按种子分布回流,而非均匀回流全图,
|
|
317
|
+
这使"孤岛节点"不会稀释种子附近的关联强度。两个后端遵循同一规则,
|
|
318
|
+
归一化后分数差小于 1e-6,排序一致;仅迭代轮数可能相差一轮。
|
|
319
|
+
"""
|
|
320
|
+
if params is None:
|
|
321
|
+
params = DiffusionParams()
|
|
322
|
+
if not 0.0 < params.damping < 1.0:
|
|
323
|
+
raise DiffusionParameterError("damping 必须在 (0, 1) 开区间内")
|
|
324
|
+
if params.max_iter < 1:
|
|
325
|
+
raise DiffusionParameterError("max_iter 必须为正整数")
|
|
326
|
+
if params.tol <= 0.0:
|
|
327
|
+
raise DiffusionParameterError("tol 必须为正数")
|
|
328
|
+
|
|
329
|
+
if isinstance(seeds, str):
|
|
330
|
+
seed_names = [seeds]
|
|
331
|
+
else:
|
|
332
|
+
seed_names = list(seeds)
|
|
333
|
+
|
|
334
|
+
seed_dist = _build_seed_distribution(graph, seed_names)
|
|
335
|
+
nodes = sorted(graph.nodes)
|
|
336
|
+
chosen = resolve_backend(backend)
|
|
337
|
+
|
|
338
|
+
if chosen == "scipy":
|
|
339
|
+
modules = _load_scipy()
|
|
340
|
+
assert modules is not None # resolve_backend 已保证
|
|
341
|
+
pi, iterations, converged = _iterate_sparse(
|
|
342
|
+
graph, seed_dist, params, nodes, modules
|
|
343
|
+
)
|
|
344
|
+
else:
|
|
345
|
+
pi, iterations, converged = _iterate_python(
|
|
346
|
+
graph, seed_dist, params, nodes
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
# 数值误差下总质量可能偏离 1,做一次归一化后再排序
|
|
350
|
+
total = sum(pi.values())
|
|
351
|
+
if total > 0.0:
|
|
352
|
+
pi = {node: value / total for node, value in pi.items()}
|
|
353
|
+
|
|
354
|
+
ranking = tuple(sorted(pi, key=lambda n: (-pi[n], n)))
|
|
355
|
+
return DiffusionResult(
|
|
356
|
+
seeds=tuple(seed_names),
|
|
357
|
+
scores=pi,
|
|
358
|
+
ranking=ranking,
|
|
359
|
+
iterations=iterations,
|
|
360
|
+
converged=converged,
|
|
361
|
+
backend=chosen,
|
|
362
|
+
)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""相关概念查询:按种子度数在「一阶排序」和「扩散补全」之间路由。
|
|
2
|
+
|
|
3
|
+
为什么需要它(v0.4.1 变更):
|
|
4
|
+
v0.4.0 提供了 diffuse(),但离线评测发现它不是万能的。在干净语料上,
|
|
5
|
+
一阶邻居的 NPMI 排序 P@10=0.190,PPR 只有 0.170;而在度数 ≤3 的孤立
|
|
6
|
+
种子上,一阶只能拿到 0.033,PPR 除以度数平方根后能到 0.167。
|
|
7
|
+
|
|
8
|
+
差别的原因是:图干净时,一阶邻居本身就是最相关的答案,把影响力扩散到
|
|
9
|
+
全图只会让「人」「大」「见」这类高连接度词占满前排;而种子孤立时只有
|
|
10
|
+
一两个邻居,一阶排序等于没有排序,必须靠多跳补全。
|
|
11
|
+
|
|
12
|
+
所以对外只暴露一个 related(),由种子度数自动决定策略:
|
|
13
|
+
度 ≥ degree_threshold → 一阶 NPMI 排序
|
|
14
|
+
度 < degree_threshold → PPR 扩散,分数除以 度数^hub_penalty
|
|
15
|
+
|
|
16
|
+
实测整体 P@10 从 0.190 提到 0.230,MRR 从 0.574 提到 0.677。
|
|
17
|
+
|
|
18
|
+
设计要点:
|
|
19
|
+
* 两种策略都只读图,不修改任何状态;
|
|
20
|
+
* 排序键统一为 (分数降序, 名称升序),同分也稳定,保证可复现;
|
|
21
|
+
* 一阶策略只返回邻居,扩散策略返回全图——这一点在 method 字段中显式标出,
|
|
22
|
+
调用方不必猜。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from leapgraph.core.propagation import diffuse
|
|
28
|
+
from leapgraph.model import (
|
|
29
|
+
DiffusionParams,
|
|
30
|
+
Graph,
|
|
31
|
+
LeapGraphError,
|
|
32
|
+
RelatedParams,
|
|
33
|
+
RelatedResult,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class RelatedParameterError(ValueError, LeapGraphError):
|
|
38
|
+
"""种子不在图内,或路由参数取值非法。"""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def related_nodes(
|
|
42
|
+
graph: Graph,
|
|
43
|
+
seed: str,
|
|
44
|
+
params: RelatedParams | None = None,
|
|
45
|
+
backend: str | None = None,
|
|
46
|
+
) -> RelatedResult:
|
|
47
|
+
"""查询与种子最相关的概念。
|
|
48
|
+
|
|
49
|
+
参数:
|
|
50
|
+
graph: 已学习好的图。
|
|
51
|
+
seed: 种子节点,须存在于图中。
|
|
52
|
+
params: 路由参数,缺省使用默认值。
|
|
53
|
+
backend: 扩散分支使用的计算后端,"python" / "scipy" / "auto";
|
|
54
|
+
None 时按环境变量与可用依赖自动选择(v0.5.0 新增)。
|
|
55
|
+
|
|
56
|
+
返回:
|
|
57
|
+
RelatedResult: 含策略名、种子度数、分数与排序。
|
|
58
|
+
|
|
59
|
+
异常:
|
|
60
|
+
RelatedParameterError: 种子不在图中,或阈值、阻尼、惩罚系数越界。
|
|
61
|
+
"""
|
|
62
|
+
params = params or RelatedParams()
|
|
63
|
+
|
|
64
|
+
if params.degree_threshold < 0:
|
|
65
|
+
raise RelatedParameterError("degree_threshold 不能为负")
|
|
66
|
+
if params.hub_penalty < 0:
|
|
67
|
+
raise RelatedParameterError("hub_penalty 不能为负")
|
|
68
|
+
if not 0.0 < params.damping < 1.0:
|
|
69
|
+
raise RelatedParameterError("damping 须在 (0, 1) 内")
|
|
70
|
+
if not graph.has_node(seed):
|
|
71
|
+
raise RelatedParameterError(f"种子 {seed!r} 不在图中")
|
|
72
|
+
|
|
73
|
+
degree = len(graph.neighbors(seed))
|
|
74
|
+
|
|
75
|
+
if degree >= params.degree_threshold:
|
|
76
|
+
scores = dict(graph.neighbors(seed))
|
|
77
|
+
ranking = tuple(sorted(scores, key=lambda n: (-scores[n], n)))
|
|
78
|
+
return RelatedResult(
|
|
79
|
+
seed=seed,
|
|
80
|
+
method="neighbors",
|
|
81
|
+
seed_degree=degree,
|
|
82
|
+
scores=scores,
|
|
83
|
+
ranking=ranking,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
result = diffuse(
|
|
87
|
+
graph, seed, DiffusionParams(damping=params.damping), backend=backend
|
|
88
|
+
)
|
|
89
|
+
scores = {}
|
|
90
|
+
for node, score in result.scores.items():
|
|
91
|
+
if node == seed:
|
|
92
|
+
continue
|
|
93
|
+
node_degree = len(graph.neighbors(node)) or 1
|
|
94
|
+
scores[node] = score / (node_degree ** params.hub_penalty)
|
|
95
|
+
ranking = tuple(sorted(scores, key=lambda n: (-scores[n], n)))
|
|
96
|
+
return RelatedResult(
|
|
97
|
+
seed=seed,
|
|
98
|
+
method="diffusion",
|
|
99
|
+
seed_degree=degree,
|
|
100
|
+
scores=scores,
|
|
101
|
+
ranking=ranking,
|
|
102
|
+
)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""带温度的邻居采样与随机游走。
|
|
2
|
+
|
|
3
|
+
采样公式(架构文档 4.3 节):
|
|
4
|
+
P(v|u) = exp(w_uv / T) / Σ_{k∈N(u)} exp(w_uk / T)
|
|
5
|
+
T → 0 趋于确定(走向最高权重邻居),T → ∞ 趋于均匀(随机跳跃)。
|
|
6
|
+
|
|
7
|
+
实现要点:
|
|
8
|
+
- 用减去最大权重的方式做数值稳定化,防止 exp 溢出。
|
|
9
|
+
- 随机源 rng 由外部注入,固定种子时输出可复现。
|
|
10
|
+
- 每一步记录候选概率与实际选择,支撑可解释输出。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
import random
|
|
17
|
+
|
|
18
|
+
from leapgraph.model import Graph, LeapGraphError, WalkParams, WalkResult, WalkStep
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class InvalidParameterError(ValueError, LeapGraphError):
|
|
22
|
+
"""温度或步数等参数非法。"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _softmax_probabilities(
|
|
26
|
+
neighbors: dict[str, float],
|
|
27
|
+
temperature: float,
|
|
28
|
+
) -> dict[str, float]:
|
|
29
|
+
"""按温度把邻居权重转成采样概率,内部做数值稳定化。"""
|
|
30
|
+
max_w = max(neighbors.values())
|
|
31
|
+
scores = {node: math.exp((w - max_w) / temperature) for node, w in neighbors.items()}
|
|
32
|
+
total = sum(scores.values())
|
|
33
|
+
return {node: score / total for node, score in scores.items()}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def sample_next(
|
|
37
|
+
graph: Graph,
|
|
38
|
+
node: str,
|
|
39
|
+
temperature: float,
|
|
40
|
+
rng: random.Random,
|
|
41
|
+
) -> str | None:
|
|
42
|
+
"""按温度从节点的邻居中采出一个;无邻居时返回 None。
|
|
43
|
+
|
|
44
|
+
参数:
|
|
45
|
+
graph: 无向带权图。
|
|
46
|
+
node: 当前节点。
|
|
47
|
+
temperature: 正的温度值。
|
|
48
|
+
rng: 外部注入的随机源。
|
|
49
|
+
|
|
50
|
+
异常:
|
|
51
|
+
InvalidParameterError: temperature <= 0。
|
|
52
|
+
"""
|
|
53
|
+
if temperature <= 0:
|
|
54
|
+
raise InvalidParameterError("temperature 必须为正数")
|
|
55
|
+
|
|
56
|
+
neighbors = graph.neighbors(node)
|
|
57
|
+
if not neighbors:
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
probs = _softmax_probabilities(neighbors, temperature)
|
|
61
|
+
nodes = list(probs)
|
|
62
|
+
weights = [probs[n] for n in nodes]
|
|
63
|
+
return rng.choices(nodes, weights=weights, k=1)[0]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def random_walk(
|
|
67
|
+
graph: Graph,
|
|
68
|
+
start: str,
|
|
69
|
+
params: WalkParams,
|
|
70
|
+
) -> WalkResult:
|
|
71
|
+
"""从起点出发执行带温度的随机游走,返回可解释结果。
|
|
72
|
+
|
|
73
|
+
参数:
|
|
74
|
+
graph: 无向带权图。
|
|
75
|
+
start: 起点,必须存在于图中。
|
|
76
|
+
params: 游走参数(温度、步数、种子)。
|
|
77
|
+
|
|
78
|
+
异常:
|
|
79
|
+
InvalidParameterError: 温度 <= 0 或步数不是正整数。
|
|
80
|
+
KeyError: 起点不在图中。
|
|
81
|
+
"""
|
|
82
|
+
if params.temperature <= 0:
|
|
83
|
+
raise InvalidParameterError("temperature 必须为正数")
|
|
84
|
+
if params.steps < 1:
|
|
85
|
+
raise InvalidParameterError("steps 必须为正整数")
|
|
86
|
+
if not graph.has_node(start):
|
|
87
|
+
raise KeyError(f"起点 {start!r} 不在图中")
|
|
88
|
+
|
|
89
|
+
rng = random.Random(params.seed)
|
|
90
|
+
path = [start]
|
|
91
|
+
steps: list[WalkStep] = []
|
|
92
|
+
current = start
|
|
93
|
+
|
|
94
|
+
for _ in range(params.steps):
|
|
95
|
+
neighbors = graph.neighbors(current)
|
|
96
|
+
if not neighbors:
|
|
97
|
+
break
|
|
98
|
+
probs = _softmax_probabilities(neighbors, params.temperature)
|
|
99
|
+
nodes = list(probs)
|
|
100
|
+
weights = [probs[n] for n in nodes]
|
|
101
|
+
chosen = rng.choices(nodes, weights=weights, k=1)[0]
|
|
102
|
+
steps.append(WalkStep(source=current, candidates=probs, chosen=chosen))
|
|
103
|
+
path.append(chosen)
|
|
104
|
+
current = chosen
|
|
105
|
+
|
|
106
|
+
return WalkResult(start=start, path=tuple(path), steps=tuple(steps))
|
leapgraph/io/__init__.py
ADDED
leapgraph/io/corpus.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""经验数据加载与清洗。
|
|
2
|
+
|
|
3
|
+
数据格式为 JSON,顶层含 episodes 字段,每个片段是概念标签列表。
|
|
4
|
+
清洗规则(PRD FR-01):标签去首尾空白、空标签丢弃、空片段丢弃、
|
|
5
|
+
重复片段保留(重复代表更高频次)。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from leapgraph.model import LeapGraphError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CorpusError(LeapGraphError):
|
|
17
|
+
"""经验数据格式、字段或读取错误。"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def load_episodes(path: str | Path) -> list[list[str]]:
|
|
21
|
+
"""加载并清洗经验数据。
|
|
22
|
+
|
|
23
|
+
参数:
|
|
24
|
+
path: JSON 文件路径。
|
|
25
|
+
|
|
26
|
+
返回:
|
|
27
|
+
list[list[str]]: 清洗后的片段列表,保留片段顺序与重复。
|
|
28
|
+
|
|
29
|
+
异常:
|
|
30
|
+
CorpusError: 文件不存在、JSON 语法错误、缺少 episodes 字段、
|
|
31
|
+
episodes 不是列表、或片段内元素不是字符串。
|
|
32
|
+
"""
|
|
33
|
+
p = Path(path)
|
|
34
|
+
if not p.exists():
|
|
35
|
+
raise CorpusError(f"文件不存在: {p}")
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
raw = p.read_text(encoding="utf-8")
|
|
39
|
+
except OSError as exc:
|
|
40
|
+
raise CorpusError(f"读取文件失败: {p} — {exc}") from exc
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
data = json.loads(raw)
|
|
44
|
+
except json.JSONDecodeError as exc:
|
|
45
|
+
raise CorpusError(
|
|
46
|
+
f"JSON 语法错误: {p} 第 {exc.lineno} 行第 {exc.colno} 列"
|
|
47
|
+
) from exc
|
|
48
|
+
|
|
49
|
+
if not isinstance(data, dict):
|
|
50
|
+
raise CorpusError(f"顶层必须是对象: {p}")
|
|
51
|
+
|
|
52
|
+
if "episodes" not in data:
|
|
53
|
+
raise CorpusError(f"缺少必需字段 'episodes': {p}")
|
|
54
|
+
|
|
55
|
+
episodes = data["episodes"]
|
|
56
|
+
if not isinstance(episodes, list):
|
|
57
|
+
raise CorpusError(f"'episodes' 必须是数组: {p}")
|
|
58
|
+
|
|
59
|
+
cleaned: list[list[str]] = []
|
|
60
|
+
for idx, episode in enumerate(episodes):
|
|
61
|
+
if not isinstance(episode, list):
|
|
62
|
+
raise CorpusError(f"第 {idx} 个片段必须是数组: {p}")
|
|
63
|
+
labels: list[str] = []
|
|
64
|
+
for label in episode:
|
|
65
|
+
if not isinstance(label, str):
|
|
66
|
+
raise CorpusError(f"第 {idx} 个片段含非字符串标签: {p}")
|
|
67
|
+
stripped = label.strip()
|
|
68
|
+
if stripped:
|
|
69
|
+
labels.append(stripped)
|
|
70
|
+
# 空片段丢弃,非空片段保留(含重复片段)
|
|
71
|
+
if labels:
|
|
72
|
+
cleaned.append(labels)
|
|
73
|
+
|
|
74
|
+
return cleaned
|