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

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

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

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

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

  • הוספת תווית ללוקאל במפה.

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

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

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

  • תוצאות סיווג מובילות.

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

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

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

הרצת ההסקה ב-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 לקבלת הוראות.

כדאי לעיין מדריך CocoaPods עבור על הוספת רצפי מודעות לפרויקט Xcode.

מוסיפים את ה-Pod TensorFlowLiteTaskAudio בקובץ ה-Podfile.

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

צריך לוודא שמודל .tflite שבו משתמשים לצורך הסקת מסקנות את ה-App Bundle.

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

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

  • קלט אודיו tensor (kTfLiteFloat32)

    • קטע אודיו בגודל [batch x samples].
    • אין תמיכה בהֶקֵּשׁ מנתונים מרובים (הפונקציה batch חייבת להיות 1).
    • במודלים מרובי-ערוצים, הערוצים צריכים להיות משולבים.
  • Tensor ציון פלט (kTfLiteFloat32)

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