Руководство по классификации текста для Python

Задача «Классификатор текста MediaPipe» позволяет классифицировать текст по набору определенных категорий, таких как положительные или отрицательные настроения. Категории определяются используемой вами моделью и способом обучения этой модели. Эти инструкции покажут вам, как использовать классификатор текста с Python.

Вы можете увидеть эту задачу в действии, просмотрев веб-демо . Дополнительные сведения о возможностях, моделях и параметрах конфигурации этой задачи см. в разделе Обзор .

Пример кода

В примере кода классификатора текста представлена ​​полная реализация этой задачи на Python. Этот код поможет вам протестировать эту задачу и приступить к созданию собственного приложения для классификации текста. Вы можете просматривать, запускать и редактировать пример кода классификатора текста, используя только веб-браузер.

Если вы реализуете классификатор текста для Raspberry Pi, обратитесь к примеру приложения Raspberry Pi .

Настраивать

This section describes key steps for setting up your development environment and code projects specifically to use Text Classifier. Общие сведения о настройке среды разработки для использования задач MediaPipe, включая требования к версии платформы, см. в руководстве по настройке Python .

Пакеты

Text Classifier uses the mediapipe pip package. You can install these dependencies with the following:

$ python -m pip install mediapipe

Imports

Import the following classes to access the Text Classifier task functions:

from mediapipe.tasks import python
from mediapipe.tasks.python import text

Модель

The MediaPipe Text Classifier task requires a trained model that is compatible with this task. For more information on available trained models for Text Classifier, see the task overview Models section .

Select and download a model, and then store it in a local directory:

model_path = '/absolute/path/to/text_classifier.tflite'

Specify the path of the model with the BaseOptions object model_asset_path parameter, as shown below:

base_options = BaseOptions(model_asset_path=model_path)

Create the task

The MediaPipe Text Classifier task uses the create_from_options function to set up the task. The create_from_options function accepts values for configuration options to set the classifier options. You can also initialize the task using the create_from_model_path factory function. The create_from_model_path function accepts a relative or absolute path to the trained model file. For more information on configuration options, see Configuration options .

The following code demonstrates how to build and configure this task.

base_options = python.BaseOptions(model_asset_path=model_path)
options = text.TextClassifierOptions(base_options=base_options)

with python.text.TextClassifier.create_from_options(options) as classifier:
  classification_result = classifier.classify(text)

Configuration options

This task has the following configuration options for Android apps:

Option Name Описание Диапазон значений Значение по умолчанию
display_names_locale Sets the language of labels to use for display names provided in the metadata of the task's model, if available. Default is en for English. You can add localized labels to the metadata of a custom model using the TensorFlow Lite Metadata Writer API Locale code ru
max_results Sets the optional maximum number of top-scored classification results to return. If < 0, all available results will be returned. Any positive numbers -1
score_threshold Sets the prediction score threshold that overrides the one provided in the model metadata (if any). Results below this value are rejected. Any float Не задано
category_allowlist Sets the optional list of allowed category names. If non-empty, classification results whose category name is not in this set will be filtered out. Duplicate or unknown category names are ignored. This option is mutually exclusive with category_denylist and using both results in an error. Любые струны Не задано
category_denylist Sets the optional list of category names that are not allowed. If non-empty, classification results whose category name is in this set will be filtered out. Duplicate or unknown category names are ignored. This option is mutually exclusive with category_allowlist and using both results in an error. Любые струны Не задано

Подготовьте данные

Text Classifier works with text ( str ) data. The task handles the data input preprocessing, including tokenization and tensor preprocessing.

All preprocessing is handled within the classify function. There is no need for additional preprocessing of the input text beforehand.

input_text = 'The input text to be classified.'

Запустите задачу

The Text Classifier uses the classify function to trigger inferences. For text classification, this means returning the possible categories for the input text.

The following code demonstrates how to execute the processing with the task model.

with python.text.TextClassifier.create_from_options(options) as classifier:
  classification_result = classifier.classify(text)

Handle and display results

The Text Classifier outputs a TextClassifierResult object containing a list of possible categories for the input text. The categories are defined by the the model you use, so if you want different categories, pick a different model, or retrain an existing one.

The following shows an example of the output data from this task:

TextClassificationResult:
  Classification #0 (single classification head):
    ClassificationEntry #0:
      Category #0:
        category name: "positive"
        score: 0.8904
        index: 0
      Category #1:
        category name: "negative"
        score: 0.1096
        index: 1

This result has been obtained by running the BERT-classifier on the input text: "an imperfect but overall entertaining mystery" .