История страницы
...
Train a classification model Version 1 (python)
ГруппаGroup "Robin AI", подгруппа "Машинное обучениеsubgroup "Classifier (Robin)".
Описание
Данное действие обучает модель классификации текста. Задача классификации - определение типа объекта из двух или более существующих классов. В зависимости от задачи классификации подбираются подходящие типы классификаторов. Используется совместно с действием "Классифицировать текст".
Description
This action trains a text classification model. The classification task is to determine the object type from two or more existing classes. Depending on the classification task, suitable classifier types are selected. It is used together with the "Classify text" action.
More details on classification methods can be found here: Более подробно о методах классификации можно посмотреть здесь: Обзор методов классификации в машинном обучении с помощью Scikit-Learn (tproger.ru)
Параметры действия
...
Action parameters
Input parameters
- The path to the source folder - the path to the folder with data for training the classification model. Inside the folder there are subfolders with classes whose names are the name of the class. Inside each subfolder there should be .txt files with different texts that correspond to the class. The text formats are created by the User.
- Path to the resulting folder - path to the folder where the trained classification model will be saved. In the specified folder 2 files should be created
- Данные для обучения - путь к папке с данными для обучения модели классификации. Внутри папки содержатся подпапки с классами, названия которых – это название класса. Внутри каждой подпапки должны быть файлы формата .txt. с различными текстами, которые соответствуют классу. Форматы текстов создаются Пользователем.
- Папка с результатом - путь к папке, в которую будет сохранена обученная модель классификации. В указанной папке должно быть создано 2 файла: machine_model.pkl – модель машинного обучения, и - machine learning model, and tfidf_model.pk – сохранение словаря, токены - saving dictionary, tokens.
- Method - the method that will be used to train the classification model. Methods are based on different classification algorithms. The method is selected by the User. The following methods can be used to train the classification model:
Метод - метод, который будет использоваться для обучения модели классификации. методы базируются на различных алгоритмах классификации. Метод выбирает Пользователь. Для обучения модели классификации могут быть использованы следующие методы:- Выбрать наиболее подходящий – Choose the most suitable
- SVC - метод опорных векторов support vector method
- RandomForest - decision tree classifierRandomForest - классификатор дерева решений
- GradientBoosting
- AdaBoost
- nTree - классификатор дерева решенийdecision tree classifier
- KNeighboors - метод к-ближайших соседейk-nearest neighbor method
- Naive Bayes - наивный байесовский метод
- Перезаписать- если значение параметра "true", и в папке с результатом уже существует файл с таким же именем и расширением, то он будет перезаписан. Если значение параметра"false", файл перезаписан не будет, и действие выдаст ошибку. Файлы machine_model.pcl and tiff_model.pk должны быть уникальны в указанной папке.
- naive Bayesian method
- Overwrite - if the value of the parameter is "true" and a file with the same name and extension already exists in the folder with the result, it will be overwritten. If the value is "false", the file will not be overwritten and the action will generate an error. The files machine_model.pcl and tiff_model.pk must be unique in the specified folder.
- Custom Stop Words - path to a txt file that contains stop words that will not be considered when training the classification model. Each stop word should be written on a new line. Words that carry little meaning for classification, but are frequently encountered, e.g., in letters:
- Good morning!
- Hello!
- Sincerely
- Доброе утро!
- Добрый день!
- С уважением,
- tel:
- email:
- Словосочетания - путь к txt-файлу, содержащему словосочетания, которые при обучении модели важно не разделять на отдельные слова для сохранения смысла всей фразы. Каждое словосочетание должно быть записано на новой строке. Словосочетания нужны для указания важности фразы целиком, без разделения по словам. Например: юридическое лицо, операция по чеку, чек по операции, срочный вопрос, группа компаний, стратегия развития.
Выходные параметры
- Результат - результат показывает процент точности обученной модели, полученный путем сравнения тестовой и тренировочной выборки в процентном соотношении.
Настройки
- Word combinations - the path to a txt file containing word combinations, which when training the model it is important not to split into separate words to preserve the meaning of the whole phrase. Each phrase should be written on a new line. Word combinations are needed to indicate the importance of the phrase as a whole, without dividing it by words. For example: legal entity, check transaction, check transaction, urgent matter, group of companies, development strategy.
Output parameters
- Result - the result shows the percentage of accuracy of the trained model obtained by comparing the test and training sample as a percentage.
Settings
Property | Description | Type | Filling example | Mandatory field |
---|---|---|---|---|
Parameters | ||||
The path to the source folder | The path to the data folder for training the classification model. Inside the folder there are subfolders whose names are the name of the class. Inside each subfolder there should be txt files with various texts that correspond to the class |
Свойство
Описание
Тип данных
Обязательное
. | Robin.FolderPath | C:\ |
doc\ |
img |
Да
Yes | |||
Path to the resulting folder | The path to the folder where the trained classification model will be saved. | Robin.FolderPath | C:\ |
doc\ |
img |
Yes |
Method | The method that will be used to train the classification model. The default value is RandomForest. | Robin.String |
Перезаписать
Yes | ||
Overwrite | If the value is «true», and a file with the same name and extension already exists in the folder with the result, then it will be overwritten. If «false», the file will not be overwritten, and the action will return an error. | Robin.Boolean |
true |
Стоп-слова
No | |
Custom Stop Words | The path to the txt file that contains stop words that will not be taken into account when training the classification model. Each stop word must be written on a new line |
. | Robin.FilePath |
No | |
Word combination | The path to the txt file containing phrases, which, when training the model, it is important not to divide into separate words in order to preserve the meaning of the entire phrase. Each phrase must be written on a new line |
. | Robin.FilePath |
No | ||||
Results | ||||
---|---|---|---|---|
Result | The percentage of accuracy of the trained model |
. | Robin.Numeric |
Особые условия использования
Special conditions of use
In the list of training methods of the parameter "Method", when changing the studio language to English, the name of the method "Choose the most suitable" is changed to В списке методов обучения параметра "Метод" при смене языка студии на английский название метода "Выбрать наиболее подходящий" сменяется на название "Choose the most suitable", остальные варианты остаются на английском.
При невыполнении условий проверки параметров робот будет выдавать следующие сообщения об ошибках:
the other options remain in English.
The robot will generate the following error messages if the parameter check conditions are not met:
Condition | Exception | Text of error messages | |||||
---|---|---|---|---|---|---|---|
Checks for "The path to the source folder" parameter | |||||||
If the permissible length is exceeded in the path name | ValidationError | Path name length limit exceeded | |||||
Условие | Исключение | Текст сообщений об ошибках | |||||
Проверки для параметра "Путь к исходной папке" | Если в имени пути превышена допустимая длина | ValidationError | Превышено ограничение на длину имени пути "{folder_path}" | Если в имени пути используются недопустимые символы | |||
If invalid characters are used in the path name | ValidationError | Invalid characters in the path name | ValidationError | Недопустимые символы в имени пути "{folder_path}" | |||
Если директория не найденаIf the directory is not found | DirectoryNotFound | Директория The directory "{folder_path}" не найденаЕсли путь не является директориейwas not found | |||||
If the path is not a directory | DirectoryNotFound | Ресурс The resource "{folder_path}" не является директориейis not a directory | |||||
If the folder cannot be accessed | DirectoryNotAvailable | Read access error to | Если к папке нет доступа | DirectoryNotAvailable | Ошибка доступа к "{folder_path}" для чтения | Проверки для параметра "Путь к папке с результатом" | |
Checks for "Path to the resulting folder" parameter | |||||||
If the permissible length is exceeded in the path name | ValidationError | The length limit for the path name | Если в имени пути превышена допустимая длина | ValidationError | Превышено ограничение на длину имени пути "{folder_path}" has been exceeded | ||
If invalid characters are used in the path name | ValidationError | Invalid characters in the path name | Если в имени пути используются недопустимые символы | ValidationError | Недопустимые символы в имени пути "{folder_path}" | ||
Если директория не найденаIf the directory is not found | DirectoryNotFound | Директория The directory "{folder_path}" не найденаЕсли путь не является директориейwas not found | |||||
If the path is not a directory | DirectoryNotFound | Ресурс The resource "{folder_path}" не является директориейis not a directory | |||||
If the folder does not have accessЕсли у папки нет доступа | DirectoryNotAvailable | Ошибка доступа к Error accessing "{folder_path}" для записиfor a record | |||||
Check for the file | Проверка для файлаmachine_model.pkl, | который будет сохранен в "Путь к папке с результатом"which will be saved in the "Path to the resulting folder" | |||||
If the file already exists and "Overwrite" is not selected | FileAlreadyExists | The file at path | Если файл уже существует и не выбран параметр "Перезаписать" | FileAlreadyExists | Файл по пути: {result_file_path} уже существуетalready exists | ||
Check for the file | tfidf_model.pk, | который будет сохранен в "Путь к папке с результатом"which will be saved in the "Path to the resulting folder" | |||||
If the file already exists and "Overwrite" is not selected | FileAlreadyExists | The file at path | Если файл уже существует и не выбран параметр "Перезаписать" | FileAlreadyExists | Файл по пути: {result_file_path} уже существуетalready exists | ||
Check for the "Custom Stop Words" parameter | |||||||
If the permissible length is exceeded in the path name | ValidationError | Path name length limit exceeded | Проверка для параметра "Пользовательские стоп-слова" | Если в имени пути превышена допустимая длина | ValidationError | Превышено ограничение на длину имени пути "{folder_path}" | |
If invalid characters are used in the path name | ValidationError | Invalid characters in the path name | Если в имени пути используются недопустимые символы | ValidationError | Недопустимые символы в имени пути "{folder_path}" | ||
Если файл не найденIf the file is not found | FileNotFound | Файл The file "{file_path}" не найденЕсли путь не является файломwas not found | |||||
If the path is not a file | FileNotFound | Ресурс The resource "{folder_path}" не является файломis not a file | |||||
If the file does not have access | FileNotAvailable | Read access error to | Если у файла нет доступа | FileNotAvailable | Ошибка доступа к "{folder_path}" для чтенияОшибка чтения файла, например неправильная кодировка | ||
Error reading a file, e.g. wrong encoding | ValidationError | Ошибка чтения Error reading .txt файла по пути file at path {filepath}: {ex} | |||||
У входного файла расширение не The input file does not have a .txt extension | ValidationError | Файл по пути The file at path {list_words_path} имеет неверное расширение. Допустимые значенияhas an invalid extension. Valid values: .txt | |||||
Check for the "Word combinations" parameter | |||||||
If the permissible length is exceeded in the path name | ValidationError | The length limit for the path name | Проверка для параметра "Словосочетания" | Если в имени пути превышена допустимая длина | ValidationError | Превышено ограничение на длину имени пути "{folder_path}" has been exceeded | |
If invalid characters are used in the path name | ValidationError | Invalid characters in the path name | Если в имени пути используются недопустимые символы | ValidationError | Недопустимые символы в имени пути "{folder_path}" | ||
Если файл не найденIf the file is not found | FileNotFound | Файл The file "{file_path}" не найденЕсли путь не является файломwas not found | |||||
If the path is not a file | FileNotFound | Ресурс The resource "{folder_path}" не является файломis not a file | |||||
If the file does not have access | FileNotAvailable | Read access error to | Если у файла нет доступа | FileNotAvailable | Ошибка доступа к "{folder_path}" для чтенияОшибка чтения файла, например неправильная кодировка | ||
Error reading a file, e.g. wrong encoding | ValidationError | Ошибка чтения Error reading .txt файла по пути file at path {filepath}: {ex} | |||||
У входного файла расширение не The input file does not have a .txt extension | ValidationError | Файл по пути The file at {list_words_path} имеет неверное расширение. Допустимые значения: .txt | |||||
Если после прохода по папкам и очистки текстов нет ни одного текста для обучения | ValidationError | Ошибка входных данных: нет подходящих данных или данные пустые |
Примеры работы действия
1. Все параметры настроены верно:
"Данные для обучения" - Папка с результатом с необходимой структурой данных,
"Папка с результатом" - существующая папка.
Установить действие группы Robin AI «Обучить модель классификации» на рабочую область;
Корректно настроить параметры действия;
Запустить робота.
Результат: Робот сохранит обученную модель в указанной папке,
2. Указаны неверные пути в:
"Данные для обучения";
"Папка с результатом";
"Стоп-слова";
"Словосочетания".
Установить действие группы Robin AI «Обучить модель классификации» на рабочую область;
Корректно настроить параметры действия;
Запустить робота.
Результат: Робот выдаст ошибку, связанную с несуществующим адресом папки/файла.
3. Указаны неверные форматы файлов в:
"Стоп-слова";
"Словосочетания".
Установить действие группы Robin AI «Обучить модель классификации» на рабочую область;
Корректно настроить параметры действия;
Запустить робота.
Результат: Робот вернет ошибку, так как не может прочитать файлы.
4. Обученная модель (файлы) уже существует в указанном пути "Папка с результатом", но выключено "Перезаписать":
Установить действие группы Robin AI «Обучить модель классификации» на рабочую область;
Корректно настроить параметры действия. Не включать "Перезаписать";
Запустить робота.
Результат: Робот выдаст ошибку, так как не может записать файлы.
5. В папке "Данные для обучения" нет файлов для обучения:
Установить действие группы Robin AI «Обучить модель классификации» на рабочую область;
Корректно настроить параметры действия.
Запустить робота.
Результат: Робот выдаст ошибку.
Пример использования
Задача
Обучить модель классификации.
Решение
Воспользоваться действием "Обучить модель классификации".
Реализация
1.Для задания параметров модели обучения Пользователю необходимо создать данные для обучения:
данные для обучения - дерево объектов, состоящее из двух папок:
Исходная папка:
в ней классы:
В каждой папке папка с классом:
Подготовить словосочетания.
txt-файл, содержащий словосочетания, которые при обучении модели важно не разделять на отдельные слова для сохранения смысла всей фразы. Каждое словосочетание должно быть записано на новой строке, указывать фразы надо целиком, без разделения по словам, например: операции по чеку
Подготовить стоп-слова.
txt-файл, который содержит стоп-слова, которые не будут учитываться при обучении модели классификации. Каждое стоп-слово должно быть записано на новой строке, например:
has an invalid extension. Valid values: .txt | ||
If after going through the folders and clearing the texts, there is no text to study | ValidationError | Input data error: no suitable data or empty data |
Examples of how the action works
1. All parameters are set correctly:
"The path to the source folder" - Result folder with the required data structure,
"Path to the resulting folder" - existing folder.
Set the Robin AI group action "Train classification model" to the workspace;
Correctly set the action parameters;
Launch the robot.
Result: The robot will save the trained model in the specified folder.
2. The wrong paths in:
"The path to the source file";
"Path to the resulting folder";
"Custom Stop Words";
"Word combinations".
Set the Robin AI group action "Train classification model" to the workspace;
Correctly configure the action parameters;
Launch the robot.
Result: The robot will generate an error related to a non-existent folder/file address.
3. Incorrect file formats are specified in:
"Custom Stop Words";
"Word combinations".
Set the Robin AI group action "Train classification model" to the workspace;
Correctly configure the action parameters;
Launch the robot.
Result: The robot will return an error because it cannot read the files.
4. The trained model (files) already exists in the specified path "Path to the resulting folder", but "Overwrite" is turned off:
Set the Robin AI group action "Train classification model" to the workspace;
Correctly set the action parameters. Do not include "Overwrite";
Launch the robot.
Result: The robot will give an error because it cannot write the files.
5. There are no files for training in the "Training data" folder:
Set the Robin AI group action "Train classification model" to workspace;
Correctly configure the action parameters.
Launch the robot.
Result: The robot will generate an error.
Example of use
Task
Train the classification model.
Solution
Use the "Train a classification model" action.
Implementation
1. To set the parameters of the training model, the User needs to create the training data:
training data - a tree of objects consisting of two folders:
Source folder:
classes in it:
Each folder has a folder with a class in it:
Prepare word combinations.
txt-file containing word combinations, which during model training it is important not to divide into separate words in order to preserve the meaning of the whole phrase. Each word combination should be written on a new line, phrases should be specified as a whole, without dividing by words, for example: operations by receipt.
Prepare stop words.
txt-file that contains stop words that will not be considered when training the classification model. Each stop word should be written on a new line, for example:
- Good morning!
- Hello!
- Sincerely
- Доброе утро!
- Добрый день!
- С уважением,
- tel:
- email:
2. Перенести на рабочую область действие "Обучить модель классификации"Transfer the "Train classification model" action to the workspace.
3. Настроить параметры действия " Обучить модель классификации"Set the parameters of the "Train classification model" action.
4. . Нажать на кнопку "Старт" в верхней панели.
Результат
Click on the "Start" button in the top panel.
Result
The program robot completed successfullyПрограммный робот отработал успешно.
...