שילוב מסווגי אודיו

סיווג אודיו הוא תרחיש נפוץ לשימוש בלמידת מכונה כדי לסווג את סוגי הצלילים. לדוגמה, היא יכולה לזהות את מיני הציפורים לפי השירים שלהן.

אפשר להשתמש ב-Task Library AudioClassifier API כדי לפרוס את מסווגי האודיו המותאמים אישית או את המסווגים שאומנו מראש באפליקציה לנייד.

התכונות העיקריות של AudioClassifier API

  • עיבוד של קלט אודיו, למשל המרה של קידוד PCM 16 ביט לקידוד PCM Float ומניפולציה של מאגר זמני של אודיו.

  • תווית של מיקום במפה

  • תמיכה במודל סיווג עם כמה ראשי סיווג.

  • תמיכה בסיווג עם תווית אחת ועם כמה תוויות.

  • סף הניקוד לסינון התוצאות.

  • תוצאות הסיווג המובילות (k).

  • רשימת ההיתרים ורשימת הישויות החסומות של התווית.

מודלים נתמכים של מסווג אודיו

המודלים הבאים תואמים בוודאות ל-API של AudioClassifier.

הסקת מסקנות ב-Java

דוגמה לשימוש ב-AudioClassifier באפליקציית Android מופיעה באפליקציית ההפניה לסיווג אודיו.

שלב 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);

אפשר לעיין בקוד המקור וב-javadoc כדי לראות עוד אפשרויות להגדרת AudioClassifier.

הפעלת הסקה ב-iOS

שלב 1: התקנת יחסי התלות

ספריית המשימות תומכת בהתקנה באמצעות CocoaPods. מוודאים ש-CocoaPods מותקן במערכת. הוראות מפורטות זמינות במדריך להתקנת CocoaPods.

פרטים על הוספת pods לפרויקט Xcode מופיעים במדריך ל-CocoaPods.

מוסיפים את ה-Pod‏ TensorFlowLiteTaskAudio ל-Podfile.

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: ‏ PortAudio מותקן אוטומטית כשמתקינים את חבילת pip‏ tflite-support.

שלב 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.

דרישות התאימות של המודל

ממשק ה-API‏ AudioClassifier מצפה לקבל מודל TFLite עם מטא-נתונים של מודל TFLite חובה. אפשר לראות דוגמאות ליצירת מטא-נתונים עבור מסווגי אודיו באמצעות TensorFlow Lite Metadata Writer API.

מודלים תואמים לסיווג אודיו צריכים לעמוד בדרישות הבאות:

  • טנסור של קלט אודיו (kTfLiteFloat32)

    • קטע אודיו בגודל [batch x samples].
    • אין תמיכה בהסקת מסקנות באצווה (הערך של batch צריך להיות 1).
    • במודלים מרובי-ערוצים, הערוצים צריכים להיות משולבים.
  • טנזור של ציון הפלט (kTfLiteFloat32)

    • [1 x N] array עם N מייצג את מספר הכיתה.
    • מיפוי תווית אופציונלי (אבל מומלץ) כ-AssociatedFile-s עם סוג TENSOR_AXIS_LABELS, שמכיל תווית אחת בכל שורה. הקובץ הראשון מסוג AssociatedFile (אם יש כזה) משמש למילוי השדה label (שנקרא class_name ב-C++‎) בתוצאות. השדה display_name מתמלא מהקובץ המשויך (אם יש כזה) שהלוקאל שלו תואם לשדה display_names_locale של AudioClassifierOptions שבו נעשה שימוש בזמן היצירה (ברירת המחדל היא en, כלומר אנגלית). אם אף אחד מהם לא זמין, רק השדה index של התוצאות יאוכלס.