Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Fix infertopics ignoring topiced neighbors when untopiced ones outnumber them (#1373)

Muneeb Ullahba9d52310a1e
diff --git a/src/python/txtai/graph/base.py b/src/python/txtai/graph/base.py
index c6f63494..a25f0645 100644
--- a/src/python/txtai/graph/base.py
+++ b/src/python/txtai/graph/base.py
@@ -760,7 +760,7 @@ class Graph:
ids = ids.keys() if ids else None
# Infer topic
- topic = Counter(self.attribute(x, "topic") for x in ids).most_common(1)[0][0] if ids else None
+ topic = self.commonattribute(ids, "topic")
if topic:
# Add id to topic list and set topic attribute
self.topics[topic].append(node)
@@ -770,5 +770,21 @@ class Graph:
self.addattribute(node, "topicrank", len(self.topics[topic]) - 1)
# Infer category
- category = Counter(self.attribute(x, "category") for x in ids).most_common(1)[0][0]
- self.addattribute(node, "category", category)
+ category = self.commonattribute([x for x in ids if self.attribute(x, "topic") == topic], "category")
+ if category:
+ self.addattribute(node, "category", category)
+
+ def commonattribute(self, ids, attribute):
+ """
+ Gets the most common non-empty attribute value across a list of nodes.
+
+ Args:
+ ids: list of node ids
+ attribute: attribute name
+
+ Returns:
+ most common value or None if no node has the attribute
+ """
+
+ values = Counter(value for value in (self.attribute(x, attribute) for x in ids or []) if value is not None)
+ return values.most_common(1)[0][0] if values else None
diff --git a/test/python/testgraph.py b/test/python/testgraph.py
index aebae332..afacfe74 100644
--- a/test/python/testgraph.py
+++ b/test/python/testgraph.py
@@ -320,6 +320,30 @@ class TestGraph(unittest.TestCase):
self.assertEqual(len(graph.topics), 6)
self.assertEqual(len(graph.categories), 6)
+ def testInferTopics(self):
+ """
+ Test inferring topics when most neighbors have no topic
+ """
+
+ graph = GraphFactory.create({"backend": "networkx"})
+ graph.initialize()
+ graph.topics = {"t": [0]}
+
+ graph.addnode(0, topic="t", topicrank=0, category="c")
+ for x in range(1, 4):
+ graph.addnode(x, updated=True)
+ graph.addnode(4, updated=True)
+
+ for x, y in [(1, 2), (2, 3), (1, 3), (1, 0)]:
+ graph.addedge(x, y)
+
+ graph.infertopics()
+
+ self.assertEqual([graph.attribute(x, "topic") for x in range(4)], ["t"] * 4)
+ self.assertEqual(graph.topics["t"], [0, 1, 2, 3])
+ self.assertEqual(graph.attribute(1, "category"), "c")
+ self.assertIsNone(graph.attribute(4, "topic"))
+
@patch.dict(os.environ, {"ALLOW_PICKLE": "True"})
def testLegacy(self):
"""