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

Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.

Phân loại âm thanh là một trường hợp sử dụng phổ biến của Học máy để 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 giọng hót của chúng.

API Bộ phân loại âm thanh của Thư viện AudioClassifier vụ có thể được sử dụng để triển khai các bộ phân loại âm thanh tùy chỉnh hoặc các bộ phân loại âm thanh được đào tạo trước vào ứng dụng dành cho thiết bị 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.

  • Nhãn bản đồ địa phương.

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

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

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

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

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

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

Các mô hình 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 chiếu Phân loại âm thanh để biết ví dụ sử dụng AudioClassifier phân loại âm thanh 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 không nên nén tệp 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.0'
    // Import the GPU delegate plugin Library for GPU inference
    implementation 'org.tensorflow:tensorflow-lite-gpu-delegate-plugin:0.4.0'
}

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 để biết thêm tùy chọn để định cấu hình AudioClassifier .

Chạy suy luận trong iOS

Bước 1: Cài đặt các phần 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 CocoaPods để biết chi tiết về cách thêm nhóm vào dự án Xcode.

Thêm nhóm TensorFlowLiteTaskAudio trong 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 để định cấu hình TFLAudioClassifier .

Chạy suy luận bằng 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 để định 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 để định cấu hình AudioClassifier .

Yêu cầu về khả năng tương thích của mô hình

API AudioClassifier mong đợi một 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 TensorFlow Lite Metadata Writer .

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:

  • Bộ căng âm thanh đầu vào (kTfLiteFloat32)

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

    • [1 x N] mảng 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. AssociatedFile đầu tiên như vậy (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ó cái nào trong số này, chỉ trường index của kết quả sẽ được điền.