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

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

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

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

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

  • תווית אזור מפה.

  • תומך במודל סיווג רב ראשי.

  • תומך הן בסיווג של תווית אחת והן בסיווג רב תווית.

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

  • תוצאות הסיווג העליון-k.

  • תווית רשימת היתרים ורשימת דחייה.

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

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

הפעל הסקה ב-Java

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

שלב 1: ייבא תלות Gradle והגדרות אחרות

העתק את קובץ מודל .tflite לספריית הנכסים של מודול האנדרואיד שבו המודל יופעל. ציין שאין לדחוס את הקובץ, והוסף את ספריית 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: התקן את התלות

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

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

הוסף את הפוד TensorFlowLiteTaskAudio ב-Podfile.

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

ודא שמודל .tflite שבו תשתמש להסקת מסקנות קיים בחבילת האפליקציות שלך.

שלב 2: שימוש במודל

מָהִיר

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

מטרה ג

// 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
  • לינוקס: הפעל את sudo apt-get update && apt-get install libportaudio2
  • Mac ו-Windows: PortAudio מותקן אוטומטית בעת התקנת חבילת tflite-support pip.

שלב 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] עם N מייצג את מספר המחלקה.
    • מפות תוויות אופציונליות (אך מומלצות) כ-AssociatedFile-s עם סוג TENSOR_AXIS_LABELS, המכילות תווית אחת בכל שורה. ה-AssociatedFile הראשון כזה (אם קיים) משמש למילוי שדה label (ששמו כ- class_name ב-C++) של התוצאות. השדה display_name ממולא מה-AssociatedFile (אם קיים) שהמקום שלו תואם לשדה display_names_locale של AudioClassifierOptions המשמשים בזמן היצירה ("en" כברירת מחדל, כלומר אנגלית). אם אף אחד מאלה אינו זמין, רק שדה index של התוצאות יתמלא.