-
Notifications
You must be signed in to change notification settings - Fork 3
/
run_search.py
499 lines (441 loc) · 15.8 KB
/
run_search.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
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
import argparse
import json
import os
import traceback
from typing import (
Dict,
List,
Tuple
)
from topnum.data.vowpal_wabbit_text_collection import VowpalWabbitTextCollection
from topnum.scores import (
DiversityScore,
EntropyScore,
HoldoutPerplexityScore,
IntratextCoherenceScore,
PerplexityScore,
SimpleTopTokensCoherenceScore,
SophisticatedTopTokensCoherenceScore,
SilhouetteScore,
CalinskiHarabaszScore,
LikelihoodBasedScore
)
from topnum.model_constructor import KnownModel
from topnum.scores.diversity_score import L2
from topnum.scores.entropy_score import RENYI as RENYI_ENTROPY_NAME
from topnum.scores.base_score import BaseScore
from topnum.search_methods.constants import (
DEFAULT_MAX_NUM_TOPICS,
DEFAULT_MIN_NUM_TOPICS
)
from topnum.search_methods.optimize_scores_method import OptimizeScoresMethod
from topnum.search_methods.renormalization_method import (
RenormalizationMethod,
PHI_RENORMALIZATION_MATRIX,
THETA_RENORMALIZATION_MATRIX
)
MESSAGE_MODALITY_FORMAT = (
'Format: <modality name>, or <modality name>:<modality weight>.'
' Weight assumed to be 1.0 if not specified'
)
def _main():
parser = argparse.ArgumentParser(prog='run_search')
parser.add_argument(
'vw_file_path',
help='Path to the file with text collection in vowpal wabbit format'
)
parser.add_argument(
'-mf', '--model-family',
help=f'The family of models to optimize the number of topics for',
default=KnownModel.PLSA.value,
choices=[m.value for m in KnownModel],
required=False
)
parser.add_argument(
'main_modality',
help=f'Main modality in text. {MESSAGE_MODALITY_FORMAT}'
)
parser.add_argument(
'output_file_path',
help='File to write the result of the search in'
)
# TODO: extract modalities from text if none specified
parser.add_argument(
'-m', '--modality',
help=f'Other modality to take into account. {MESSAGE_MODALITY_FORMAT}',
action='append',
dest='modalities'
)
subparsers = parser.add_subparsers(
help='Method for searching an appropriate number of topics',
dest='search_method'
)
parser_optimize_scores = subparsers.add_parser(
'optimize_scores',
help='Find the number of topics which optimizes the score'
' (gives it max or min depending on the score)'
)
parser_renormalize = subparsers.add_parser(
'renormalize',
help='Fulfil topic matrix renormalization'
' to find the best number of topics relative to Renyi entropy'
)
parser_optimize_scores.add_argument(
'--max-num-topics',
help='Maximum number of topics',
type=int,
default=DEFAULT_MAX_NUM_TOPICS
)
parser_optimize_scores.add_argument(
'--min-num-topics',
help='Minimum number of topics',
type=int,
default=DEFAULT_MIN_NUM_TOPICS
)
parser_optimize_scores.add_argument(
'--num-topics-interval',
help='The number of topics the next model is bigger than the previous one',
type=int,
default=10
)
parser_optimize_scores.add_argument(
'--num-fit-iterations',
help='Number of fit iterations for model training',
type=int,
default=100
)
parser_optimize_scores.add_argument(
'--num-restarts',
help='Number of models to train,'
' each of which differs from the others by random seed'
' used for initialization.'
' Search results will be averaged over models '
' (suffix _std means standard deviation for restarts).', # TODO: check English
type=int,
default=3
)
subparsers_optimize_scores = parser_optimize_scores.add_subparsers(
help='Method for searching an appropriate number of topics',
dest='score_name'
)
# TODO: try to run with several identical scores (for testing purposes)
parser_optimize_perplexity = subparsers_optimize_scores.add_parser(
'perplexity',
help='Perplexity -> min'
)
parser_optimize_holdout_perplexity = subparsers_optimize_scores.add_parser(
'holdout_perplexity',
help='As usual perplexity, but on holdout sample'
)
parser_optimize_renyi_entropy = subparsers_optimize_scores.add_parser(
'renyi_entropy',
help='Renyi entropy -> min'
)
subparsers_optimize_scores.add_parser(
'calinski_harabasz',
help='CH -> max'
)
subparsers_optimize_scores.add_parser(
'silhouette',
help='SilhouetteScore -> max'
)
subparsers_optimize_scores.add_parser(
'diversity',
help='Diversity -> max'
)
parser_optimize_likelihood = subparsers_optimize_scores.add_parser(
'likelihood',
help='AIC / BIC / Approximate MDL -> min'
)
parser_optimize_likelihood.add_argument(
'--mode',
help='A type of information criterion',
choices=['AIC', 'BIC', 'MDL'],
default='AIC'
)
parser_optimize_intratext = subparsers_optimize_scores.add_parser(
'intratext_coherence',
help='Intratext coherence -> max'
)
parser_optimize_toptokens = subparsers_optimize_scores.add_parser(
'top_tokens_coherence',
help='Top tokens coherence -> max'
)
# TODO: check this score using command line
parser_optimize_holdout_perplexity.add_argument(
'--test-vw-file-path',
help='Path to the holdout data as vw file',
type=str,
required=True
)
parser_optimize_renyi_entropy.add_argument(
'-f', '--threshold-factor',
help='A greater than zero factor'
' by which the default 1/|W| threshold should be multiplied by',
type=float,
default=1.0
)
# TODO: add args for parser_optimize_intratext
# TODO: add args for parser_optimize_toptokens
parser_optimize_toptokens.add_argument(
'--cooc-file',
help='File with word cooccurrence values in the format'
' [[["word_1", "word_2"], 6.27], [["word_1", "word_3"], 1.32], ...],'
' i.e. there should be a list, where each item is another list:'
' word pair as yet another list and a numeric value corresponding to this word pair',
type=str,
default=None
)
parser_renormalize.add_argument(
'--matrix',
help='Matrix to be used for renormalization',
type=str,
default='phi',
choices=['phi', 'theta']
)
# TODO: think about it: maybe these args better make general for all methods?
parser_renormalize.add_argument(
'--max-num-topics',
help='Maximum number of topics',
type=int,
default=DEFAULT_MAX_NUM_TOPICS
)
parser_renormalize.add_argument(
'--min-num-topics',
help='Minimum number of topics',
type=int,
default=DEFAULT_MIN_NUM_TOPICS
)
parser_renormalize.add_argument(
'--num-fit-iterations',
help='Number of fit iterations for model training',
type=int,
default=100
)
parser_renormalize.add_argument(
'--num-restarts',
help='Number of models to train,'
' each of which differs from the others by random seed'
' used for initialization.'
' Search results will be averaged over models '
' (suffix _std means standard deviation for restarts).', # TODO: check English
type=int,
default=3
)
# parser_some_other = subparsers.add_parser('other', help='some help')
args, unparsed_args = parser.parse_known_args()
main_modality_name, modalities = _parse_modalities(args.main_modality, args.modalities)
modality_names = list(modalities.keys())
vw_file_path = args.vw_file_path
output_file_path = args.output_file_path
text_collection = VowpalWabbitTextCollection(
vw_file_path,
main_modality=main_modality_name,
modalities=modalities
)
if not os.path.isfile(vw_file_path):
raise ValueError(
f'File not found on path vw_file_path: "{vw_file_path}"!'
)
if not os.path.isdir(os.path.dirname(output_file_path))\
and len(os.path.dirname(output_file_path)) > 0:
raise ValueError(
f'Directory not found for output file output_file_path: "{output_file_path}"!'
)
if args.search_method == 'optimize_scores':
min_num_topics = args.min_num_topics
max_num_topics = args.max_num_topics
num_topics_interval = args.num_topics_interval
num_fit_iterations = args.num_fit_iterations
num_restarts = args.num_restarts
model_family = args.model_family
scores = list()
scores.append(_build_score(args, text_collection, modality_names, main_modality_name))
while len(unparsed_args) > 0:
current_args, unparsed_args = parser_optimize_scores.parse_known_args(
unparsed_args
)
scores.append(
_build_score(current_args, text_collection, modality_names, main_modality_name)
)
_optimize_scores(
scores,
model_family,
text_collection,
output_file_path,
min_num_topics=min_num_topics,
max_num_topics=max_num_topics,
num_topics_interval=num_topics_interval,
num_fit_iterations=num_fit_iterations,
num_restarts=num_restarts
)
elif args.search_method == 'renormalize':
min_num_topics = args.min_num_topics
max_num_topics = args.max_num_topics
num_fit_iterations = args.num_fit_iterations
num_restarts = args.num_restarts
if args.matrix == 'phi':
matrix = PHI_RENORMALIZATION_MATRIX
elif args.matrix == 'theta':
matrix = THETA_RENORMALIZATION_MATRIX
else:
raise ValueError(f'matrix: {args.matrix}') # ideally never happens
_renormalize(
text_collection,
output_file_path,
matrix=matrix,
min_num_topics=min_num_topics,
max_num_topics=max_num_topics,
num_fit_iterations=num_fit_iterations,
num_restarts=num_restarts
)
else:
raise ValueError(args.search_method)
text_collection._remove_dataset()
# TODO: test
def _extract_modality_name_and_weight(
modality: str,
default_weight: float = 1.0) -> Tuple[str, float]:
if ':' not in modality:
modality_name = modality
modality_weight = default_weight
else:
components = modality.split(':')
assert len(components) == 2
modality_name = modality.split(':')[0]
modality_weight = float(modality.split(':')[1])
return modality_name, modality_weight
def _parse_modalities(
main_modality: str, raw_modalities: List[str]) -> Tuple[str, Dict[str, float]]:
modalities = dict()
main_modality_name, main_modality_weight = _extract_modality_name_and_weight(
main_modality
)
modalities[main_modality_name] = main_modality_weight
# TODO: test weights: main @modality:5, -m @modality:2, -m @modality
if raw_modalities is not None:
for modality in raw_modalities:
modality_name, modality_weight = _extract_modality_name_and_weight(
modality
)
modalities[modality_name] = modality_weight
return main_modality_name, modalities
def _build_score(
args: argparse.Namespace,
text_collection: VowpalWabbitTextCollection,
modality_names: List[str],
main_modality_name: str) -> BaseScore:
# TODO: modality_names should be available via text_collection
if args.score_name == 'perplexity':
return PerplexityScore(
'perplexity_score',
class_ids=modality_names
)
elif args.score_name == 'holdout_perplexity':
test_text_collection = VowpalWabbitTextCollection(
args.test_vw_file_path,
main_modality=main_modality_name,
modalities=modality_names
)
return HoldoutPerplexityScore(
name='holdout_perplexity_score',
test_dataset=test_text_collection._to_dataset()
)
elif args.score_name == 'renyi_entropy':
return EntropyScore(
'renyi_entropy_score',
entropy=RENYI_ENTROPY_NAME,
threshold_factor=args.threshold_factor,
class_ids=modality_names
)
elif args.score_name == 'calinski_harabasz':
return CalinskiHarabaszScore(
'calinski_harabasz_score',
validation_dataset=text_collection._to_dataset()
)
elif args.score_name == 'silhouette':
return SilhouetteScore(
'silhouette_score',
validation_dataset=text_collection._to_dataset()
)
elif args.score_name == 'diversity':
return DiversityScore(
'l2_diversity_score',
metric=L2,
class_ids=modality_names
)
elif args.score_name == 'intratext_coherence':
return IntratextCoherenceScore(
'intratext_coherence_score',
data=text_collection
)
elif args.score_name == 'top_tokens_coherence' and args.cooc_file is None:
# Actually, this one also can tame custom coocs, but in a bit different format:
# with modalities, like ((@m, w1), (@m, w2)): 17.5, ...
return SophisticatedTopTokensCoherenceScore(
'top_tokens_coherence_score',
data=text_collection
)
elif args.score_name == 'top_tokens_coherence' and args.cooc_file is not None:
cooc_file = args.cooc_file
if not os.path.isfile(cooc_file):
raise ValueError(f'Coocs file not fould on path "{cooc_file}"!')
try:
raw_coocs_values = json.loads(open(cooc_file, 'r').read())
except json.JSONDecodeError:
raise ValueError(
f'Coocs file "{cooc_file}" doesn\'t seem like valid JSON!'
f' Error: {traceback.format_exc()}'
)
cooc_values = {
tuple(d[0]): d[1] for d in raw_coocs_values
}
return SimpleTopTokensCoherenceScore(
'top_tokens_coherence_score',
cooccurrence_values=cooc_values,
data=text_collection,
)
else:
raise ValueError(f'Unknown score name "{args.score_name}"!')
def _optimize_scores(
scores: List[BaseScore],
model_family: str,
text_collection: VowpalWabbitTextCollection,
output_file_path: str,
min_num_topics: int,
max_num_topics: int,
num_topics_interval: int,
num_fit_iterations: int,
num_restarts: int) -> None:
optimizer = OptimizeScoresMethod(
scores=scores,
model_family=model_family,
min_num_topics=min_num_topics,
max_num_topics=max_num_topics,
num_topics_interval=num_topics_interval,
num_fit_iterations=num_fit_iterations,
num_restarts=num_restarts
)
optimizer.search_for_optimum(text_collection)
with open(output_file_path, 'w') as f:
f.write(json.dumps(optimizer._result))
def _renormalize(
text_collection: VowpalWabbitTextCollection,
output_file_path: str,
matrix: str,
min_num_topics: int,
max_num_topics: int,
num_fit_iterations: int,
num_restarts: int) -> None:
optimizer = RenormalizationMethod(
matrix_for_renormalization=matrix,
min_num_topics=min_num_topics,
max_num_topics=max_num_topics,
num_fit_iterations=num_fit_iterations,
num_restarts=num_restarts
)
optimizer.search_for_optimum(text_collection)
with open(output_file_path, 'w') as f:
f.write(json.dumps(optimizer._result))
if __name__ == '__main__':
_main()