オーディオ分類器を統合する

音声分類は、音声の種類を分類するための機械学習の一般的な使用例です。たとえば、鳴き声によって鳥の種類を識別できます。

タスク ライブラリAudioClassifier API を使用して、カスタム オーディオ分類子または事前トレーニングされたオーディオ分類子をモバイル アプリにデプロイできます。

AudioClassifier API の主な機能

  • 入力オーディオ処理。たとえば、PCM 16 ビット エンコーディングから PCM Float エンコーディングへの変換やオーディオ リング バッファの操作。

  • ラベルマップのロケール。

  • マルチヘッド分類モデルをサポートします。

  • 単一ラベル分類と複数ラベル分類の両方をサポートします。

  • 結果をフィルタリングするためのスコアしきい値。

  • Top-k 分類結果。

  • ホワイトリストと拒否リストにラベルを付けます。

サポートされている音声分類器モデル

以下のモデルはAudioClassifier API との互換性が保証されています。

Javaで推論を実行する

Android アプリでAudioClassifierを使用する例については、音声分類リファレンス アプリを参照してください。

ステップ 1: Gradle の依存関係とその他の設定をインポートする

.tfliteモデル ファイルを、モデルが実行される Android モジュールのアセット ディレクトリにコピーします。ファイルを圧縮しないように指定し、TensorFlow Lite ライブラリをモジュールのbuild.gradleファイルに追加します。

android {
    // Other settings

    // Specify that the tflite file should not be compressed when building the APK package.
    aaptOptions {
        noCompress "tflite"
    }
}

dependencies {
    // Other dependencies

    // Import the Audio Task Library dependency (NNAPI is included)
    implementation 'org.tensorflow:tensorflow-lite-task-audio:0.4.4'
    // Import the GPU delegate plugin Library for GPU inference
    implementation 'org.tensorflow:tensorflow-lite-gpu-delegate-plugin:0.4.4'
}

ステップ 2: モデルの使用

// Initialization
AudioClassifierOptions options =
    AudioClassifierOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setMaxResults(1)
        .build();
AudioClassifier classifier =
    AudioClassifier.createFromFileAndOptions(context, modelFile, options);

// Start recording
AudioRecord record = classifier.createAudioRecord();
record.startRecording();

// Load latest audio samples
TensorAudio audioTensor = classifier.createInputTensorAudio();
audioTensor.load(record);

// Run inference
List<Classifications> results = audioClassifier.classify(audioTensor);

AudioClassifier構成するためのその他のオプションについては、ソース コードと javadocを参照してください。

iOS で推論を実行する

ステップ 1: 依存関係をインストールする

タスク ライブラリは、CocoaPods を使用したインストールをサポートしています。 CocoaPods がシステムにインストールされていることを確認してください。手順については、 CocoaPods インストール ガイドを参照してください。

Xcode プロジェクトへのポッドの追加の詳細については、 CocoaPods ガイドを参照してください。

TensorFlowLiteTaskAudioポッドを Podfile に追加します。

target 'MyAppWithTaskAPI' do
  use_frameworks!
  pod 'TensorFlowLiteTaskAudio'
end

推論に使用する.tfliteモデルがアプリ バンドルに存在することを確認してください。

ステップ 2: モデルの使用

迅速

// Imports
import TensorFlowLiteTaskAudio
import AVFoundation

// Initialization
guard let modelPath = Bundle.main.path(forResource: "sound_classification",
                                            ofType: "tflite") else { return }

let options = AudioClassifierOptions(modelPath: modelPath)

// Configure any additional options:
// options.classificationOptions.maxResults = 3

let classifier = try AudioClassifier.classifier(options: options)

// Create Audio Tensor to hold the input audio samples which are to be classified.
// Created Audio Tensor has audio format matching the requirements of the audio classifier.
// For more details, please see:
// https://github.com/tensorflow/tflite-support/blob/master/tensorflow_lite_support/ios/task/audio/core/audio_tensor/sources/TFLAudioTensor.h
let audioTensor = classifier.createInputAudioTensor()

// Create Audio Record to record the incoming audio samples from the on-device microphone.
// Created Audio Record has audio format matching the requirements of the audio classifier.
// For more details, please see:
https://github.com/tensorflow/tflite-support/blob/master/tensorflow_lite_support/ios/task/audio/core/audio_record/sources/TFLAudioRecord.h
let audioRecord = try classifier.createAudioRecord()

// Request record permissions from AVAudioSession before invoking audioRecord.startRecording().
AVAudioSession.sharedInstance().requestRecordPermission { granted in
    if granted {
        DispatchQueue.main.async {
            // Start recording the incoming audio samples from the on-device microphone.
            try audioRecord.startRecording()

            // Load the samples currently held by the audio record buffer into the audio tensor.
            try audioTensor.load(audioRecord: audioRecord)

            // Run inference
            let classificationResult = try classifier.classify(audioTensor: audioTensor)
        }
    }
}

目標 C

// Imports
#import <TensorFlowLiteTaskAudio/TensorFlowLiteTaskAudio.h>
#import <AVFoundation/AVFoundation.h>

