Hierarchy
The topics that you create can be hierarchically reduced. In order to understand the potential hierarchical
structure of the topics, we can use scipy.cluster.hierarchy to create clusters and visualize how
they relate to one another. This might help to select an appropriate nr_topics when reducing the number
of topics that you have created. To visualize this hierarchy, run the following:
topic_model.visualize_hierarchy()
Note
Do note that this is not the actual procedure of .reduce_topics() when nr_topics is set to
auto since HDBSCAN is used to automatically extract topics. The visualization above closely resembles
the actual procedure of .reduce_topics() when any number of nr_topics is selected.
Hierarchical labels¶
Although visualizing this hierarchy gives us information about the structure, it would be helpful to see what happens to the topic representations when merging topics. To do so, we first need to calculate the representations of the hierarchical topics:
First, we train a basic BERTopic model:
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))["data"]
topic_model = BERTopic(verbose=True)
topics, probs = topic_model.fit_transform(docs)
hierarchical_topics = topic_model.hierarchical_topics(docs)
To visualize these results, we simply need to pass the resulting hierarchical_topics to our .visualize_hierarchy function:
topic_model.visualize_hierarchy(hierarchical_topics=hierarchical_topics)
If you hover over the black circles, you will see the topic representation at that level of the hierarchy. These representations help you understand the effect of merging certain topics. Some might be logical to merge whilst others might not. Moreover, we can now see which sub-topics can be found within certain larger themes.
Text-based topic tree¶
Although this gives a nice overview of the potential hierarchy, hovering over all black circles can be tiresome. Instead, we can
use topic_model.get_topic_tree to create a text-based representation of this hierarchy. Although the general structure is more difficult
to view, we can see better which topics could be logically merged:
>>> tree = topic_model.get_topic_tree(hierarchical_topics)
>>> print(tree)
.
ââatheists_atheism_god_moral_atheist
ââatheists_atheism_god_atheist_argument
â âââ ââatheists_atheism_god_atheist_argument ââ Topic: 21
â âââ ââbr_god_exist_genetic_existence ââ Topic: 124
âââ ââmoral_morality_objective_immoral_morals ââ Topic: 29
Click here to view the full tree.
.
ââpeople_armenian_said_god_armenians
â ââgod_jesus_jehovah_lord_christ
â â ââgod_jesus_jehovah_lord_christ
â â â ââjehovah_lord_mormon_mcconkie_god
â â â â âââ ââra_satan_thou_god_lucifer ââ Topic: 94
â â â â âââ ââjehovah_lord_mormon_mcconkie_unto ââ Topic: 78
â â â ââjesus_mary_god_hell_sin
â â â ââjesus_hell_god_eternal_heaven
â â â â ââhell_jesus_eternal_god_heaven
â â â â â âââ ââjesus_tomb_disciples_resurrection_john ââ Topic: 69
â â â â â âââ ââhell_eternal_god_jesus_heaven ââ Topic: 53
â â â â âââ ââaaron_baptism_sin_law_god ââ Topic: 89
â â â âââ ââmary_sin_maria_priest_conception ââ Topic: 56
â â âââ ââmarriage_married_marry_ceremony_marriages ââ Topic: 110
â ââpeople_armenian_armenians_said_mr
â ââpeople_armenian_armenians_said_israel
â â ââgod_homosexual_homosexuality_atheists_sex
â â â ââhomosexual_homosexuality_sex_gay_homosexuals
â â â â âââ ââkinsey_sex_gay_men_sexual ââ Topic: 44
â â â â ââhomosexuality_homosexual_sin_homosexuals_gay
â â â â âââ ââgay_homosexual_homosexuals_sexual_cramer ââ Topic: 50
â â â â âââ ââhomosexuality_homosexual_sin_paul_sex ââ Topic: 27
â â â ââgod_atheists_atheism_moral_atheist
â â â ââislam_quran_judas_islamic_book
â â â â âââ ââjim_context_challenges_articles_quote ââ Topic: 36
â â â â ââislam_quran_judas_islamic_book
â â â â âââ ââislam_quran_islamic_rushdie_muslims ââ Topic: 31
â â â â âââ ââjudas_scripture_bible_books_greek ââ Topic: 33
â â â ââatheists_atheism_god_moral_atheist
â â â ââatheists_atheism_god_atheist_argument
â â â â âââ ââatheists_atheism_god_atheist_argument ââ Topic: 21
â â â â âââ ââbr_god_exist_genetic_existence ââ Topic: 124
â â â âââ ââmoral_morality_objective_immoral_morals ââ Topic: 29
â â ââarmenian_armenians_people_israel_said
â â ââarmenian_armenians_israel_people_jews
â â â ââtax_rights_government_income_taxes
â â â â âââ âârights_right_slavery_slaves_residence ââ Topic: 106
â â â â ââtax_government_taxes_income_libertarians
â â â â âââ ââgovernment_libertarians_libertarian_regulation_party ââ Topic: 58
â â â â âââ ââtax_taxes_income_billion_deficit ââ Topic: 41
â â â ââarmenian_armenians_israel_people_jews
â â â ââgun_guns_militia_firearms_amendment
â â â â âââ ââblacks_penalty_death_cruel_punishment ââ Topic: 55
â â â â âââ ââgun_guns_militia_firearms_amendment ââ Topic: 7
â â â ââarmenian_armenians_israel_jews_turkish
â â â âââ ââisrael_israeli_jews_arab_jewish ââ Topic: 4
â â â âââ ââarmenian_armenians_turkish_armenia_azerbaijan ââ Topic: 15
â â ââstephanopoulos_president_mr_myers_ms
â â âââ ââserbs_muslims_stephanopoulos_mr_bosnia ââ Topic: 35
â â âââ ââmyers_stephanopoulos_president_ms_mr ââ Topic: 87
â ââbatf_fbi_koresh_compound_gas
â âââ ââreno_workers_janet_clinton_waco ââ Topic: 77
â ââbatf_fbi_koresh_gas_compound
â ââbatf_koresh_fbi_warrant_compound
â â âââ ââbatf_warrant_raid_compound_fbi ââ Topic: 42
â â âââ ââkoresh_batf_fbi_children_compound ââ Topic: 61
â âââ ââfbi_gas_tear_bds_building ââ Topic: 23
ââuse_like_just_dont_new
ââgame_team_year_games_like
â ââgame_team_games_25_year
â â ââgame_team_games_25_season
â â â ââwindow_printer_use_problem_mhz
â â â â ââmhz_wire_simms_wiring_battery
â â â â â ââsimms_mhz_battery_cpu_heat
â â â â â â ââsimms_pds_simm_vram_lc
â â â â â â â âââ ââpds_nubus_lc_slot_card ââ Topic: 119
â â â â â â â âââ ââsimms_simm_vram_meg_dram ââ Topic: 32
â â â â â â ââmhz_battery_cpu_heat_speed
â â â â â â ââmhz_cpu_speed_heat_fan
â â â â â â â ââmhz_cpu_speed_heat_fan
â â â â â â â â âââ ââfan_cpu_heat_sink_fans ââ Topic: 92
â â â â â â â â âââ ââmhz_speed_cpu_fpu_clock ââ Topic: 22
â â â â â â â âââ ââmonitor_turn_power_computer_electricity ââ Topic: 91
â â â â â â ââbattery_batteries_concrete_duo_discharge
â â â â â â âââ ââduo_battery_apple_230_problem ââ Topic: 121
â â â â â â âââ ââbattery_batteries_concrete_discharge_temperature ââ Topic: 75
â â â â â ââwire_wiring_ground_neutral_outlets
â â â â â ââwire_wiring_ground_neutral_outlets
â â â â â â ââwire_wiring_ground_neutral_outlets
â â â â â â â âââ ââleds_uv_blue_light_boards ââ Topic: 66
â â â â â â â âââ ââwire_wiring_ground_neutral_outlets ââ Topic: 120
â â â â â â ââscope_scopes_phone_dial_number
â â â â â â âââ ââdial_number_phone_line_output ââ Topic: 93
â â â â â â âââ ââscope_scopes_motorola_generator_oscilloscope ââ Topic: 113
â â â â â ââcelp_dsp_sampling_antenna_digital
â â â â â âââ ââantenna_antennas_receiver_cable_transmitter ââ Topic: 70
â â â â â âââ ââcelp_dsp_sampling_speech_voice ââ Topic: 52
â â â â ââwindow_printer_xv_mouse_windows
â â â â ââwindow_xv_error_widget_problem
â â â â â ââerror_symbol_undefined_xterm_rx
â â â â â â âââ ââsymbol_error_undefined_doug_parse ââ Topic: 63
â â â â â â âââ âârx_remote_server_xdm_xterm ââ Topic: 45
â â â â â ââwindow_xv_widget_application_expose
â â â â â ââwindow_widget_expose_application_event
â â â â â â âââ ââgc_mydisplay_draw_gxxor_drawing ââ Topic: 103
â â â â â â âââ ââwindow_widget_application_expose_event ââ Topic: 25
â â â â â ââxv_den_polygon_points_algorithm
â â â â â âââ ââden_polygon_points_algorithm_polygons ââ Topic: 28
â â â â â âââ ââxv_24bit_image_bit_images ââ Topic: 57
â â â â ââprinter_fonts_print_mouse_postscript
â â â â ââprinter_fonts_print_font_deskjet
â â â â â âââ ââscanner_logitech_grayscale_ocr_scanman ââ Topic: 108
â â â â â ââprinter_fonts_print_font_deskjet
â â â â â âââ ââprinter_print_deskjet_hp_ink ââ Topic: 18
â â â â â âââ ââfonts_font_truetype_tt_atm ââ Topic: 49
â â â â ââmouse_ghostscript_midi_driver_postscript
â â â â ââghostscript_midi_postscript_files_file
â â â â â âââ ââghostscript_postscript_pageview_ghostview_dsc ââ Topic: 104
â â â â â ââmidi_sound_file_windows_driver
â â â â â âââ ââlocation_mar_file_host_rwrr ââ Topic: 83
â â â â â âââ ââmidi_sound_driver_blaster_soundblaster ââ Topic: 98
â â â â âââ ââmouse_driver_mice_ball_problem ââ Topic: 68
â â â ââgame_team_games_25_season
â â â ââ1st_sale_condition_comics_hulk
â â â â ââsale_condition_offer_asking_cd
â â â â â ââcondition_stereo_amp_speakers_asking
â â â â â â âââ ââmiles_car_amfm_toyota_cassette ââ Topic: 62
â â â â â â âââ ââamp_speakers_condition_stereo_audio ââ Topic: 24
â â â â â ââgames_sale_pom_cds_shipping
â â â â â ââpom_cds_sale_shipping_cd
â â â â â â âââ ââsize_shipping_sale_condition_mattress ââ Topic: 100
â â â â â â âââ ââpom_cds_cd_sale_picture ââ Topic: 37
â â â â â âââ ââgames_game_snes_sega_genesis ââ Topic: 40
â â â â ââ1st_hulk_comics_art_appears
â â â â ââ1st_hulk_comics_art_appears
â â â â â ââlens_tape_camera_backup_lenses
â â â â â â âââ ââtape_backup_tapes_drive_4mm ââ Topic: 107
â â â â â â âââ ââlens_camera_lenses_zoom_pouch ââ Topic: 114
â â â â â ââ1st_hulk_comics_art_appears
â â â â â âââ ââ1st_hulk_comics_art_appears ââ Topic: 105
â â â â â âââ ââbooks_book_cover_trek_chemistry ââ Topic: 125
â â â â ââtickets_hotel_ticket_voucher_package
â â â â âââ ââhotel_voucher_package_vacation_room ââ Topic: 74
â â â â âââ ââtickets_ticket_june_airlines_july ââ Topic: 84
â â â ââgame_team_games_season_hockey
â â â ââgame_hockey_team_25_550
â â â â âââ ââespn_pt_pts_game_la ââ Topic: 17
â â â â âââ ââteam_25_game_hockey_550 ââ Topic: 2
â â â âââ ââyear_game_hit_baseball_players ââ Topic: 0
â â ââbike_car_greek_insurance_msg
â â ââcar_bike_insurance_cars_engine
â â â ââcar_insurance_cars_radar_engine
â â â â ââinsurance_health_private_care_canada
â â â â â âââ ââinsurance_health_private_care_canada ââ Topic: 99
â â â â â âââ ââinsurance_car_accident_rates_sue ââ Topic: 82
â â â â ââcar_cars_radar_engine_detector
â â â â ââcar_radar_cars_detector_engine
â â â â â âââ ââradar_detector_detectors_ka_alarm ââ Topic: 39
â â â â â ââcar_cars_mustang_ford_engine
â â â â â âââ ââclutch_shift_shifting_transmission_gear ââ Topic: 88
â â â â â âââ ââcar_cars_mustang_ford_v8 ââ Topic: 14
â â â â ââoil_diesel_odometer_diesels_car
â â â â ââodometer_oil_sensor_car_drain
â â â â â âââ ââodometer_sensor_speedo_gauge_mileage ââ Topic: 96
â â â â â âââ ââoil_drain_car_leaks_taillights ââ Topic: 102
â â â â âââ ââdiesel_diesels_emissions_fuel_oil ââ Topic: 79
â â â ââbike_riding_ride_bikes_motorcycle
â â â ââbike_ride_riding_bikes_lane
â â â â âââ ââbike_ride_riding_lane_car ââ Topic: 11
â â â â âââ ââbike_bikes_miles_honda_motorcycle ââ Topic: 19
â â â âââ ââcountersteering_bike_motorcycle_rear_shaft ââ Topic: 46
â â ââgreek_msg_kuwait_greece_water
â â ââgreek_msg_kuwait_greece_water
â â â ââgreek_msg_kuwait_greece_dog
â â â â ââgreek_msg_kuwait_greece_dog
â â â â â ââgreek_kuwait_greece_turkish_greeks
â â â â â â âââ ââgreek_greece_turkish_greeks_cyprus ââ Topic: 71
â â â â â â âââ ââkuwait_iraq_iran_gulf_arabia ââ Topic: 76
â â â â â ââmsg_dog_drugs_drug_food
â â â â â ââdog_dogs_cooper_trial_weaver
â â â â â â âââ ââclinton_bush_quayle_reagan_panicking ââ Topic: 101
â â â â â â ââdog_dogs_cooper_trial_weaver
â â â â â â âââ ââcooper_trial_weaver_spence_witnesses ââ Topic: 90
â â â â â â âââ ââdog_dogs_bike_trained_springer ââ Topic: 67
â â â â â ââmsg_drugs_drug_food_chinese
â â â â â âââ ââmsg_food_chinese_foods_taste ââ Topic: 30
â â â â â âââ ââdrugs_drug_marijuana_cocaine_alcohol ââ Topic: 72
â â â â ââwater_theory_universe_science_larsons
â â â â ââwater_nuclear_cooling_steam_dept
â â â â â âââ âârocketry_rockets_engines_nuclear_plutonium ââ Topic: 115
â â â â â ââwater_cooling_steam_dept_plants
â â â â â âââ ââwater_dept_phd_environmental_atmospheric ââ Topic: 97
â â â â â âââ ââcooling_water_steam_towers_plants ââ Topic: 109
â â â â ââtheory_universe_larsons_larson_science
â â â â âââ ââtheory_universe_larsons_larson_science ââ Topic: 54
â â â â âââ ââoort_cloud_grbs_gamma_burst ââ Topic: 80
â â â ââhelmet_kirlian_photography_lock_wax
â â â ââhelmet_kirlian_photography_leaf_mask
â â â â ââkirlian_photography_leaf_pictures_deleted
â â â â â ââdeleted_joke_stuff_maddi_nickname
â â â â â â âââ ââjoke_maddi_nickname_nicknames_frank ââ Topic: 43
â â â â â â âââ ââdeleted_stuff_bookstore_joke_motto ââ Topic: 81
â â â â â âââ ââkirlian_photography_leaf_pictures_aura ââ Topic: 85
â â â â ââhelmet_mask_liner_foam_cb
â â â â âââ ââhelmet_liner_foam_cb_helmets ââ Topic: 112
â â â â âââ ââmask_goalies_77_santore_tl ââ Topic: 123
â â â ââlock_wax_paint_plastic_ear
â â â âââ ââlock_cable_locks_bike_600 ââ Topic: 117
â â â ââwax_paint_ear_plastic_skin
â â â âââ ââwax_paint_plastic_scratches_solvent ââ Topic: 65
â â â âââ ââear_wax_skin_greasy_acne ââ Topic: 116
â â ââm4_mp_14_mw_mo
â â ââm4_mp_14_mw_mo
â â â âââ ââm4_mp_14_mw_mo ââ Topic: 111
â â â âââ ââtest_ensign_nameless_deane_deanebinahccbrandeisedu ââ Topic: 118
â â âââ ââites_cheek_hello_hi_ken ââ Topic: 3
â ââspace_medical_health_disease_cancer
â ââmedical_health_disease_cancer_patients
â â âââ ââcancer_centers_center_medical_research ââ Topic: 122
â â ââhealth_medical_disease_patients_hiv
â â ââpatients_medical_disease_candida_health
â â â âââ ââcandida_yeast_infection_gonorrhea_infections ââ Topic: 48
â â â ââpatients_disease_cancer_medical_doctor
â â â âââ ââhiv_medical_cancer_patients_doctor ââ Topic: 34
â â â âââ ââpain_drug_patients_disease_diet ââ Topic: 26
â â âââ ââhealth_newsgroup_tobacco_vote_votes ââ Topic: 9
â ââspace_launch_nasa_shuttle_orbit
â ââspace_moon_station_nasa_launch
â â âââ ââsky_advertising_billboard_billboards_space ââ Topic: 59
â â âââ ââspace_station_moon_redesign_nasa ââ Topic: 16
â ââspace_mission_hst_launch_orbit
â ââspace_launch_nasa_orbit_propulsion
â â âââ ââspace_launch_nasa_propulsion_astronaut ââ Topic: 47
â â âââ ââorbit_km_jupiter_probe_earth ââ Topic: 86
â âââ ââhst_mission_shuttle_orbit_arrays ââ Topic: 60
ââdrive_file_key_windows_use
ââkey_file_jpeg_encryption_image
â ââkey_encryption_clipper_chip_keys
â â âââ ââkey_clipper_encryption_chip_keys ââ Topic: 1
â â âââ ââentry_file_ripem_entries_key ââ Topic: 73
â ââjpeg_image_file_gif_images
â ââmotif_graphics_ftp_available_3d
â â ââmotif_graphics_openwindows_ftp_available
â â â âââ ââopenwindows_motif_xview_windows_mouse ââ Topic: 20
â â â âââ ââgraphics_widget_ray_3d_available ââ Topic: 95
â â âââ ââ3d_machines_version_comments_contact ââ Topic: 38
â ââjpeg_image_gif_images_format
â âââ ââgopher_ftp_files_stuffit_images ââ Topic: 51
â âââ ââjpeg_image_gif_format_images ââ Topic: 13
ââdrive_db_card_scsi_windows
ââdb_windows_dos_mov_os2
â âââ ââcopy_protection_program_software_disk ââ Topic: 64
â âââ ââdb_windows_dos_mov_os2 ââ Topic: 8
ââdrive_card_scsi_drives_ide
ââdrive_scsi_drives_ide_disk
â âââ ââdrive_scsi_drives_ide_disk ââ Topic: 6
â âââ ââmeg_sale_ram_drive_shipping ââ Topic: 12
ââcard_modem_monitor_video_drivers
âââ ââcard_monitor_video_drivers_vga ââ Topic: 5
âââ ââmodem_port_serial_irq_com ââ Topic: 10
Visualize Hierarchical Documents¶
We can extend the previous method by calculating the topic representation at different levels of the hierarchy and plotting them on a 2D plane. To do so, we first need to calculate the hierarchical topics:
from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
from bertopic import BERTopic
from umap import UMAP
# Prepare embeddings
docs = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))['data']
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = sentence_model.encode(docs, show_progress_bar=False)
# Train BERTopic and extract hierarchical topics
topic_model = BERTopic().fit(docs, embeddings)
hierarchical_topics = topic_model.hierarchical_topics(docs)
# Run the visualization with the original embeddings
topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, embeddings=embeddings)
# Reduce dimensionality of embeddings, this step is optional but much faster to perform iteratively:
reduced_embeddings = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit_transform(embeddings)
topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, reduced_embeddings=reduced_embeddings)
Note
The visualization above was generated with the additional parameter hide_document_hover=True which disables the
option to hover over the individual points and see the content of the documents. This makes the resulting visualization
smaller and fit into your RAM. However, it might be interesting to set hide_document_hover=False to hover
over the points and see the content of the documents.