音訊分類是機器學習的常見用途,可分類聲音類型。例如,這項功能可以根據鳥類的叫聲辨識品種。
您可以使用 Task Library AudioClassifier API,將自訂或預先訓練的音訊分類器部署到行動應用程式中。
AudioClassifier API 的主要功能
輸入音訊處理,例如將 PCM 16 位元編碼轉換為 PCM Float 編碼,以及操控音訊環形緩衝區。
標記地圖語言區域。
支援多頭分類模型。
支援單一標籤和多標籤分類。
篩選結果的分數門檻。
前 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);
如要瞭解設定 AudioClassifier 的其他選項,請參閱原始碼和 Javadoc。
在 iOS 中執行推論
步驟 1:安裝依附元件
工作程式庫支援使用 CocoaPods 安裝。請確認系統已安裝 CocoaPods。如需操作說明,請參閱 CocoaPods 安裝指南。
如要瞭解如何將 Pod 新增至 Xcode 專案,請參閱 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-supportpip 套件時,系統會自動安裝 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 Metadata Writer API 為音訊分類器建立中繼資料的範例。
相容的音訊分類器模型應符合下列需求:
輸入音訊張量 (kTfLiteFloat32)
- 大小為
[batch x samples]的音訊片段。 - 不支援批次推論 (
batch必須為 1)。 - 如果是多管道模型,管道必須交錯。
- 大小為
輸出分數張量 (kTfLiteFloat32)
[1 x N]陣列,其中N代表類別編號。- 選用 (但建議使用) 標籤對應檔,以 AssociatedFile 形式提供,類型為 TENSOR_AXIS_LABELS,每行包含一個標籤。系統會使用第一個這類 AssociatedFile (如有) 填入結果的
label欄位 (在 C++ 中命名為class_name)。系統會從與建立時AudioClassifierOptions的display_names_locale欄位 (預設為「en」,即英文) 相符的 AssociatedFile 填入display_name欄位 (如有)。如果沒有任何可用的項目,系統只會填入結果的index欄位。