장난감 연구소

음 높이(Pitch) 예측 모델 정리 본문

토이프로젝트

음 높이(Pitch) 예측 모델 정리

changi1122 2024. 7. 24. 13:40

    음악 오디오 파일에서 가수의 노래 목소리의 음 높이를 추출하는 작업을 하면서, 사용해 본 음 높이 예측(Pitch Estimation) 모델을 정리하였습니다. 기계학습과 관련해서 잘 알고 있지는 않지만, 관련된 글이 없어 개인적으로 사용할 때 참고용으로 적어 보았습니다.

     

    CREPE

    CREPE는 New York University의 연구자들이 2018년 발표한 모델로, CNN을 기반으로 한 Pitch 예측 모델이다. 발표한 논문은 [1802.06182] CREPE: A Convolutional Representation for Pitch Estimation (arxiv.org)에서 확인할 수 있다.

    코드와 파이썬 패키지를 제공하는데 깃허브 저장소는 GitHub - marl/crepe: CREPE: A Convolutional REpresentation for Pitch Estimation -- pre-trained model (ICASSP 2018)에서 확인할 수 있다.

    설치

    $ pip install --upgrade tensorflow  # if you don't already have tensorflow >= 2.0.0
    $ pip install crepe

    오디오 파일 로드 및 예측

    import crepe
    from scipy.io import wavfile
    
    sr, audio = wavfile.read('/path/to/audiofile.wav')
    time, frequency, confidence, activation = crepe.predict(audio, sr, model_capacity='large', step_size=32, viterbi=False)

    주요 파라미터

    audio 오디오 샘플 np.ndarray [shape=(N,) or (N, C)]
    sr sample rate 정수
    model_capacity 모델 크기 'tiny', 'small', 'medium', 'large', 'full’
    step_size 한 개의 음높이를 예측할 길이 (ms) 기본값 : 10ms
    viterbi 예측 결과를 부드럽게 만들지 여부  

    예측 결과

    time 시간
    frequency 예측한 Pitch 값 (Hz)
    confidence voice activity의 신뢰도 (0~1)
    activation The raw activation matrix [shape=(T, 360)]

     

    SPICE

    SPICE 모델은 2019년 구글의 연구자들이 발표한 Pitch 예측 모델이다. 발표한 논문은 [1910.11664] SPICE: Self-supervised Pitch Estimation (arxiv.org)에서 확인할 수 있다. 모델에 대한 설명이 담긴 구글의 블로그 글도 있다.

    아키텍처를 보면 Convolutional encoder로 이뤄져 있다고 하고, Convolutional encoder는 Pitch로 맵핑되는 single scalar embedding을 만들어 낸다고 한다. (아마 transformer 모델의 encoder와 비슷할 것 같다.)

    모델은 Tensorflow를 필요로 하고, Tensorflow Hub에서 로드할 수 있다.

    Google | spice | Kaggle

    리샘플링

    SPICE 모델은 입력으로 넣을 오디오 파일의 sampling rate가 16000hz이어야 한다. 아니라면 아래 코드와 같이 리샘플링을 직접 해줘야 한다.

    EXPECTED_SAMPLE_RATE = 16000
    
    def convert_audio_for_model(file_path, output_file='converted_audio_file.wav'):
        audio = AudioSegment.from_file(file_path)
        audio = audio.set_frame_rate(EXPECTED_SAMPLE_RATE).set_channels(1)
        audio.export(output_file, format="wav")
        return output_file

    오디오 파일 로드 및 예측

    import tensorflow as tf
    import tensorflow_hub as hub
    from scipy.io import wavfile
    
    sample_rate, audio_samples = wavfile.read(converted_audio_file, 'rb')
    
    model = hub.load("https://tfhub.dev/google/spice/2")
    
    # We now feed the audio to the SPICE tf.hub model to obtain pitch and uncertainty outputs as tensors.
    model_output = model.signatures["serving_default"](tf.constant(audio_samples, tf.float32))
    
    pitch_outputs = model_output["pitch"]
    uncertainty_outputs = model_output["uncertainty"]

    파라미터

    SPICE는 파라미터를 설정할 수 없고, sample rate는 16000hz, step_size는 32ms로 고정되어 있다.

    예측 결과

    dict 자료형

    pitch 예측된 값 (hz로 추가 변환 필요함)
    uncertainty 불확실성 (0~1)

    예측 결과 값을 Hz 단위로 변환

    def output2hz(pitch_output):
      # Calibration constants
      PT_OFFSET = 25.58
      PT_SLOPE = 63.07
      FMIN = 10.0;
      BINS_PER_OCTAVE = 12.0;
      cqt_bin = pitch_output * PT_SLOPE + PT_OFFSET;
      return FMIN * 2.0 ** (1.0 * cqt_bin / BINS_PER_OCTAVE)

    제시된 성능 비교

     

    PESTO

    PESTO는 프랑스의 학교인 Télécom Paris와 Sony의 연구자가 2023년 발표한 Pitch 예측 모델이다. 논문은 [2309.02265] PESTO: Pitch Estimation with Self-supervised Transposition-equivariant Objective (arxiv.org)에서 확인할 수 있다.

    구조는 아래 사진과 같다.

     

    CREPE와 유사하게 코드와 파이썬 패키지를 제공하는데 깃허브 저장소는 GitHub - SonyCSLParis/pesto: Self-supervised learning for fast pitch estimation에서 확인할 수 있다. 입력과 예측 결과도 CREPE와 유사하다.

    설치

    pip install pesto-pitch
    pip install soundfile

    오디오 로드 및 예측

    import torchaudio
    import pesto
    
    # predict the pitch of your audio tensors directly within your own Python code
    x, sr = torchaudio.load("my_file.wav")
    x = x.mean(dim=0)  # PESTO takes mono audio as input
    timesteps, pitch, confidence, activations = pesto.predict(x, sr)

    주요 파라미터

    x 입력 오디오 샘플 np.ndarray [shape=(N,) or (N, C)]
    sr sample rate 정수
    model_name 모델 이름 standard 모델이나 custom PESTO 모델 (기본값 : "mir-1k”)
    model_capacity 모델 크기 'tiny', 'small', 'medium', 'large', 'full’
    step_size 한 개의 음높이를 예측할 길이 (ms) 기본값 : 10ms

    예측 결과

    timesteps 시간
    preds 예측한 Pitch 값 (Hz)
    confidence Frame에 voice가 존재하는지 신뢰도 (0~1)
    activations activations of the model

    제시된 성능 비교