音声分類器を統合する

音声分類は、音の種類を分類する ML の一般的なユースケースです。たとえば、鳥の鳴き声から鳥の種類を特定できます。

Task Library AudioClassifier API を使用して、カスタム音声分類子または事前トレーニング済みの音声分類子をモバイルアプリにデプロイできます。

AudioClassifier API の主な機能

  • 入力音声処理(PCM 16 ビット エンコードから PCM Float エンコードへの変換、音声リングバッファの操作など)。

  • ラベルマップの言語 / 地域。

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

  • シングルラベル分類とマルチラベル分類の両方をサポートします。

  • 結果をフィルタするスコアのしきい値。

  • 上位 k 個の分類結果。

  • ラベルの許可リストと拒否リスト。

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

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

Java で推論を実行する

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

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

.tflite モデルファイルを、モデルが実行される Android モジュールの assets ディレクトリにコピーします。ファイルを圧縮しないように指定し、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
    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 プロジェクトに Pod を追加する方法について詳しくは、CocoaPods ガイドをご覧ください。

Podfile に TensorFlowLiteTaskAudio Pod を追加します。

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

推論に使用する .tflite モデルがアプリバンドルに含まれていることを確認します。

ステップ 2: モデルを使用する

Swift

// 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)
        }
    }
}

Objective-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: tflite-support pip パッケージをインストールすると、PortAudio が自動的にインストールされます。

ステップ 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 メタデータ ライター API を使用して音声分類子のメタデータを作成する例をご覧ください。

互換性のある音声分類モデルは、次の要件を満たしている必要があります。

  • 入力音声テンソル(kTfLiteFloat32)

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

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