Hierarchical Topic Modeling
You might expect some topics in your corpus to belong to a hierarchy of topics. Some models in Turftopic allow you to investigate hierarchical relations and build a taxonomy of topics in a corpus.
Models in Turftopic that can model hierarchical relations will have a hierarchy
property, that you can manipulate and print/visualize:
from turftopic import ClusteringTopicModel
model = ClusteringTopicModel(n_reduce_to=10).fit(corpus)
# We cut at level 3 for plotting, since the hierarchy is very deep
model.hierarchy.cut(3).plot_tree()
Drag and click to zoom, hover to see word importance
1. Divisive/Top-down Hierarchical Modeling
In divisive modeling, you start from larger structures, higher up in the hierarchy, and divide topics into smaller sub-topics on-demand. This is how hierarchical modeling works in KeyNMF, which, by default does not discover a topic hierarchy, but you can divide topics to as many subtopics as you see fit.
As a demonstration, let's load a corpus, that we know to have hierarchical themes.
from sklearn.datasets import fetch_20newsgroups
corpus = fetch_20newsgroups(
subset="all",
remove=("headers", "footers", "quotes"),
categories=[
"comp.os.ms-windows.misc",
"comp.sys.ibm.pc.hardware",
"talk.religion.misc",
"alt.atheism",
],
).data
In this case, we have two base themes, which are computers, and religion. Let us fit a KeyNMF model with two topics to see if the model finds these.
from turftopic import KeyNMF
model = KeyNMF(2, top_n=15, random_state=42).fit(corpus)
model.print_topics()
Topic ID | Highest Ranking |
---|---|
0 | windows, dos, os, disk, card, drivers, file, pc, files, microsoft |
1 | atheism, atheist, atheists, religion, christians, religious, belief, christian, god, beliefs |
The results conform our intuition. Topic 0 seems to revolve around IT, while Topic 1 around atheism and religion. We can already suspect, however that more granular topics could be discovered in this corpus. For instance Topic 0 contains terms related to operating systems, like windows and dos, but also components, like disk and card.
We can access the hierarchy of topics in the model at the current stage, with the model's hierarchy
property.
print(model.hierarchy)
├── 0: windows, dos, os, disk, card, drivers, file, pc, files, microsoft
└── 1: atheism, atheist, atheists, religion, christians, religious, belief, christian, god, beliefs
There isn't much to see yet, the model contains a flat hierarchy of the two topics we discovered and we are at root level. We can dissect these topics, by adding a level to the hierarchy.
Let us add 3 subtopics to each topic on the root level.
model.hierarchy.divide_children(n_subtopics=3)
├── 0: windows, dos, os, disk, card, drivers, file, pc, files, microsoft
│ ├── 0.0: dos, file, disk, files, program, windows, disks, shareware, norton, memory
│ ├── 0.1: os, unix, windows, microsoft, apps, nt, ibm, ms, os2, platform
│ └── 0.2: card, drivers, monitor, driver, vga, ram, motherboard, cards, graphics, ati
...
As you can see, the model managed to identify meaningful subtopics of the two larger topics we found earlier. Topic 0 got divided into a topic mostly concerned with dos and windows, a topic on operating systems in general, and one about hardware.
You can also divide individual topics to a number of subtopics, by using the divide()
method.
Let us divide Topic 0.0 to 5 subtopics.
model.hierarchy[0][0].divide(5)
model.hierarchy
├── 0: windows, dos, os, disk, card, drivers, file, pc, files, microsoft
│ ├── 0.0: dos, file, disk, files, program, windows, disks, shareware, norton, memory
│ │ ├── 0.0.1: file, files, ftp, bmp, program, windows, shareware, directory, bitmap, zip
│ │ ├── 0.0.2: os, windows, unix, microsoft, crash, apps, crashes, nt, pc, operating
...
2. Agglomerative/Bottom-up Hierarchical Modeling
In other models, hierarchies arise from starting from smaller, more specific topics, and then merging them together based on their similarity until a desired number of top-level topics are obtained.
This is how it is done in clustering topic models like BERTopic and Top2Vec. Clustering models typically find a lot of topics, and it can help with interpretation to merge topics until you gain 10-20 top-level topics.
You can either do this by default on a clustering model by setting n_reduce_to
on initialization or you can do it manually with reduce_topics()
.
For more details, check our guide on Clustering models.
from turftopic import ClusteringTopicModel
model = ClusteringTopicModel(
n_reduce_to=10,
feature_importance="centroid",
reduction_method="smallest",
reduction_topic_representation="centroid",
reduction_distance_metric="cosine",
)
model.fit(corpus)
print(model.hierarchy)
├── -1: documented, obsolete, et4000, concerns, dubious, embedded, hardware, xfree86, alternative, seeking
├── 20: hitter, pitching, batting, hitters, pitchers, fielder, shortstop, inning, baseman, pitcher
├── 284: nhl, goaltenders, canucks, sabres, hockey, bruins, puck, oilers, canadiens, flyers
│ ├── 242: sportschannel, espn, nbc, nhl, broadcasts, broadcasting, broadcast, mlb, cbs, cbc
│ │ ├── 171: stadium, tickets, mlb, ticket, sportschannel, mets, inning, nationals, schedule, cubs
│ │ │ └── ...
│ │ └── 21: sportschannel, nbc, espn, nhl, broadcasting, broadcasts, broadcast, hockey, cbc, cbs
│ └── 236: nhl, goaltenders, canucks, sabres, puck, oilers, andreychuk, bruins, goaltender, leafs
...
API reference
turftopic.hierarchical.TopicNode
dataclass
Node for a topic in a topic hierarchy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
ContextualModel
|
Underlying topic model, which the hierarchy is based on. |
required |
path
|
tuple[int]
|
Path that leads to this node from the root of the tree. |
()
|
word_importance
|
Optional[ndarray]
|
Importance of each word in the vocabulary for given topic. |
None
|
document_topic_vector
|
Optional[ndarray]
|
Importance of the topic in all documents in the corpus. |
None
|
children
|
Optional[list[TopicNode]]
|
List of subtopics within this topic. |
None
|
Source code in turftopic/hierarchical.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
|
description
property
Returns a high level description of the topic with its path in the tree and top words.
level
property
Indicates how deep down the hierarchy the topic is.
copy(deep=True)
Creates a copy of the given node.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
deep
|
bool
|
Indicates whether the copy should be deep or shallow. Deep copies are done recursively, while shallow copies only contain references to the original children. |
True
|
Returns:
Type | Description |
---|---|
Copy of original hierarchy.
|
|
Source code in turftopic/hierarchical.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
|
create_root(model, components, document_topic_matrix)
classmethod
Creates root node from a topic models' components and topic importances in documents.
Source code in turftopic/hierarchical.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
|
cut(max_depth)
Cuts hierarchy at a given depth, returns copy of the hierarchy with levels beyond max_depth removed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_depth
|
int
|
Maximum level of nodes to keep. |
required |
Returns:
Type | Description |
---|---|
TopicNode
|
Hierarchy cut at the given level. Contains a deep copy of the original nodes. |
Source code in turftopic/hierarchical.py
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
|
flatten()
Returns new hierarchy with only the leaves of the tree.
Returns:
Type | Description |
---|---|
TopicNode
|
Root node containing all leaves in a hierarchy. Copies of the original nodes. |
Source code in turftopic/hierarchical.py
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
|
get_words(top_k=10)
Returns top words and words importances for the topic.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
top_k
|
int
|
Number of top words to return. |
10
|
Returns:
Type | Description |
---|---|
list[tuple[str, float]]
|
List of word, importance pairs. |
Source code in turftopic/hierarchical.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
|
plot_tree()
Plots hierarchy as an interactive tree in Plotly.
Source code in turftopic/hierarchical.py
301 302 303 |
|
print_tree(top_k=10, max_depth=None)
Print hierarchy in tree form.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
top_k
|
int
|
Number of words to print for each topic. |
10
|
max_depth
|
Optional[int]
|
Maximum depth at which topics should be printed in the hierarchy. If None, the entire hierarchy is printed. |
None
|
Source code in turftopic/hierarchical.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
|
turftopic.hierarchical.DivisibleTopicNode
dataclass
Bases: TopicNode
Node for a topic in a topic hierarchy that can be subdivided.
Source code in turftopic/hierarchical.py
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
|
clear()
Deletes children of the given node.
Source code in turftopic/hierarchical.py
424 425 426 427 |
|
divide(n_subtopics, **kwargs)
Divides current node into smaller subtopics. Only works when the underlying model is a divisive hierarchical model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_subtopics
|
int
|
Number of topics to divide the topic into. |
required |
Source code in turftopic/hierarchical.py
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
|
divide_children(n_subtopics, **kwargs)
Divides all children of the current node to smaller topics. Only works when the underlying model is a divisive hierarchical model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_subtopics
|
int
|
Number of topics to divide the topics into. |
required |
Source code in turftopic/hierarchical.py
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
|
turftopic.models._hierarchical_clusters.ClusterNode
dataclass
Bases: TopicNode
Hierarchical Topic Node for clustering models. Supports merging topics based on a hierarchical merging strategy.
Source code in turftopic/models/_hierarchical_clusters.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
|
_estimate_children_components()
Estimates feature importances based on a fitted clustering.
Source code in turftopic/models/_hierarchical_clusters.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
|
create_root(model, labels)
classmethod
Creates root node from a topic models' components and topic importances in documents.
Source code in turftopic/models/_hierarchical_clusters.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
|
join_topics(to_join, joint_id=None)
Joins a number of topics into a new topic with a given ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
to_join
|
Sequence[int]
|
Children in the hierarchy to join (IDs indicate the last element of the path). |
required |
joint_id
|
Optional[int]
|
ID to give to the joint topic. By default, this will be the topic with the smallest ID. |
None
|
Source code in turftopic/models/_hierarchical_clusters.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
|