-
Notifications
You must be signed in to change notification settings - Fork 1
/
02_run_bertopic.py
182 lines (154 loc) · 4.58 KB
/
02_run_bertopic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
import os
import json
import random
import argparse
from figures_utils import draw_topic_keywords
from hdbscan import HDBSCAN
from umap import UMAP
from bertopic import BERTopic
import bertopic._save_utils as save_utils
import numpy as np
from utils import (
count_nb_files,
create_dir,
existing_dir_path,
vectorizer,
preprocess,
load_embeddings,
SBERT_NAME,
DEFAULT_SAVE_SIZE,
RANDOM_SEED,
)
parser = argparse.ArgumentParser()
parser.add_argument(
"input_path",
help="Path to a folder or to a .tar.xz archive containing all input csv files",
type=existing_dir_path,
)
parser.add_argument(
"embeddings_folder",
help="Path to a folder containing .npz embeddings. It is the output_folder arg in 01_encode_with_sbert.py",
)
parser.add_argument(
"output_folder",
help="Path to a folder that will be created and contain the BERTopic model",
type=create_dir,
)
parser.add_argument(
"--save-size",
help="Size of saved files (in embeddings_folder) in number of vectors",
type=int,
default=DEFAULT_SAVE_SIZE,
)
parser.add_argument(
"--small",
help=("run the script on one week of data"),
action="store_true",
)
args = parser.parse_args()
embeddings_path = os.path.join(
args.embeddings_folder, "tweets_sentence-camembert-large.npz"
)
hdbscan_model = HDBSCAN(
min_cluster_size=3,
metric="euclidean",
cluster_selection_method="eom",
prediction_data=True,
)
umap_model = UMAP(
n_neighbors=15,
n_components=5,
min_dist=0.0,
metric="cosine",
low_memory=False,
random_state=RANDOM_SEED,
)
if args.small:
vectorizer.min_df = 3
topic_model = BERTopic(
vectorizer_model=vectorizer,
hdbscan_model=hdbscan_model,
umap_model=umap_model,
nr_topics=10 if args.small else 100,
# Hyperparameters
top_n_words=10,
verbose=True,
calculate_probabilities=True,
)
class NpEncoder(json.JSONEncoder):
"""From https://stackoverflow.com/a/57915246/6053864"""
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return super(NpEncoder, self).default(obj)
def save_ctfidf_config(model, path):
"""Save parameters to recreate CountVectorizer and c-TF-IDF."""
config = {}
# Recreate ClassTfidfTransformer
config["ctfidf_model"] = {
"bm25_weighting": model.ctfidf_model.bm25_weighting,
"reduce_frequent_words": model.ctfidf_model.reduce_frequent_words,
}
# Recreate CountVectorizer
cv_params = model.vectorizer_model.get_params()
del cv_params["tokenizer"], cv_params["preprocessor"], cv_params["dtype"]
if not isinstance(cv_params["analyzer"], str):
del cv_params["analyzer"]
config["vectorizer_model"] = {
"params": cv_params,
"vocab": model.vectorizer_model.vocabulary_,
}
with path.open("w") as f:
json.dump(config, f, indent=2, cls=NpEncoder)
save_utils.save_ctfidf_config = save_ctfidf_config
docs = np.array(
[
doc
for doc in preprocess(
args.input_path, count_nb_files(args.input_path), apply_unidecode=True
)
]
)
max_index, embeddings = load_embeddings(
embeddings_path,
args.save_size,
docs.shape[0],
)
print("Fitting topic model with params: {}".format(topic_model.hdbscan_model.__dict__))
if args.small:
random.seed(a=RANDOM_SEED)
indices = random.choices(range(len(docs)), k=1000)
docs = docs[indices]
embeddings = embeddings[indices]
topics, probs = topic_model.fit_transform(docs, embeddings)
topic_model.save(
os.path.join(args.output_folder, "small"),
serialization="safetensors",
save_ctfidf=True,
save_embedding_model=SBERT_NAME,
)
else:
topics, probs = topic_model.fit_transform(docs, embeddings)
# Save model
topic_model.save(
args.output_folder,
serialization="safetensors",
save_ctfidf=True,
save_embedding_model=SBERT_NAME,
)
new_topics = topic_model.reduce_outliers(
docs, topics, probabilities=probs, strategy="probabilities", threshold=0.3
)
topic_model.update_topics(docs, topics=new_topics, vectorizer_model=vectorizer)
print(topic_model.get_topic_info())
for i, row in topic_model.get_topic_info().iterrows():
topic = row["Topic"]
top_list = topic_model.get_topic(topic)
top_words, top_ctfidf = zip(*top_list)
draw_topic_keywords(
topic, top_words, top_ctfidf, sorted(range(len(top_words)), reverse=True)
)