整合 BERT 自然語言分類器

Task Library BertNLClassifier API 與 NLClassifier 非常相似,兩者皆可將輸入文字分類到不同類別,但此 API 專為 Bert 相關模型量身打造,這類模型需要在 TFLite 模型外部進行 Wordpiece 和 Sentencepiece 符號化。

BertNLClassifier API 的主要功能

  • 接受單一字串做為輸入,使用該字串執行分類並輸出配對做為分類結果。

  • 對輸入文字執行圖形外的 WordpieceSentencepiece 符號化。

支援的 BertNLClassifier 模型

下列模型與 BertNLClassifier API 相容。

在 Java 中執行推論

步驟 1:匯入 Gradle 依附元件和其他設定

.tflite 模型檔案複製到將執行模型的 Android 模組的 assets 目錄。指定檔案不應壓縮,並將 TensorFlow Lite 程式庫新增至模組的 build.gradle 檔案

android {
    // Other settings

    // Specify tflite file should not be compressed for the app apk
    aaptOptions {
        noCompress "tflite"
    }

}

dependencies {
    // Other dependencies

    // Import the Task Text Library dependency (NNAPI is included)
    implementation 'org.tensorflow:tensorflow-lite-task-text:0.4.4'
}

步驟 2:使用 API 執行推論

// Initialization
BertNLClassifierOptions options =
    BertNLClassifierOptions.builder()
        .setBaseOptions(BaseOptions.builder().setNumThreads(4).build())
        .build();
BertNLClassifier classifier =
    BertNLClassifier.createFromFileAndOptions(context, modelFile, options);

// Run inference
List<Category> results = classifier.classify(input);

如需更多詳細資訊,請參閱 原始碼

在 Swift 中執行推論

步驟 1:匯入 CocoaPods

在 Podfile 中新增 TensorFlowLiteTaskText pod

target 'MySwiftAppWithTaskAPI' do
  use_frameworks!
  pod 'TensorFlowLiteTaskText', '~> 0.4.4'
end

步驟 2:使用 API 執行推論

// Initialization
let bertNLClassifier = TFLBertNLClassifier.bertNLClassifier(
      modelPath: bertModelPath)

// Run inference
let categories = bertNLClassifier.classify(text: input)

如需更多詳細資訊,請參閱 原始碼

在 C++ 中執行推論

// Initialization
BertNLClassifierOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<BertNLClassifier> classifier = BertNLClassifier::CreateFromOptions(options).value();

// Run inference with your input, `input_text`.
std::vector<core::Category> categories = classifier->Classify(input_text);

如需更多詳細資訊,請參閱 原始碼

在 Python 中執行推論

步驟 1:安裝 pip 套件

pip install tflite-support

步驟 2:使用模型

# Imports
from tflite_support.task import text

# Initialization
classifier = text.BertNLClassifier.create_from_file(model_path)

# Run inference
text_classification_result = classifier.classify(text)

如需設定 BertNLClassifier 的更多選項,請參閱原始碼

範例結果

以下是使用 Model Maker 的 MobileBert 模型對電影評論進行分類的範例結果。

輸入:「it's a charming and often affecting journey」

輸出

category[0]: 'negative' : '0.00006'
category[1]: 'positive' : '0.99994'

使用您自己的模型和測試資料試用適用於 BertNLClassifier 的簡易 CLI 示範工具

模型相容性需求

BetNLClassifier API 預期使用具備強制性 TFLite 模型中繼資料的 TFLite 模型。

中繼資料應符合下列需求

  • 適用於 Wordpiece/Sentencepiece Tokenizer 的 input_process_units

  • 3 個輸入張量,名稱分別為「ids」、「mask」和「segment_ids」,做為 tokenizer 的輸出

  • 1 個 float32 類型的輸出張量,可選擇附加標籤檔案。如果附加標籤檔案,該檔案應為純文字檔,每行一個標籤,且標籤數量應與模型輸出的類別數量相符。