1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
| import networkx as nx
class SemanticMemory:
def __init__(self):
self.concept_graph = nx.DiGraph()
self.concept_embeddings = {}
self.relation_types = [
"is_a", "part_of", "has_property",
"causes", "prevents", "related_to"
]
def add_concept(self, concept: str, properties: Dict = None):
"""添加概念节点"""
if concept not in self.concept_graph:
self.concept_graph.add_node(
concept,
properties=properties or {},
activation=0.0,
last_activated=None
)
# 生成概念嵌入
self.concept_embeddings[concept] = self._embed_concept(concept)
def add_relation(self, concept1: str, relation: str, concept2: str,
strength: float = 1.0):
"""添加概念关系"""
self.add_concept(concept1)
self.add_concept(concept2)
self.concept_graph.add_edge(
concept1, concept2,
relation=relation,
strength=strength,
created_at=time.time()
)
def activate_concept(self, concept: str, activation: float = 1.0):
"""激活概念(扩散激活)"""
if concept not in self.concept_graph:
return
# 设置初始激活
self.concept_graph.nodes[concept]["activation"] = activation
self.concept_graph.nodes[concept]["last_activated"] = time.time()
# 扩散激活
self._spread_activation(concept, activation, decay=0.5, depth=3)
def _spread_activation(self, source: str, activation: float,
decay: float, depth: int):
"""扩散激活算法"""
if depth <= 0 or activation < 0.1:
return
# 激活相邻节点
for neighbor in self.concept_graph.neighbors(source):
edge_data = self.concept_graph[source][neighbor]
spread_activation = activation * edge_data["strength"] * decay
current_activation = self.concept_graph.nodes[neighbor].get("activation", 0)
new_activation = current_activation + spread_activation
self.concept_graph.nodes[neighbor]["activation"] = min(1.0, new_activation)
# 递归扩散
self._spread_activation(neighbor, spread_activation, decay, depth - 1)
def query_concepts(self, query: str, k: int = 5) -> List[str]:
"""查询相关概念"""
# 激活查询相关概念
query_concepts = self._extract_concepts_from_text(query)
for concept in query_concepts:
self.activate_concept(concept)
# 获取激活度最高的概念
activated_concepts = [
(node, data["activation"])
for node, data in self.concept_graph.nodes(data=True)
if data["activation"] > 0
]
activated_concepts.sort(key=lambda x: x[1], reverse=True)
return [concept for concept, _ in activated_concepts[:k]]
|