Tích hợp phân loại âm thanh

Phân loại âm thanh là trường hợp sử dụng phổ biến của Machine Learning để phân loại các loại âm thanh. Ví dụ, nó có thể xác định các loài chim bằng tiếng hót của chúng.

Bạn có thể sử dụng API AudioClassifier Thư viện tác vụ để triển khai các trình phân loại âm thanh tùy chỉnh hoặc các trình phân loại âm thanh được đào tạo trước vào ứng dụng di động của bạn.

Các tính năng chính của API AudioClassifier

  • Xử lý âm thanh đầu vào, ví dụ: chuyển đổi mã hóa PCM 16 bit sang mã hóa PCM Float và thao tác với bộ đệm vòng âm thanh.

  • Dán nhãn địa điểm bản đồ.

  • Hỗ trợ mô hình phân loại nhiều đầu.

  • Hỗ trợ cả phân loại một nhãn và đa nhãn.

  • Ngưỡng điểm để lọc kết quả.

  • Kết quả phân loại Top-k.

  • Gắn nhãn danh sách cho phép và danh sách từ chối.

Các mô hình phân loại âm thanh được hỗ trợ

Các mẫu sau được đảm bảo tương thích với API AudioClassifier .

Chạy suy luận trong Java

Xem ứng dụng tham khảo Phân loại âm thanh để biết ví dụ về cách sử dụng AudioClassifier trong ứng dụng Android.

Bước 1: Nhập phần phụ thuộc Gradle và các cài đặt khác

Sao chép tệp mô hình .tflite vào thư mục nội dung của mô-đun Android nơi mô hình sẽ được chạy. Chỉ định rằng tệp sẽ không được nén và thêm thư viện TensorFlow Lite vào tệp build.gradle của mô-đun:

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

Bước 2: Sử dụng mô hình

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

Xem mã nguồn và javadoc để có thêm tùy chọn định cấu AudioClassifier .

Chạy suy luận trong iOS

Bước 1: Cài đặt các phụ thuộc

Thư viện tác vụ hỗ trợ cài đặt bằng CocoaPods. Đảm bảo rằng CocoaPods đã được cài đặt trên hệ thống của bạn. Vui lòng xem hướng dẫn cài đặt CocoaPods để được hướng dẫn.

Vui lòng xem hướng dẫn của CocoaPods để biết chi tiết về cách thêm nhóm vào dự án Xcode.

Thêm nhóm TensorFlowLiteTaskAudio vào Podfile.

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

Đảm bảo rằng mô hình .tflite bạn sẽ sử dụng để suy luận có trong gói ứng dụng của bạn.

Bước 2: Sử dụng mô hình

Nhanh

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

Mục tiêu 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];

        });
    }
}];

Xem mã nguồn để biết thêm tùy chọn cấu hình TFLAudioClassifier .

Chạy suy luận trong Python

Bước 1: Cài đặt gói pip

pip install tflite-support
  • Linux: Chạy sudo apt-get update && apt-get install libportaudio2
  • Mac và Windows: PortAudio được cài đặt tự động khi cài đặt gói pip tflite-support .

Bước 2: Sử dụng mô hình

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

Xem mã nguồn để biết thêm tùy chọn cấu hình AudioClassifier .

Chạy suy luận trong 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();

Xem mã nguồn để biết thêm tùy chọn cấu hình AudioClassifier .

Yêu cầu tương thích mô hình

API AudioClassifier yêu cầu mô hình TFLite với Siêu dữ liệu mô hình TFLite bắt buộc. Xem ví dụ về cách tạo siêu dữ liệu cho bộ phân loại âm thanh bằng API Trình ghi siêu dữ liệu TensorFlow Lite .

Các mô hình phân loại âm thanh tương thích phải đáp ứng các yêu cầu sau:

  • Tenor âm thanh đầu vào (kTfLiteFloat32)

    • clip âm thanh có kích thước [batch x samples] .
    • suy luận hàng loạt không được hỗ trợ ( batch buộc phải là 1).
    • đối với các mô hình đa kênh, các kênh cần được xen kẽ.
  • Tenor điểm đầu ra (kTfLiteFloat32)

    • Mảng [1 x N] với N đại diện cho số lớp.
    • (các) bản đồ nhãn tùy chọn (nhưng được khuyến nghị) dưới dạng AssociatedFile-s với loại TENSOR_AXIS_LABELS, chứa một nhãn trên mỗi dòng. Tệp liên kết đầu tiên (nếu có) được sử dụng để điền vào trường label (được đặt tên là class_name trong C++) của kết quả. Trường display_name được điền từ AssociatedFile (nếu có) có ngôn ngữ khớp với trường display_names_locale của AudioClassifierOptions được sử dụng tại thời điểm tạo ("en" theo mặc định, tức là tiếng Anh). Nếu không có sẵn những thứ này thì chỉ có trường index của kết quả sẽ được điền.