상세 컨텐츠

본문 제목

4. Custom Audio PyTorch Dataset with Torchaudio

Coding/Sound

by linguana 2021. 6. 18. 20:14

본문

본 포스팅은 다음 [1] 영상을 보고 작성한 것임을 미리 밝힙니다.

  "Welcome to new exciting video in the ..."라는 오프닝 멘트와 함께 시작하는 이 영상, 참 재밌다. 

  오디오 분야에서 커스텀 데이터셋을 만드는 방식을 알려드림. Urban Sound Dataset 8K를 이용해서 해보자. [2] 에서 다운로드 할 수 있다.

  데이터를 다루기 위해선 (1) Dataset (2) Dataloader 이 두 가지가 필요한데, Dataloader는 단순히데이터를 로딩하기 위해 사용하는 wrapper다. 근데 여기에서 관심있는 건 wrapper가 아니고 데이터셋임!

  10개 폴더 있음. 10 classes.

import os

from torch.utils.data import Dataset
import pandas as pd
import torchaudio


class UrbanSoundDataset(Dataset):

  # Always, constructor first
  def __init__(self, annotations_file, audio_dir):
    self.annotations = pd.read_csv(annotations_file)
    self.audio_dir = audio_dir

  # We want to return the number of samples in the dataset
  def __len__(self): # len(usd)
    return len(self.annotations)

  def __getitem__(self, index): # a_list(1) -> a_list.__getitem__(1)
    audio_samples_path = self._get_audio_samples_path(index)
    label = self._get_audio_sample_label(index)
    signal, sr = torchaudio.load(audio_sample_path)
    return signal, label

  # implement private methods
  def _get_audio_sample_path(self, index):
    fold = f"fold{self.annotations.iloc[index, 5]}"
    path = os.path.join(self.audio_dir, fold, self.annotations.iloc[index, 0])
    return path
  
  def _get_audio_sample_label(self, index):
    return self.annotations.iloc[index, 6]

if __name__ = "__main__":
  ANNOTATIONS_FILE = "path/to/annotations/file.csv"
  AUDIO_DIR = "path/to/audio"

  usd = UrbanSoundDataset(ANNOTATIONS_FILE, AUDIO_DIR)

  print(f"There are {len(usd)} samples in the dataset.")

  signal, label = usd[0]

  이 정도로 작성하면 적어도 데이터를 불러올 수는 있겠다. 하지만 우리가 원하는 문제를 해결하기 위해선 이 음성 데이터에서 정보를 추출할 수 있는 형식으로 변환해야 한다. 그 방법은 (Mel-Spectrogram) 다음 시간에 알아보자.


Reference

[1] Custom Audio PyTorch Dataset with Torchaudio - YouTube
[2] UrbanSound8K - Urban Sound Datasets (weebly.com)

'Coding > Sound' 카테고리의 다른 글

CTC loss  (0) 2022.05.05
Understanding automated assessment of speaking with Jing Xu  (0) 2021.12.03
Query, Key, and Value in Attention  (0) 2021.06.10
Transformer  (0) 2021.06.03
Attention  (0) 2021.05.31

관련글 더보기