オーディオ分類は、機械学習を使用してサウンド タイプを分類する一般的なユース ケースです。たとえば、鳴き声で鳥の種類を識別できます。
タスク ライブラリのAudioClassifier
API を使用して、カスタム オーディオ分類子または事前トレーニング済みのオーディオ分類子をモバイル アプリにデプロイできます。
AudioClassifier API の主な機能
入力オーディオ処理。たとえば、PCM 16 ビット エンコーディングを PCM Float エンコーディングに変換し、オーディオ リング バッファを操作します。
ラベル マップ ロケール。
マルチヘッド分類モデルのサポート。
シングルラベル分類とマルチラベル分類の両方をサポートします。
結果をフィルタリングするためのスコアしきい値。
上位 k 分類の結果。
許可リストと拒否リストにラベルを付けます。
サポートされている音声分類モデル
以下のモデルは、 AudioClassifier
API との互換性が保証されています。
音声分類用に TensorFlow Lite Model Makerによって作成されたモデル。
モデルの互換性要件を満たすカスタム モデル。
Java で推論を実行する
Android アプリでAudioClassifier
を使用する例については、 Audio Classification リファレンス アプリを参照してください。
ステップ 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 (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 インストール ガイドを参照してください。
Pod を Xcode プロジェクトに追加する方法の詳細については、 CocoaPods ガイドを参照してください。
TensorFlowLiteTaskAudio
に TensorFlowLiteTaskAudio ポッドを追加します。
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:
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 Model Metadataを持つ 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
フィールドは、作成時に使用されたAudioClassifierOptions
のdisplay_names_locale
フィールド (デフォルトでは "en"、つまり英語) と一致するロケールを持つ AssociatedFile (存在する場合) から入力されます。これらのいずれも使用できない場合は、結果のindex
フィールドのみが入力されます。
-