Integracja klasyfikatorów dźwięku

Klasyfikacja dźwięku to typowy przypadek użycia uczenia maszynowego do klasyfikowania różnych typów dźwięków. Potrafi na przykład rozpoznawać gatunki ptaków na podstawie ich śpiewu.

Za pomocą interfejsu Task Library API AudioClassifier można wdrożyć niestandardową ścieżkę dźwiękową lub klasyfikatory już wytrenowane.

Najważniejsze funkcje interfejsu AudioClassifier API

  • Wejściowe przetwarzanie dźwięku, np. konwersja 16-bitowego kodowania PCM na PCM Kodowanie Floating i manipulacja buforem pierścieniowym dźwięku.

  • Język mapy etykiet.

  • Obsługa modelu klasyfikacji wielogłowej.

  • Obsługiwana jest zarówno klasyfikacja z 1 etykietą, jak i z wieloma etykietami.

  • Próg oceny do filtrowania wyników.

  • Wyniki klasyfikacji Top-K.

  • Listy dozwolonych i odrzuconych etykiet.

Obsługiwane modele klasyfikatorów audio

Te modele gwarantują zgodność z modelem AudioClassifier API.

Uruchom wnioskowanie w Javie

Zobacz Aplikacja referencyjna dotycząca klasyfikacji dźwięku dla przykładu użycia funkcji AudioClassifier w aplikacji na Androida.

Krok 1. Zaimportuj zależność Gradle i inne ustawienia

Skopiuj plik modelu .tflite do katalogu zasobów modułu Androida w którym będzie uruchamiany model. Określ, że plik nie powinien być skompresowany. dodaj bibliotekę TensorFlow Lite do pliku build.gradle modułu:

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'
}

Krok 2. Korzystanie z modelu

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

Zobacz kod źródłowy i javadoc , aby uzyskać więcej opcji konfigurowania AudioClassifier.

Uruchom wnioskowanie w iOS

Krok 1. Zainstaluj zależności

Biblioteka zadań obsługuje instalację za pomocą CocoaPods. Upewnij się, że CocoaPods jest zainstalowany w systemie. Zapoznaj się z Przewodnik instalacji CocoaPods .

Zapoznaj się z Przewodnik po CocoaPods dotyczący dowiesz się więcej o dodawaniu podów do projektu Xcode.

Dodaj pod plik TensorFlowLiteTaskAudio w pliku Podfile.

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

Sprawdź, czy dostępny jest model .tflite, którego będziesz używać do wnioskowania pakietu aplikacji.

Krok 2. Korzystanie z modelu

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];

        });
    }
}];

Zobacz kod źródłowy , aby uzyskać więcej opcji konfigurowania TFLAudioClassifier.

Uruchom wnioskowanie w Pythonie

Krok 1. Zainstaluj pakiet pip

pip install tflite-support
  • Linux: uruchom sudo apt-get update && apt-get install libportaudio2
  • Mac i Windows: aplikacja PortAudio jest instalowana automatycznie podczas instalowania Pakiet pip: tflite-support.

Krok 2. Korzystanie z modelu

# 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)

Zobacz kod źródłowy , aby uzyskać więcej opcji konfigurowania AudioClassifier.

Uruchom wnioskowanie w 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();

Zobacz kod źródłowy , aby uzyskać więcej opcji konfigurowania AudioClassifier.

Wymagania dotyczące zgodności z modelem

Interfejs API AudioClassifier wymaga modelu TFLite z obowiązkowym ustawieniem Metadane modelu TFLite. Zobacz przykłady tworzenia metadanych do klasyfikatorów audio za pomocą TensorFlow Lite Metadata Writer API.

Zgodne modele klasyfikatorów audio powinny spełniać te wymagania:

  • Wejściowy tensor dźwięku (kTfLiteFloat32)

    • klip audio o rozmiarze [batch x samples].
    • wnioskowanie wsadowe nie jest obsługiwane (wartość batch musi wynosić 1).
    • w przypadku modeli wielokanałowych kanały muszą być przeplatane.
  • Tensor wyniku wyjściowego (kTfLiteFloat32)

    • Tablica [1 x N] z N reprezentuje numer klasy.
    • opcjonalne (ale zalecane) etykiety map jako AssociatedFile-s z typem TENSOR_AXIS_LABELS, zawierający po jednej etykiecie na wiersz. Pierwsza taka Element AssociatedFile (jeśli istnieje) służy do wypełnienia pola label (o nazwie class_name w C++) wyników. Pole display_name jest wypełnione z elementu AssociatedFile (jeśli istnieje), którego język zgodny z Pole display_names_locale z AudioClassifierOptions wykorzystywane podczas czas utworzenia („en” – domyślnie „en”, czyli w języku angielskim). Jeśli żadna z tych opcji nie pasuje dostępne, zostanie wypełnione tylko pole index wyników.