Datasets 文档

数据集特征

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

数据集特征

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
  • sentence1sentence2 数据类型是 string

🤗 Datasets 还支持许多其他数据类型,例如 bool, float32binary 等。

请参阅 Value 以获取支持的数据类型完整列表。

ClassLabel 特征告知 🤗 Datasets label 列包含两个类别。这些类别被标记为 not_equivalentequivalent。标签在数据集中以整数形式存储。当你检索标签时,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 字段是使用特征字典构建的,它包含两个子字段 textanswer_start,它们分别是 stringint32 的列表。

请参阅 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 的列,其中包含三个重要字段:

  • 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 类型仅为你提供音频文件的路径或字节流,而不会将其解码为 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 的列,它将存储为字节的图像加载为 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。如果你使用更高的精度,会收到警告且数组将被向下转换为 uint8。对于灰度图像,只要与 Pillow 兼容,你可以使用任何想要的整数或浮点精度。如果你的图像整数或浮点精度过高,会显示警告,在这种情况下数组将被向下转换:int64 数组会被转换为 int32,float64 数组会被转换为 float32。

Json 特征

数据集基于 Arrow,而 Arrow 是一种列式格式,因此它要求每个示例具有相同的类型和子类型,且字典具有相同的键和值类型。当字段类型不匹配时,加载数据集会报错,并且字典中缺失的字段将用 None 填充,以便所有字典具有相同的键和值类型。

为了避免这种情况并允许在没有错误的情况下使用混合类型,你可以使用 on_mixed_types="use_json",或者通过 features= 指定 Json 类型

>>> 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

另一个关于工具调用(tool calling)数据和 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"}
在 GitHub 上更新

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