오디오 분류 기준 통합

오디오 분류는 오디오 분류를 위해 머신러닝의 일반적인 사용 사례로, 살펴보겠습니다. 예를 들어 노래로 새의 종을 식별할 수 있습니다.

Task Library AudioClassifier API를 사용하여 커스텀 오디오를 배포할 수 있습니다. 선행 학습된 분류 기준을 모바일 앱에 적용합니다.

AudioClassifier API의 주요 기능

  • 입력 오디오 처리 예: PCM 16비트 인코딩을 PCM으로 변환 오디오 링 버퍼의 부동 인코딩 및 조작

  • 라벨 지도 언어

  • 멀티헤드 분류 모델 지원

  • 단일 라벨과 멀티 라벨 분류를 모두 지원합니다.

  • 결과를 필터링하기 위한 점수 기준

  • Top-k 분류 결과입니다.

  • 라벨 허용 목록 및 차단 목록

지원되는 오디오 분류기 모델

다음 모델은 AudioClassifier과(와) 호환됩니다. API에 액세스할 수 있습니다.

Java에서 추론 실행

자세한 내용은 오디오 분류 참조 앱 Android 앱에서 AudioClassifier를 사용하는 예입니다.

1단계: Gradle 종속 항목 및 기타 설정 가져오기

.tflite 모델 파일을 Android 모듈의 assets 디렉터리에 복사합니다. 지정할 수도 있습니다 파일을 압축하지 않도록 지정합니다. 모듈의 build.gradle 파일에 TensorFlow Lite 라이브러리를 추가합니다.

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단계: 종속 항목 설치

작업 라이브러리는 CocoaPods를 사용한 설치를 지원합니다. CocoaPods가 이(가) 시스템에 설치되어 있습니다. 자세한 내용은 CocoaPods 설치 가이드 를 참조하세요.

자세한 내용은 CocoaPods 가이드 Xcode 프로젝트에 포드를 추가하는 방법을 자세히 알아보세요.

Podfile에 TensorFlowLiteTaskAudio 포드를 추가합니다.

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: 컴퓨터 설치 시 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 구성 옵션을 참조하세요.

모델 호환성 요구사항

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 필드가 채워졌습니다. 언어가 다음과 일치하는 AssociatedFile (있는 경우)을 다음에서 사용된 AudioClassifierOptionsdisplay_names_locale 필드: 생성 시간(기본값: en, 예: 영어) 다음 중 어느 것도 해당되지 않는 경우 결과의 index 필드만 채워집니다.