// Initialization
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"sound_classification" ofType:@"tflite"];

TFLAudioClassifierOptions *options =
    [[TFLAudioClassifierOptions alloc] initWithModelPath:modelPath];

// Configure any additional options:
// options.classificationOptions.maxResults = 3;

TFLAudioClassifier *classifier = [TFLAudioClassifier audioClassifierWithOptions:options
                                                                          error:nil];

// Create Audio Tensor to hold the input audio samples which are to be classified.
// Created Audio Tensor has audio format matching the requirements of the audio classifier.
// For more details, please see:
// https://github.com/tensorflow/tflite-support/blob/master/tensorflow_lite_support/ios/task/audio/core/audio_tensor/sources/TFLAudioTensor.h
TFLAudioTensor *audioTensor = [classifier createInputAudioTensor];

// Create Audio Record to record the incoming audio samples from the on-device microphone.
// Created Audio Record has audio format matching the requirements of the audio classifier.
// For more details, please see:
https://github.com/tensorflow/tflite-support/blob/master/tensorflow_lite_support/ios/task/audio/core/audio_record/sources/TFLAudioRecord.h
TFLAudioRecord *audioRecord = [classifier createAudioRecordWithError:nil];

// Request record permissions from AVAudioSession before invoking -[TFLAudioRecord startRecordingWithError:].
[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
    if (granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // Start recording the incoming audio samples from the on-device microphone.
            [audioRecord startRecordingWithError:nil];

            // Load the samples currently held by the audio record buffer into the audio tensor.
            [audioTensor loadAudioRecord:audioRecord withError:nil];

            // Run inference
            TFLClassificationResult *classificationResult =
                [classifier classifyWithAudioTensor:audioTensor error:nil];

        });
    }
}];

TFLAudioClassifierを構成するためのその他のオプションについては、ソース コードを参照してください。

Python で推論を実行する

ステップ 1: pip パッケージをインストールする

pip install tflite-support
  • Linux: sudo apt-get update && apt-get install libportaudio2を実行します。
  • Mac および Windows: PortAudio は、 tflite-support pip パッケージをインストールするときに自動的にインストールされます。

ステップ 2: モデルの使用

# Imports
from tflite_support.task import audio
from tflite_support.task import core
from tflite_support.task import processor

# Initialization
base_options = core.BaseOptions(file_name=model_path)
classification_options = processor.ClassificationOptions(max_results=2)
options = audio.AudioClassifierOptions(base_options=base_options, classification_options=classification_options)
classifier = audio.AudioClassifier.create_from_options(options)

# Alternatively, you can create an audio classifier in the following manner:
# classifier = audio.AudioClassifier.create_from_file(model_path)

# Run inference
audio_file = audio.TensorAudio.create_from_wav_file(audio_path, classifier.required_input_buffer_size)
audio_result = classifier.classify(audio_file)

AudioClassifier構成するためのその他のオプションについては、ソース コードを参照してください。

C++ で推論を実行する

// Initialization
AudioClassifierOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<AudioClassifier> audio_classifier = AudioClassifier::CreateFromOptions(options).value();

// Create input audio buffer from your `audio_data` and `audio_format`.
// See more information here: tensorflow_lite_support/cc/task/audio/core/audio_buffer.h
int input_size = audio_classifier->GetRequiredInputBufferSize();
const std::unique_ptr<AudioBuffer> audio_buffer =
    AudioBuffer::Create(audio_data, input_size, audio_format).value();

// Run inference
const ClassificationResult result = audio_classifier->Classify(*audio_buffer).value();

AudioClassifier構成するためのその他のオプションについては、ソース コードを参照してください。

モデルの互換性要件

AudioClassifier API は、必須のTFLite モデル メタデータを持つ TFLite モデルを想定しています。 TensorFlow Lite Metadata Writer APIを使用してオーディオ分類器のメタデータを作成する例を参照してください。

互換性のあるオーディオ分類器モデルは、次の要件を満たす必要があります。

  • 入力オーディオ テンソル (kTfLiteFloat32)

    • サイズ[batch x samples]のオーディオ クリップ。
    • バッチ推論はサポートされていません ( batch 1 である必要があります)。
    • マルチチャネル モデルの場合、チャネルをインターリーブする必要があります。
  • 出力スコア テンソル (kTfLiteFloat32)

    • [1 x N]配列Nはクラス番号を表します。
    • オプションの (ただし推奨される) ラベル マップは、タイプ TENSOR_AXIS_LABELS の AssociatedFile-s として、1 行に 1 つのラベルを含みます。最初の AssociatedFile (存在する場合) は、結果のlabelフィールド (C++ ではclass_nameという名前) を埋めるために使用されます。 display_nameフィールドには、ロケールが作成時に使用されるAudioClassifierOptionsdisplay_names_localeフィールドと一致する AssociatedFile (存在する場合) から入力されます (デフォルトでは「en」、つまり英語)。これらのいずれも使用できない場合は、結果のindexフィールドのみが入力されます。