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
leapgraph/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""LeapGraph:从经验数据学习概念关联的零依赖算法库。
|
|
2
|
+
|
|
3
|
+
顶层导出核心类与函数,使用者可通过 import leapgraph 访问全部公共能力。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from leapgraph.model import (
|
|
7
|
+
DiffusionParams,
|
|
8
|
+
DiffusionResult,
|
|
9
|
+
Edge,
|
|
10
|
+
Graph,
|
|
11
|
+
LeapGraphError,
|
|
12
|
+
LearningParams,
|
|
13
|
+
RelatedParams,
|
|
14
|
+
RelatedResult,
|
|
15
|
+
WalkParams,
|
|
16
|
+
WalkResult,
|
|
17
|
+
WalkStep,
|
|
18
|
+
)
|
|
19
|
+
from leapgraph.core.cycles import find_cycles
|
|
20
|
+
from leapgraph.core.learning import learn_weights
|
|
21
|
+
from leapgraph.core.propagation import (
|
|
22
|
+
BACKEND_ENV,
|
|
23
|
+
DiffusionParameterError,
|
|
24
|
+
diffuse,
|
|
25
|
+
reset_backend_cache,
|
|
26
|
+
resolve_backend,
|
|
27
|
+
)
|
|
28
|
+
from leapgraph.core.relevance import RelatedParameterError, related_nodes
|
|
29
|
+
from leapgraph.core.walking import random_walk
|
|
30
|
+
from leapgraph.service import LeapGraph, UnknownNodeError
|
|
31
|
+
from leapgraph.io.corpus import CorpusError
|
|
32
|
+
from leapgraph.io.ingest import (
|
|
33
|
+
IngestError,
|
|
34
|
+
IngestParams,
|
|
35
|
+
build_episodes,
|
|
36
|
+
ingest_file,
|
|
37
|
+
normalize_fullwidth,
|
|
38
|
+
strip_appendix,
|
|
39
|
+
)
|
|
40
|
+
from leapgraph.io.serialize import VersionMismatchError
|
|
41
|
+
|
|
42
|
+
__version__ = "0.6.0"
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"DiffusionParams",
|
|
46
|
+
"DiffusionResult",
|
|
47
|
+
"DiffusionParameterError",
|
|
48
|
+
"Edge",
|
|
49
|
+
"Graph",
|
|
50
|
+
"LeapGraphError",
|
|
51
|
+
"LearningParams",
|
|
52
|
+
"RelatedParams",
|
|
53
|
+
"RelatedResult",
|
|
54
|
+
"RelatedParameterError",
|
|
55
|
+
"WalkParams",
|
|
56
|
+
"WalkResult",
|
|
57
|
+
"WalkStep",
|
|
58
|
+
"LeapGraph",
|
|
59
|
+
"UnknownNodeError",
|
|
60
|
+
"CorpusError",
|
|
61
|
+
"VersionMismatchError",
|
|
62
|
+
"IngestError",
|
|
63
|
+
"IngestParams",
|
|
64
|
+
"learn_weights",
|
|
65
|
+
"random_walk",
|
|
66
|
+
"diffuse",
|
|
67
|
+
"resolve_backend",
|
|
68
|
+
"reset_backend_cache",
|
|
69
|
+
"BACKEND_ENV",
|
|
70
|
+
"related_nodes",
|
|
71
|
+
"find_cycles",
|
|
72
|
+
"build_episodes",
|
|
73
|
+
"ingest_file",
|
|
74
|
+
"normalize_fullwidth",
|
|
75
|
+
"strip_appendix",
|
|
76
|
+
]
|
leapgraph/cli.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"""命令行适配层:解析参数、调用 LeapGraph、格式化输出、映射退出码。
|
|
2
|
+
|
|
3
|
+
本层是唯一把异常转成用户可读信息并设置退出码的地方,库使用者直接面向异常编程。
|
|
4
|
+
|
|
5
|
+
退出码约定:
|
|
6
|
+
0 成功;1 未预期错误;2 输入数据/参数错误;3 版本不兼容;4 起点不存在。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from leapgraph import (
|
|
17
|
+
CorpusError,
|
|
18
|
+
DiffusionParameterError,
|
|
19
|
+
DiffusionParams,
|
|
20
|
+
IngestError,
|
|
21
|
+
IngestParams,
|
|
22
|
+
LearningParams,
|
|
23
|
+
LeapGraph,
|
|
24
|
+
RelatedParameterError,
|
|
25
|
+
RelatedParams,
|
|
26
|
+
UnknownNodeError,
|
|
27
|
+
VersionMismatchError,
|
|
28
|
+
WalkParams,
|
|
29
|
+
__version__,
|
|
30
|
+
)
|
|
31
|
+
from leapgraph.core.walking import InvalidParameterError
|
|
32
|
+
from leapgraph.io.ingest import ingest_file, load_stopwords
|
|
33
|
+
|
|
34
|
+
# 内置演示数据(demo 子命令使用,不依赖外部文件)
|
|
35
|
+
DEMO_EPISODES = [
|
|
36
|
+
["月色", "思念", "中秋", "烧烤"],
|
|
37
|
+
["月色", "思念", "中秋"],
|
|
38
|
+
["月色", "思念", "中秋"],
|
|
39
|
+
["大树", "木材", "房屋", "家"],
|
|
40
|
+
["大树", "木材", "房屋", "家"],
|
|
41
|
+
["海洋", "绵羊", "岛屿"],
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
46
|
+
parser = argparse.ArgumentParser(
|
|
47
|
+
prog="leapgraph",
|
|
48
|
+
description="从经验数据学习概念关联、执行概率跳跃与闭环检测",
|
|
49
|
+
)
|
|
50
|
+
parser.add_argument("--version", action="version", version=f"leapgraph {__version__}")
|
|
51
|
+
sub = parser.add_subparsers(dest="command")
|
|
52
|
+
|
|
53
|
+
p_learn = sub.add_parser("learn", help="从经验数据学习并保存图")
|
|
54
|
+
p_learn.add_argument("-i", "--input", required=True, help="经验数据 JSON 文件")
|
|
55
|
+
p_learn.add_argument("-o", "--output", required=True, help="输出图 JSON 文件")
|
|
56
|
+
p_learn.add_argument("--no-smoothing", action="store_true", help="关闭加一平滑")
|
|
57
|
+
p_learn.add_argument(
|
|
58
|
+
"--min-cooccurrence", type=int, default=2,
|
|
59
|
+
help="共现次数下限,低于此值的概念对不建边,默认 2",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
p_ingest = sub.add_parser("ingest", help="从纯文本提取概念片段")
|
|
63
|
+
p_ingest.add_argument("-i", "--input", required=True, help="输入文本文件(UTF-8)")
|
|
64
|
+
p_ingest.add_argument("-o", "--output", required=True, help="输出经验数据 JSON")
|
|
65
|
+
p_ingest.add_argument(
|
|
66
|
+
"--unit", choices=["sentence", "paragraph"], default="sentence",
|
|
67
|
+
help="片段切分单位,默认按句子",
|
|
68
|
+
)
|
|
69
|
+
p_ingest.add_argument("--no-pos", action="store_true", help="不按词性过滤,只靠停用词")
|
|
70
|
+
p_ingest.add_argument("--min-length", type=int, default=1, help="词长下限,默认 1")
|
|
71
|
+
p_ingest.add_argument(
|
|
72
|
+
"--max-terms", type=int, default=0,
|
|
73
|
+
help="单片段最大词数,0 不限;长文建议 20",
|
|
74
|
+
)
|
|
75
|
+
p_ingest.add_argument(
|
|
76
|
+
"--keep-appendix", action="store_true",
|
|
77
|
+
help="不剥离文末注释区;默认会剥离(注疏本、校注本建议保持默认)",
|
|
78
|
+
)
|
|
79
|
+
p_ingest.add_argument("--stopwords", help="自定义停用词文件,每行一个,追加到内置表")
|
|
80
|
+
p_ingest.add_argument("--userdict", help="jieba 自定义词典,按行填写领域术语")
|
|
81
|
+
|
|
82
|
+
p_walk = sub.add_parser("walk", help="从起点执行带温度的跳跃")
|
|
83
|
+
p_walk.add_argument("-g", "--graph", required=True, help="图 JSON 文件")
|
|
84
|
+
p_walk.add_argument("-s", "--start", required=True, help="起点概念")
|
|
85
|
+
p_walk.add_argument("-n", "--steps", type=int, default=5, help="步数,默认 5")
|
|
86
|
+
p_walk.add_argument("-t", "--temperature", type=float, default=1.0, help="温度,默认 1.0")
|
|
87
|
+
p_walk.add_argument("--seed", type=int, default=None, help="随机种子")
|
|
88
|
+
|
|
89
|
+
p_cycles = sub.add_parser("cycles", help="枚举图中的闭环")
|
|
90
|
+
p_cycles.add_argument("-g", "--graph", required=True, help="图 JSON 文件")
|
|
91
|
+
p_cycles.add_argument("--max-length", type=int, default=6, help="最大环长度,默认 6")
|
|
92
|
+
|
|
93
|
+
p_diffuse = sub.add_parser("diffuse", help="从种子扩散,输出全图相关度排序")
|
|
94
|
+
p_diffuse.add_argument("-g", "--graph", required=True, help="图 JSON 文件")
|
|
95
|
+
p_diffuse.add_argument(
|
|
96
|
+
"-s", "--seed", required=True, action="append",
|
|
97
|
+
help="种子概念,可重复指定多个",
|
|
98
|
+
)
|
|
99
|
+
p_diffuse.add_argument("-k", "--top", type=int, default=10, help="输出前 k 名,默认 10")
|
|
100
|
+
p_diffuse.add_argument(
|
|
101
|
+
"--damping", type=float, default=0.85,
|
|
102
|
+
help="阻尼系数,取值 (0,1),越大扩散越远,默认 0.85",
|
|
103
|
+
)
|
|
104
|
+
p_diffuse.add_argument(
|
|
105
|
+
"--include-seeds", action="store_true", help="结果中包含种子本身(默认剔除)"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
p_related = sub.add_parser("related", help="查询与某概念最相关的概念(自动选策略)")
|
|
109
|
+
p_related.add_argument("-g", "--graph", required=True, help="图 JSON 文件")
|
|
110
|
+
p_related.add_argument("-s", "--seed", required=True, help="种子概念")
|
|
111
|
+
p_related.add_argument("-k", "--top", type=int, default=10, help="输出前 k 名,默认 10")
|
|
112
|
+
p_related.add_argument(
|
|
113
|
+
"--degree-threshold", type=int, default=4,
|
|
114
|
+
help="度数达到该值时用一阶排序,低于则用扩散补全,默认 4",
|
|
115
|
+
)
|
|
116
|
+
p_related.add_argument(
|
|
117
|
+
"--hub-penalty", type=float, default=0.5,
|
|
118
|
+
help="扩散时按度数惩罚枢纽词,越大惩罚越强,默认 0.5",
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
sub.add_parser("demo", help="用内置数据跑通全流程")
|
|
122
|
+
|
|
123
|
+
return parser
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def cmd_learn(args: argparse.Namespace) -> int:
|
|
127
|
+
lg = LeapGraph.from_file(args.input, LearningParams(
|
|
128
|
+
smoothing=not args.no_smoothing,
|
|
129
|
+
min_cooccurrence=args.min_cooccurrence,
|
|
130
|
+
))
|
|
131
|
+
lg.save(args.output)
|
|
132
|
+
print(f"学习完成:{len(lg.graph.nodes)} 个节点,{len(lg.graph.edges)} 条边 → {args.output}")
|
|
133
|
+
return 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def cmd_ingest(args: argparse.Namespace) -> int:
|
|
137
|
+
stopwords = IngestParams().stopwords
|
|
138
|
+
if args.stopwords:
|
|
139
|
+
stopwords = stopwords | load_stopwords(args.stopwords)
|
|
140
|
+
|
|
141
|
+
params = IngestParams(
|
|
142
|
+
unit=args.unit,
|
|
143
|
+
min_length=args.min_length,
|
|
144
|
+
use_pos=not args.no_pos,
|
|
145
|
+
max_terms=args.max_terms,
|
|
146
|
+
stopwords=stopwords,
|
|
147
|
+
userdict=args.userdict,
|
|
148
|
+
strip_appendix=not args.keep_appendix,
|
|
149
|
+
)
|
|
150
|
+
episodes = ingest_file(args.input, params)
|
|
151
|
+
if not episodes:
|
|
152
|
+
print(
|
|
153
|
+
"未提取到任何片段:文本可能全是停用词,或每个单元的概念不足两个",
|
|
154
|
+
file=sys.stderr,
|
|
155
|
+
)
|
|
156
|
+
return 2
|
|
157
|
+
|
|
158
|
+
concepts = {word for episode in episodes for word in episode}
|
|
159
|
+
payload = {
|
|
160
|
+
"episodes": episodes,
|
|
161
|
+
"meta": {
|
|
162
|
+
"source": str(args.input),
|
|
163
|
+
"unit": args.unit,
|
|
164
|
+
"use_pos": not args.no_pos,
|
|
165
|
+
"episode_count": len(episodes),
|
|
166
|
+
"concept_count": len(concepts),
|
|
167
|
+
},
|
|
168
|
+
}
|
|
169
|
+
Path(args.output).write_text(
|
|
170
|
+
json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
|
171
|
+
)
|
|
172
|
+
print(f"提取完成:{len(episodes)} 个片段,{len(concepts)} 个概念 → {args.output}")
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def cmd_walk(args: argparse.Namespace) -> int:
|
|
177
|
+
lg = LeapGraph.load(args.graph)
|
|
178
|
+
result = lg.walk(args.start, WalkParams(
|
|
179
|
+
temperature=args.temperature, steps=args.steps, seed=args.seed
|
|
180
|
+
))
|
|
181
|
+
print(" → ".join(result.path))
|
|
182
|
+
for i, step in enumerate(result.steps, 1):
|
|
183
|
+
probs = ", ".join(f"{n}={p:.3f}" for n, p in step.candidates.items())
|
|
184
|
+
print(f" 第{i}步 {step.source}: [{probs}] → 选 {step.chosen}")
|
|
185
|
+
return 0
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def cmd_cycles(args: argparse.Namespace) -> int:
|
|
189
|
+
lg = LeapGraph.load(args.graph)
|
|
190
|
+
cycles = lg.cycles(args.max_length)
|
|
191
|
+
if not cycles:
|
|
192
|
+
print("未发现闭环")
|
|
193
|
+
else:
|
|
194
|
+
print(f"发现 {len(cycles)} 个闭环:")
|
|
195
|
+
for c in cycles:
|
|
196
|
+
print(" " + " → ".join(c) + " → " + c[0])
|
|
197
|
+
return 0
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def cmd_diffuse(args: argparse.Namespace) -> int:
|
|
201
|
+
lg = LeapGraph.load(args.graph)
|
|
202
|
+
result = lg.diffuse(args.seed, DiffusionParams(damping=args.damping))
|
|
203
|
+
seeds = "、".join(args.seed)
|
|
204
|
+
rank = 1
|
|
205
|
+
for node, score in result.top(args.top, exclude_seeds=not args.include_seeds):
|
|
206
|
+
print(f"{rank:>3}. {node:<12} {score:.6f}")
|
|
207
|
+
rank += 1
|
|
208
|
+
print(
|
|
209
|
+
f"\n种子:{seeds};节点 {len(result.scores)} 个;"
|
|
210
|
+
f"迭代 {result.iterations} 轮,{'已收敛' if result.converged else '未收敛'}",
|
|
211
|
+
file=sys.stderr,
|
|
212
|
+
)
|
|
213
|
+
return 0
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def cmd_demo(args: argparse.Namespace) -> int:
|
|
217
|
+
print("LeapGraph 演示(内置数据)\n")
|
|
218
|
+
lg = LeapGraph.from_episodes(DEMO_EPISODES)
|
|
219
|
+
print(f"学习结果:{len(lg.graph.nodes)} 个节点,{len(lg.graph.edges)} 条边")
|
|
220
|
+
print("\n月色的邻居:")
|
|
221
|
+
for node, w in sorted(lg.graph.neighbors("月色").items(), key=lambda x: -x[1]):
|
|
222
|
+
print(f" {node}: {w:.3f}")
|
|
223
|
+
print("\n从月色跳跃 5 步(种子 42):")
|
|
224
|
+
print(" " + " → ".join(lg.walk("月色", WalkParams(steps=5, seed=42)).path))
|
|
225
|
+
cycles = lg.cycles()
|
|
226
|
+
print(f"\n闭环:{len(cycles)} 个")
|
|
227
|
+
for c in cycles[:5]:
|
|
228
|
+
print(" " + " → ".join(c) + " → " + c[0])
|
|
229
|
+
return 0
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def cmd_related(args: argparse.Namespace) -> int:
|
|
233
|
+
lg = LeapGraph.load(args.graph)
|
|
234
|
+
result = lg.related(args.seed, RelatedParams(
|
|
235
|
+
degree_threshold=args.degree_threshold,
|
|
236
|
+
hub_penalty=args.hub_penalty,
|
|
237
|
+
))
|
|
238
|
+
for rank, (node, score) in enumerate(result.top(args.top), 1):
|
|
239
|
+
print(f"{rank:>3}. {node:<12} {score:.6f}")
|
|
240
|
+
strategy = "一阶邻居" if result.method == "neighbors" else "扩散补全"
|
|
241
|
+
print(
|
|
242
|
+
f"\n种子:{result.seed};度数 {result.seed_degree},走{strategy};"
|
|
243
|
+
f"候选 {len(result.ranking)} 个",
|
|
244
|
+
file=sys.stderr,
|
|
245
|
+
)
|
|
246
|
+
return 0
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
HANDLERS = {
|
|
250
|
+
"learn": cmd_learn,
|
|
251
|
+
"walk": cmd_walk,
|
|
252
|
+
"cycles": cmd_cycles,
|
|
253
|
+
"diffuse": cmd_diffuse,
|
|
254
|
+
"related": cmd_related,
|
|
255
|
+
"demo": cmd_demo,
|
|
256
|
+
"ingest": cmd_ingest,
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def main(argv: list[str] | None = None) -> int:
|
|
261
|
+
parser = build_parser()
|
|
262
|
+
args = parser.parse_args(argv)
|
|
263
|
+
if args.command is None:
|
|
264
|
+
parser.print_help()
|
|
265
|
+
return 0
|
|
266
|
+
|
|
267
|
+
try:
|
|
268
|
+
return HANDLERS[args.command](args)
|
|
269
|
+
except CorpusError as exc:
|
|
270
|
+
print(f"数据错误:{exc}", file=sys.stderr)
|
|
271
|
+
return 2
|
|
272
|
+
except IngestError as exc:
|
|
273
|
+
print(f"文本错误:{exc}", file=sys.stderr)
|
|
274
|
+
return 2
|
|
275
|
+
except VersionMismatchError as exc:
|
|
276
|
+
print(f"版本错误:{exc}", file=sys.stderr)
|
|
277
|
+
return 3
|
|
278
|
+
except UnknownNodeError as exc:
|
|
279
|
+
print(f"起点错误:{exc}", file=sys.stderr)
|
|
280
|
+
return 4
|
|
281
|
+
except DiffusionParameterError as exc:
|
|
282
|
+
print(f"扩散参数错误:{exc}", file=sys.stderr)
|
|
283
|
+
return 4
|
|
284
|
+
except RelatedParameterError as exc:
|
|
285
|
+
print(f"相关度参数错误:{exc}", file=sys.stderr)
|
|
286
|
+
return 4
|
|
287
|
+
except InvalidParameterError as exc:
|
|
288
|
+
print(f"参数错误:{exc}", file=sys.stderr)
|
|
289
|
+
return 2
|
|
290
|
+
except (OSError, ValueError, KeyError) as exc:
|
|
291
|
+
print(f"错误:{exc}", file=sys.stderr)
|
|
292
|
+
return 2
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
if __name__ == "__main__":
|
|
296
|
+
sys.exit(main())
|
leapgraph/core/cycles.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""简单环枚举与规范化去重。
|
|
2
|
+
|
|
3
|
+
算法依据架构文档 4.4 节:
|
|
4
|
+
1. 对每个节点作起点做 DFS,路径记录已访问节点。
|
|
5
|
+
2. 只允许回到起点且路径长度 >= 3 时记录为环(排除 A-B-A 来回走)。
|
|
6
|
+
3. 规范化:环按字典序旋转到最小表示,并与反向环比较取较小者作为唯一键。
|
|
7
|
+
4. 集合去重后按长度、字典序排序返回。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from leapgraph.model import Graph
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _canonical_cycle(cycle: tuple[str, ...]) -> tuple[str, ...]:
|
|
16
|
+
"""把环规范化:所有旋转中取字典序最小者,再与反向比较取较小者。"""
|
|
17
|
+
n = len(cycle)
|
|
18
|
+
rotations = [cycle[i:] + cycle[:i] for i in range(n)]
|
|
19
|
+
forward = min(rotations)
|
|
20
|
+
reversed_cycle = tuple(reversed(cycle))
|
|
21
|
+
reverse_rotations = [reversed_cycle[i:] + reversed_cycle[:i] for i in range(n)]
|
|
22
|
+
backward = min(reverse_rotations)
|
|
23
|
+
return forward if forward <= backward else backward
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def find_cycles(
|
|
27
|
+
graph: Graph,
|
|
28
|
+
max_length: int = 6,
|
|
29
|
+
) -> list[tuple[str, ...]]:
|
|
30
|
+
"""枚举图中长度不超过 max_length 的简单环,去重后排序返回。
|
|
31
|
+
|
|
32
|
+
参数:
|
|
33
|
+
graph: 无向带权图。
|
|
34
|
+
max_length: 环的最大节点数,默认 6。小于 3 时无环可返回。
|
|
35
|
+
|
|
36
|
+
返回:
|
|
37
|
+
list[tuple[str, ...]]: 每个环为节点序列(不含重复的收尾起点),
|
|
38
|
+
按 (长度, 字典序) 排序。
|
|
39
|
+
"""
|
|
40
|
+
if max_length < 3:
|
|
41
|
+
return []
|
|
42
|
+
|
|
43
|
+
found: set[tuple[str, ...]] = set()
|
|
44
|
+
|
|
45
|
+
def dfs(start: str, current: str, visited: tuple[str, ...]) -> None:
|
|
46
|
+
for nxt in sorted(graph.neighbors(current)):
|
|
47
|
+
if nxt == start:
|
|
48
|
+
# 长度至少 3 才算环,排除 A-B-A
|
|
49
|
+
if len(visited) >= 3:
|
|
50
|
+
found.add(_canonical_cycle(visited))
|
|
51
|
+
elif nxt not in visited and len(visited) < max_length:
|
|
52
|
+
dfs(start, nxt, visited + (nxt,))
|
|
53
|
+
|
|
54
|
+
for node in sorted(graph.nodes):
|
|
55
|
+
dfs(node, node, (node,))
|
|
56
|
+
|
|
57
|
+
return sorted(found, key=lambda c: (len(c), c))
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""关联权重学习:从经验片段统计共现,计算 NPMI 权重生成无向图。
|
|
2
|
+
|
|
3
|
+
本模块只依赖数据层 model.py,不接触文件与命令行。权重完全由输入数据决定,
|
|
4
|
+
代码中不含任何写死的"某概念与某概念相关"规则。
|
|
5
|
+
|
|
6
|
+
算法依据:
|
|
7
|
+
设 N 为经验片段数,cnt(a) 为含 a 的片段数,cooc(a,b) 为 a、b 同框的片段数。
|
|
8
|
+
P(a) = (cnt(a) + s) / (N + s)
|
|
9
|
+
P(a,b) = (cooc(a,b) + s) / (N + s)
|
|
10
|
+
PMI(a,b) = log( P(a,b) / (P(a) * P(b)) )
|
|
11
|
+
NPMI(a,b) = PMI(a,b) / ( -log P(a,b) )
|
|
12
|
+
NPMI 把权重压到 [-1, 1],负值截断为 0;cooc 低于 min_cooccurrence 的概念对不建边。
|
|
13
|
+
|
|
14
|
+
v0.2 变更(修复 PPMI 稀有词虚高缺陷):
|
|
15
|
+
- v0.1 用 PPMI 且边缘概率按标签总数归一、联合概率按片段数归一,
|
|
16
|
+
两个概率空间不一致,导致只同框一次的冷门对反而权重最高。
|
|
17
|
+
- v0.2 改用 NPMI,边缘与联合概率统一按片段数归一,并加共现次数下限,
|
|
18
|
+
使权重与共现强度正相关。经真实诗词数据验证(见 07-真实数据验证报告)。
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import math
|
|
24
|
+
from collections import Counter
|
|
25
|
+
|
|
26
|
+
from leapgraph.model import Graph, LearningParams
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def learn_weights(
|
|
30
|
+
episodes: list[list[str]],
|
|
31
|
+
params: LearningParams,
|
|
32
|
+
) -> Graph:
|
|
33
|
+
"""从经验片段学习概念间的关联权重,返回无向带权图。
|
|
34
|
+
|
|
35
|
+
参数:
|
|
36
|
+
episodes: 经验片段列表,每个片段是概念标签列表。
|
|
37
|
+
params: 学习参数(平滑、权重下限、共现次数下限)。
|
|
38
|
+
|
|
39
|
+
返回:
|
|
40
|
+
Graph: 每条边带权重与共现次数;无共现或共现不足的概念对不产生边。
|
|
41
|
+
|
|
42
|
+
说明:
|
|
43
|
+
min_cooccurrence 在统计阶段生效:同框次数低于该值的概念对直接跳过,
|
|
44
|
+
不参与后续计算。加一平滑作用于概率估计,避免零概率。
|
|
45
|
+
NPMI 归一化分母为 -log P(a,b);当 P(a,b)=1 该值趋零,退化为使用 PMI。
|
|
46
|
+
"""
|
|
47
|
+
# 步骤 1-2:统计边缘计数与共现计数
|
|
48
|
+
concept_count: Counter[str] = Counter()
|
|
49
|
+
cooc_count: Counter[tuple[str, str]] = Counter()
|
|
50
|
+
n_episodes = 0
|
|
51
|
+
|
|
52
|
+
for episode in episodes:
|
|
53
|
+
# 同一片段内去重,避免重复标签夸大共现
|
|
54
|
+
labels = list(dict.fromkeys(episode))
|
|
55
|
+
if not labels:
|
|
56
|
+
continue
|
|
57
|
+
n_episodes += 1
|
|
58
|
+
concept_count.update(labels)
|
|
59
|
+
# 无序对,按字典序规范化
|
|
60
|
+
for i in range(len(labels)):
|
|
61
|
+
for j in range(i + 1, len(labels)):
|
|
62
|
+
a, b = labels[i], labels[j]
|
|
63
|
+
if a > b:
|
|
64
|
+
a, b = b, a
|
|
65
|
+
cooc_count[(a, b)] += 1
|
|
66
|
+
|
|
67
|
+
graph = Graph()
|
|
68
|
+
if n_episodes == 0:
|
|
69
|
+
return graph
|
|
70
|
+
|
|
71
|
+
smooth = 1.0 if params.smoothing else 0.0
|
|
72
|
+
denom = n_episodes + smooth
|
|
73
|
+
|
|
74
|
+
# 边缘概率:按片段数归一(与联合概率同一空间)
|
|
75
|
+
p_a = {c: (cnt + smooth) / denom for c, cnt in concept_count.items()}
|
|
76
|
+
|
|
77
|
+
for (a, b), cooc in cooc_count.items():
|
|
78
|
+
if cooc < params.min_cooccurrence:
|
|
79
|
+
continue
|
|
80
|
+
p_ab = (cooc + smooth) / denom
|
|
81
|
+
joint = p_a[a] * p_a[b]
|
|
82
|
+
if joint <= 0:
|
|
83
|
+
continue
|
|
84
|
+
pmi = math.log(p_ab / joint)
|
|
85
|
+
neg_log = -math.log(p_ab)
|
|
86
|
+
# P(a,b)=1 表示两概念在所有片段中完全绑定(此时 p_a=p_b=1,PMI=0),
|
|
87
|
+
# 是最强关联:NPMI 分母趋零,直接给上界 1.0,而非误判为 0 丢弃。
|
|
88
|
+
weight = 1.0 if neg_log <= 1e-12 else max(0.0, pmi / neg_log)
|
|
89
|
+
# 浮点误差可能使 NPMI 略超 1(如 1.0000000000000009),clamp 到理论值域
|
|
90
|
+
weight = min(1.0, weight)
|
|
91
|
+
if not math.isfinite(weight) or weight <= params.min_weight:
|
|
92
|
+
continue
|
|
93
|
+
graph.add_edge(a, b, weight, cooc)
|
|
94
|
+
|
|
95
|
+
return graph
|