Klasyfikacja dźwięku to typowy przypadek użycia uczenia maszynowego do klasyfikowania typów dźwięków. Może na przykład rozpoznawać gatunki ptaków po ich śpiewie.
Interfejs AudioClassifier Task Library API umożliwia wdrażanie w aplikacji mobilnej niestandardowych lub wstępnie wytrenowanych klasyfikatorów dźwięku.
Najważniejsze funkcje interfejsu AudioClassifier API
Przetwarzanie dźwięku wejściowego, np. konwertowanie kodowania PCM 16-bitowego na kodowanie PCM Float i manipulowanie buforem pierścieniowym audio.
Etykieta lokalizacji na mapie.
Obsługa modelu klasyfikacji z wieloma głowicami.
Obsługuje klasyfikację z użyciem jednej i wielu etykiet.
Próg wyniku do filtrowania wyników.
Wyniki klasyfikacji k najlepszych wyników.
Lista dozwolonych i odrzuconych etykiet.
Obsługiwane modele klasyfikatora audio
Te modele są zgodne z AudioClassifierAPI.
Modele utworzone za pomocą TensorFlow Lite Model Maker for Audio Classification.
Wstępnie wytrenowane modele klasyfikacji zdarzeń audio w TensorFlow Hub.
modele niestandardowe, które spełniają wymagania dotyczące zgodności modeli;
Uruchamianie wnioskowania w Javie
Przykład użycia AudioClassifier w aplikacji na Androida znajdziesz w aplikacji referencyjnej do klasyfikacji dźwięku.
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ć kompresowany, i 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);
Więcej opcji konfigurowania AudioClassifier znajdziesz w kodzie źródłowym i dokumentacji Javadoc.
Uruchamianie wnioskowania na iOS
Krok 1. Zainstaluj zależności
Biblioteka zadań obsługuje instalację za pomocą CocoaPods. Upewnij się, że w systemie jest zainstalowany CocoaPods. Instrukcje znajdziesz w przewodniku instalacji CocoaPods.
Szczegółowe informacje o dodawaniu podów do projektu w Xcode znajdziesz w przewodniku po CocoaPods.
Dodaj pod TensorFlowLiteTaskAudio do pliku Podfile.
target 'MyAppWithTaskAPI' do
use_frameworks!
pod 'TensorFlowLiteTaskAudio'
end
Upewnij się, że model .tflite, którego będziesz używać do wnioskowania, znajduje się w pakiecie 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];
});
}
}];
Więcej opcji konfigurowania TFLAudioClassifier znajdziesz w kodzie źródłowym.
Uruchamianie wnioskowania w Pythonie
Krok 1. Zainstaluj pakiet pip
pip install tflite-support
- Linux: kliknij
sudo apt-get update && apt-get install libportaudio2. - Mac i Windows: PortAudio jest instalowany automatycznie podczas instalacji pakietu
tflite-supportpip.
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)
Więcej opcji konfigurowania AudioClassifier znajdziesz w kodzie źródłowym.
Uruchamianie wnioskowania 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();
Więcej opcji konfigurowania AudioClassifier znajdziesz w kodzie źródłowym.
Wymagania dotyczące zgodności modeli
Interfejs AudioClassifier API oczekuje modelu TFLite z obowiązkowymi metadanymi modelu TFLite. Zobacz przykłady tworzenia metadanych dla klasyfikatorów audio za pomocą interfejsu API do tworzenia metadanych TensorFlow Lite.
Zgodne modele klasyfikatora dźwięku powinny spełniać te wymagania:
Tensor dźwięku wejściowego (kTfLiteFloat32)
- klip audio o rozmiarze
[batch x samples]. - wnioskowanie zbiorcze nie jest obsługiwane (
batchmusi mieć wartość 1). - W przypadku modeli wielokanałowych kanały muszą być przeplatane.
- klip audio o rozmiarze
Tensor wyniku wyjściowego (kTfLiteFloat32)
[1 x N]tablica zNreprezentuje numer klasy.- opcjonalne (ale zalecane) mapy etykiet jako AssociatedFile-s z typem TENSOR_AXIS_LABELS, zawierające po 1 etykiecie w wierszu; Pierwszy taki element AssociatedFile (jeśli występuje) jest używany do wypełnienia pola
label(w C++ oznaczanego jakoclass_name) w wynikach. Poledisplay_namejest wypełniane na podstawie pola AssociatedFile (jeśli istnieje), którego język jest zgodny z polemdisplay_names_localeelementuAudioClassifierOptionsużytego w momencie tworzenia (domyślnie „en”, czyli angielski). Jeśli żadne z tych pól nie jest dostępne, wypełnione zostanie tylko poleindexw wynikach.