集成音频分类器

音频分类是机器学习的一个常见使用场景, 声音类型。例如,它可以根据鸟叫声识别鸟类的物种。

Task Library AudioClassifier API 可用于部署您的自定义音频 分类器或预训练分类器集成到您的移动应用中。

AudioClassifier API 的主要功能

  • 输入音频处理,例如将 PCM 16 位编码转换为 PCM 对音频环形缓冲区进行浮点编码和操作。

  • 标记地图语言区域。

  • 支持多头分类模型。

  • 同时支持单标签分类和多标签分类。

  • 用于过滤结果的分数阈值。

  • Top-k 分类结果。

  • 标签许可名单和拒绝名单。

支持的音频分类器模型

以下模型保证与 AudioClassifier兼容 API。

使用 Java 运行推理

请参阅 音频分类参考应用 获取在 Android 应用中使用 AudioClassifier 的示例。

第 1 步:导入 Gradle 依赖项和其他设置

.tflite 模型文件复制到 Android 模块的 assets 目录中 将运行模型的位置。指定不应压缩该文件,并且 将 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 步:安装依赖项

Task 库支持使用 CocoaPods 进行安装。确保 CocoaPods 。请参阅 CocoaPods 安装指南 了解相关说明。

请参阅 CocoaPods 指南 了解有关将 Pod 添加到 Xcode 项目的详细信息。

在 Podfile 中添加 TensorFlowLiteTaskAudio Pod。

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:在安装 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 的更多选项。

模型兼容性要求

AudioClassifier API 需要一个具有强制性要求的 TFLite 模型, TFLite 模型元数据。查看相关示例 使用 TensorFlow Lite Metadata Writer API

兼容的音频分类器模型应满足以下要求:

  • 输入音频张量 (kTfLiteFloat32)

    • 大小为 [batch x samples] 的音频片段。
    • 不支持批量推理(batch 必须为 1)。
    • 对于多通道模型,通道需要交错。
  • 输出得分张量 (kTfLiteFloat32)

    • N 表示类编号的 [1 x N] 数组。
    • 可选(但建议)将映射标记为具有类型的 AssociatedFile-s TENSOR_AXIS_LABELS,每行包含一个标签。第一个这样的 AssociatedFile(如果有)用于填充 label 字段(名为 class_name)。display_name 字段已填充 (如果有),则从其语言区域与 AudioClassifierOptions 的“display_names_locale”字段,在 创建时间(默认为“en”,即英语)。如果以上两种情况均不适用 可用,系统只会填充结果的 index 字段。