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

This commit is contained in:
Muneeb Ullah
2026-10-10 06:33:12 -04:00
committed by GitHub
parent ca9563daac
commit ba9d52310a
2 changed files with 43 additions and 3 deletions
+19 -3
View File
@@ -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
+24
View File
@@ -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):
"""