The Text Classifier task lets you classify text into a set of defined categories, such as positive or negative sentiment. The categories are determined based on the model you use and how that model was trained. These instructions show you how to use the Text Classifier in iOS apps. The code sample described in these instructions is available on GitHub.
The MediaPipe Tasks example code is a basic implementation of a Text Classifier app for iOS.
You can use the app as a starting point for your own iOS app, or refer to it when modifying an existing app. You can refer to the Text Classifier example code on GitHub.
Download the code
The following instructions show you how to create a local copy of the example code using the git command line tool.
To download the example code:
Clone the git repository using the following command:
git clone https://github.com/googlesamples/mediapipe
Optionally, configure your git instance to use sparse checkout, so you have only the files for the Text Classifier example app:
cd mediapipe git sparse-checkout init --cone git sparse-checkout set examples/text_classification/ios/
After creating a local version of the example code, you can install the MediaPipe task library, open the project using Xcode, and run the app. For instructions, see the Setup Guide for iOS.
The following files contain the crucial code for the Text Classifier example application:
- TextClassifierHelper.swift: Initializes the text classifier and handles the model selection.
- ViewController.swift: Implements the UI and formats the results.
This section describes key steps for setting up your development environment and code projects to use Text Classifier. For general information on setting up your development environment for using MediaPipe tasks, including platform version requirements, see the Setup guide for iOS.
Text Classifier uses the
MediaPipeTasksText library, which must be installed
using CocoaPods. The library is compatible with both Swift and Objective-C apps
and does not require any additional language-specific setup.
Add the MediaPipeTasksText pod in the
Podfile using the following code:
target 'MyTextClassifierApp' do
If your app includes unit test targets, refer to the Set Up Guide for
iOS for additional information on setting up
The MediaPipe Text Classifier task requires a trained model that is compatible with this task. For more information about the available trained models for Text Classifier, see the task overview Models section.
Select and download a model, and add it to your project directory using Xcode. For instructions on how to add files to your Xcode project, refer to Managing files and folders in your Xcode project.
BaseOptions.modelAssetPath property to specify the path to the model
in your app bundle. For a code example, see the next section.
Create the task
You can create the Text Classifier task by calling one of its initializers. The
TextClassifier(options:) initializer sets values for the configuration
If you don't need a Text Classifier initialized with customized configuration
options, you can use the
TextClassifier(modelPath:) initializer to create a
Text Classifier with the default options. For more information about configuration
options, see Configuration Overview.
The following code demonstrates how to build and configure this task.
let modelPath = Bundle.main.path(forResource: "model",
let options = TextClassifierOptions()
options.baseOptions.modelAssetPath = modelPath
options.scoreThreshold = 0.6
let textClassifier = try TextClassifier(options: options)
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
MPPTextClassifierOptions *options = [[MPPTextClassifierOptions alloc] init];
options.baseOptions.modelAssetPath = modelPath;
options.scoreThreshold = 0.6;
MPPTextClassifier *textClassifier =
[[MPPTextClassifier alloc] initWithOptions:options error:nil];
This task has the following configuration options for iOS apps:
|Sets the language of labels to use for display names provided in the
metadata of the task's model, if available. Default is
English. You can add localized labels to the metadata of a custom model
using the TensorFlow Lite Metadata Writer API
|Sets the optional maximum number of top-scored classification results to return. If < 0, all available results will be returned.
|Any positive numbers
|Sets the prediction score threshold that overrides the one provided in the model metadata (if any). Results below this value are rejected.
|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
categoryDenylist and using
both results in an error.
|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
categoryAllowlist and using both results in an error.
Text Classifier works with text data. The task handles the data input preprocessing, including tokenization and tensor preprocessing.
All preprocessing is handled within the
classify(text:) function. There is no
need for additional preprocessing of the input text beforehand.
let text = "The input text to be classified."
NSString *text = @"The input text to be classified.";
Run the task
To run the Text Classifier, use the
classify(text:) method. The Text Classifier
returns the possible categories for the input text.
let result = try textClassifier.classify(text: text)
MPPTextClassifierResult *result = [textClassifier classifyText:text
Note: The task blocks the current thread until it finishes running inference on the text. To avoid blocking the current thread, execute the processing in a background thread using iOS Dispatch or NSOperation frameworks.
Handle and display results
Upon running inference, the Text Classifier task returns a
object which contains the list of possible categories for the input text. The
categories are defined by 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:
Classification #0 (single classification head):
category name: "positive"
category name: "negative"
This result has been obtained by running the BERT-classifier on the input text:
"an imperfect but overall entertaining mystery".
The ViewController.swift file in the example code demonstrates how to display the detection results returned from the task.