Datasets documentation

Datasetの機能

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

and get access to the augmented documentation experience

to get started

Datasetの機能

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カラムに2つのクラスが含まれていることを認識します。クラスは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 という2つのサブフィールドを含みます。これらはそれぞれ、string と int32 のリストです。

ネストされたサブフィールドを独立したカラムとして抽出する方法については、flattenセクションを参照してください。

配列の機能タイプは、さまざまなサイズの配列を作成するのに便利です。Array2D を使用して2次元の配列を作成でき、Array5D を使用して5次元の配列を作成することもできます。

>>> features = Features({'a': Array2D(shape=(1, 3), dtype='int32')})

配列型では、配列の最初の次元を動的にすることもできます。これにより、文などの可変長のシーケンスを、入力を均一な形状にパディングや切り詰めずに処理できます。

>>> features = Features({'a': Array3D(shape=(None, 5, 2), dtype='int32')})

オーディオ機能

オーディオデータセットには、Audio型の列があり、3つの重要なフィールドが含まれています。

  • array: 1次元配列として表されたデコード済みオーディオデータ。
  • 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'}

画像機能

画像データセットには、バイトとして保存された画像からPIL.Imageオブジェクトを読み込む、型が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)にエンコードされます。

For multi-channels arrays like RGB or RGBA, only uint8 is supported. If you use a larger precision, you get a warning and the array is downcasted to uint8. For gray-scale images you can use the integer or float precision you want as long as it is compatible with Pillow. A warning is shown if your image integer or float precision is too high, and in this case the array is downcated: an int64 array is downcasted to int32, and a float64 array is downcasted to float32.

メッシュ機能

メッシュデータセットには、Mesh型の列があり、3Dメッシュファイルをtrimeshオブジェクトとして読み込みます。

メッシュデータセットを読み込み、メッシュ列を呼び出すと、Mesh機能がメッシュファイルを自動的にデコードします。

>>> from datasets import load_dataset, Mesh

>>> dataset = load_dataset("VINAY-UMRETHE/My-Mesh-Dataset", split="train")
>>> dataset[0]["mesh"]
<trimesh.Scene(len(geometry)=33)>

ファイルの内容に応じて、trimesh は trimesh.Trimesh オブジェクトまたは trimesh.Scene オブジェクトを返す場合があります。

行インデックスを先に使用してメッシュデータセットにインデックスし、その後mesh列 - dataset[0]["mesh"] - を使用することで、データセット内のすべてのメッシュファイルをデコードすることを避けてください。そうしないと、データセットが大きい場合、この処理は低速で時間がかかる可能性があります。

decode=False を指定すると、Mesh 型はメッシュファイルをtrimesh でデコードせずに、そのパスまたはバイト列を返します。

>>> dataset = load_dataset("VINAY-UMRETHE/My-Mesh-Dataset", split="train").cast_column("mesh", Mesh(decode=False))
>>> dataset[0]["mesh"]
{'bytes': b'...',
 'path': '00001.glb'}

Mesh機能は、.glb、.gltf、.ply、.stlファイルをサポートしています。埋め込みバイトの場合、保存されたpathを使用してメッシュファイルのタイプを推測します。

Json機能

Datasets は列形式である Arrow をベースにしているため、すべての例が同じ型とサブタイプを持ち、辞書が同じキーと値の型を持つことを前提としています。 フィールドの型が一致しない場合、Datasets の読み込みはエラーになります。また、辞書の欠損フィールドには 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"}
Update on GitHub