ap.utils

ap.utils.bpe.load_bpe_models(bpe_path: str) dict

Загружает обученные BPE модели.

Параметры

bpe_path (str) – путь до папки с обученными BPE моделями.

ap.utils.dictionary.get_num_entries(dictionary: artm.dictionary.Dictionary) int

Возвращает размер словаря.

Параметры

dictionary (artm.Dictionary) – словарь тематической модели

Результат

количество токенов в словаре

ap.utils.dictionary.limit_classwise(dictionary: artm.dictionary.Dictionary, cls_ids: Iterable[str], max_dictionary_size: int, tmp_dir: str, out_file: str)

Ограничивает словарь.

Таким образом, что в разрезе каждоого class id будет не более max_dictionary_size токенов. Сохраняет словарь в текстовым форматом в файле out_file.

Параметры
  • dictionary (artm.Dictionary) – исходный словарь

  • cls_ids (list) – модальности

  • max_dictionary_size (int) – максимальный размер словаря в разрезе модальности

  • tmp_dir (str) – директория для хранения промежуточных результатов

  • out_file (str) – файл, в котором сохраняется результат

ap.utils.emb_metrics.generate_theta(path_models, save_path)

Function to generate theta matrix.

Параметры
  • path_models (str) – a path with artm models

  • save_path (str) – a path for save theta matrices

ap.utils.emb_metrics.get_analogy_distribution(path_models, save_path)

Function to get analogy distribution for models.

Args:

path_models (str):

a path with artm models

save_path (str):

a path for save theta matrices

Результат

dict with distribution of analogy measure

Тип результата

pair_analogy (dict)

ap.utils.emb_metrics.get_cos_distribution(path_models, save_path, path_categories)

Function to get cosine distribution in classes for models.

Параметры
  • path_models (str) – a path with artm models

  • save_path (str) – a path for save theta matrices

  • path_categories (str) – a path with classes (json)

Результат

dict with distribution of cosine measure for classes

Тип результата

pair_cos (dict)

ap.utils.emb_metrics.get_mean_classes_intersection(path_models, save_path, path_categories)

Function to evaluate classes intersection.

Args:

path_models (str):

a path with artm models

save_path (str):

a path for save theta matrices

path_categories (str):

a path with classes (json)

Результат

DataFrame with evaluation of classes intersection

Тип результата

(pd.DataFrame)

ap.utils.emb_metrics.get_topic_profile(path_models, save_path)

Function to get topic profiles for models.

Параметры
  • path_models (str) – a path with artm models

  • save_path (str) – a path for save theta matrices

Результат

DataFrame with topic profiles for models

Тип результата

(pd.DataFrame)

ap.utils.general.batch_names(starts_from, count) Generator[str, None, None]

Генерирует названия батчей в соответствие с форматом BatchVectorizer.

Параметры
  • starts_from – название файла последнего батча в директории

  • count – количество батчей

Результат

Генератор имен батчей

Тип результата

(Generator[str, None, None])

ap.utils.general.docs_from_pack(pack) Dict[str, Dict[str, str]]

Создает dict документов из pack.

Параметры

pack (ap.topic_model.v1.TopicModelBase_pb2.DocumentPack) – TODO

Результат

dict из документов

ap.utils.general.ensure_directory(path: str) str

Создает директорию, если ее нет, и возвращает path.

Параметры

path (str) – путь к директории

Результат

path

ap.utils.general.id_to_str(id) str

Конвертирует DocId в строку.

Параметры

id (DocId) – id документа

Результат

Строка из DocId

Рекурсивное удаление файлов и директорий.

Параметры

path (Path) – путь, по которому необходимо удалить все файлы.

ap.utils.graphics_for_emb_metrics.show_analogy_distribution(model_name, pair_analogy, path_save_figs, lang, n_bins)

Function to visualize analogy distribution.

ap.utils.graphics_for_emb_metrics.show_cos_distribution(cos_distribution, path_save_figs, rubrics, lang, n_bins)

Function to visualize cos distribution.

ap.utils.rank_metric.quality_of_models(path_train_lang, bcg_topic_list, metrics_to_calculate, mode, path_model, path_experiment_result, matrix_norm_metric, path_subsamples, path_rubrics, path_test, current_languages, recalculate_test_thetas, **kwargs)

Function to calculate quality of models.

Параметры
  • path_train_lang (str) – path to train thetas by languages

  • bcg_topic_list (list of str) – backgroung topics of a topic model for example init as: bcg_topic_list = [„topic_0“]

  • metrics_to_calculate (list of str ('analogy', 'eucl')) – list of names of proximity measures to use in ranking

  • path_model (str) – path to models

  • path_experiment_result (pathlib.Path) – path to the folder to save results of models

  • matrix_norm_metric (callable) – a way to measure norm of a matrix of vectors for example init as: matrix_norm_metric = np.linalg.norm

  • path_subsamples (str) – path to folder with subsemples of different languages in json format

  • path_rubrics (str) – path to file with rubrics of documents in json format

  • path_test (str) – path to folder with txt files for calculate metrics

  • current_languages (list of str) – names of languages to use to calculate metrics

  • recalculate_test_thetas (bool) – True means rebuild thetas False means load existing thetas

Результат

словарь словарей - по имени модели хранятся названия метрик,

по названиям метрик хранятся значения метрик этих моделей

Тип результата

quality_experiment (dict)

class ap.utils.subsamples_creator.MakeSubsamples(languages: list, path_to_save_subsamples: str, path_to_data: str, path_rubrics: str, mode: str, subsample_size: int = 1000)

Class for saving subsamples of document indices.

Параметры
  • languages (list) – list of str of languages to use in subsamples

  • path_to_save_subsamples (str) – path to file in json format to save subsamples

  • path_to_data (str) – path to data for which subsamples will be created expected data in txt format

  • path_rubrics (str) – path to json file with rubrics of documents

  • mode ('test' or 'wiki') – kind of data for which subsamples will be created

  • subsample_size (int) – The size of the subsample. The default is 1000.

get_subsamples()

Function saving subsamples of document indices.

Класс для работы с данными в формате Vowpal Wabbit.

class ap.utils.vowpal_wabbit.VowpalWabbit(use_counters)

Класс сохранения VW файлов.

convert_doc(doc: Dict[str, str]) Dict[str, Union[str, Counter]]

Конвертирует исходный документ в формат BOW.

Параметры

документа (doc словарь язык->текст) –

Тип результата

словарь язык->BOW документа. Если use_counters==True, словарь в виде Counter

save_docs(target_file: TextIO, doc: Dict[str, Dict[str, str]])

Конвертирует документы в BOW и сохраняет их.

Параметры
  • target_file – путь к файлу

  • doc – сырые документы