資料集文件
資料集特徵
並獲得增強的文件體驗
開始使用
資料集特徵
Features 定義了資料集的內部結構。它用於指定底層的序列化格式。對您來說更有趣的是,Features 包含了關於所有事項的高階資訊,從欄位名稱與類型,到 ClassLabel 皆包含在內。您可以將 Features 視為資料集的骨幹。
Features 的格式很簡單:dict[column_name, column_type]。它是一個由欄位名稱與欄位類型配對而成的字典。欄位類型為描述您所擁有的資料類型提供了廣泛的選項。
讓我們來看看 GLUE 基準測試中 MRPC 資料集的特徵
>>> from datasets import load_dataset
>>> dataset = load_dataset('nyu-mll/glue', 'mrpc', split='train')
>>> dataset.features
{'idx': Value('int32'),
'label': ClassLabel(names=['not_equivalent', 'equivalent']),
'sentence1': Value('string'),
'sentence2': Value('string'),
}Value 特徵會告知 🤗 Datasets
idx的資料類型是int32。sentence1和sentence2的資料類型是string。
🤗 Datasets 支援許多其他資料類型,例如 bool、float32 和 binary 等,族繁不及備載。
請參閱 Value 以取得受支援資料類型的完整列表。
ClassLabel 特徵會告知 🤗 Datasets label 欄位包含兩個類別。這些類別被標記為 not_equivalent 和 equivalent。標籤在資料集中以整數儲存。當您檢索標籤時,ClassLabel.int2str() 和 ClassLabel.str2int() 會執行整數值與標籤名稱之間的相互轉換。
如果您的資料類型包含物件列表,那麼您會想要使用 List 特徵。還記得 SQuAD 資料集嗎?
>>> from datasets import load_dataset
>>> dataset = load_dataset('rajpurkar/squad', split='train')
>>> dataset.features
{'id': Value('string'),
'title': Value('string'),
'context': Value('string'),
'question': Value('string'),
'answers': {'text': List(Value('string')),
'answer_start': List(Value('int32'))}}answers 欄位是使用特徵字典所建構的,並且包含兩個子欄位:text 和 answer_start,它們分別是 string 和 int32 的列表。
請參閱 flatten 章節,了解如何將巢狀子欄位提取為獨立的欄位。
陣列 (Array) 特徵類型對於建立各種大小的陣列很有用。您可以使用 Array2D 建立二維陣列,甚至可以使用 Array5D 建立五維陣列。
>>> features = Features({'a': Array2D(shape=(1, 3), dtype='int32')})陣列類型還允許陣列的第一個維度是動態的。這對於處理變動長度的序列(例如句子)非常有用,而無需將輸入填充 (pad) 或截斷 (truncate) 為統一的形狀。
>>> features = Features({'a': Array3D(shape=(None, 5, 2), dtype='int32')})音訊特徵 (Audio feature)
音訊資料集有一個類型為 Audio 的欄位,其中包含三個重要欄位:
array:以一維陣列表示的已解碼音訊資料。path:已下載音訊檔案的路徑。sampling_rate:音訊資料的取樣率。
當您載入音訊資料集並呼叫音訊欄位時,Audio 特徵會自動解碼並重新取樣音訊檔案。
>>> from datasets import load_dataset, Audio
>>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train")
>>> dataset[0]["audio"]
<datasets.features._torchcodec.AudioDecoder object at 0x11642b6a0>請先使用列索引,再使用
audio欄位來索引音訊資料集(例如dataset[0]["audio"]),以避免解碼和重新取樣資料集中的所有音訊檔案。否則,如果您擁有大型資料集,這可能是一個緩慢且耗時的過程。
若設為 decode=False,Audio 類型只會提供音訊檔案的路徑或位元組 (bytes),而不會將其解碼為 torchcodec AudioDecoder 物件。
>>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train").cast_column("audio", Audio(decode=False))
>>> dataset[0]
{'audio': {'bytes': None,
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav'},
'english_transcription': 'I would like to set up a joint account with my partner',
'intent_class': 11,
'lang_id': 4,
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
'transcription': 'I would like to set up a joint account with my partner'}影像特徵 (Image feature)
影像資料集有一個類型為 Image 的欄位,它會從以位元組儲存的影像中載入 PIL.Image 物件。
當您載入影像資料集並呼叫影像欄位時,Image 特徵會自動解碼影像檔案。
>>> from datasets import load_dataset, Image
>>> dataset = load_dataset("AI-Lab-Makerere/beans", split="train")
>>> dataset[0]["image"]
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x500 at 0x125506CF8>請先使用列索引,再使用
image欄位來索引影像資料集(例如dataset[0]["image"]),以避免解碼資料集中的所有影像檔案。否則,如果您擁有大型資料集,這可能是一個緩慢且耗時的過程。
若設為 decode=False,Image 類型只會提供影像檔案的路徑或位元組,而不會將其解碼為 PIL.Image。
>>> dataset = load_dataset("AI-Lab-Makerere/beans", split="train").cast_column("image", Image(decode=False))
>>> dataset[0]["image"]
{'bytes': None,
'path': '/Users/username/.cache/huggingface/datasets/downloads/extracted/772e7c1fba622cff102b85dd74bcce46e8168634df4eaade7bedd3b8d91d3cd7/train/healthy/healthy_train.265.jpg'}根據資料集的不同,您可能會獲得本地已下載影像的路徑,或者如果資料集不是由單個檔案組成的,則會獲得以位元組形式的影像內容。
您也可以從 numpy 陣列定義影像資料集。
>>> ds = Dataset.from_dict({"i": [np.zeros(shape=(16, 16, 3), dtype=np.uint8)]}, features=Features({"i": Image()}))在這種情況下,numpy 陣列會被編碼為 PNG(如果像素值精度很重要,則為 TIFF)。
對於像 RGB 或 RGBA 這樣的多通道陣列,僅支援 uint8。如果您使用更高的精度,將會收到警告,並且陣列會被向下轉換 (downcasted) 為 uint8。對於灰階影像,只要與 Pillow 相容,您可以使用想要的整數或浮點精度。如果影像的整數或浮點精度過高,會顯示警告,在這種情況下,陣列會被向下轉換:int64 陣列被轉換為 int32,float64 陣列被轉換為 float32。
Json 特徵 (Json feature)
資料集基於 Arrow,這是一種欄位格式,因此它們要求每個範例具有相同的類型和子類型,並且字典具有相同的鍵和值類型。載入資料集時,如果欄位類型不匹配,會發生錯誤;如果字典中的欄位缺失,則會填入 None,以確保所有字典具有相同的鍵和值類型。
為了避免這種情況並允許混合類型而不報錯,您可以使用 on_mixed_types="use_json",或者使用 Json 類型來指定 features=。
>>> ds = Dataset.from_dict({"a": [0, "foo", {"subfield": "bar"}]})
Traceback (most recent call last):
...
File "pyarrow/error.pxi", line 92, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: Could not convert 'foo' with type str: tried to convert to int64
>>> features = Features({"a": Json()})
>>> ds = Dataset.from_dict({"a": [0, "foo", {"subfield": "bar"}]}, features=features)
>>> ds.features
{'a': Json()}
>>> list(ds["a"])
[0, "foo", {"subfield": "bar"}]這對於具有任意鍵和值的字典列表也很有用,可以避免使用 None 填充缺失的欄位。
>>> ds = Dataset.from_dict({"a": [[{"b": 0}, {"c": 0}]]})
>>> ds.features
{'a': List({'b': Value('int64'), 'c': Value('int64')})}
>>> list(ds["a"])
[[{'b': 0, 'c': None}, {'b': None, 'c': 0}]] # missing fields are filled with None
>>> features = Features({"a": List(Json())})
>>> ds = Dataset.from_dict({"a": [[{"b": 0}, {"c": 0}]]}, features=features)
>>> ds.features
{'a': List(Json())}
>>> list(ds["a"])
[[{'b': 0}, {'c': 0}]] # OK另一個關於工具呼叫資料與 on_mixed_types="use_json" 參數的範例(對於不需要手動指定 features= 的情況非常有用)。
>>> messages = [
... {"role": "user", "content": "Turn on the living room lights and play my electronic music playlist."},
... {"role": "assistant", "tool_calls": [
... {"type": "function", "function": {
... "name": "control_light",
... "arguments": {"room": "living room", "state": "on"}
... }},
... {"type": "function", "function": {
... "name": "play_music",
... "arguments": {"playlist": "electronic"} # mixed-type here since keys ["playlist"] and ["room", "state"] are different
... }}]
... },
... {"role": "tool", "name": "control_light", "content": "The lights in the living room are now on."},
... {"role": "tool", "name": "play_music", "content": "The music is now playing."},
... {"role": "assistant", "content": "Done!"}
... ]
>>> ds = Dataset.from_dict({"messages": [messages]}, on_mixed_types="use_json")
>>> ds.features
{'messages': List({'role': Value('string'), 'content': Value('string'), 'tool_calls': List(Json()), 'name': Value('string')})}
>>> ds[0][1]["tool_calls"][0]["function"]["arguments"]
{"room": "living room", "state": "on"}