Tích hợp thuật toán phân loại âm thanh

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ụ: ứng dụng này có thể xác định loài chim bằng tiếng hót của chúng.

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

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

  • Xử lý âm thanh đầu vào, ví dụ: chuyển đổi mã hoá PCM 16 bit thành mã hoá PCM Float và thao tác với vùng đệm vòng âm thanh.

  • Gắn nhãn ngôn ngữ trên 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à nhiều nhãn.

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

  • k kết quả phân loại hàng đầu.

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

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

Các mô hình sau đây chắc chắn sẽ tương thích với API AudioClassifier.

Chạy suy luận bằng Java

Hãy xem ứng dụng tham chiếu Phân loại âm thanh để biết ví dụ về cách sử dụng AudioClassifier trong một ứng dụng Android.

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

Sao chép tệp mô hình .tflite vào thư mục tài sản của mô-đun Android nơi mô hình sẽ chạy. Chỉ định rằng tệp 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
    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);

Hãy xem mã nguồn và javadoc để biết thêm các lựa 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ợ việc cài đặt bằng CocoaPods. Đảm bảo bạn đã cài đặt CocoaPods trên hệ thống. Vui lòng xem hướng dẫn cài đặt CocoaPods để biết hướng dẫn.

Vui lòng xem hướng dẫn về CocoaPods để biết thông tin chi tiết về cách thêm pod 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 mà bạn 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

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];

        });
    }
}];

Hãy xem mã nguồn để biết thêm các lựa chọn định 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 sẽ tự động cài đặt khi bạn cài đặt gói tflite-support pip.

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)

Hãy xem mã nguồn để biết thêm các lựa chọn định cấu hình AudioClassifier.

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

Hãy xem mã nguồn để biết thêm các lựa 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 yêu cầu một mô hình TFLite có 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 các trình phân loại âm thanh bằng API Trình ghi siêu dữ liệu TensorFlow Lite.

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

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

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

    • Mảng [1 x N]N biểu thị số lớp.
    • (các) bản đồ nhãn không bắt buộc(nhưng nên dùng) dưới dạng AssociatedFile-s có 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 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 sẵn từ AssociatedFile (nếu có) có ngôn ngữ khớp với trường display_names_locale của AudioClassifierOptions được 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ó trường nào trong số này, thì chỉ trường index của kết quả sẽ được điền.