整合音訊分類器

音訊分類是機器學習中常見的用例,用於分類聲音類型。例如,它可以透過鳥鳴聲辨識鳥類物種。

Task Library AudioClassifier API 可用於將您的自訂音訊分類器或預先訓練的分類器部署到您的行動應用程式中。

AudioClassifier API 的主要功能

  • 輸入音訊處理,例如將 PCM 16 位元編碼轉換為 PCM 浮點編碼,以及音訊環形緩衝區的操作。

  • 標籤地圖語言環境。

  • 支援多頭分類模型。

  • 同時支援單標籤和多標籤分類。

  • 分數閾值以篩選結果。

  • 前 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 (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);

請參閱 原始碼和 javadoc,以取得更多配置 AudioClassifier 的選項。

在 iOS 中執行推論

步驟 1:安裝依賴項

Task Library 支援使用 CocoaPods 安裝。請確保您的系統上已安裝 CocoaPods。請參閱 CocoaPods 安裝指南以取得說明。

請參閱 CocoaPods 指南,以取得將 Pod 新增至 Xcode 專案的詳細資訊。

在 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 Metadata Writer API 建立音訊分類器中繼資料的範例。

相容的音訊分類器模型應符合以下要求

  • 輸入音訊張量 (kTfLiteFloat32)

    • 大小為 [batch x samples] 的音訊片段。
    • 不支援批次推論 (batch 必須為 1)。
    • 對於多聲道模型,聲道需要交錯。
  • 輸出分數張量 (kTfLiteFloat32)

    • 包含 N 個類別數量的 [1 x N] 陣列。
    • 選用 (但建議) 標籤地圖作為類型為 TENSOR_AXIS_LABELS 的 AssociatedFile,每行包含一個標籤。第一個此類 AssociatedFile(如果有的話)用於填寫結果的 label 欄位(在 C++ 中命名為 class_name)。display_name 欄位從 AssociatedFile(如果有的話)填寫,其語言環境與建立時使用的 AudioClassifierOptionsdisplay_names_locale 欄位 ("en" 預設值,即英文) 相符。如果這些都不可用,則只會填寫結果的 index 欄位。