音声分類器を統合する

音声分類は、音声を分類するための機械学習の一般的なユースケースで、 サポートします。たとえば、歌で鳥の種類を特定できます。

タスク ライブラリの AudioClassifier API を使用してカスタム オーディオをデプロイ可能 モバイルアプリに取り込むことができます

AudioClassifier API の主な機能

  • 入力音声処理(例:PCM 16 ビット エンコーディングの PCM への変換 浮動小数点エンコードとオーディオ リング バッファの操作。

  • 地図の言語 / 地域にラベルを付けます。

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

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

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

  • トップ 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
    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);

詳しくは、 ソースコードと javadoc AudioClassifier を構成するその他のオプションをご覧ください。

iOS で推論を実行する

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

タスク ライブラリは、CocoaPods を使用したインストールをサポートしています。CocoaPods が Cloud Shell で がインストールされていることを確認できます。詳しくは、 CocoaPods インストール ガイド をご覧ください。

詳しくは、 CocoaPods ガイド: Xcode プロジェクトに Pod を追加する方法を詳しく説明します。

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 の場合: 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)

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