資料集文件

與 NumPy 搭配使用

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

與 NumPy 搭配使用

本文件是關於如何在 datasets 中使用 NumPy 的快速入門,特別著重於如何從我們的資料集中取得 numpy.ndarray 物件,以及如何使用它們來訓練基於 NumPy 的模型(例如 scikit-learn 模型)。

資料集格式

預設情況下,資料集會傳回一般的 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 表格的封裝(wrapper),它允許從資料集中的陣列快速讀取為 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)}

然而,此邏輯通常需要較慢的形狀比較和資料複製。為了避免這種情況,您必須明確使用 Array 特徵類型並指定張量的形狀

>>> 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 只支援數值。

ImageAudio 特徵類型也受到支援。

若要使用 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 本身沒有內建的資料載入功能,因此您需要將 NumPy 陣列具體化(例如 X, y)以用於 scikit-learn,或是使用像 PyTorch 這樣的函式庫,透過 DataLoader 來載入資料。

使用 with_format('numpy')

從資料集中取得 NumPy 陣列最簡單的方法是使用 with_format('numpy') 方法。假設我們想在 MNIST 資料集上訓練一個類神經網路,該資料集可在 HuggingFace Hub 上取得:https://huggingface.co/datasets/mnist

>>> 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() 方法以批次(batches)方式將資料集餵給基於 NumPy 的模型。

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

© . This site is unofficial and not affiliated with Hugging Face, Inc.