Bunka¶
The Bunka class for managing and analyzing textual data using various NLP techniques.
Examples:
from bunkatopics import Bunka
from datasets import load_dataset
import random
# Extract Data
dataset = load_dataset("rguo123/trump_tweets")["train"]["content"]
docs = random.sample(dataset, 1000)
bunka = Bunka()
topics = bunka.fit_transform(docs)
bunka.visualize_topics(width=800, height=800)
Source code in bunkatopics/_bunkatopics.py
74 75 76 77 78 79 80 81 82 83 84 85 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 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 418 419 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 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 |
|
__init__(embedding_model=None, projection_model=None, language='english')
¶
Initialize a BunkaTopics instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
embedding_model |
Embeddings
|
An optional embedding model for generating document embeddings. If not provided, a default model will be used based on the specified language. Default is None. |
None
|
projection_model |
optional
|
An optional projection model to reduce the dimensionality of the embeddings. Default is None. |
None
|
Source code in bunkatopics/_bunkatopics.py
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 |
|
clean_data_by_topics()
¶
Filters and cleans the dataset based on user-selected topics.
This method presents a UI with checkboxes for each topic in the dataset. The user can select topics to keep, and the data will be filtered accordingly. It merges the filtered documents and topics data, renames columns for clarity, and calculates the percentage of data retained after cleaning.
Attributes Updated
- self.df_cleaned: DataFrame containing the merged and cleaned documents and topics.
Logging
- Logs the percentage of data retained after cleaning.
Side Effects
- Updates
self.df_cleaned
with the cleaned data. - Displays interactive widgets for user input.
- Logs information about the data cleaning process.
Note
- This method uses interactive widgets (checkboxes and a button) for user input.
- The cleaning process is triggered by clicking the 'Clean Data' button.
Source code in bunkatopics/_bunkatopics.py
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 |
|
fit(docs, ids=None, pre_computed_embeddings=None, metadata=None, sampling_size_for_terms=1000, language=None)
¶
Fits the Bunka model to the provided list of documents.
This method processes the documents, extracts terms, generates embeddings, and applies dimensionality reduction to prepare the data for topic modeling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
docs |
List[str]
|
A list of document strings. |
required |
ids |
Optional[List[DOC_ID]]
|
Optional. A list of identifiers for the documents. If not provided, UUIDs are generated. |
None
|
metadata |
t.Optional[t.List[str]
|
A of metadata dictionaries for the documents. |
None
|
sampling_size_for_terms |
Optional[int]
|
The number of documents to sample for term extraction. Default is 2000. |
1000
|
Source code in bunkatopics/_bunkatopics.py
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 |
|
get_clean_topic_name(llm, use_doc=False, context='everything')
¶
Enhances topic names using a language model for cleaner and more meaningful representations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
llm |
LLM
|
The language model used for cleaning topic names. |
required |
use_doc |
bool
|
Flag to determine whether to use document context in the cleaning process. Default is False. |
False
|
context |
str
|
The broader context within which the topics are related Default is "everything". For instance, if you are looking at Computer Science, then update context = 'Computer Science' |
'everything'
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: A DataFrame containing the topics with cleaned names. |
Note
This method leverages a language model to refine the names of the topics generated by the model, aiming for more understandable and relevant topic descriptors.
Source code in bunkatopics/_bunkatopics.py
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 |
|
get_topic_repartition(width=1200, height=800)
¶
Creates a bar plot to visualize the distribution of topics by size.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
width |
int
|
The width of the bar plot. Default is 1200. |
1200
|
height |
int
|
The height of the bar plot. Default is 800. |
800
|
Returns:
Type | Description |
---|---|
Figure
|
go.Figure: A Plotly graph object figure representing the topic distribution bar plot. |
Note
This method generates a visualization that illustrates the number of documents associated with each topic, helping to understand the prevalence and distribution of topics within the document set. It provides a clear and concise bar plot for easy interpretation of the topic sizes.
Source code in bunkatopics/_bunkatopics.py
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 |
|
get_topics(n_clusters=5, ngrams=[1, 2], name_length=5, top_terms_overall=2000, min_count_terms=2, ranking_terms=20, max_doc_per_topic=20, custom_clustering_model=None, min_docs_per_cluster=10)
¶
Computes and organizes topics from the documents using specified parameters.
This method uses a topic modeling process to identify and characterize topics within the data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_clusters |
int
|
The number of clusters to form. Default is 5. |
5
|
ngrams |
List[int]
|
The n-gram range to consider for topic extraction. Default is [1, 2]. |
[1, 2]
|
name_length |
int
|
The length of the name for topics. Default is 10. |
5
|
top_terms_overall |
int
|
The number of top terms to consider overall. Default is 2000. |
2000
|
min_count_terms |
int
|
The minimum count of terms to be considered. Default is 2. |
2
|
min_docs_per_cluster |
int
|
Minimum count of documents per topic |
10
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: A DataFrame containing the topics and their associated data. |
Note
The method applies topic modeling using the specified parameters and updates the internal state with the resulting topics. It also associates the identified topics with the documents.
Source code in bunkatopics/_bunkatopics.py
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 418 419 420 421 422 423 424 425 426 427 428 429 |
|
load_bunka(path)
¶
Load the Bunka model from disk.
This method loads the Bunka model from disk by reading the serialized documents and terms.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
str
|
The directory path from where the model will be loaded. |
required |
Returns:
Name | Type | Description |
---|---|---|
bunka |
Bunka
|
The loaded Bunka model. |
Source code in bunkatopics/_bunkatopics.py
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
|
manually_clean_topics()
¶
Allows manual renaming of topic names in the dataset.
This method facilitates the manual editing of topic names based on their IDs. If no changes are made, it retains the original topic names.
The updated topic names are then applied to the topics
attribute of the class instance.
Attributes Updated
- self.topics: Each topic in this list gets its name updated based on the changes.
Logging
- Logs the percentage of data retained after cleaning.
Side Effects
- Modifies the
name
attribute of each topic inself.topics
based on user input or defaults. - Displays interactive widgets for user input.
- Logs information about the data cleaning process.
Note
- This method uses interactive widgets (text fields and a button) for user input.
- The cleaning process is triggered by clicking the 'Apply Changes' button.
Source code in bunkatopics/_bunkatopics.py
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 |
|
remove_outliers(threshold=6)
¶
Removes outliers from the dataset based on a specified threshold.
This method applies an outlier detection algorithm to identify and remove outliers Args: threshold (int): The threshold value for outlier detection. Default is 6.
Source code in bunkatopics/_bunkatopics.py
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
|
save_bunka(path='bunka_dumps')
¶
Save the Bunka model to disk.
This method saves the Bunka model to disk by serializing its documents and terms.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
str
|
The directory path where the model will be saved. Defaults to "bunka_dumps". |
'bunka_dumps'
|
Examples:
python
from bunkatopics import Bunka
bunka = Bunka()
...
bunka.save_bunka('bunka_dumps')
Source code in bunkatopics/_bunkatopics.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
|
visualize_bourdieu(llm=None, x_left_words=['war'], x_right_words=['peace'], y_top_words=['men'], y_bottom_words=['women'], height=1500, width=1500, display_percent=True, clustering=False, topic_n_clusters=10, topic_terms=2, topic_ngrams=[1, 2], topic_top_terms_overall=1000, gen_topic_language='english', manual_axis_name=None, use_doc_gen_topic=False, radius_size=0.3, convex_hull=True, density=True, colorscale='delta', label_size_ratio_clusters=100, label_size_ratio_label=50, label_size_ratio_percent=10, min_docs_per_cluster=5)
¶
Creates and visualizes a Bourdieu Map using specified parameters and a generative model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
llm |
Optional[str]
|
The generative model to be used. Default is None. |
None
|
x_left_words |
List[str]
|
Words defining the left and left x axes. |
['war']
|
x_right_words |
List[str]
|
Words defining the left and right x axes. |
['peace']
|
y_top_words |
List[str]
|
Words defining the left and top y axes. |
['men']
|
y_bottom_words |
List[str]
|
Words defining the top and bottom y axes. |
['women']
|
height |
int
|
Dimensions of the visualization. Default to 1500. |
1500
|
width |
int
|
Dimensions of the visualization. Default to 1500. |
1500
|
display_percent |
bool
|
Flag to display percentages on the map. Default is True. |
True
|
clustering |
bool
|
Whether to apply clustering on the map. Default is False. |
False
|
topic_n_clusters |
int
|
Number of clusters for topic modeling. Default is 10. |
10
|
topic_terms |
int
|
Length of topic names. Default is 2. |
2
|
topic_ngrams |
List[int]
|
N-gram range for topic modeling. Default is [1, 2]. |
[1, 2]
|
topic_top_terms_overall |
int
|
Top terms to consider overall. Default is 1000. |
1000
|
gen_topic_language |
str
|
Language for topic generation. Default is "english". |
'english'
|
manual_axis_name |
Optional[dict]
|
Custom axis names for the map. Default is None. |
None
|
use_doc_gen_topic |
bool
|
Flag to use document context in topic generation. Default is False. |
False
|
radius_size |
float
|
Radius size for the map isualization. Default is 0.3. |
0.3
|
convex_hull |
bool
|
Whether to include a convex hull in the visualization. Default is True. |
True
|
colorscale |
str
|
colorscale for the Density Plot (Default is delta) |
'delta'
|
density |
bool
|
Whether to display a density map |
True
|
Returns:
Type | Description |
---|---|
Figure
|
go.Figure: A Plotly graph object figure representing the Bourdieu Map. |
Note
The Bourdieu Map is a sophisticated visualization that plots documents and topics based on specified word axes, using a generative model for dynamic analysis. This method handles the complex process of generating and plotting this map, offering a range of customization options for detailed analysis.
Source code in bunkatopics/_bunkatopics.py
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 |
|
visualize_bourdieu_one_dimension(left=['negative'], right=['positive'], width=800, height=800, explainer=False)
¶
Visualizes the document set on a one-dimensional Bourdieu axis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
left |
List[str]
|
List of words representing the left side of the axis. |
['negative']
|
right |
List[str]
|
List of words representing the right side of the axis. |
['positive']
|
width |
int
|
Width of the generated visualization. Default is 800. |
800
|
height |
int
|
Height of the generated visualization. Default is 800. |
800
|
explainer |
bool
|
Flag to include an explainer figure. Default is False. |
False
|
Returns:
Type | Description |
---|---|
Figure
|
t.Tuple[go.Figure, t.Union[plt.Figure, None]]: A tuple containing the main visualization figure |
Union[Figure, None]
|
and an optional explainer figure (if explainer is True). |
Note
This method creates a one-dimensional Bourdieu-style visualization, plotting documents along an axis defined by contrasting word sets. It helps in understanding the distribution of documents in terms of these contrasting word concepts. An optional explainer figure can provide additional insight into specific terms used in the visualization.
Source code in bunkatopics/_bunkatopics.py
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 |
|
visualize_dimensions(dimensions=['positive', 'negative', 'fear', 'love'], width=500, height=500, template='plotly_dark')
¶
Visualizes the similarity scores between a given query and the document set.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
width |
int
|
Width of the visualization. Default is 600. |
500
|
height |
int
|
Height of the visualization. Default is 300. |
500
|
Returns:
Type | Description |
---|---|
Figure
|
A tuple (fig, percent) where 'fig' is a Plotly graph object figure representing the |
Figure
|
visualization and 'percent' is the percentage of documents above the similarity threshold. |
Note
This method creates a visualization showing how closely documents in the set relate to the specified query. Documents with similarity scores above the threshold are highlighted, providing a visual representation of their relevance to the query.
Source code in bunkatopics/_bunkatopics.py
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 |
|
visualize_topics(show_text=True, label_size_ratio=100, point_size_ratio=100, width=1000, height=1000, colorscale='delta', density=True, convex_hull=True, color=None)
¶
Generates a visualization of the identified topics in the document set.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
show_text |
bool
|
Whether to display text labels on the visualization. Default is True. |
True
|
label_size_ratio |
int
|
The size ratio of the labels in the visualization. Default is 100. |
100
|
width |
int
|
The width of the visualization figure. Default is 1000. |
1000
|
height |
int
|
The height of the visualization figure. Default is 1000. |
1000
|
colorscale |
str
|
colorscale for the Density Plot (Default is delta) |
'delta'
|
density |
bool
|
Whether to display a density map |
True
|
convex_hull |
bool
|
Whether to display lines around the clusters |
True
|
color |
str
|
What category to use to display the color |
None
|
Returns:
Type | Description |
---|---|
Figure
|
go.Figure: A Plotly graph object figure representing the topic visualization. |
Note
This method creates a 'Bunka Map', a graphical representation of the topics, using Plotly for interactive visualization. It displays how documents are grouped into topics and can include text labels for clarity.
Source code in bunkatopics/_bunkatopics.py
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 |
|