Datasets documentation

NumPy와 함께 사용

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v4.8.4).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

NumPy와 함께 사용

이 문서는 datasets를 NumPy와 함께 사용하는 방법에 대한 간단한 소개입니다. 특히 데이터셋에서 numpy.ndarray 객체를 가져오는 방법과, 이를 사용하여 scikit-learn 모델과 같은 NumPy 기반 모델을 학습하는 방법에 중점을 둡니다.

데이터셋 형식

기본적으로 datasets는 정수, 실수, 문자열, 리스트 등 일반적인 Python 객체를 반환합니다.

NumPy 배열을 대신 받으려면 데이터셋의 형식을 numpy로 설정할 수 있습니다:

>>> from datasets import Dataset
>>> data = [[1, 2], [3, 4]]
>>> ds = Dataset.from_dict({"data": data})
>>> ds = ds.with_format("numpy")
>>> ds[0]
{'data': array([1, 2])}
>>> ds[:2]
{'data': array([
    [1, 2],
    [3, 4]])}

Dataset 객체는 Arrow 테이블의 래퍼로, 데이터셋의 배열에서 NumPy 배열로의 빠른 읽기를 허용합니다.

동일한 절차가 DatasetDict 객체에도 적용되므로, DatasetDict의 형식을 numpy로 설정하면 해당 Dataset 전체가 numpy 형식으로 포맷팅됩니다:

>>> from datasets import DatasetDict
>>> data = {"train": {"data": [[1, 2], [3, 4]]}, "test": {"data": [[5, 6], [7, 8]]}}
>>> dds = DatasetDict.from_dict(data)
>>> dds = dds.with_format("numpy")
>>> dds["train"][:2]
{'data': array([
    [1, 2],
    [3, 4]])}

N차원 배열

데이터셋이 N차원 배열로 구성되어 있는 경우, 기본적으로 shape이 고정되어 있으면 동일한 배열로 간주됩니다:

>>> from datasets import Dataset
>>> data = [[[1, 2],[3, 4]], [[5, 6],[7, 8]]]  # fixed shape
>>> ds = Dataset.from_dict({"data": data})
>>> ds = ds.with_format("numpy")
>>> ds[0]
{'data': array([[1, 2],
        [3, 4]])}
>>> from datasets import Dataset
>>> data = [[[1, 2],[3]], [[4, 5, 6],[7, 8]]]  # varying shape
>>> ds = Dataset.from_dict({"data": data})
>>> ds = ds.with_format("numpy")
>>> ds[0]
{'data': array([array([1, 2]), array([3])], dtype=object)}

그러나 이러한 로직은 느린 shape 비교와 데이터 복사를 요구하는 경우가 많습니다. 이를 피하려면 Array feature type을 명시적으로 사용하고 텐서의 shape를 지정해야 합니다:

>>> from datasets import Dataset, Features, Array2D
>>> data = [[[1, 2],[3, 4]],[[5, 6],[7, 8]]]
>>> features = Features({"data": Array2D(shape=(2, 2), dtype='int32')})
>>> ds = Dataset.from_dict({"data": data}, features=features)
>>> ds = ds.with_format("numpy")
>>> ds[0]
{'data': array([[1, 2],
        [3, 4]])}
>>> ds[:2]
{'data': array([[[1, 2],
         [3, 4]],
 
        [[5, 6],
         [7, 8]]])}

기타 기능 유형

ClassLabel 데이터가 배열로 올바르게 변환됩니다:

>>> from datasets import Dataset, Features, ClassLabel
>>> labels = [0, 0, 1]
>>> features = Features({"label": ClassLabel(names=["negative", "positive"])})
>>> ds = Dataset.from_dict({"label": labels}, features=features)
>>> ds = ds.with_format("numpy")
>>> ds[:3]
{'label': array([0, 0, 1])}

NumPy는 숫자만 지원하므로 문자열 및 바이너리 객체는 변경되지 않습니다.

Image와 Audio 기능 유형도 지원됩니다.

Image 기능 유형을 사용하려면 vision 추가 항목을 pip install datasets[vision]으로 설치해야 합니다.

>>> from datasets import Dataset, Features, Image
>>> images = ["path/to/image.png"] * 10
>>> features = Features({"image": Image()})
>>> ds = Dataset.from_dict({"image": images}, features=features)
>>> ds = ds.with_format("numpy")
>>> ds[0]["image"].shape
(512, 512, 3)
>>> ds[0]
{'image': array([[[ 255, 255, 255],
              [ 255, 255, 255],
              ...,
              [ 255, 255, 255],
              [ 255, 255, 255]]], dtype=uint8)}
>>> ds[:2]["image"].shape
(2, 512, 512, 3)
>>> ds[:2]
{'image': array([[[[ 255, 255, 255],
              [ 255, 255, 255],
              ...,
              [ 255, 255, 255],
              [ 255, 255, 255]]]], dtype=uint8)}

Audio 기능 유형을 사용하려면 audio 추가 항목을 pip install datasets[audio]로 설치해야 합니다.

>>> from datasets import Dataset, Features, Audio
>>> audio = ["path/to/audio.wav"] * 10
>>> features = Features({"audio": Audio()})
>>> ds = Dataset.from_dict({"audio": audio}, features=features)
>>> ds = ds.with_format("numpy")
>>> ds[0]["audio"]["array"]
array([-0.059021  , -0.03894043, -0.00735474, ...,  0.0133667 ,
              0.01809692,  0.00268555], dtype=float32)
>>> ds[0]["audio"]["sampling_rate"]
array(44100, weak_type=True)

데이터 로딩

NumPy에는 내장된 데이터 로딩 기능이 없으므로, scikit-learn에서 사용할 X, y와 같은 NumPy 배열을 직접 생성하거나, PyTorch와 같은 라이브러리를 사용해 DataLoader로 데이터를 로드해야 합니다.

with_format('numpy') 사용

데이터셋에서 NumPy 배열을 가져오는 가장 쉬운 방법은 with_format('numpy') 메서드를 사용하는 것입니다. HuggingFace Hub의 https://huggingface.co/datasets/mnist에 있는 MNIST dataset으로 신경망을 학습하고 싶다고 가정해 보겠습니다.

>>> from datasets import load_dataset
>>> ds = load_dataset("ylecun/mnist")
>>> ds = ds.with_format("numpy")
>>> ds["train"][0]
{'image': array([[  0,   0,   0, ...],
                       [  0,   0,   0, ...],
                       ...,
                       [  0,   0,   0, ...],
                       [  0,   0,   0, ...]], dtype=uint8),
 'label': array(5)}

Dataset.iter() 메서드를 사용하여 NumPy 기반 모델에 데이터셋을 배치 단위로 공급할 수 있습니다.

>>> for epoch in range(epochs):
...     for batch in ds["train"].iter(batch_size=32):
...         x, y = batch["image"], batch["label"]
...         ...
Update on GitHub