A tool for automatically configuring a text classification pipeline for intent prediction.
Project description
AutoIntent
Инструмент для автоматической конфигурации пайплайна классификации текстов для предсказания интента. Построен на представлении о том, что алгоритм предсказания интента можно разбить на четыре шага (TODO обновить схему):
- RegExp: классификация простейших примеров, которые описываются регулярными выражениями
- Retrieval: поиск похожих текстов, для которых известна метка класса
- Scoring: оценка принадлежности каждому из классов
- Prediction: предсказание метки класса и детекция out-of-scope примеров
Установка
- Скопировать проект:
git clone https://github.com/voorhs/AutoIntent.git
cd AutoIntent
- Установить пакет:
pip install .
Использование
Оптимизация
В текущей alpha-версии оптимизацию можно запустить командой autointent:
Примеры использования:
autointent data.train_path=default-multiclass
autointent data.train_path=default-multilabel hydra.job_logging.root.level=INFO
autointent data.train_path=data/intent_records/ac_robotic_new.json \
data.force_multilabel=true \
logs.dirpath=experiments/multiclass_as_multilabel/ \
logs.run_name=robotics_new_testing \
augmentation.regex_sampling=10 \
augmentation.multilabel_generation_config="[0, 4000, 1000]" # currently doesn't work, omit this line
# currently doesn't work due to problems with to_multilabel when dataset contains only regexp but no utterances
autointent data.train_path=data/intent_records/ac_robotic_new.json \
data.test_path=data/intent_records/ac_robotic_val.json \
data.force_multilabel=true \
augmentation.regex_sampling=20
autointent data.train_path=default-multiclass \
data.test_path=data/intent_records/banking77_test.json \
seed=42
Все опции в виде yaml (показаны дефолтные значения):
data:
# Path to a json file with training data. Set to "default" to use banking77 data stored within the
# autointent package.
train_path: ???
# Path to a json file with test records. Skip this option if you want to use a random subset of the
# training sample as test data.
test_path: null
# Set to true if your data is multiclass but you want to train the multilabel classifier.
force_multilabel: false
task:
# Path to a yaml configuration file that defines the optimization search space.
# Omit this to use the default configuration.
search_space_path: null
logs:
# Name of the run prepended to optimization assets dirname (generated randomly if omitted)
run_name: "awful_hippo_10-30-2024_19-42-12"
# Location where to save optimization logs that will be saved as `<logs_dir>/<run_name>_<cur_datetime>/logs.json`.
# Omit to use current working directory. <-- on Windows it is not correct
dirpath: "/home/user/AutoIntent/awful_hippo_10-30-2024_19-42-12"
dump_dir: "/home/user/AutoIntent/runs/awful_hippo_10-30-2024_19-42-12/modules_dumps"
vector_index:
# Location where to save faiss database file. Omit to use your system's default cache directory.
db_dir: null
# Specify device in torch notation
device: cpu
augmentation:
# Number of shots per intent to sample from regular expressions. This option extends sample utterance
# within multiclass intent records.
regex_sampling: 0
# Config string like "[20, 40, 20, 10]" means 20 one-label examples, 40 two-label examples, 20 three-label examples,
# 10 four-label examples. This option extends multilabel utterance records.
multilabel_generation_config: null
embedder:
# batch size for embedding computation.
batch_size: 1
# sentence length limit for embedding computation
max_length: null
#Affects the randomness
seed: 0
# String from {DEBUG,INFO,WARNING,ERROR,CRITICAL}. Omit to use ERROR by default.
hydra.job_logging.root.level: "ERROR"
Как задавать конфигурационные опции
- Вариант 1 - в коммандной строке в виде key=value. Пример:
autointent embedder.batch_size=32
- Вариант 2 - в конфигурационном yaml файле. Создайте в отдельной папке yaml файл со следующей структурой my_config.yaml:
defaults:
- optimization_config
- _self_
- override hydra/job_logging: custom
# put the configuration options you want to override here. The full structure is presented above.
# Here is just an example with the same options as for the command line variant above.
embedder:
embedder_batch_size: 32
Запускаем AutoIntent:
autointent --config-path=/path/to/config/directory --config-name=my_config
Важно:
- указывайте полный путь в опции config-path.
- не используйте tab в yaml файле.
- желательно чтобы имя файла отличалось от optimization_config.yaml, чтобы избежать warnings от hydra
Вы можете использовать комбинацию Варианта 1 и 2. Опции из коммандной строки имеют наивысший приоритет.
Вместе с пакетом предоставляются дефолтные конфиг и данные (5-shot banking77 / 20-shot dstc3).
Примеры:
- примеры входных данных: data
- примеры конфигов: example_configs
Инференс
После проведённой оптимизации найденный классификатор можно загрузить и использовать для предсказания:
autointent \
data.train_path="tests/assets/data/clinc_subset_multiclass.json" \
task.search_space_path="tests/assets/configs/multiclass.yaml"
autointent-inference \
data_path="experiments/hydra-configs/data/utterances.json" \
source_dir="tasty_auk_10-21-2024_14-24-48" \
output_path="test-infer"
Все опции инференса:
data_path Path to a json list of string containing utterances
for which you want to make a prediction.
source_dir Path to a directory with optimization assets.
output_path Path to a resulting json file with predictions made for
your utterances from data_path
log_level String from {DEBUG,INFO,WARNING,ERROR,CRITICAL}.
Omit to use ERROR by default.
Постановка задачи и формат входных данных
Решается задача классификации текста с возможностью отказа от классификации (в случае, когда текст не попадает ни в один класс).
Для решения этой задачи необходимо собрать для каждого интента словарик, подобный следующему:
{
"intent_id": 0,
"intent_name": "activate_my_card",
"regexp_full_match": [
"(alexa ){0,1}are we having a communication problem",
"(alexa ){0,1}i don't think you understand",
"what",
"I did not get what do you mean"
],
"regexp_partial_match": [
"activate my card",
]
}
Расшифровка полей:
intent_idметка класса (пока что поддерживается только консистентная разметка 0..N)intent_nameопциональный параметрregexp_full_matchграмматика, описывающая представителей данного класса (используется затем в связке сre.fullmatch(pattern, text))regexp_partial_matchграмматика, описывающая только часть представителей данного класса (используется затем в связке сre.match(pattern, text))
Если есть примеры фраз, то стоит собрать их в другой словарик:
"utterances": [
{
"text": "I tried activating my plug-in and it didn't piece of work",
"label": 0
},
{
"text": "I want to open an account for my children",
"label": 1
},
{
"text": "How old do you need to be to use the banks services?",
"label": 1
},
...
]
Если одна фраза может содержать несколько лейблов, то так:
"utterances": [
{
"text": "can you please give me the address and the postcode",
"label": [
10
]
},
{
"text": "alright thank you goodbye",
"label": [
2,
12
]
},
...
]
Если у фраза относится к разряду out-of-scope, то поле label не нужно указывать.
Multilabel
Для решения задачи multilabel классификации, формат данный другой (см. примеры в data/multi_label_data).
RegExp Node
# in development
Retrieval Node
Из входных данных извлекаются все sample_utterances со своими метками классов и помещаются в поисковый индекс. Этот индекс пригождается на шаге Scoring для модулей KNNScorer и DNNCScorer.
Результатом оптимизации этого компонента является поисковый индекс.
VectorDBRetriever
Под капотом ChromaDB.
Гиперпараметры:
- название модели би-энкодера с huggingface
- число кандидатов для ретрива
Scoring Node
Результатом оптимизации этого компонента является моделька, которая принимает на вход текст и выдает оценки принадлежности каждому классу.
KNNScorer
Обычный метод ближайших соседей. Для поиска используется индекс, добытый на шаге Retrieval.
Гиперпараметры:
- число ближайших соседей
LinearScorer
Обычная логистическая регрессия. В качестве признаков используются эмбединги из векторного индекса.
Гиперпараметры отсутствуют.
DNNCScorer
Метод, заимствованный из статьи "discriminative nearest neighbor out-of-scope detection". Алгоритм:
- Ретрив
kсоседей с помощью поискового индекса - Использование кросс-энкодера для оценки близости между текстом и
kсоседями - Выдать метку класса того соседа, который наиболее близок к текущему тексту по мнению кросс-энкодера
Гиперпараметры:
- название модели кросс-энкодера с huggingface
- число соседей
k
Prediction Node
Результатом оптимизации этого компонента является решающее правило, которое
- детектирует OOS
- выдает метку класса на основе оценок, полученных с этапа Scoring
ArgmaxPredictor
Выдает метку того класса, скор которого не меньше всех остальных. Не детектирует OOS.
ThresholdPredictor
Выдает метку того класса, скор которого не меньше всех остальных. Если скор этого класса меньше некоторого порога, то выдается OOS. Порог задается при инициализации модуля.
JinoosPredictor
Выдает метку того класса, скор которого не меньше всех остальных. Если скор этого класса меньше некоторого порога, то выдается OOS. Порог подбирается автоматически с помощью оптимизации метрики jinoos, заимствованной из статьи DNNC.
Оптимизация
Оптимизация пайплайна происходит путем независимой оптимизации каждого отдельного модуля под выбранную метрику. На текущий момент реализован метод полного перебора.
Для компоненты RegExp реализованы следующие метрики, цель которых проверить, что регулярные выражения разных интентов не конфликтуют:
regexp_partial_accuracyregexp_partial_precision
Multi-class классификация
Retrieval:
retrieval_hit_rateretrieval_mapretrieval_mrrretrieval_ndcgretrieval_precision
Scoring:
scoring_accuracyscoring_f1scoring_log_likelihoodscoring_precisionscoring_recallscoring_roc_auc
Prediction:
prediction_accuracyprediction_f1prediction_precisionprediction_recallprediction_roc_auc
Multi-label классификация
Retrieval:
- все те же метрики, но в формате макро усреднения (к названию метрики нужно добавить
_intersecting):retrieval_hit_rate_intersectingretrieval_map_intersectingretrieval_mrr_intersectingretrieval_ndcg_intersectingretrieval_precision_intersecting
- все те же метрики, но над бинарными метками, где 0 или 1 определяется тем, есть ли хотя бы одна общая метка (к названию метрики нужно добавить
_macro):retrieval_hit_rate_macroretrieval_map_macroretrieval_mrr_macroretrieval_ndcg_macroretrieval_precision_macroScoring:
- все те же, но в формате макро усреднения (под теми же названиями):
scoring_accuracyscoring_f1scoring_log_likelihoodscoring_precisionscoring_recallscoring_roc_auc
scoring_neg_ranking_lossscoring_neg_coveragescoring_hit_rate
Prediction:
- все те же, но в формате макро усреднения (под теми же названиями)
prediction_accuracyprediction_f1prediction_precisionprediction_recallprediction_roc_auc
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file test_ci_release-0.2.7.tar.gz.
File metadata
- Download URL: test_ci_release-0.2.7.tar.gz
- Upload date:
- Size: 84.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d02d002d7a2027aa242bb02a58b4a1b98290e816dfe2b8c08191a2b4c51538ad
|
|
| MD5 |
0b2d1f0fd61f7a6c097fda67f1be3c0d
|
|
| BLAKE2b-256 |
34910cb9fa7235f2871fce481be5523960092b63fc985ef50559652c267ae677
|
Provenance
The following attestation bundles were made for test_ci_release-0.2.7.tar.gz:
Publisher:
release.yaml on Samoed/test_ci_release
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
test_ci_release-0.2.7.tar.gz -
Subject digest:
d02d002d7a2027aa242bb02a58b4a1b98290e816dfe2b8c08191a2b4c51538ad - Sigstore transparency entry: 152430461
- Sigstore integration time:
-
Permalink:
Samoed/test_ci_release@a775a56d5ddc66bd9fbf3611e9214cad18f61f42 -
Branch / Tag:
refs/tags/v0.2.7 - Owner: https://github.com/Samoed
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@a775a56d5ddc66bd9fbf3611e9214cad18f61f42 -
Trigger Event:
release
-
Statement type:
File details
Details for the file test_ci_release-0.2.7-py3-none-any.whl.
File metadata
- Download URL: test_ci_release-0.2.7-py3-none-any.whl
- Upload date:
- Size: 119.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
db88190a9d2a51fcc10034a75b42105fc21efa62aff62a5e1277c450714e50cf
|
|
| MD5 |
775dc1928a606e8c4249a1b69faaa1a3
|
|
| BLAKE2b-256 |
1748c8064509069558308ed8cb8a6e47d2352743277258f51a12bed24cab92c8
|
Provenance
The following attestation bundles were made for test_ci_release-0.2.7-py3-none-any.whl:
Publisher:
release.yaml on Samoed/test_ci_release
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
test_ci_release-0.2.7-py3-none-any.whl -
Subject digest:
db88190a9d2a51fcc10034a75b42105fc21efa62aff62a5e1277c450714e50cf - Sigstore transparency entry: 152430463
- Sigstore integration time:
-
Permalink:
Samoed/test_ci_release@a775a56d5ddc66bd9fbf3611e9214cad18f61f42 -
Branch / Tag:
refs/tags/v0.2.7 - Owner: https://github.com/Samoed
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@a775a56d5ddc66bd9fbf3611e9214cad18f61f42 -
Trigger Event:
release
-
Statement type: