Datasets 文档

主要类

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

主类

DatasetInfo

class datasets.DatasetInfo

< >

( description: str = <factory> citation: str = <factory> homepage: str = <factory> license: str = <factory> features: typing.Optional[datasets.features.features.Features] = None post_processed: typing.Optional[datasets.info.PostProcessedInfo] = None supervised_keys: typing.Optional[datasets.info.SupervisedKeysData] = None builder_name: typing.Optional[str] = None dataset_name: typing.Optional[str] = None config_name: typing.Optional[str] = None version: typing.Union[str, datasets.utils.version.Version, NoneType] = None splits: typing.Optional[datasets.splits.SplitDict] = None download_checksums: typing.Optional[dict] = None download_size: typing.Optional[int] = None post_processing_size: typing.Optional[int] = None dataset_size: typing.Optional[int] = None size_in_bytes: typing.Optional[int] = None )

参数

  • description (str) — A description of the dataset.
  • citation (str) — A BibTeX citation of the dataset.
  • homepage (str) — A URL to the official homepage for the dataset.
  • license (str) — The dataset’s license. It can be the name of the license or a paragraph containing the terms of the license.
  • features (Features, 可选) — 用于指定数据集列类型的特征。
  • post_processed (PostProcessedInfo, 可选) — 关于数据集可能进行后处理的资源的 PostProcessedInfo 信息。例如,它可以包含索引信息。
  • supervised_keys (SupervisedKeysData, 可选) — Specifies the input feature and the label for supervised learning if applicable for the dataset (legacy from TFDS).
  • builder_name (str, 可选) — 用于创建数据集的 GeneratorBasedBuilder 子类的名称。它也是数据集构建器类名称的 snake_case 版本。
  • config_name (str, 可选) — 从 BuilderConfig 派生的配置名称。
  • version (strVersion, 可选) — 数据集的版本。
  • splits (dict, 可选) — 拆分名称与元数据之间的映射。
  • download_checksums (dict, 可选) — 数据集校验和下载 URL 及其相应元数据的映射。
  • download_size (int, 可选) — 用于生成数据集所需下载文件的大小(以字节为单位)。
  • post_processing_size (int, 可选) — 后处理后数据集的大小(以字节为单位),如果有的话。
  • dataset_size (int, 可选) — 所有拆分的 Arrow 表的总大小(以字节为单位)。
  • size_in_bytes (int, 可选) — 与数据集关联的所有文件(下载的文件 + Arrow 文件)的总大小(以字节为单位)。
  • **config_kwargs (其他关键字参数) — 传递给 BuilderConfig 并用于 DatasetBuilder 的关键字参数。

有关数据集的信息。

DatasetInfo 记录数据集,包括其名称、版本和特征。有关完整列表,请参阅构造函数参数和属性。

并非所有字段在构造时都知道,并且可能稍后更新。

from_directory

< >

( dataset_info_dir: str storage_options: typing.Optional[dict] = None )

参数

  • dataset_info_dir (str) — 包含元数据文件的目录。这应该是特定数据集版本的根目录。
  • storage_options (dict, 可选) — 如果适用,传递给文件系统后端的键/值对。

    Added in 2.9.0

dataset_info_dir 中的 JSON 文件创建 DatasetInfo

此函数会更新所有动态生成的字段(num_examples、hash、创建时间等)的 DatasetInfo

这将覆盖所有先前的元数据。

示例

>>> from datasets import DatasetInfo
>>> ds_info = DatasetInfo.from_directory("/path/to/directory/")

write_to_directory

< >

( dataset_info_dir pretty_print = False storage_options: typing.Optional[dict] = None )

参数

  • dataset_info_dir (str) — 目标目录。
  • pretty_print (bool, defaults to False) — 如果为 True,则以 4 个空格的缩进对 JSON 进行美化打印。
  • storage_options (dict, optional) — 传递给文件系统后端的键/值对(如果有)。

    Added in 2.9.0

DatasetInfo 和 license(如果存在)作为 JSON 文件写入 dataset_info_dir

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.info.write_to_directory("/path/to/directory/")

Dataset

基类 Dataset 实现了一个由 Apache Arrow 表支持的 Dataset。

class datasets.Dataset

< >

( arrow_table: Table info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None indices_table: typing.Optional[datasets.table.Table] = None fingerprint: typing.Optional[str] = None )

由 Arrow 表支持的 Dataset。

add_column

< >

( name: str column: typing.Union[list, numpy.ndarray] new_fingerprint: typing.Optional[str] = None feature: typing.Union[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.LargeList, datasets.features.features.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf, datasets.features.nifti.Nifti, NoneType] = None )

参数

  • name (str) — 列名。
  • column (listnp.array) — 要添加的列数据。
  • feature (FeatureTypeNone, defaults to None) — 列数据类型。

将列添加到 Dataset。

Added in 1.7

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> more_text = ds["text"]
>>> ds = ds.add_column(name="text_2", column=more_text)
>>> ds
Dataset({
    features: ['text', 'label', 'text_2'],
    num_rows: 1066
})

add_item

< >

( item: dict new_fingerprint: typing.Optional[str] = None )

参数

  • item (dict) — 要添加的项目数据。

将项目添加到 Dataset。

Added in 1.7

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> new_review = {'label': 0, 'text': 'this movie is the absolute worst thing I have ever seen'}
>>> ds = ds.add_item(new_review)
>>> ds[-1]
{'label': 0, 'text': 'this movie is the absolute worst thing I have ever seen'}

from_file

< >

( filename: str info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None indices_filename: typing.Optional[str] = None in_memory: bool = False )

参数

  • filename (str) — 数据集的ファイル名。
  • info (DatasetInfo, optional) — 数据集信息,如描述、引用等。
  • split (NamedSplit, optional) — 数据集划分的名称。
  • indices_filename (str, optional) — 索引的文件名。
  • in_memory (bool, defaults to False) — 是否将数据复制到内存中。

在 filename 处实例化一个由 Arrow 表支持的 Dataset。

from_buffer

< >

( buffer: Buffer info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None indices_buffer: typing.Optional[pyarrow.lib.Buffer] = None )

参数

  • buffer (pyarrow.Buffer) — Arrow 缓冲区。
  • info (DatasetInfo, optional) — 数据集信息,如描述、引用等。
  • split (NamedSplit, optional) — 数据集划分的名称。
  • indices_buffer (pyarrow.Buffer, optional) — 索引 Arrow 缓冲区。

实例化一个由 Arrow 缓冲区支持的 Dataset。

from_pandas

< >

( df: DataFrame features: typing.Optional[datasets.features.features.Features] = None info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None preserve_index: typing.Optional[bool] = None )

参数

  • df (pandas.DataFrame) — 包含数据集的 DataFrame。
  • features (Features, 可选) — 数据集的特征。
  • info (DatasetInfo, 可选) — 数据集信息,如描述、引用等。
  • split (NamedSplit, 可选) — 数据集分片名称。
  • preserve_index (bool, 可选) — 是否将索引存储为结果 Dataset 中的附加列。默认值 None 会将索引存储为列,但 RangeIndex 除外,后者仅存储为元数据。使用 preserve_index=True 可强制将其存储为列。

pandas.DataFrame 转换为 pyarrow.Table 以创建 Dataset

结果 Arrow Table 中的列类型是从 DataFrame 中 pandas.Series 的 dtype 推断出来的。对于非对象 Series,NumPy dtype 会转换为其 Arrow 等效项。对于 object 类型,我们需要通过查看 Series 中的 Python 对象来猜测数据类型。

请注意,object dtype 的 Series 不包含足够的信息以始终产生有意义的 Arrow 类型。如果我们无法推断出类型(例如,因为 DataFrame 长度为 0 或 Series 仅包含 None/nan 对象),则类型将设置为 null。可以通过构造显式特征并将其传递给此函数来避免此行为。

重要提示:使用 from_pandas() 创建的数据集驻留在内存中,因此没有关联的缓存目录。这将来可能会改变,但在目前,如果你想减少内存使用,你应该将其写回磁盘并使用例如 save_to_disk / load_from_disk 重新加载。

示例

>>> ds = Dataset.from_pandas(df)

from_dict

< >

( mapping: dict features: typing.Optional[datasets.features.features.Features] = None info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None )

参数

  • mapping (Mapping) — 字符串到数组或 Python 列表的映射。
  • features (Features, 可选) — 数据集的特征。
  • info (DatasetInfo, 可选) — 数据集信息,如描述、引用等。
  • split (NamedSplit, 可选) — 数据集分片名称。

dict 转换为 pyarrow.Table 以创建 Dataset

重要提示:使用 from_dict() 创建的数据集驻留在内存中,因此没有关联的缓存目录。这将来可能会改变,但在目前,如果你想减少内存使用,你应该将其写回磁盘并使用例如 save_to_disk / load_from_disk 重新加载。

from_generator

< >

( generator: typing.Callable features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False gen_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None split: NamedSplit = NamedSplit('train') fingerprint: typing.Optional[str] = None **kwargs )

参数

  • generator ( —Callable): 一个通过 yield 产生样本的生成器函数。
  • features (Features, 可选) — 数据集的特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 用于缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • gen_kwargs(dict, 可选) — 要传递给 generator 可调用对象的关键字参数。您可以通过在 gen_kwargs 中传递分片列表并设置 num_proc 大于 1 来定义分片数据集。
  • num_proc (int, 可选, 默认为 None) — 在本地下载和生成数据集时的进程数。如果数据集由多个文件组成,这很有用。默认情况下禁用多进程。如果 num_proc 大于 1,则 gen_kwargs 中的所有列表值必须具有相同的长度。这些值将在分发给生成器调用时进行拆分。分片数将是 gen_kwargs 中最短列表的长度与 num_proc 中的较小值。

    Added in 2.7.0

  • split (NamedSplit, 默认为 Split.TRAIN) — 分配给数据集的分片名称。

    Added in 2.21.0

  • fingerprint (str, 可选) — 用于生成数据集 ID 的指纹。默认情况下,fingerprint 是通过哈希生成器函数和所有参数生成的,如果它使用大型对象(如 AI 模型)可能会很慢。

    Added in 4.3.0

  • **kwargs (其他关键字参数) — 传递给 :GeneratorConfig 的关键字参数。

从生成器创建 Dataset。

示例

>>> def gen():
...     yield {"text": "Good", "label": 0}
...     yield {"text": "Bad", "label": 1}
...
>>> ds = Dataset.from_generator(gen)
>>> def gen(shards):
...     for shard in shards:
...         with open(shard) as f:
...             for line in f:
...                 yield {"line": line}
...
>>> shards = [f"data{i}.txt" for i in range(32)]
>>> ds = Dataset.from_generator(gen, gen_kwargs={"shards": shards})

data

< >

( )

支持数据集的 Apache Arrow 表。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.data
MemoryMappedTable
text: string
label: int64
----
text: [["compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .","the soundtrack alone is worth the price of admission .","rodriguez does a splendid job of racial profiling hollywood style--casting excellent latin actors of all ages--a trend long overdue .","beneath the film's obvious determination to shock at any cost lies considerable skill and determination , backed by sheer nerve .","bielinsky is a filmmaker of impressive talent .","so beautifully acted and directed , it's clear that washington most certainly has a new career ahead of him if he so chooses .","a visual spectacle full of stunning images and effects .","a gentle and engrossing character study .","it's enough to watch huppert scheming , with her small , intelligent eyes as steady as any noir villain , and to enjoy the perfectly pitched web of tension that chabrol spins .","an engrossing portrait of uncompromising artists trying to create something original against the backdrop of a corporate music industry that only seems to care about the bottom line .",...,"ultimately , jane learns her place as a girl , softens up and loses some of the intensity that made her an interesting character to begin with .","ah-nuld's action hero days might be over .","it's clear why deuces wild , which was shot two years ago , has been gathering dust on mgm's shelf .","feels like nothing quite so much as a middle-aged moviemaker's attempt to surround himself with beautiful , half-naked women .","when the precise nature of matthew's predicament finally comes into sharp focus , the revelation fails to justify the build-up .","this picture is murder by numbers , and as easy to be bored by as your abc's , despite a few whopping shootouts .","hilarious musical comedy though stymied by accents thick as mud .","if you are into splatter movies , then you will probably have a reasonably good time with the salton sea .","a dull , simple-minded and stereotypical tale of drugs , death and mind-numbing indifference on the inner-city streets .","the feature-length stretch . . . strains the show's concept ."]]
label: [[1,1,1,1,1,1,1,1,1,1,...,0,0,0,0,0,0,0,0,0,0]]

cache_files

< >

( )

包含数据集的 Apache Arrow 表的缓存文件。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.cache_files
[{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-validation.arrow'}]

num_columns

< >

( )

数据集中列的数量。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.num_columns
2

num_rows

< >

( )

数据集中行的数量(与 Dataset.len() 相同)。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.num_rows
1066

column_names

< >

( )

数据集中列的名称。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.column_names
['text', 'label']

shape

< >

( )

数据集的形状(列数,行数)。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.shape
(1066, 2)

unique

< >

( column: str ) list

参数

  • column (str) — 列名(使用 column_names 列出所有列名)。

返回

list

给定列中唯一元素的列表。

返回给定列中唯一元素的列表。

这在底层后端实现,因此速度非常快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.unique('label')
[1, 0]

flatten

< >

( new_fingerprint: typing.Optional[str] = None max_depth = 16 ) Dataset

参数

  • new_fingerprint (str, 可选) — 转换后数据集的新指纹。如果为 None,则使用先前指纹和转换参数的哈希值来计算新指纹。

返回

数据集

一个具有展平列的数据集副本。

展平表。具有 struct 类型的每个列都会被展平为一个 struct 字段的列。其他列保持不变。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad", split="train")
>>> ds.features
{'id': Value('string'),
 'title': Value('string'),
 'context': Value('string'),
 'question': Value('string'),
 'answers': {'text': List(Value('string')),
 'answer_start': List(Value('int32'))}}
>>> ds = ds.flatten()
>>> ds
Dataset({
    features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
    num_rows: 87599
})

cast

< >

( features: Features batch_size: typing.Optional[int] = 1000 keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 num_proc: typing.Optional[int] = None ) Dataset

参数

  • features (Features) — 用于将数据集转换为的新特征。特征中的字段名称必须与当前的列名匹配。数据类型也必须可以相互转换。对于非平凡的转换,例如 str <-> ClassLabel,您应该使用 map() 来更新数据集。
  • batch_size (int, 默认为 1000) — 批次中提供给 cast 的示例数量。如果 batch_size <= 0batch_size == None,则将整个数据集作为单个批次提供给 cast。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • load_from_cache_file (bool, 默认为 True 如果缓存已启用) — 如果可以识别存储 function 当前计算结果的缓存文件,则使用它而不是重新计算。
  • cache_file_name (str, 可选, 默认为 None) — 为缓存文件提供一个路径名称。它用于存储计算结果而不是自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入操作的每行行数。此值是内存使用和处理速度之间的良好权衡。较大的值使处理执行更少的查找,较小的值在运行 map() 时消耗的临时内存更少。
  • num_proc (int, 可选, 默认为 None) — 用于多进程的处理数量。默认情况下不使用多进程。

返回

数据集

一个具有转换后特征的数据集副本。

将数据集转换为一组新特征。

示例

>>> from datasets import load_dataset, ClassLabel, Value
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> new_features = ds.features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds.features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('large_string')}

cast_column

< >

( column: str feature: typing.Union[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.LargeList, datasets.features.features.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf, datasets.features.nifti.Nifti] new_fingerprint: typing.Optional[str] = None )

参数

  • column (str) — 列名。
  • feature (FeatureType) — 目标特征。
  • new_fingerprint (str, 可选) — 转换后数据集的新指纹。如果为 None,则使用先前指纹和转换参数的哈希值来计算新指纹。

用于解码的列特征转换。

示例

>>> from datasets import load_dataset, ClassLabel
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds.features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('string')}

remove_columns

< >

( column_names: typing.Union[str, list[str]] new_fingerprint: typing.Optional[str] = None ) Dataset

参数

  • column_names (Union[str, List[str]]) — 要删除的列的名称。
  • new_fingerprint (str, 可选) — 转换后数据集的新指纹。如果为 None,则使用先前指纹和转换参数的哈希值来计算新指纹。

返回

数据集

一个不包含要删除的列的数据集对象副本。

从数据集中删除一个或多个列以及与之相关的特征。

您也可以使用带有 remove_columns 参数的 map() 来删除列,但当前方法不会复制剩余列的数据,因此速度更快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.remove_columns('label')
Dataset({
    features: ['text'],
    num_rows: 1066
})
>>> ds = ds.remove_columns(column_names=ds.column_names) # Removing all the columns returns an empty dataset with the `num_rows` property set to 0
Dataset({
    features: [],
    num_rows: 0
})

rename_column

< >

( original_column_name: str new_column_name: str new_fingerprint: typing.Optional[str] = None ) Dataset

参数

  • original_column_name (str) — 要重命名的列的名称。
  • new_column_name (str) — 列的新名称。
  • new_fingerprint (str, 可选) — 转换后数据集的新指纹。如果为 None,则使用先前指纹和转换参数的哈希值来计算新指纹。

返回

数据集

一个具有重命名列的数据集副本。

重命名数据集中的列,并将与原始列关联的特征移动到新列名下。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.rename_column('label', 'label_new')
Dataset({
    features: ['text', 'label_new'],
    num_rows: 1066
})

rename_columns

< >

( column_mapping: dict new_fingerprint: typing.Optional[str] = None ) Dataset

参数

  • column_mapping (Dict[str, str]) — 一个将列重命名为其新名称的映射
  • new_fingerprint (str, optional) — 转换后数据集的新指纹。如果为 None,则使用上一个指纹和转换参数的哈希值来计算新指纹。

返回

数据集

重命名列后的数据集的副本

重命名数据集中的多个列,并将与原始列关联的特征移动到新列名下。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.rename_columns({'text': 'text_new', 'label': 'label_new'})
Dataset({
    features: ['text_new', 'label_new'],
    num_rows: 1066
})

select_columns

< >

( column_names: typing.Union[str, list[str]] new_fingerprint: typing.Optional[str] = None ) Dataset

参数

  • column_names (Union[str, List[str]]) — 要保留的列的名称。
  • new_fingerprint (str, optional) — 转换后数据集的新指纹。如果为 None,则使用上一个指纹和转换参数的哈希值来计算新指纹。

返回

数据集

仅包含所选列的数据集对象的副本。

从数据集中选择一个或多个列以及与它们关联的特征。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.select_columns(['text'])
>>> ds
Dataset({
    features: ['text'],
    num_rows: 1066
})

class_encode_column

< >

( column: str include_nulls: bool = False )

参数

  • column (str) — 要转换(使用 column_names 列出所有列名)的列的名称
  • include_nulls (bool, 默认为 False) — 是否在类标签中包含空值。如果为 True,空值将被编码为 "None" 类标签。

    Added in 1.14.2

将给定列转换为 ClassLabel 并更新表格。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("google/boolq", split="validation")
>>> ds.features
{'answer': Value('bool'),
 'passage': Value('string'),
 'question': Value('string')}
>>> ds = ds.class_encode_column('answer')
>>> ds.features
{'answer': ClassLabel(num_classes=2, names=['False', 'True']),
 'passage': Value('string'),
 'question': Value('string')}

__len__

< >

( )

数据集中样本的数量。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.__len__
<bound method Dataset.__len__ of Dataset({
    features: ['text', 'label'],
    num_rows: 1066
})>

__iter__

< >

( )

遍历样本。

如果使用 [~datasets.Dataset.set_format] 设置了格式,则返回的行将具有所选的格式。

iter

< >

( batch_size: int drop_last_batch: bool = False )

参数

  • batch_size (int) — 要产生的每个批次的大小。
  • drop_last_batch (bool, default False) — 是否应丢弃小于 batch_size 的最后一个批次

遍历大小为 batch_size 的批次。

如果使用 [~datasets.Dataset.set_format] 设置了格式,则返回的行将具有所选的格式。

formatted_as

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

参数

  • type (str, optional) — 输出类型,选择自 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars']None 意味着 getitem 返回 Python 对象(默认)。
  • columns (List[str], optional) — 要在输出中格式化的列。None 表示 __getitem__ 返回所有列(默认)。
  • output_all_columns (bool, defaults to False) — 保留未格式化的列(作为 Python 对象)在输出中。
  • **format_kwargs (附加关键字参数) — 传递给转换函数(如 np.arraytorch.tensortensorflow.ragged.constant)的关键字参数。

用于 with 语句。设置 __getitem__ 返回格式(类型和列)。

set_format

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

参数

  • type (str, optional) — 输出类型,选择自 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars']None 意味着 __getitem__ 返回 Python 对象(默认)。
  • columns (List[str], optional) — 要在输出中格式化的列。None 表示 __getitem__ 返回所有列(默认)。
  • output_all_columns (bool, defaults to False) — 保留未格式化的列(作为 Python 对象)在输出中。
  • **format_kwargs (附加关键字参数) — 传递给转换函数(如 np.arraytorch.tensortensorflow.ragged.constant)的关键字参数。

with 语句中使用。设置 __getitem__ 返回格式(类型和列)。格式 type(例如“numpy”)用于在 $\text{使用 }\text{__getitem__}$ 时格式化批次。也可以使用 [~datasets.Dataset.set_transform] 通过自定义转换进行格式化。

在调用 set_format 后可以调用 [~datasets.Dataset.map]。由于 map 可能会添加新列,因此格式化列的列表

会被更新。在这种情况下,如果你在数据集上应用 map 来添加一个新列,那么这个新列将按以下方式格式化:

new formatted columns = (all columns - previously unformatted columns)

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.set_format(type='numpy', columns=['text', 'label'])
>>> ds.format
{'type': 'numpy',
'format_kwargs': {},
'columns': ['text', 'label'],
'output_all_columns': False}

set_transform

< >

( transform: typing.Optional[typing.Callable] columns: typing.Optional[list] = None output_all_columns: bool = False )

参数

  • transform (Callable, optional) — 用户定义的格式化转换,替换 set_format() 定义的格式。格式化函数是一个可调用对象,它接收一个批次(作为 dict)作为输入并返回一个批次。此函数在 __getitem__ 中返回对象之前应用。
  • columns (List[str], optional) — 要格式化的列。如果指定,则转换的输入批次仅包含这些列。
  • output_all_columns (bool, defaults to False) — 在输出中保留未格式化的列(作为 Python 对象)。如果设置为 True,则其他未格式化的列将与转换的输出一起保留。

使用此转换设置 __getitem__ 的返回格式。调用 __getitem__ 时,转换会即时应用于批次。与 set_format() 类似,可以使用 reset_format() 重置。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
>>> def encode(batch):
...     return tokenizer(batch['text'], padding=True, truncation=True, return_tensors='pt')
>>> ds.set_transform(encode)
>>> ds[0]
{'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1]),
 'input_ids': tensor([  101, 29353,  2135, 15102,  1996,  9428, 20868,  2890,  8663,  6895,
         20470,  2571,  3663,  2090,  4603,  3017,  3008,  1998,  2037, 24211,
         5637,  1998, 11690,  2336,  1012,   102]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0])}

reset_format

< >

( )

__getitem__ 的返回格式重置为 Python 对象和所有列。

self.set_format() 相同

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.set_format(type='numpy', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds.format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}
>>> ds.reset_format()
>>> ds.format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}

with_format

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

参数

  • type (str, optional) — 输出类型,可选值包括 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars']None 表示 __getitem__ 返回 Python 对象(默认)。
  • columns (List[str], optional) — 要格式化的列。None 表示 __getitem__ 返回所有列(默认)。
  • output_all_columns (bool, defaults to False) — 保留未格式化的列(作为 Python 对象)在输出中。
  • **format_kwargs (additional keyword arguments) — 传递给转换函数的关键字参数,例如 np.arraytorch.tensortensorflow.ragged.constant

使用此转换设置 __getitem__ 的返回格式(类型和列)。数据格式化是即时应用的。格式 type(例如“numpy”)用于格式化批次,当使用 __getitem__ 时。

也可以使用 with_transform() 使用自定义转换进行格式化。

set_format() 不同,with_format 返回一个新的 Dataset 对象。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}
>>> ds = ds.with_format("torch")
>>> ds.format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'torch'}
>>> ds[0]
{'text': 'compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 'label': tensor(1),
 'input_ids': tensor([  101, 18027, 16310, 16001,  1103,  9321,   178, 11604,  7235,  6617,
        1742,  2165,  2820,  1206,  6588, 22572, 12937,  1811,  2153,  1105,
        1147, 12890, 19587,  6463,  1105, 15026,  1482,   119,   102,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
 'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])}

with_transform

< >

( transform: typing.Optional[typing.Callable] columns: typing.Optional[list] = None output_all_columns: bool = False )

参数

  • transform (Callable, optional) — 用户定义的格式化转换,替换 set_format() 定义的格式。格式化函数是一个可调用对象,它接收一个批次(作为 dict)作为输入并返回一个批次。此函数在 __getitem__ 中返回对象之前应用。
  • columns (List[str], optional) — 要格式化的列。如果指定,则转换的输入批次仅包含这些列。
  • output_all_columns (bool, defaults to False) — 在输出中保留未格式化的列(作为 Python 对象)。如果设置为 True,则其他未格式化的列将与转换的输出一起保留。

使用此转换设置 __getitem__ 的返回格式。调用 __getitem__ 时,转换会即时应用于批次。

set_format() 类似,可以使用 reset_format() 重置。

set_transform() 不同,with_transform 返回一个新的 Dataset 对象。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> def encode(example):
...     return tokenizer(example["text"], padding=True, truncation=True, return_tensors='pt')
>>> ds = ds.with_transform(encode)
>>> ds[0]
{'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1, 1, 1, 1]),
 'input_ids': tensor([  101, 18027, 16310, 16001,  1103,  9321,   178, 11604,  7235,  6617,
         1742,  2165,  2820,  1206,  6588, 22572, 12937,  1811,  2153,  1105,
         1147, 12890, 19587,  6463,  1105, 15026,  1482,   119,   102]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0])}

__getitem__

< >

( key )

可用于按列名(字符串)或按行索引(整数索引、索引可迭代对象或布尔值)进行索引。

cleanup_cache_files

< >

( int

返回

int

已删除文件的数量。

清理数据集缓存目录中的所有缓存文件,如果存在当前使用的缓存文件,则排除它。

在运行此命令时,请小心,确保没有其他进程正在使用其他缓存文件。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.cleanup_cache_files()
10

map

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 features: typing.Optional[datasets.features.features.Features] = None disable_nullable: bool = False fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None suffix_template: str = '_{rank:05d}_of_{num_proc:05d}' new_fingerprint: typing.Optional[str] = None desc: typing.Optional[str] = None try_original_type: typing.Optional[bool] = True )

参数

  • function (Callable) — 具有以下签名之一的函数:

    • function(example: Dict[str, Any]) -> Dict[str, Any] 如果 batched=Falsewith_indices=Falsewith_rank=False
    • function(example: Dict[str, Any], *extra_args) -> Dict[str, Any] 如果 batched=Falsewith_indices=True 和/或 with_rank=True(每个额外参数一个)
    • function(batch: Dict[str, List]) -> Dict[str, List] 如果 batched=Truewith_indices=Falsewith_rank=False
    • function(batch: Dict[str, List], *extra_args) -> Dict[str, List] 如果 batched=Truewith_indices=True 和/或 with_rank=True(每个额外参数一个)

    对于高级用法,函数还可以返回 pyarrow.Table。如果函数是异步的,则 map 将并行运行您的函数。此外,如果您的函数不返回任何内容(None),则 map 将运行您的函数并保持数据集不变。如果未提供函数,则默认为身份函数:lambda x: x

  • with_indices (bool, defaults to False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx[, rank]): ...
  • with_rank (bool, defaults to False) — 向 function 提供进程秩。请注意,在这种情况下,function 的签名应为 def function(example[, idx], rank): ...
  • input_columns (Optional[Union[str, List[str]]], defaults to None) — 要作为位置参数传递给 function 的列。如果为 None,则将一个映射到所有已格式化列的 dict 作为单个参数传递。
  • batched (bool, defaults to False) — 向 function 提供示例批次。
  • batch_size (int, optional, defaults to 1000) — Number of examples per batch provided to function if batched=True. If batch_size <= 0 or batch_size == None, provide the full dataset as a single batch to function.
  • drop_last_batch (bool, defaults to False) — Whether a last batch smaller than the batch_size should be dropped instead of being processed by the function.
  • remove_columns (Optional[Union[str, List[str]]], defaults to None) — Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of function, i.e. if function is adding columns with names in remove_columns, these columns will be kept.
  • keep_in_memory (bool, defaults to False) — Keep the dataset in memory instead of writing it to a cache file.
  • load_from_cache_file (Optional[bool], defaults to True if caching is enabled) — If a cache file storing the current computation from function can be identified, use it instead of recomputing.
  • cache_file_name (str, optional, defaults to None) — Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name.
  • writer_batch_size (int, defaults to 1000) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running map.
  • features (Optional[datasets.Features], defaults to None) — Use a specific Features to store the cache file instead of the automatically generated one.
  • disable_nullable (bool, defaults to False) — Disallow null values in the table.
  • fn_kwargs (Dict, optional, defaults to None) — Keyword arguments to be passed to function.
  • num_proc (int, optional, defaults to None) — The number of processes to use for multiprocessing.

    • If None or 0, no multiprocessing is used and the operation runs in the main process.
    • If greater than 1, one or multiple worker processes are used to process data in parallel. Note: The function passed to map() must be picklable for multiprocessing to work correctly (i.e., prefer functions defined at the top level of a module, not inside another function or class). suffixtemplate (str): If cache_file_name is specified, then this suffix will be added at the end of the base name of each. Defaults to `”{rank:05d}of{num_proc:05d}”. For example, if cache_file_nameis "processed.arrow", then forrank=1andnum_proc=4, the resulting file would be “processed_00001_of_00004.arrow”` for the default suffix.
  • new_fingerprint (str, optional, defaults to None) — The new fingerprint of the dataset after transform. If None, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.
  • desc (str, optional, defaults to None) — Meaningful description to be displayed alongside with the progress bar while mapping examples.
  • try_original_type (Optional[bool], defaults to True) — Try to keep the types of the original columns (e.g. int32 -> int32). Set to False if you want to always infer new types.

Apply a function to all the examples in the table (individually or in batches) and update the table. If your function returns a column that already exists, then it overwrites it.

You can specify whether the function should be batched or not with the batched parameter

  • If batched is False, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. {"text": "Hello there !"}.
  • If batched is True and batch_size is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is {"text": ["Hello there !"]}.
  • If batched is True and batch_size is n > 1, then the function takes a batch of n examples as input and can return a batch with n examples, or with an arbitrary number of examples. Note that the last batch may have less than n examples. A batch is a dictionary, e.g. a batch of n examples is {"text": ["Hello there !"] * n}.

If the function is asynchronous, then map will run your function in parallel, with up to one thousand simultaneous calls. It is recommended to use a asyncio.Semaphore in your function if you want to set a maximum number of operations that can run at the same time.

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> ds[0:3]["text"]
['Review: compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 'Review: the soundtrack alone is worth the price of admission .',
 'Review: rodriguez does a splendid job of racial profiling hollywood style--casting excellent latin actors of all ages--a trend long overdue .']

# process a batch of examples
>>> ds = ds.map(lambda example: tokenizer(example["text"]), batched=True)
# set number of processors
>>> ds = ds.map(add_prefix, num_proc=4)

过滤器

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None suffix_template: str = '_{rank:05d}_of_{num_proc:05d}' new_fingerprint: typing.Optional[str] = None desc: typing.Optional[str] = None )

参数

  • function (Callable) — Callable with one of the following signatures:

    • function(example: Dict[str, Any]) -> bool if batched=False and with_indices=False and with_rank=False
    • function(example: Dict[str, Any], *extra_args) -> bool if batched=False and with_indices=True and/or with_rank=True (one extra arg for each)
    • function(batch: Dict[str, List]) -> List[bool] if batched=True and with_indices=False and with_rank=False
    • function(batch: Dict[str, List], *extra_args) -> List[bool] if batched=True and with_indices=True and/or with_rank=True (one extra arg for each)

    If the function is asynchronous, then filter will run your function in parallel. If no function is provided, defaults to an always True function: lambda x: True.

  • with_indices (bool, defaults to False) — Provide example indices to function. Note that in this case the signature of function should be def function(example, idx[, rank]): ....
  • with_rank (bool, defaults to False) — Provide process rank to function. Note that in this case the signature of function should be def function(example[, idx], rank): ....
  • input_columns (str or List[str], optional) — The columns to be passed into function as positional arguments. If None, a dict mapping to all formatted columns is passed as one argument.
  • batched (bool, defaults to False) — Provide batch of examples to function.
  • batch_size (int, optional, defaults to 1000) — Number of examples per batch provided to function if batched = True. If batched = False, one example per batch is passed to function. If batch_size <= 0 or batch_size == None, provide the full dataset as a single batch to function.
  • keep_in_memory (bool, defaults to False) — Keep the dataset in memory instead of writing it to a cache file.
  • load_from_cache_file (Optional[bool], 默认为 True, 只要启用了缓存) — 如果能找到存储当前计算的缓存文件,则使用它,而不是重新计算。
  • cache_file_name (str, optional) — 提供缓存文件的路径名。它用于存储计算结果,而不是自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器的每次写入操作的行数。此值在处理过程中的内存使用和处理速度之间取得了良好平衡。值越高,处理时查找次数越少;值越低,运行 map 时消耗的临时内存越少。
  • fn_kwargs (dict, optional) — 要传递给 function 的关键字参数。
  • num_proc (int, optional, 默认为 None) — 用于多进程的进程数。

    • 如果为 None0,则不使用多进程,操作将在主进程中运行。
    • 如果大于 1,则使用一个或多个工作进程并行处理数据。注意:传递给 map() 的函数必须是可序列化的,才能正确使用多进程(即,优先使用定义在模块顶层的函数,而不是定义在另一个函数或类内部)。
  • suffix_template (str) — 如果指定了 cache_file_name,则此后缀将添加到每个基本名称的末尾。例如,如果 cache_file_name"processed.arrow",则对于 rank = 1num_proc = 4,生成的文件的名称将是 "processed_00001_of_00004.arrow"(对于默认后缀,默认为 _{rank:05d}_of_{num_proc:05d})。
  • new_fingerprint (str, optional) — 转换后的数据集的新指纹。如果为 None,则使用上一个指纹和转换参数的哈希值来计算新指纹。
  • desc (str, optional, 默认为 None) — 在过滤示例时,与进度条一起显示的有意义的描述。

通过批处理将过滤函数应用于表中的所有元素,并更新表,使其仅包含符合过滤函数的示例。

如果函数是异步的,则 filter 将并行运行您的函数,最多支持一千个并发调用(可配置)。如果您想设置同时运行的操作的最大数量,建议在函数中使用 asyncio.Semaphore

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.filter(lambda x: x["label"] == 1)
>>> ds
Dataset({
    features: ['text', 'label'],
    num_rows: 533
})

选择

< >

( indices: Iterable keep_in_memory: bool = False indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 new_fingerprint: typing.Optional[str] = None )

参数

  • indices (range, list, iterable, ndarraySeries) — 用于索引的范围、列表或一维数组。如果索引对应于连续范围,则仅对 Arrow 表进行切片。但是,传递一个非连续的索引列表会创建索引映射,这效率低得多,但仍比重新创建由所需行组成的 Arrow 表要快。
  • keep_in_memory (bool, 默认为 False) — 将索引映射保留在内存中,而不是将其写入缓存文件。
  • indices_cache_file_name (str, optional, 默认为 None) — 提供缓存文件的路径名。它用于存储索引映射,而不是自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器的每次写入操作的行数。此值在处理过程中的内存使用和处理速度之间取得了良好平衡。值越高,处理时查找次数越少;值越低,运行 map 时消耗的临时内存越少。
  • new_fingerprint (str, optional, 默认为 None) — 转换后的数据集的新指纹。如果为 None,则使用上一个指纹和转换参数的哈希值来计算新指纹。

创建一个新数据集,其中包含根据索引列表/数组选择的行。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.select(range(4))
>>> ds
Dataset({
    features: ['text', 'label'],
    num_rows: 4
})

sort

< >

( column_names: typing.Union[str, collections.abc.Sequence[str]] reverse: typing.Union[bool, collections.abc.Sequence[bool]] = False null_placement: str = 'at_end' keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 new_fingerprint: typing.Optional[str] = None )

参数

  • column_names (Union[str, Sequence[str]]) — 要排序的列名。
  • reverse (Union[bool, Sequence[bool]], 默认为 False) — 如果为 True,则按降序排序,而不是升序。如果提供单个布尔值,则该值应用于所有列名的排序。否则,必须提供一个与 column_names 长度和顺序相同的布尔值列表。
  • null_placement (str, 默认为 at_end) — 如果为 at_startfirst,则将 None 值放在开头;如果为 at_endlast,则放在末尾。

    Added in 1.14.2

  • keep_in_memory (bool, 默认为 False) — 将排序后的索引保留在内存中,而不是将其写入缓存文件。
  • load_from_cache_file (Optional[bool], 默认为 True, 只要启用了缓存) — 如果能找到存储排序索引的缓存文件,则使用它,而不是重新计算。
  • indices_cache_file_name (str, optional, 默认为 None) — 提供缓存文件的路径名。它用于存储排序后的索引,而不是自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器的每次写入操作的行数。值越高,缓存文件越小;值越低,消耗的临时内存越少。
  • new_fingerprint (str, optional, 默认为 None) — 转换后的数据集的新指纹。如果为 None,则使用上一个指纹和转换参数的哈希值来计算新指纹。

根据单个或多个列创建已排序的新数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset('cornell-movie-review-data/rotten_tomatoes', split='validation')
>>> ds['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> sorted_ds = ds.sort('label')
>>> sorted_ds['label'][:10]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> another_sorted_ds = ds.sort(['label', 'text'], reverse=[True, False])
>>> another_sorted_ds['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

shuffle

< >

( seed: typing.Optional[int] = None generator: typing.Optional[numpy.random._generator.Generator] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 new_fingerprint: typing.Optional[str] = None )

参数

  • seed (int, optional) — 初始化默认 BitGenerator 的种子,如果 generator=None。如果为 None,则将从操作系统获取新的、不可预测的熵。如果传递了 intarray_like[ints],则它将传递给 SeedSequence 以派生初始 BitGenerator 状态。
  • generator (numpy.random.Generator, optional) — 用于计算数据集行排列的 NumPy 随机生成器。如果 generator=None(默认),则使用 np.random.default_rng(NumPy 的默认 BitGenerator (PCG64))。
  • keep_in_memory (bool, 默认 False) — 将打乱后的索引保存在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], 默认如果启用了缓存则为 True) — 如果能识别出存储打乱后索引的缓存文件,则使用它而不是重新计算。
  • indices_cache_file_name (str, optional) — 提供缓存文件的路径名。它用于存储打乱后的索引,而不是使用自动生成的缓存文件名。
  • writer_batch_size (int, 默认 1000) — 缓存文件写入器的每次写入操作的行数。此值在处理过程中的内存使用和处理速度之间取得了良好的权衡。值越高,处理过程中的查找次数越少,值越低,在运行 map 时消耗的临时内存越少。
  • new_fingerprint (str, optional, 默认 None) — 转换后的数据集的新指纹。如果为 None,则使用前一个指纹和转换参数的哈希值来计算新指纹。

创建一个新的 Dataset,其中包含打乱顺序的行。

当前打乱操作使用 numpy 随机生成器。您可以提供一个 NumPy BitGenerator 来使用,或者一个种子来初始化 NumPy 的默认随机生成器(PCG64)。

打乱操作会获取索引列表 [0:len(my_dataset)] 并对其进行打乱以创建索引映射。然而,一旦您的 Dataset 具有索引映射,其速度可能会降低 10 倍。这是因为需要一个额外的步骤来获取要读取的行索引,更重要的是,您不再读取连续的数据块。为了恢复速度,您需要使用 Dataset.flatten_indices() 重新写入磁盘上的整个数据集,该方法会删除索引映射。

不过,这可能需要很长时间,具体取决于您的数据集大小。

my_dataset[0]  # fast
my_dataset = my_dataset.shuffle(seed=42)
my_dataset[0]  # up to 10x slower
my_dataset = my_dataset.flatten_indices()  # rewrite the shuffled dataset on disk as contiguous chunks of data
my_dataset[0]  # fast again

在这种情况下,我们建议切换到 IterableDataset,并利用其快速的近似打乱方法 IterableDataset.shuffle()

它只会打乱分片顺序,并在您的数据集中添加一个打乱缓冲区,从而保持数据集的最佳速度。

my_iterable_dataset = my_dataset.to_iterable_dataset(num_shards=128)
for example in enumerate(my_iterable_dataset):  # fast
    pass

shuffled_iterable_dataset = my_iterable_dataset.shuffle(seed=42, buffer_size=100)

for example in enumerate(shuffled_iterable_dataset):  # as fast as before
    pass

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

# set a seed
>>> shuffled_ds = ds.shuffle(seed=42)
>>> shuffled_ds['label'][:10]
[1, 0, 1, 1, 0, 0, 0, 0, 0, 0]

skip

< >

( n: int )

参数

  • n (int) — 要跳过的元素数量。

创建一个新的 Dataset,跳过前 n 个元素。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]
>>> ds = ds.skip(1)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'},
 {'label': 1,
 'text': 'if you sometimes like to go to the movies to have fun , wasabi is a good place to start .'}]

take

< >

( n: int )

参数

  • n (int) — 要获取的元素数量。

创建一个新的 Dataset,仅包含前 n 个元素。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> small_ds = ds.take(2)
>>> list(small_ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'}]

train_test_split

< >

( test_size: typing.Union[float, int, NoneType] = None train_size: typing.Union[float, int, NoneType] = None shuffle: bool = True stratify_by_column: typing.Optional[str] = None seed: typing.Optional[int] = None generator: typing.Optional[numpy.random._generator.Generator] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None train_indices_cache_file_name: typing.Optional[str] = None test_indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 train_new_fingerprint: typing.Optional[str] = None test_new_fingerprint: typing.Optional[str] = None )

参数

  • test_size (Union[float, int, None], optional) — 测试集的大小。如果为 float,则应在 0.01.0 之间,表示包含在测试集中的数据集的比例。如果为 int,则表示测试样本的绝对数量。如果为 None,则设置为训练大小的补集。如果 train_size 也为 None,则设置为 0.25
  • train_size (Union[float, int, None], optional) — 训练集的大小。如果为 float,则应在 0.01.0 之间,表示包含在训练集中的数据集的比例。如果为 int,则表示训练样本的绝对数量。如果为 None,则自动设置为测试大小的补集。
  • shuffle (bool, optional, 默认 True) — 在分割之前是否打乱数据。
  • stratify_by_column (str, optional, 默认 None) — 用于进行数据分层的标签列的名称。
  • seed (int, optional) — 如果 generator=None,则用于初始化默认 BitGenerator 的种子。如果为 None,则将从操作系统中提取新的、不可预测的熵。如果传递了 intarray_like[ints],则将其传递给 SeedSequence 以派生初始 BitGenerator 状态。
  • generator (numpy.random.Generator, optional) — 用于计算数据集行排列的 NumPy 随机生成器。如果 generator=None(默认),则使用 np.random.default_rng(NumPy 的默认 BitGenerator (PCG64))。
  • keep_in_memory (bool, 默认 False) — 将分割后的索引保存在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], 默认如果启用了缓存则为 True) — 如果能识别出存储分割后索引的缓存文件,则使用它而不是重新计算。
  • train_cache_file_name (str, optional) — 提供缓存文件的路径名。它用于存储训练集索引,而不是使用自动生成的缓存文件名。
  • test_cache_file_name (str, optional) — 提供缓存文件的路径名。它用于存储测试集索引,而不是使用自动生成的缓存文件名。
  • writer_batch_size (int, 默认 1000) — 缓存文件写入器的每次写入操作的行数。此值在处理过程中的内存使用和处理速度之间取得了良好的权衡。值越高,处理过程中的查找次数越少,值越低,在运行 map 时消耗的临时内存越少。
  • train_new_fingerprint (str, optional, 默认 None) — 转换后的训练集的新指纹。如果为 None,则使用前一个指纹和转换参数的哈希值来计算新指纹。
  • test_new_fingerprint (str, optional, 默认 None) — 转换后的测试集的新指纹。如果为 None,则使用前一个指纹和转换参数的哈希值来计算新指纹。

返回一个字典(datasets.DatasetDict),包含两个随机的训练和测试子集(traintest Dataset 分割)。分割根据 test_sizetrain_sizeshuffle 创建。

此方法类似于 scikit-learn 的 train_test_split

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.train_test_split(test_size=0.2, shuffle=True)
DatasetDict({
    train: Dataset({
        features: ['text', 'label'],
        num_rows: 852
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 214
    })
})

# set a seed
>>> ds = ds.train_test_split(test_size=0.2, seed=42)

# stratified split
>>> ds = load_dataset("stanfordnlp/imdb",split="train")
Dataset({
    features: ['text', 'label'],
    num_rows: 25000
})
>>> ds = ds.train_test_split(test_size=0.2, stratify_by_column="label")
DatasetDict({
    train: Dataset({
        features: ['text', 'label'],
        num_rows: 20000
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 5000
    })
})

shard

< >

( num_shards: int index: int contiguous: bool = True keep_in_memory: bool = False indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 )

参数

  • num_shards (int) — 将数据集分成多少个分片。
  • index (int) — 要选择和返回的分片是哪个。
  • contiguous — (bool, 默认为 True): 是否为分片选择连续的索引块。
  • keep_in_memory (bool, 默认为 False) — 将数据集保留在内存中,而不是写入缓存文件。
  • indices_cache_file_name (str, 可选) — 提供缓存文件的路径名称。它用于存储每个分片的索引,而不是自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 这仅涉及索引映射。缓存文件写入器每次写入操作的索引数。此值在处理期间的内存使用量与处理速度之间取得了良好的折衷。值越高,处理的查找次数越少,值越低,在运行 map 时消耗的临时内存越少。

从数据集中返回 index-nth 片,该数据集被分成 num_shards 份。

这会确定性地分片。dataset.shard(n, i) 会将数据集分成连续的块,因此可以在处理后轻松地将它们连接回来。如果 len(dataset) % n == l,则前 l 个数据集的长度都为 (len(dataset) // n) + 1,而其余数据集的长度为 (len(dataset) // n)datasets.concatenate_datasets([dset.shard(n, i) for i in range(n)]) 返回一个与原始数据集顺序相同的多维数据集。

注意:n 应小于或等于数据集中元素的数量 len(dataset)

另一方面,dataset.shard(n, i, contiguous=False) 包含所有索引模 n = i 的数据集元素。

确保在使用任何随机化运算符(如 shuffle)之前进行分片。最好在数据集管道的早期使用分片运算符。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds
Dataset({
    features: ['text', 'label'],
    num_rows: 1066
})
>>> ds = ds.shard(num_shards=2, index=0)
>>> ds
Dataset({
    features: ['text', 'label'],
    num_rows: 533
})

repeat

< >

( num_times: int )

参数

  • num_times (int) — 重复数据集的次数。

创建一个新的 Dataset,该数据集将底层数据集重复 num_times 次。

与 itertools.repeat 类似,重复一次仅返回完整数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> ds = ds.take(2).repeat(2)
>>> list(ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'},
 {'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]

to_tf_dataset

< >

( batch_size: typing.Optional[int] = None columns: typing.Union[str, list[str], NoneType] = None shuffle: bool = False collate_fn: typing.Optional[typing.Callable] = None drop_remainder: bool = False collate_fn_args: typing.Optional[dict[str, typing.Any]] = None label_cols: typing.Union[str, list[str], NoneType] = None prefetch: bool = True num_workers: int = 0 num_test_batches: int = 20 )

参数

  • batch_size (int, 可选) — 从数据集中加载批次的大小。默认为 None,这意味着数据集不会被分批,但返回的数据集稍后可以使用 tf_dataset.batch(batch_size) 进行分批。
  • columns (List[str]str, 可选) — 要加载到 tf.data.Dataset 中的数据集列。可以使用 collate_fn 创建的、在原始数据集中不存在的列名。
  • shuffle(bool, 默认为 False) — 加载时是否打乱数据集顺序。推荐训练时设为 True,验证/评估时设为 False
  • drop_remainder(bool, 默认为 False) — 加载时删除最后一个不完整的批次。确保数据集产生的每个批次在批次维度上都具有相同的长度。
  • collate_fn(Callable, 可选) — 一个函数或可调用对象(如 DataCollator),它将样本列表进行组合以形成一个批次。
  • collate_fn_args (Dict, 可选) — 传递给 collate_fn 的可选关键字参数 dict
  • label_cols (List[str]str, 默认为 None) — 要作为标签加载的数据集列。请注意,许多模型会内部计算损失,而不是让 Keras 进行计算,在这种情况下,可以将标签传递给这里是可选的,只要它们存在于输入 columns 中即可。
  • prefetch (bool, 默认为 True) — 是否在单独的线程中运行数据加载器,并维护一小批数据的缓冲区用于训练。通过允许在模型训练时在后台加载数据来提高性能。
  • num_workers (int, 默认为 0) — 用于加载数据集的工作线程数。
  • num_test_batches (int, 默认为 20) — 用于推断数据集输出签名的批次数。此数字越高,签名就越准确,但创建数据集所需的时间也越长。

从底层 Dataset 创建一个 tf.data.Dataset。此 tf.data.Dataset 将加载和组合 Dataset 中的批次,并适合传递给 model.fit()model.predict() 等方法。数据集将为输入和标签都产生 dict,除非 dict 只包含一个键,在这种情况下,将改为生成原始 tf.Tensor

示例

>>> ds_train = ds["train"].to_tf_dataset(
...    columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'],
...    shuffle=True,
...    batch_size=16,
...    collate_fn=data_collator,
... )

push_to_hub

< >

( repo_id: str config_name: str = 'default' set_default: typing.Optional[bool] = None split: typing.Optional[str] = None data_dir: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = False max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[int] = None embed_external_files: bool = True num_proc: typing.Optional[int] = None )

参数

  • repo_id (str) — 要推送到的存储库 ID,格式如下:<user>/<dataset_name><org>/<dataset_name>。也接受 <dataset_name>,它将默认为已登录用户的命名空间。
  • config_name (str, 默认为 “default”) — 数据集的配置名称(或子集)。默认为“default”。
  • set_default (bool, 可选) — 是否将此配置设置为默认配置。否则,默认配置是名为“default”的配置。
  • split (str, 可选) — 将分配给此数据集的拆分名称。默认为 self.split
  • data_dir (str, optional) — 目录名称,用于存放上传的数据文件。如果与“default”不同,则默认为 config_name,否则为“data”。

    Added in 2.17.0

  • commit_message (str, optional) — 用于提交的消息。默认为 "Upload dataset"
  • commit_description (str, optional) — 将要创建的 commit 的描述。如果 create_pr 为 True,则同时也是 PR 的描述。

    Added in 2.16.0

  • private (bool, optional) — 是否将仓库设为私有。如果为 None (默认值),则仓库将为公共仓库,除非组织的默认设置为私有。如果仓库已存在,则忽略此值。
  • token (str, optional) — Hugging Face Hub 的身份验证令牌。如果未传入令牌,将默认为使用 huggingface-cli login 登录时本地保存的令牌。如果未传入令牌且用户未登录,则会引发错误。
  • revision (str, optional) — 用于推送上传文件的分支。默认为 "main" 分支。

    Added in 2.15.0

  • create_pr (bool, optional, defaults to False) — 是否创建 PR(拉取请求)来上传文件,或者直接提交。

    Added in 2.15.0

  • max_shard_size (int or str, optional, defaults to "500MB") — 要上传到 hub 的数据集分片的最大大小。如果表示为字符串,则需要为数字后跟单位(例如 "5MB")。
  • num_shards (int, optional) — 要写入的分片数。默认情况下,分片数取决于 max_shard_size

    Added in 2.8.0

  • embed_external_files (bool, defaults to True) — 是否将文件字节嵌入分片中。特别是,它会在推送以下类型的字段之前执行:

    • AudioImage:移除本地路径信息并将文件内容嵌入 Parquet 文件中。
  • num_proc (int, optional, defaults to None) — 处理和上传数据集时使用的进程数。如果数据集包含大量样本或媒体文件需要嵌入,这将很有帮助。默认情况下禁用多进程。

    Added in 4.0.0

将数据集作为 Parquet 数据集推送到 hub。数据集使用 HTTP 请求推送,无需安装 git 或 git-lfs。

默认情况下,生成的 Parquet 文件是自包含的。如果您的数据集包含 ImageAudioVideo 数据,Parquet 文件将存储您的图像或音频文件的字节。您可以通过将 embed_external_files 设置为 False 来禁用此功能。

示例

>>> dataset.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB")
>>> dataset.push_to_hub("<organization>/<dataset_id>", num_shards=1024)

如果您的数据集有多个分割(例如 train/validation/test)

>>> train_dataset.push_to_hub("<organization>/<dataset_id>", split="train")
>>> val_dataset.push_to_hub("<organization>/<dataset_id>", split="validation")
>>> # later
>>> dataset = load_dataset("<organization>/<dataset_id>")
>>> train_dataset = dataset["train"]
>>> val_dataset = dataset["validation"]

如果您想为数据集添加新的配置(或子集)(例如,如果数据集有多个任务/版本/语言)

>>> english_dataset.push_to_hub("<organization>/<dataset_id>", "en")
>>> french_dataset.push_to_hub("<organization>/<dataset_id>", "fr")
>>> # later
>>> english_dataset = load_dataset("<organization>/<dataset_id>", "en")
>>> french_dataset = load_dataset("<organization>/<dataset_id>", "fr")

save_to_disk

< >

( dataset_path: typing.Union[str, bytes, os.PathLike] max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[int] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None )

参数

  • dataset_path (path-like) — 数据集目录的路径(例如 dataset/train)或远程 URI(例如 s3://my-bucket/dataset/train),数据集将保存到此处。
  • max_shard_size (int or str, optional, defaults to "500MB") — 要保存到文件系统的数据集分片的最大大小。如果表示为字符串,则需要为数字后跟单位(例如 "50MB")。
  • num_shards (int, optional) — 要写入的分片数。默认情况下,分片数取决于 max_shard_sizenum_proc

    Added in 2.8.0

  • num_proc (int, optional) — 下载和生成数据集时的进程数。默认情况下禁用多进程。

    Added in 2.8.0

  • storage_options (dict, optional) — 传递给文件系统后端的键/值对,如果有的话。

    Added in 2.8.0

使用 save_to_disk 将数据集保存到数据集目录,或使用 fsspec.spec.AbstractFileSystem 的任何实现保存到文件系统。

对于 ImageAudioVideo 数据

所有 Image()、Audio() 和 Video() 数据都存储在 arrow 文件中。如果想存储路径或 URL,请使用 Value("string") 类型。

示例

>>> ds.save_to_disk("path/to/dataset/directory")
>>> ds.save_to_disk("path/to/dataset/directory", max_shard_size="1GB")
>>> ds.save_to_disk("path/to/dataset/directory", num_shards=1024)

load_from_disk

< >

( dataset_path: typing.Union[str, bytes, os.PathLike] keep_in_memory: typing.Optional[bool] = None storage_options: typing.Optional[dict] = None ) Dataset or DatasetDict

参数

  • dataset_path (path-like) — 数据集目录的路径(例如 "dataset/train")或远程 URI(例如 "s3//my-bucket/dataset/train"),数据集将从此加载。
  • keep_in_memory (bool, defaults to None) — 是否将数据集保留在内存中,而不是将其写入缓存文件。如果为 None,除非通过将 datasets.config.IN_MEMORY_MAX_SIZE 设置为非零值来明确启用,否则不会将数据集复制到内存中。有关更多详细信息,请参阅 改进性能 部分。
  • storage_options (dict, optional) — 传递给文件系统后端的键/值对,如果有的话。

    Added in 2.8.0

返回

DatasetDatasetDict

  • 如果 dataset_path 是数据集目录的路径,则加载的数据集。
  • 如果 dataset_path 是数据集字典目录的路径,则加载包含每个分割的 datasets.DatasetDict

使用 save_to_disk 从数据集目录加载数据集,或使用 fsspec.spec.AbstractFileSystem 的任何实现从文件系统加载数据集。

示例

>>> ds = load_from_disk("path/to/dataset/directory")

flatten_indices

< >

( keep_in_memory: bool = False cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 features: typing.Optional[datasets.features.features.Features] = None disable_nullable: bool = False num_proc: typing.Optional[int] = None new_fingerprint: typing.Optional[str] = None )

参数

  • keep_in_memory (bool, defaults to False) — 在内存中保留数据集,而不是将其写入缓存文件。
  • cache_file_name (str, optional, default None) — 提供缓存文件的路径名。它用于存储计算结果,而不是自动生成的缓存文件名。
  • writer_batch_size (int, defaults to 1000) — 写入缓存文件的每批记录数。此值在处理过程中的内存使用量和处理速度之间取得了很好的平衡。值越高,处理过程中的查找次数越少;值越低,运行 map 时消耗的临时内存越少。
  • features (Optional[datasets.Features], defaults to None) — 使用特定的 Features 来存储缓存文件,而不是自动生成的。
  • disable_nullable (bool, defaults to False) — 允许表中包含 null 值。
  • num_proc (int, optional, default None) — 生成缓存时的最大进程数。已缓存的分片按顺序加载。
  • new_fingerprint (str, optional, defaults to None) — 转换后数据集的新指纹。如果为 None,则使用前一个指纹和转换参数的哈希来计算新指纹。

通过展平索引映射来创建和缓存新数据集。

to_csv

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **to_csv_kwargs ) int

参数

  • path_or_buf (PathLike or FileOrBuffer) — 要保存数据集的文件路径(例如 file.csv)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.csv)或 BinaryIO。
  • batch_size (int, optional) — 一次性加载和写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • num_proc (int, optional) — 用于多进程的数量。默认情况下不使用多进程。在这种情况下,batch_size 默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE,但如果您有足够的计算能力,可以将其设置为默认值的 5 倍或 10 倍。
  • storage_options (dict, optional) — 传递给文件系统后端的键/值对(如果存在)。

    Added in 2.19.0

  • **to_csv_kwargs (additional keyword arguments) — 传递给 pandas 的 pandas.DataFrame.to_csv 的参数。

    Changed in 2.10.0

    现在,如果未指定,index 默认为 False

    如果要写入索引,请传递 index=True,并通过传递 index_label 来为索引列设置名称。

返回

int

写入的字符数或字节数。

将数据集导出到 CSV

示例

>>> ds.to_csv("path/to/dataset/directory")

to_pandas

< >

( batch_size: typing.Optional[int] = None batched: bool = False )

参数

  • batch_size (int, optional) — 如果 batchedTrue,则批次的数量(行数)。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • batched (bool) — 设置为 True 可返回一个生成器,该生成器会以 batch_size 行的批次形式生成数据集。默认为 False(一次性返回整个数据集)。

将数据集返回为 pandas.DataFrame。对于大型数据集,也可以返回一个生成器。

示例

>>> ds.to_pandas()

to_dict

< >

( batch_size: typing.Optional[int] = None batched: bool = False )

参数

  • batch_size (int, optional) — 如果 batchedTrue,则批次的数量(行数)。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • batched (bool) — 设置为 True 可返回一个生成器,该生成器会以 batch_size 行的批次形式生成数据集。默认为 False(一次性返回整个数据集)。

将数据集返回为 Python 字典。对于大型数据集,也可以返回一个生成器。

示例

>>> ds.to_dict()

to_json

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **to_json_kwargs ) int

参数

  • path_or_buf (PathLike or FileOrBuffer) — 要保存数据集的文件路径(例如 file.json)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.json)或 BinaryIO。
  • batch_size (int, optional) — 一次性加载和写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • num_proc (int, optional) — 用于多进程的数量。默认情况下不使用多进程。在这种情况下,batch_size 默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE,但如果您有足够的计算能力,可以将其设置为默认值的 5 倍或 10 倍。
  • storage_options (dict, optional) — 传递给文件系统后端的键/值对(如果存在)。

    Added in 2.19.0

  • **to_json_kwargs (additional keyword arguments) — 传递给 pandas 的 pandas.DataFrame.to_json 的参数。默认参数为 lines=Trueorient=“records”

    Changed in 2.11.0

    orient"split""table" 时,index 参数默认为 False

    如果要写入索引,请传递 index=True

返回

int

写入的字符数或字节数。

将数据集导出到 JSON Lines 或 JSON。

默认的输出格式是 JSON Lines。要导出到 JSON,请传递 lines=False 参数和所需的 orient

示例

>>> ds.to_json("path/to/dataset/directory/filename.jsonl")

to_parquet

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **parquet_writer_kwargs ) int

参数

  • path_or_buf (PathLike or FileOrBuffer) — 要保存数据集到的文件路径(例如 file.parquet)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.parquet)或 BinaryIO。
  • batch_size (int, optional) — 一次性加载到内存并写入的批次大小。默认情况下,它以 datasets.config.MAX_ROW_GROUP_SIZE 定义的、未压缩字节大小最大为“100MB”的行组为目标。
  • storage_options (dict, optional) — 传递给文件系统后端的键/值对(如果有)。

    Added in 2.19.0

  • **parquet_writer_kwargs (附加关键字参数) — 传递给 PyArrow 的 pyarrow.parquet.ParquetWriter 的参数。

返回

int

写入的字符数或字节数。

将数据集导出到 parquet

示例

>>> ds.to_parquet("path/to/dataset/directory")

to_sql

< >

( name: str con: typing.Union[str, ForwardRef('sqlalchemy.engine.Connection'), ForwardRef('sqlalchemy.engine.Engine'), ForwardRef('sqlite3.Connection')] batch_size: typing.Optional[int] = None **sql_writer_kwargs ) int

参数

  • name (str) — SQL 表的名称。
  • con (strsqlite3.Connectionsqlalchemy.engine.Connectionsqlalchemy.engine.Connection) — 用于写入数据库的 URI 字符串或 SQLite3/SQLAlchemy 连接对象。
  • batch_size (int, optional) — 一次性加载到内存并写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • **sql_writer_kwargs (附加关键字参数) — 传递给 pandas 的 pandas.DataFrame.to_sql 的参数。

    Changed in 2.11.0

    现在,如果未指定 index,则默认为 False

    如果要写入索引,请传递 index=True 并且还通过传递 index_label 为索引列设置名称。

返回

int

写入的记录数。

将数据集导出到 SQL 数据库。

示例

>>> # con provided as a connection URI string
>>> ds.to_sql("data", "sqlite:///my_own_db.sql")
>>> # con provided as a sqlite3 connection object
>>> import sqlite3
>>> con = sqlite3.connect("my_own_db.sql")
>>> with con:
...     ds.to_sql("data", con)

to_iterable_dataset

< >

( num_shards: typing.Optional[int] = 1 )

参数

  • num_shards (int, default to 1) — 在实例化可迭代数据集时定义的切片数量。这在需要正确洗牌的大型数据集,以及例如使用 PyTorch DataLoader 或在分布式设置中启用快速并行加载时特别有用。使用 datasets.Dataset.shard() 定义切片:它仅对数据进行切片而不在磁盘上写入任何内容。

从映射式 datasets.Dataset 获取一个 datasets.IterableDataset。这等同于使用 datasets.load_dataset() 以流式模式加载数据集,但由于数据从本地文件流式传输,因此速度快得多。

与映射式数据集相反,可迭代数据集是惰性的,只能被迭代(例如,使用 for 循环)。由于它们在训练循环中按顺序读取,因此可迭代数据集比映射式数据集快得多。应用于可迭代数据集的所有转换,如过滤或处理,都在您开始迭代数据集时即时完成。

尽管如此,仍可以使用 datasets.IterableDataset.shuffle() 洗牌可迭代数据集。这是一种快速的近似洗牌,如果您有多个切片并且指定了足够大的缓冲区大小,效果最好。

为了获得最佳速度性能,请确保您的数据集没有索引映射。如果是这种情况,数据不是连续读取的,有时会很慢。您可以使用 ds = ds.flatten_indices() 在切换到可迭代数据集之前,将数据集写入连续的数据块并获得最佳速度。

示例

基本用法

>>> ids = ds.to_iterable_dataset()
>>> for example in ids:
...     pass

使用惰性过滤和处理

>>> ids = ds.to_iterable_dataset()
>>> ids = ids.filter(filter_fn).map(process_fn)  # will filter and process on-the-fly when you start iterating over the iterable dataset
>>> for example in ids:
...     pass

使用分片来启用高效洗牌

>>> ids = ds.to_iterable_dataset(num_shards=64)  # the dataset is split into 64 shards to be iterated over
>>> ids = ids.shuffle(buffer_size=10_000)  # will shuffle the shards order and use a shuffle buffer for fast approximate shuffling when you start iterating
>>> for example in ids:
...     pass

使用 PyTorch DataLoader

>>> import torch
>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.filter(filter_fn).map(process_fn)
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards to each worker to load, filter and process when you start iterating
>>> for example in ids:
...     pass

使用 PyTorch DataLoader 和洗牌

>>> import torch
>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.shuffle(buffer_size=10_000)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards from the shuffled list of shards to each worker when you start iterating
>>> for example in ids:
...     pass

在分布式设置中,例如使用 PyTorch DDP 配合 PyTorch DataLoader 和洗牌

>>> from datasets.distributed import split_dataset_by_node
>>> ids = ds.to_iterable_dataset(num_shards=512)
>>> ids = ids.shuffle(buffer_size=10_000, seed=42)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> ids = split_dataset_by_node(ds, world_size=8, rank=0)  # will keep only 512 / 8 = 64 shards from the shuffled lists of shards when you start iterating
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards from this node's list of shards to each worker when you start iterating
>>> for example in ids:
...     pass

使用洗牌和多个 epoch

>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.shuffle(buffer_size=10_000, seed=42)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> for epoch in range(n_epochs):
...     ids.set_epoch(epoch)  # will use effective_seed = seed + epoch to shuffle the shards and for the shuffle buffer when you start iterating
...     for example in ids:
...         pass
在使用 PyTorch DataLoader 或在分布式设置中时,请随时使用 `IterableDataset.set_epoch()`。

add_faiss_index

< >

( column: str index_name: typing.Optional[str] = None device: typing.Optional[int] = None string_factory: typing.Optional[str] = None metric_type: typing.Optional[int] = None custom_index: typing.Optional[ForwardRef('faiss.Index')] = None batch_size: int = 1000 train_size: typing.Optional[int] = None faiss_verbose: bool = False dtype = <class 'numpy.float32'> )

参数

  • column (str) — 用于将向量添加到索引中的列。
  • index_name (str, optional) — 索引的 index_name/标识符。这是调用 get_nearest_examples()search() 时使用的 index_name。默认为 column
  • device (Union[int, List[int]], optional) — 如果是正整数,则是要使用的 GPU 的索引。如果是负整数,则使用所有 GPU。如果传入正整数列表,则仅在这些 GPU 上运行。默认为 CPU。
  • string_factory (str, optional) — 这传递给 Faiss 索引工厂以创建索引。默认索引类是 IndexFlat
  • metric_type (int, optional) — 度量类型。例如:faiss.METRIC_INNER_PRODUCTfaiss.METRIC_L2
  • custom_index (faiss.Index, optional) — 您已经实例化并配置好的自定义 Faiss 索引。
  • batch_size (int) — 在将向量添加到 FaissIndex 时使用的批次大小。默认为 1000

    Added in 2.4.0

  • train_size (int, optional) — 如果索引需要训练步骤,则指定将使用多少个向量来训练索引。
  • faiss_verbose (bool, defaults to False) — 启用 Faiss 索引的详细信息输出。
  • dtype (data-type) — 被索引的 numpy 数组的数据类型。默认为 np.float32

添加一个使用 Faiss 进行快速检索的密集索引。默认情况下,索引是在指定列的向量上进行的。如果您想在 GPU 上运行,可以指定 device (device 必须是 GPU 索引)。您可以在此处找到有关 Faiss 的更多信息

示例

>>> ds = datasets.load_dataset('community-datasets/crime_and_punish', split='train')
>>> ds_with_embeddings = ds.map(lambda example: {'embeddings': embed(example['line']}))
>>> ds_with_embeddings.add_faiss_index(column='embeddings')
>>> # query
>>> scores, retrieved_examples = ds_with_embeddings.get_nearest_examples('embeddings', embed('my new query'), k=10)
>>> # save index
>>> ds_with_embeddings.save_faiss_index('embeddings', 'my_index.faiss')

>>> ds = datasets.load_dataset('community-datasets/crime_and_punish', split='train')
>>> # load index
>>> ds.load_faiss_index('embeddings', 'my_index.faiss')
>>> # query
>>> scores, retrieved_examples = ds.get_nearest_examples('embeddings', embed('my new query'), k=10)

add_faiss_index_from_external_arrays

< >

( external_arrays: <built-in function array> index_name: str device: typing.Optional[int] = None string_factory: typing.Optional[str] = None metric_type: typing.Optional[int] = None custom_index: typing.Optional[ForwardRef('faiss.Index')] = None batch_size: int = 1000 train_size: typing.Optional[int] = None faiss_verbose: bool = False dtype = <class 'numpy.float32'> )

参数

  • external_arrays (np.array) — 如果你想使用库外部的数组进行索引,可以设置 external_arrays。它将使用 external_arrays 来创建 Faiss 索引,而不是使用给定 column 中的数组。
  • index_name (str) — 索引的 index_name/标识符。这是用于调用 get_nearest_examples()search()index_name
  • device (可选 Union[int, List[int]], 可选) — 如果是正整数,则是要使用的 GPU 索引。如果是负整数,则使用所有 GPU。如果传入正整数列表,则仅在这些 GPU 上运行。默认为 CPU。
  • string_factory (str, 可选) — 此参数将传递给 Faiss 的索引工厂,以创建索引。默认索引类是 IndexFlat
  • metric_type (int, 可选) — 度量类型。例如:faiss.faiss.METRIC_INNER_PRODUCTfaiss.METRIC_L2
  • custom_index (faiss.Index, 可选) — 您已经实例化并配置好的自定义 Faiss 索引。
  • batch_size (int, 可选) — 在将向量添加到 FaissIndex 时使用的批次大小。默认值为 1000。

    Added in 2.4.0

  • train_size (int, 可选) — 如果索引需要训练步骤,则指定将使用多少向量来训练索引。
  • faiss_verbose (bool, 默认为 False) — 启用 Faiss 索引的详细信息输出。
  • dtype (numpy.dtype) — 被索引的 numpy 数组的数据类型。默认为 np.float32。

使用 Faiss 为快速检索添加一个密集索引。该索引是使用 external_arrays 的向量创建的。如果您想在 GPU 上运行(device 必须是 GPU 索引),您可以指定 device。您可以在此处找到有关 Faiss 的更多信息

save_faiss_index

< >

( index_name: str file: typing.Union[str, pathlib.PurePath] storage_options: typing.Optional[dict] = None )

参数

  • index_name (str) — 索引的 index_name/标识符。这是用于调用 .get_nearest.search 的 index_name。
  • file (str) — 序列化到磁盘或远程 URI(例如 "s3://my-bucket/index.faiss")的 faiss 索引的路径。
  • storage_options (dict, 可选) — 传递给文件系统后端的键/值对(如果有)。

    Added in 2.11.0

将 FaissIndex 保存到磁盘。

load_faiss_index

< >

( index_name: str file: typing.Union[str, pathlib.PurePath] device: typing.Union[list[int], int, NoneType] = None storage_options: typing.Optional[dict] = None )

参数

  • index_name (str) — 索引的 index_name/标识符。这是用于调用 .get_nearest.search 的 index_name。
  • file (str) — 序列化到磁盘或远程 URI(例如 "s3://my-bucket/index.faiss")的 faiss 索引的路径。
  • device (可选 Union[int, List[int]]) — 如果是正整数,则是要使用的 GPU 索引。如果是负整数,则使用所有 GPU。如果传入正整数列表,则仅在这些 GPU 上运行。默认为 CPU。
  • storage_options (dict, 可选) — 传递给文件系统后端的键/值对(如果有)。

    Added in 2.11.0

从磁盘加载 FaissIndex。

如果要进行其他配置,您可以通过执行 .get_index(index_name).faiss_index 来访问 faiss 索引对象,以使其符合您的需求。

add_elasticsearch_index

< >

( column: str index_name: typing.Optional[str] = None host: typing.Optional[str] = None port: typing.Optional[int] = None es_client: typing.Optional[ForwardRef('elasticsearch.Elasticsearch')] = None es_index_name: typing.Optional[str] = None es_index_config: typing.Optional[dict] = None )

参数

  • column (str) — 要添加到索引中的文档列。
  • index_name (str, 可选) — 用于调用 get_nearest_examples()search()index_name/标识符。默认情况下,它对应于 column
  • host (str, 可选, 默认为 localhost) — ElasticSearch 运行的主机。
  • port (str, 可选, 默认为 9200) — ElasticSearch 运行的端口。
  • es_client (elasticsearch.Elasticsearch, 可选) — 用于创建索引的 elasticsearch 客户端,前提是 host 和 port 为 None
  • es_index_name (str, 可选) — 用于创建索引的 elasticsearch 索引名称。
  • es_index_config (dict, 可选) — elasticsearch 索引的配置。默认配置是:

使用 ElasticSearch 为快速检索添加一个文本索引。这是就地完成的。

示例

>>> es_client = elasticsearch.Elasticsearch()
>>> ds = datasets.load_dataset('community-datasets/crime_and_punish', split='train')
>>> ds.add_elasticsearch_index(column='line', es_client=es_client, es_index_name="my_es_index")
>>> scores, retrieved_examples = ds.get_nearest_examples('line', 'my new query', k=10)

load_elasticsearch_index

< >

( index_name: str es_index_name: str host: typing.Optional[str] = None port: typing.Optional[int] = None es_client: typing.Optional[ForwardRef('Elasticsearch')] = None es_index_config: typing.Optional[dict] = None )

参数

  • index_name (str) — 索引的 index_name/标识符。这是调用 get_nearestsearch 时使用的索引名称。
  • es_index_name (str) — 要加载的 elasticsearch 索引的名称。
  • host (str, 可选, 默认为 localhost) — ElasticSearch 运行的主机。
  • port (str, 可选, 默认为 9200) — ElasticSearch 运行的端口。
  • es_client (elasticsearch.Elasticsearch, 可选) — 如果 hostportNone,则用于创建索引的 elasticsearch 客户端。
  • es_index_config (dict, 可选) — elasticsearch 索引的配置。默认配置为:

使用 ElasticSearch 加载现有文本索引以实现快速检索。

list_indexes

< >

( )

列出所有已附加索引的 colindex_nameumn/标识符。

get_index

< >

( index_name: str )

参数

  • index_name (str) — 索引名称。

列出所有已附加索引的 index_name/标识符。

drop_index

< >

( index_name: str )

参数

  • index_name (str) — 索引的 index_name/标识符。

删除具有指定列的索引。

search

< >

( index_name: str query: typing.Union[str, <built-in function array>] k: int = 10 **kwargs ) (scores, indices)

参数

  • index_name (str) — 索引的名称/标识符。
  • query (Union[str, np.ndarray]) — 如果 index_name 是文本索引,则查询为字符串;如果 index_name 是向量索引,则为 numpy 数组。
  • k (int) — 要检索的示例数量。

返回

(scores, indices)

一个元组 (scores, indices),其中

  • scores (List[List[float]): 从 FAISS(默认 IndexFlatL2)或 ElasticSearch 检索到的示例的分数
  • indices (List[List[int]]): 检索到的示例的索引

在数据集中查找最接近查询的示例索引。

search_batch

< >

( index_name: str queries: typing.Union[list[str], <built-in function array>] k: int = 10 **kwargs ) (total_scores, total_indices)

参数

  • index_name (str) — 索引的 index_name/标识符。
  • queries (Union[List[str], np.ndarray]) — 如果 index_name 是文本索引,则查询为字符串列表;如果 index_name 是向量索引,则为 numpy 数组。
  • k (int) — 每个查询要检索的示例数量。

返回

(total_scores, total_indices)

一个元组 (total_scores, total_indices),其中

  • total_scores (List[List[float]): 每个查询从 FAISS(默认 IndexFlatL2)或 ElasticSearch 检索到的示例的分数
  • total_indices (List[List[int]]): 每个查询检索到的示例的索引

在数据集中查找最接近查询的示例索引。

get_nearest_examples

< >

( index_name: str query: typing.Union[str, <built-in function array>] k: int = 10 **kwargs ) (scores, examples)

参数

  • index_name (str) — 索引的 index_name/标识符。
  • query (Union[str, np.ndarray]) — 如果 index_name 是文本索引,则查询为字符串;如果 index_name 是向量索引,则为 numpy 数组。
  • k (int) — 要检索的示例数量。

返回

(scores, examples)

一个元组 (scores, examples),其中

  • scores (List[float]): 从 FAISS(默认 IndexFlatL2)或 ElasticSearch 检索到的示例的分数
  • examples (dict): 检索到的示例

查找数据集中最接近查询的示例。

get_nearest_examples_batch

< >

( index_name: str queries: typing.Union[list[str], <built-in function array>] k: int = 10 **kwargs ) (total_scores, total_examples)

参数

  • index_name (str) — 索引的 index_name/标识符。
  • queries (Union[List[str], np.ndarray]) — 如果 index_name 是文本索引,则查询为字符串列表;如果 index_name 是向量索引,则为 numpy 数组。
  • k (int) — 每个查询要检索的示例数量。

返回

(total_scores, total_examples)

一个元组 (total_scores, total_examples),其中

  • total_scores (List[List[float]): 每个查询从 FAISS(默认 IndexFlatL2)或 ElasticSearch 检索到的示例的分数
  • total_examples (List[dict]): 每个查询检索到的示例

查找数据集中最接近查询的示例。

info

< >

( )

DatasetInfo 对象,包含数据集中的所有元数据。

split

< >

( )

NamedSplit 对象,对应一个命名的数据集分片。

builder_name

< >

( )

引用

< >

( )

config_name

< >

( )

dataset_size

< >

( )

description

< >

( )

download_checksums

< >

( )

download_size

< >

( )

features

< >

( )

homepage

< >

( )

许可证

< >

( )

size_in_bytes

< >

( )

supervised_keys

< >

( )

版本

< >

( )

from_csv

< >

( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False num_proc: typing.Optional[int] = None **kwargs )

参数

  • path_or_paths (path-likepath-like 列表) — CSV 文件的路径。
  • split (NamedSplit, 可选) — 分配给数据集的名称。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • num_proc (int, 可选, 默认为 None) — 下载和本地生成数据集时的进程数。当数据集由多个文件组成时,这很有帮助。默认情况下禁用多进程。

    Added in 2.8.0

  • **kwargs (其他关键字参数) — 传递给 pandas.read_csv 的关键字参数。

从 CSV 文件创建数据集。

示例

>>> ds = Dataset.from_csv('path/to/dataset.csv')

from_json

< >

( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False field: typing.Optional[str] = None num_proc: typing.Optional[int] = None **kwargs )

参数

  • path_or_paths (path-likepath-like 列表) — JSON 或 JSON Lines 文件的路径。
  • split (NamedSplit, 可选) — 分配给数据集的名称。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • field (str, 可选) — 数据集所在的 JSON 文件的字段名。
  • num_proc (int, optional, 默认为 None) — 下载和本地生成数据集时的进程数。如果数据集由多个文件组成,则此参数非常有用。默认情况下,多进程是禁用的。

    Added in 2.8.0

  • **kwargs (additional keyword arguments) — Keyword arguments to be passed to JsonConfig.

从 JSON 或 JSON Lines 文件创建数据集。

示例

>>> ds = Dataset.from_json('path/to/dataset.json')

from_parquet

< >

( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False columns: typing.Optional[list[str]] = None num_proc: typing.Optional[int] = None **kwargs )

参数

  • path_or_paths (path-likepath-like列表) — Parquet 文件路径。
  • split (NamedSplit, optional) — 要分配给数据集的分割名称。
  • features (Features, optional) — 数据集特征。
  • cache_dir (str, optional, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • columns (List[str], optional) — 如果不为 None,则只从文件中读取这些列。列名可以是嵌套字段的前缀,例如“a”将选择“a.b”、“a.c”和“a.d.e”。
  • num_proc (int, optional, 默认为 None) — 下载和本地生成数据集时的进程数。如果数据集由多个文件组成,则此参数非常有用。默认情况下,多进程是禁用的。

    Added in 2.8.0

  • **kwargs (additional keyword arguments) — Keyword arguments to be passed to ParquetConfig.

从 Parquet 文件创建数据集。

示例

>>> ds = Dataset.from_parquet('path/to/dataset.parquet')

from_text

< >

( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False num_proc: typing.Optional[int] = None **kwargs )

参数

  • path_or_paths (path-likepath-like列表) — Text 文件路径。
  • split (NamedSplit, optional) — 要分配给数据集的分割名称。
  • features (Features, optional) — 数据集特征。
  • cache_dir (str, optional, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • num_proc (int, optional, 默认为 None) — 下载和本地生成数据集时的进程数。如果数据集由多个文件组成,则此参数非常有用。默认情况下,多进程是禁用的。

    Added in 2.8.0

  • **kwargs (additional keyword arguments) — Keyword arguments to be passed to TextConfig.

从文本文件创建数据集。

示例

>>> ds = Dataset.from_text('path/to/dataset.txt')

from_sql

< >

( sql: typing.Union[str, ForwardRef('sqlalchemy.sql.Selectable')] con: typing.Union[str, ForwardRef('sqlalchemy.engine.Connection'), ForwardRef('sqlalchemy.engine.Engine'), ForwardRef('sqlite3.Connection')] features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False **kwargs )

参数

  • sql (strsqlalchemy.sql.Selectable) — 要执行的 SQL 查询或表名。
  • con (str, sqlite3.Connection, sqlalchemy.engine.Connectionsqlalchemy.engine.Connection) — 用于实例化数据库连接的 URI 字符串,或 SQLite3/SQLAlchemy 连接对象。
  • features (Features, optional) — 数据集特征。
  • cache_dir (str, optional, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • **kwargs (additional keyword arguments) — Keyword arguments to be passed to SqlConfig.

从 SQL 查询或数据库表创建数据集。

示例

>>> # Fetch a database table
>>> ds = Dataset.from_sql("test_data", "postgres:///db_name")
>>> # Execute a SQL query on the table
>>> ds = Dataset.from_sql("SELECT sentence FROM test_data", "postgres:///db_name")
>>> # Use a Selectable object to specify the query
>>> from sqlalchemy import select, text
>>> stmt = select([text("sentence")]).select_from(text("test_data"))
>>> ds = Dataset.from_sql(stmt, "postgres:///db_name")

只有当 con 指定为 URI 字符串时,返回的数据集才能被缓存。

align_labels_with_mapping

< >

( label2id: dict label_column: str )

参数

  • label2id (dict) — 用于对齐数据集的标签名称到 ID 的映射。
  • label_column (str) — 用于对齐标签的列名。

Align the dataset’s label ID and label name mapping to match an input label2id mapping。这在您希望确保模型的预测标签与数据集匹配时非常有用。此对齐通过使用小写标签名完成。

示例

>>> # dataset with mapping {'entailment': 0, 'neutral': 1, 'contradiction': 2}
>>> ds = load_dataset("nyu-mll/glue", "mnli", split="train")
>>> # mapping to align with
>>> label2id = {'CONTRADICTION': 0, 'NEUTRAL': 1, 'ENTAILMENT': 2}
>>> ds_aligned = ds.align_labels_with_mapping(label2id, "label")

datasets.concatenate_datasets

< >

( dsets: list info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None axis: int = 0 )

参数

  • dsets (List[datasets.Dataset]) — 要连接的数据集列表。
  • info (DatasetInfo, optional) — 数据集信息,如描述、引用等。
  • split (NamedSplit, optional) — 数据集分割的名称。
  • axis ({0, 1}, 默认为 0) — 连接的轴,其中 0 表示行(垂直),1 表示列(水平)。

    Added in 1.6.0

将具有相同模式的 Dataset 对象列表转换为单个 Dataset

示例

>>> ds3 = concatenate_datasets([ds1, ds2])

datasets.interleave_datasets

< >

( datasets: list probabilities: typing.Optional[list[float]] = None seed: typing.Optional[int] = None info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None stopping_strategy: typing.Literal['first_exhausted', 'all_exhausted', 'all_exhausted_without_replacement'] = 'first_exhausted' ) DatasetIterableDataset

参数

  • datasets (List[Dataset] or List[IterableDataset]) — 要交错的数据集列表。
  • probabilities (List[float], optional, defaults to None) — 如果指定,则新数据集是通过根据这些概率一次从一个源采样示例来构建的。
  • seed (int, optional, defaults to None) — 用于为每个示例选择源的随机种子。
  • info (DatasetInfo, optional) — 数据集信息,如描述、引用等。

    Added in 2.4.0

  • split (NamedSplit, optional) — 数据集分割的名称。

    Added in 2.4.0

  • stopping_strategy (str, defaults to first_exhausted) — 目前提供三种策略:first_exhaustedall_exhaustedall_exhausted_without_replacement。默认情况下,first_exhausted 是一种欠采样策略,即数据集构建将在一个数据集耗尽样本后停止。如果策略是 all_exhausted,我们使用一种过采样策略,即数据集构建将在所有数据集中的所有样本至少被添加一次后停止。当策略是 all_exhausted_without_replacement 时,我们确保每个数据集中的每个样本只被采样一次。请注意,如果策略是 all_exhausted,交错数据集的大小可能会非常大:
    • 没有概率时,结果数据集将有 max_length_datasets*nb_dataset 个样本。
    • 给定概率时,如果某些数据集的访问概率非常低,结果数据集将有更多样本。

返回

DatasetIterableDataset

返回类型取决于输入 datasets 参数。如果输入是 Dataset 的列表,则返回 Dataset;如果输入是 IterableDataset 的列表,则返回 IterableDataset

将多个数据集(源)交错到一个数据集中。新数据集是通过在源之间交替获取示例来构建的。

您可以在 Dataset 对象列表或 IterableDataset 对象列表上使用此函数。

  • 如果 probabilitiesNone(默认值),则新数据集是通过循环遍历每个源以获取示例来构建的。
  • 如果 probabilities 不是 None,则新数据集是通过根据提供的概率一次从随机源获取示例来构建的。

结果数据集在其中一个源数据集耗尽示例时结束,除非 oversamplingTrue,在这种情况下,结果数据集将在所有数据集至少耗尽一次示例时结束。

对可迭代数据集的说明

在分布式设置或 PyTorch DataLoader 工作进程中,停止策略按进程应用。因此,分片可迭代数据集上的“first_exhausted”策略可能生成的总样本数较少(每工作进程每子数据集最多丢失 1 个样本)。

示例

对于常规数据集(map-style)

>>> from datasets import Dataset, interleave_datasets
>>> d1 = Dataset.from_dict({"a": [0, 1, 2]})
>>> d2 = Dataset.from_dict({"a": [10, 11, 12]})
>>> d3 = Dataset.from_dict({"a": [20, 21, 22]})
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42, stopping_strategy="all_exhausted")
>>> dataset["a"]
[10, 0, 11, 1, 2, 20, 12, 10, 0, 1, 2, 21, 0, 11, 1, 2, 0, 1, 12, 2, 10, 0, 22]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42)
>>> dataset["a"]
[10, 0, 11, 1, 2]
>>> dataset = interleave_datasets([d1, d2, d3])
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted")
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> d1 = Dataset.from_dict({"a": [0, 1, 2]})
>>> d2 = Dataset.from_dict({"a": [10, 11, 12, 13]})
>>> d3 = Dataset.from_dict({"a": [20, 21, 22, 23, 24]})
>>> dataset = interleave_datasets([d1, d2, d3])
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted")
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22, 0, 13, 23, 1, 10, 24]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42)
>>> dataset["a"]
[10, 0, 11, 1, 2]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42, stopping_strategy="all_exhausted")
>>> dataset["a"]
[10, 0, 11, 1, 2, 20, 12, 13, ..., 0, 1, 2, 0, 24]
For datasets in streaming mode (iterable):

>>> from datasets import interleave_datasets
>>> d1 = load_dataset('allenai/c4', 'es', split='train', streaming=True)
>>> d2 = load_dataset('allenai/c4', 'fr', split='train', streaming=True)
>>> dataset = interleave_datasets([d1, d2])
>>> iterator = iter(dataset)
>>> next(iterator)
{'text': 'Comprar Zapatillas para niña en chancla con goma por...'}
>>> next(iterator)
{'text': 'Le sacre de philippe ier, 23 mai 1059 - Compte Rendu...'

datasets.distributed.split_dataset_by_node

< >

( dataset: ~DatasetType rank: int world_size: int ) DatasetIterableDataset

参数

  • dataset (DatasetIterableDataset) — 要按节点拆分的 dataset。
  • rank (int) — 当前节点的 rank。
  • world_size (int) — 节点总数。

返回

DatasetIterableDataset

要分配给 rank 为 rank 的节点的 dataset。

将一个 dataset 拆分为大小为 world_size 的节点池中的 rank 为 rank 的节点。

对于 map-style 数据集

每个节点被分配一个数据块,例如 rank 0 获得数据集的第一个块。为了最大化数据加载吞吐量,块由磁盘上的连续数据组成(如果可能)。

对于可迭代数据集

如果数据集的分片数是 world_size 的因子(即 dataset.num_shards % world_size == 0),则分片在节点之间均匀分配,这是最优化的。否则,每个节点保留 world_size 中的 1 个示例,跳过其他示例。

datasets.enable_caching

< >

( )

在对数据集应用转换时,数据存储在缓存文件中。缓存机制允许在已计算现有缓存文件时重新加载它。

重新加载数据集是可能的,因为缓存文件名是使用数据集指纹命名的,该指纹在每次转换后都会更新。

如果禁用,库在将转换应用于数据集时将不再重新加载缓存的数据集文件。更准确地说,如果禁用缓存

  • 缓存文件总是会被重新创建
  • 缓存文件将被写入临时目录,并在会话结束时被删除
  • 缓存文件将使用随机哈希而不是数据集指纹来命名
  • 使用 save_to_disk() 保存转换后的数据集,否则它将在会话结束时被删除
  • 缓存不会影响 load_dataset()。如果您想从头开始重新生成数据集,应该使用 load_dataset() 中的 download_mode 参数。

datasets.disable_caching

< >

( )

在对数据集应用转换时,数据存储在缓存文件中。缓存机制允许在已计算现有缓存文件时重新加载它。

重新加载数据集是可能的,因为缓存文件名是使用数据集指纹命名的,该指纹在每次转换后都会更新。

如果禁用,库在将转换应用于数据集时将不再重新加载缓存的数据集文件。更准确地说,如果禁用缓存

  • 缓存文件总是会被重新创建
  • 缓存文件将被写入临时目录,并在会话结束时被删除
  • 缓存文件将使用随机哈希而不是数据集指纹来命名
  • 使用 save_to_disk() 保存转换后的数据集,否则它将在会话结束时被删除
  • 缓存不会影响 load_dataset()。如果您想从头开始重新生成数据集,应该使用 load_dataset() 中的 download_mode 参数。

datasets.is_caching_enabled

< >

( )

在对数据集应用转换时,数据存储在缓存文件中。缓存机制允许在已计算现有缓存文件时重新加载它。

重新加载数据集是可能的,因为缓存文件名是使用数据集指纹命名的,该指纹在每次转换后都会更新。

如果禁用,库在将转换应用于数据集时将不再重新加载缓存的数据集文件。更准确地说,如果禁用缓存

  • 缓存文件总是会被重新创建
  • 缓存文件将被写入临时目录,并在会话结束时被删除
  • 缓存文件将使用随机哈希而不是数据集指纹来命名
  • 使用 save_to_disk()] 保存转换后的数据集,否则它将在会话结束时被删除
  • 缓存不会影响 load_dataset()。如果您想从头开始重新生成数据集,应该使用 load_dataset() 中的 download_mode 参数。

class datasets.Column

< >

( source: typing.Union[ForwardRef('Dataset'), ForwardRef('Column')] column_name: str )

一个 Dataset 特定列的可迭代对象。

示例

迭代数据集“text”列的文本

for text in dataset["text"]:
    ...

它也适用于嵌套列

for source in dataset["metadata"]["source"]:
    ...

DatasetDict

以“train”、“test”为例,以拆分名称作为键,以Dataset对象作为值。它还具有数据集转换方法,如map或filter,可以一次性处理所有拆分。

class datasets.DatasetDict

< >

( )

一个字典(str: datasets.Dataset 的字典),包含数据集转换方法(map, filter 等)。

data

< >

( )

每个拆分支持的 Apache Arrow 表。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.data

cache_files

< >

( )

包含支持每个拆分的 Apache Arrow 表的缓存文件。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.cache_files
{'test': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-test.arrow'}],
 'train': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-train.arrow'}],
 'validation': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-validation.arrow'}]}

num_columns

< >

( )

数据集中每个拆分的列数。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.num_columns
{'test': 2, 'train': 2, 'validation': 2}

num_rows

< >

( )

数据集中每个拆分的行数。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.num_rows
{'test': 1066, 'train': 8530, 'validation': 1066}

column_names

< >

( )

数据集中每个拆分的列名。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.column_names
{'test': ['text', 'label'],
 'train': ['text', 'label'],
 'validation': ['text', 'label']}

shape

< >

( )

数据集中每个拆分的形状(行数,列数)。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.shape
{'test': (1066, 2), 'train': (8530, 2), 'validation': (1066, 2)}

unique

< >

( column: str ) Dict[str, list]

参数

  • column (str) — 列名(通过 column_names 列出所有列名)

返回

Dict[str, list]

给定列中唯一元素的字典。

返回每个拆分中唯一元素的列表。

这在底层后端实现,因此速度非常快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.unique("label")
{'test': [1, 0], 'train': [1, 0], 'validation': [1, 0]}

cleanup_cache_files

< >

( )

清理数据集缓存目录中的所有缓存文件,但保留当前正在使用的缓存文件(如果存在)。运行此命令时要小心,确保没有其他进程正在使用其他缓存文件。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.cleanup_cache_files()
{'test': 0, 'train': 0, 'validation': 0}

map

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False with_split: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 features: typing.Optional[datasets.features.features.Features] = None disable_nullable: bool = False fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None desc: typing.Optional[str] = None try_original_type: typing.Optional[bool] = True )

参数

  • function (callable) — 具有以下签名之一:

    • function(example: Dict[str, Any]) -> Dict[str, Any] 如果 batched=False and with_indices=False
    • function(example: Dict[str, Any], indices: int) -> Dict[str, Any] 如果 batched=False and with_indices=True
    • function(batch: Dict[str, list]) -> Dict[str, list] 如果 batched=True and with_indices=False
    • function(batch: Dict[str, list], indices: list[int]) -> Dict[str, list] 如果 batched=True and with_indices=True

    对于高级用法,函数还可以返回一个 pyarrow.Table。如果函数是异步的,则 map 将并行运行您的函数。此外,如果函数返回 None(不返回任何内容),则 map 将运行您的函数并返回未更改的数据集。如果未提供函数,则默认为身份函数: lambda x: x

  • with_indices (bool, 默认为 False) — 为 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx): ...
  • with_rank (bool, 默认为 False) — 为 function 提供进程排名。请注意,在这种情况下,function 的签名应为 def function(example[, idx], rank): ...
  • with_split (bool, 默认为 False) — 为 function 提供进程拆分。请注意,在这种情况下,function 的签名应为 def function(example[, idx], split): ...
  • input_columns ([Union[str, list[str]]], optional, 默认为 None) — 将作为位置参数传递给 function 的列。如果为 None,则将一个映射到所有已格式化列的字典作为单个参数传递。
  • batched (bool, 默认为 False) — 将示例批次提供给 function
  • batch_size (int, optional, 默认为 1000) — 如果 batched=True,则提供给 function 的每批示例数;如果 batch_size <= 0batch_size == None,则将整个数据集作为单个批次提供给 function
  • drop_last_batch (bool, 默认为 False) — 是否应丢弃小于 batch_size 的最后一个批次,而不是由函数处理。
  • remove_columns ([Union[str, list[str]]], optional, 默认为 None) — 在进行映射时删除选定的列。列将在用 function 的输出更新示例之前删除,即如果 function 添加了与 remove_columns 同名的列,这些列将被保留。
  • keep_in_memory (bool, 默认为 False) — 将数据集保留在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], 如果启用缓存,则默认为 True) — 如果可以识别存储当前计算结果的缓存文件,则使用它而不是重新计算。
  • cache_file_names ([Dict[str, str]], optional, defaults to None) — 提供缓存文件的路径名。它用于存储计算结果,而不是自动生成的缓存文件名。您必须为数据集字典中的每个数据集提供一个 cache_file_name
  • writer_batch_size (int, default 1000) — 缓存文件写入器的每个写入操作的行数。此值在处理期间的内存使用和处理速度之间取得了很好的平衡。值越高,处理查找次数越少;值越低,在运行 map 时消耗的临时内存越少。
  • features ([datasets.Features], optional, defaults to None) — 使用特定的 Features 来存储缓存文件,而不是自动生成的。
  • disable_nullable (bool, defaults to False) — 禁止表中的 null 值。
  • fn_kwargs (Dict, optional, defaults to None) — 要传递给 function 的关键字参数。
  • num_proc (int, optional, defaults to None) — 用于多进程的数量。

    • 如果为 None0,则不使用多进程,操作在主进程中运行。
    • 如果大于 1,则使用一个或多个工作进程并行处理数据。注意:传递给 map() 的函数必须是可序列化的,多进程才能正常工作(即,优先使用在模块顶层定义的函数,而不是在另一个函数或类内部定义的函数)。
  • desc (str, optional, defaults to None) — 在映射示例时,显示在进度条旁的有意义的描述。
  • try_original_type (Optional[bool], defaults to True) — 尝试保留原始列的类型(例如 int32 -> int32)。如果您想始终推断新类型,请将其设置为 False。

对表中的所有示例(单独或分批)应用一个函数,并更新表。如果您的函数返回的列已存在,则会覆盖它。转换会应用于数据集字典的所有数据集。

You can specify whether the function should be batched or not with the batched parameter

  • If batched is False, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. {"text": "Hello there !"}.
  • If batched is True and batch_size is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is {"text": ["Hello there !"]}.
  • If batched is True and batch_size is n > 1, then the function takes a batch of n examples as input and can return a batch with n examples, or with an arbitrary number of examples. Note that the last batch may have less than n examples. A batch is a dictionary, e.g. a batch of n examples is {"text": ["Hello there !"] * n}.

If the function is asynchronous, then map will run your function in parallel, with up to one thousand simultaneous calls. It is recommended to use a asyncio.Semaphore in your function if you want to set a maximum number of operations that can run at the same time.

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> ds["train"][0:3]["text"]
['Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',
 'Review: the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .',
 'Review: effective but too-tepid biopic']

# process a batch of examples
>>> ds = ds.map(lambda example: tokenizer(example["text"]), batched=True)
# set number of processors
>>> ds = ds.map(add_prefix, num_proc=4)

过滤器

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None desc: typing.Optional[str] = None )

参数

  • function (Callable) — 签名如下的可调用对象:

    • 如果 batched=Falsewith_indices=Falsewith_rank=False,则为 function(example: Dict[str, Any]) -> bool
    • 如果 batched=Falsewith_indices=True 和/或 with_rank=True,则为 function(example: Dict[str, Any], *extra_args) -> bool(每个额外参数一个)
    • 如果 batched=Truewith_indices=Falsewith_rank=False,则为 function(batch: Dict[str, list]) -> list[bool]
    • 如果 batched=Truewith_indices=True 和/或 with_rank=True,则为 function(batch: Dict[str, list], *extra_args) -> list[bool](每个额外参数一个)

    如果未提供函数,则默认为一个始终返回 True 的函数:lambda x: True

  • with_indices (bool, defaults to False) — 将示例索引提供给 function。请注意,在这种情况下,function 的签名应为 def function(example, idx[, rank]): ...
  • with_rank (bool, defaults to False) — 将进程排名提供给 function。请注意,在这种情况下,function 的签名应为 def function(example[, idx], rank): ...
  • input_columns ([Union[str, list[str]]], optional, defaults to None) — 要作为位置参数传递给 function 的列。如果为 None,则将一个映射到所有已格式化列的字典作为单个参数传递。
  • batched (bool, defaults to False) — 将示例批次提供给 function
  • batch_size (int, optional, defaults to 1000) — 如果 batched=True,则提供给 function 的示例批次数量。batch_size <= 0batch_size == None 则将整个数据集作为一个批次提供给 function
  • keep_in_memory (bool, defaults to False) — 将数据集保留在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], defaults to True if caching is enabled) — 如果可以识别存储当前计算结果的缓存文件,则使用它而不是重新计算。
  • cache_file_names ([Dict[str, str]], optional, defaults to None) — 提供缓存文件的路径名。它用于存储计算结果,而不是自动生成的缓存文件名。您必须为数据集字典中的每个数据集提供一个 cache_file_name
  • writer_batch_size (int, defaults to 1000) — 缓存文件写入器的每个写入操作的行数。此值在处理期间的内存使用和处理速度之间取得了很好的平衡。值越高,处理查找次数越少;值越低,在运行 map 时消耗的临时内存越少。
  • fn_kwargs (Dict, optional, defaults to None) — 要传递给 function 的关键字参数。
  • num_proc (int, optional, defaults to None) — 用于多进程的数量。

    • 如果为 None0,则不使用多进程,操作在主进程中运行。
    • 如果大于 1,则使用一个或多个工作进程并行处理数据。注意:传递给 map() 的函数必须是可序列化的,多进程才能正常工作(即,优先使用在模块顶层定义的函数,而不是在另一个函数或类内部定义的函数)。
  • desc (str, optional, defaults to None) — 在过滤示例时,显示在进度条旁的有意义的描述。

以批次方式对表中的所有元素应用过滤函数,并更新表,使其仅包含符合过滤函数的示例。此转换会应用于数据集字典的所有数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.filter(lambda x: x["label"] == 1)
DatasetDict({
    train: Dataset({
        features: ['text', 'label'],
        num_rows: 4265
    })
    validation: Dataset({
        features: ['text', 'label'],
        num_rows: 533
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 533
    })
})

sort

< >

( column_names: typing.Union[str, collections.abc.Sequence[str]] reverse: typing.Union[bool, collections.abc.Sequence[bool]] = False null_placement: str = 'at_end' keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None indices_cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 )

参数

  • column_names (Union[str, Sequence[str]]) — 按其排序的列名。
  • reverse (Union[bool, Sequence[bool]], 默认值:False) — 如果为 True,则按降序排序而不是升序。如果提供单个布尔值,则该值应用于所有列名的排序。否则,必须提供与 column_names 长度和顺序相同的布尔值列表。
  • null_placement (str, 默认值:at_end) — 如果为 at_startfirst,则将 None 值放在开头,如果为 at_endlast,则放在末尾。
  • keep_in_memory (bool, 默认值:False) — 将排序后的索引保留在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], 如果启用缓存,默认值为 True) — 如果可以识别存储排序索引的缓存文件,则使用它而不是重新计算。
  • indices_cache_file_names ([Dict[str, str]], 可选, 默认值:None) — 提供缓存文件的路径名。它用于存储索引映射,而不是自动生成的缓存文件名。您必须为数据集字典中的每个数据集提供一个 cache_file_name
  • writer_batch_size (int, 默认值:1000) — 缓存文件写入器的每次写入操作的行数。值越高,缓存文件越小,值越低占用的临时内存越少。

根据单个或多个列创建已排序的新数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset('cornell-movie-review-data/rotten_tomatoes')
>>> ds['train']['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> sorted_ds = ds.sort('label')
>>> sorted_ds['train']['label'][:10]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> another_sorted_ds = ds.sort(['label', 'text'], reverse=[True, False])
>>> another_sorted_ds['train']['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

shuffle

< >

( seeds: typing.Union[int, dict[str, typing.Optional[int]], NoneType] = None seed: typing.Optional[int] = None generators: typing.Optional[dict[str, numpy.random._generator.Generator]] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None indices_cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 )

参数

  • seeds (Dict[str, int]int, 可选) — 如果 generator=None,则用于初始化默认 BitGenerator 的种子。如果为 None,则会从操作系统获取新的、不可预测的熵。如果传入 intarray_like[ints],则会将其传递给 SeedSequence 以派生初始 BitGenerator 状态。您可以为数据集字典中的每个数据集提供一个 seed
  • seed (int, 可选) — 如果 generator=None,则用于初始化默认 BitGenerator 的种子。seeds 的别名(如果同时提供两者,则会引发 ValueError)。
  • generators (Dict[str, *optional*, np.random.Generator]) — 用于计算数据集行排列的 Numpy 随机生成器。如果 generator=None(默认值),则使用 np.random.default_rng(NumPy 的默认 BitGenerator (PCG64))。您必须为数据集字典中的每个数据集提供一个 generator
  • keep_in_memory (bool, 默认值:False) — 将数据集保留在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], 如果启用缓存,默认值为 True) — 如果可以识别存储当前 function 计算的缓存文件,则使用它而不是重新计算。
  • indices_cache_file_names (Dict[str, str], 可选) — 提供缓存文件的路径名。它用于存储索引映射,而不是自动生成的缓存文件名。您必须为数据集字典中的每个数据集提供一个 cache_file_name
  • writer_batch_size (int, 默认值:1000) — 缓存文件写入器的每次写入操作的行数。此值在处理期间的内存使用量和处理速度之间取得了很好的平衡。值越高,处理进行的查找次数越少,值越低在运行 map 时占用的临时内存越少。

创建一个新的 Dataset,其中包含打乱顺序的行。

该转换应用于数据集字典的所有数据集。

当前打乱操作使用 numpy 随机生成器。您可以提供一个 NumPy BitGenerator 来使用,或者一个种子来初始化 NumPy 的默认随机生成器(PCG64)。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds["train"]["label"][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

# set a seed
>>> shuffled_ds = ds.shuffle(seed=42)
>>> shuffled_ds["train"]["label"][:10]
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0]

set_format

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

参数

  • type (str, 可选) — 输出类型,从 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中选择。None 表示 __getitem__ 返回 Python 对象(默认值)。
  • columns (list[str], 可选) — 要格式化的列。None 表示 __getitem__ 返回所有列(默认值)。
  • output_all_columns (bool, 默认值:False) — 在输出中保留未格式化的列(作为 Python 对象)。
  • **format_kwargs (其他关键字参数) — 传递给转换函数(如 np.arraytorch.tensortensorflow.ragged.constant)的关键字参数。

设置 __getitem__ 返回格式(类型和列)。格式设置为数据集字典中的每个数据集。

可以在调用 set_format 后调用 map。由于 map 可能会添加新列,因此格式化列的列表会更新。在这种情况下,如果您对数据集应用 map 来添加新列,则该列将被格式化

新格式化的列 = (所有列 - 先前未格式化的列)

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True)
>>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds["train"].format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}

reset_format

< >

( )

重置 __getitem__ 返回格式为 Python 对象和所有列。该转换应用于数据集字典的所有数据集。

self.set_format() 相同

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True)
>>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds["train"].format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}
>>> ds.reset_format()
>>> ds["train"].format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}

formatted_as

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

参数

  • type (str, 可选) — 输出类型,从 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中选择。None 表示 __getitem__ 返回 Python 对象(默认值)。
  • columns (list[str], 可选) — 要格式化的列。None 表示 __getitem__ 返回所有列(默认值)。
  • output_all_columns (bool, 默认值:False) — 在输出中保留未格式化的列(作为 Python 对象)。
  • **format_kwargs (其他关键字参数) — 传递给转换函数(如 np.arraytorch.tensortensorflow.ragged.constant)的关键字参数。

with 语句中使用。设置 __getitem__ 返回格式(类型和列)。该转换应用于数据集字典的所有数据集。

with_format

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

参数

  • type (str, 可选) — 输出类型,从 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中选择。None 表示 __getitem__ 返回 Python 对象(默认值)。
  • columns (list[str], 可选) — 要格式化的列。None 表示 __getitem__ 返回所有列(默认值)。
  • output_all_columns (bool, 默认值:False) — 在输出中保留未格式化的列(作为 Python 对象)。
  • **format_kwargs (其他关键字参数) — 传递给转换函数(如 np.arraytorch.tensortensorflow.ragged.constant)的关键字参数。

设置 __getitem__ 返回格式(类型和列)。数据格式化是即时应用的。格式 type(例如“numpy”)用于在使用 __getitem__ 时格式化批次。格式设置为数据集字典中的每个数据集。

也可以使用 with_transform() 使用自定义转换进行格式化。

set_format() 相反,with_format 返回一个新的 DatasetDict 对象,其中包含新的 Dataset 对象。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds["train"].format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}
>>> ds = ds.with_format("torch")
>>> ds["train"].format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'torch'}
>>> ds["train"][0]
{'text': 'compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 'label': tensor(1),
 'input_ids': tensor([  101, 18027, 16310, 16001,  1103,  9321,   178, 11604,  7235,  6617,
        1742,  2165,  2820,  1206,  6588, 22572, 12937,  1811,  2153,  1105,
        1147, 12890, 19587,  6463,  1105, 15026,  1482,   119,   102,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
 'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])}

with_transform

< >

( transform: typing.Optional[typing.Callable] columns: typing.Optional[list] = None output_all_columns: bool = False )

参数

  • transform (Callable, optional) — 用户定义的格式化转换,替换 set_format() 定义的格式。格式化函数是一个可调用对象,它接受一个批次(作为字典)作为输入并返回一个批次。此函数在返回 __getitem__ 中的对象之前应用。
  • columns (list[str], optional) — 要在输出中格式化的列。如果指定,则转换的输入批次仅包含这些列。
  • output_all_columns (bool, defaults to False) — 如果设置为 True,则输出中也保留未格式化的列(作为 python 对象)。然后,其他未格式化的列将保留转换的输出。

使用此转换设置 __getitem__ 的返回格式。在调用 __getitem__ 时,转换会动态应用于批次。转换会为数据集字典中的每个数据集设置。

set_format() 类似,可以使用 reset_format() 重置。

set_transform() 相反,with_transform 返回一个新的 DatasetDict 对象,其中包含新的 Dataset 对象。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> def encode(example):
...     return tokenizer(example['text'], truncation=True, padding=True, return_tensors="pt")
>>> ds = ds.with_transform(encode)
>>> ds["train"][0]
{'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1, 1, 1, 1, 1, 1, 1, 1]),
 'input_ids': tensor([  101,  1103,  2067,  1110, 17348,  1106,  1129,  1103,  6880,  1432,
        112,   188,  1207,   107, 14255,  1389,   107,  1105,  1115,  1119,
        112,   188,  1280,  1106,  1294,   170, 24194,  1256,  3407,  1190,
        170, 11791,  5253,   188,  1732,  7200, 10947, 12606,  2895,   117,
        179,  7766,   118,   172, 15554,  1181,  3498,  6961,  3263,  1137,
        188,  1566,  7912, 14516,  6997,   119,   102]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0])}

flatten

< >

( max_depth = 16 )

展平每个分割的 Apache Arrow 表(嵌套特征被展平)。结构化类型的每个列都被展平为每个结构化字段的一个列。其他列保持不变。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad")
>>> ds["train"].features
{'id': Value('string'),
 'title': Value('string'),
 'context': Value('string'),
 'question': Value('string'),
 'answers.text': List(Value('string')),
 'answers.answer_start': List(Value('int32'))}
>>> ds.flatten()
DatasetDict({
    train: Dataset({
        features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
        num_rows: 87599
    })
    validation: Dataset({
        features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
        num_rows: 10570
    })
})

cast

< >

( features: Features )

参数

  • features (< (Features) — 要将数据集转换为的新特征集。特征的名称和顺序必须与当前列名匹配。数据类型也必须可以从一种类型转换为另一种类型。对于非平凡的转换,例如 string <-> ClassLabel,您应该使用 < map() 来更新数据集。

将数据集转换为一组新的特征。该转换应用于数据集字典中的所有数据集。

示例

>>> from datasets import load_dataset, ClassLabel, Value
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> new_features = ds["train"].features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('large_string')}

cast_column

<> < <">< < < >

<>( < <">column: str <">feature < )

参数

  • <> column (str) — 列名。
  • <> feature (Feature) — 目标特征。

用于解码的列特征转换。

示例

>>> from datasets import load_dataset, ClassLabel
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('string')}

remove_columns

<> < <">< < < >

<>( < <">column_names: typing.Union[str, list[str]] < ) < < <"><>DatasetDict

参数

  • <> column_names (Union[str, list[str]]) — 要删除的列名(或名称列表)。

返回

DatasetDict

一个不包含要删除的列的数据集对象副本。

从数据集中每个分割中删除一列或多列以及与该列关联的特征。

该转换应用于数据集字典的所有分割。

您也可以使用带有 remove_columns 的 < map() 来删除一列,但当前方法不复制剩余列的数据,因此速度更快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds = ds.remove_columns("label")
DatasetDict({
    train: Dataset({
        features: ['text'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text'],
        num_rows: 1066
    })
})

rename_column

<> < <">< < < >

<>( < <">original_column_name: str <">new_column_name: str < )

参数

  • <> original_column_name (str) — 要重命名的列的名称。
  • <> new_column_name (str) — 列的新名称。

在数据集中重命名一个列,并将与原始列关联的特征移动到新列名下。该转换应用于数据集字典中的所有数据集。

您也可以使用带有 remove_columns 的 < map() 来重命名一个列,但当前方法

  • 负责将原始特征移动到新列名下。
  • 不将数据复制到新数据集,因此速度要快得多。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds = ds.rename_column("label", "label_new")
DatasetDict({
    train: Dataset({
        features: ['text', 'label_new'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text', 'label_new'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text', 'label_new'],
        num_rows: 1066
    })
})

rename_columns

<> < <">< < < >

<>( < <">column_mapping: dict < ) < < <"><>DatasetDict

参数

  • <> column_mapping (Dict[str, str]) — 一个将列重命名为其新名称的映射。

返回

DatasetDict

一个具有重命名列的数据集副本。

重命名数据集中的多个列,并将与原始列关联的特征移动到新列名下。该转换应用于数据集字典中的所有数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.rename_columns({'text': 'text_new', 'label': 'label_new'})
DatasetDict({
    train: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 1066
    })
})

select_columns

<> < <">< < < >

<>( < <">column_names: typing.Union[str, list[str]] < )

参数

  • <> column_names (Union[str, list[str]]) — 要保留的列名(或名称列表)。

从数据集中每个分割中选择一列或多列以及与该列关联的特征。

该转换应用于数据集字典的所有分割。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.select_columns("text")
DatasetDict({
    train: Dataset({
        features: ['text'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text'],
        num_rows: 1066
    })
})

class_encode_column

<> < <">< < < >

( column: str include_nulls: bool = False )

参数

  • <> column (str) — 要转换的列的名称。
  • <> include_nulls (bool, defaults to False) — 是否在类别标签中包含空值。如果为 True,则空值将编码为 "None" 类别标签。<。

    <
    <

    Added in 1.14.2

将给定列转换为 < ClassLabel 并更新表格。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("google/boolq")
>>> ds["train"].features
{'answer': Value('bool'),
 'passage': Value('string'),
 'question': Value('string')}
>>> ds = ds.class_encode_column("answer")
>>> ds["train"].features
{'answer': ClassLabel(num_classes=2, names=['False', 'True']),
 'passage': Value('string'),
 'question': Value('string')}

push_to_hub

<> < <">< < < >

( repo_id config_name: str = 'default' set_default: typing.Optional[bool] = None data_dir: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = False max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[dict[str, int]] = None embed_external_files: bool = True num_proc: typing.Optional[int] = None )

参数

  • repo_id (str) — 要上传到的仓库 ID,格式为:<user>/<dataset_name><org>/<dataset_name>。也可以接受 <dataset_name>,这将默认为登录用户的命名空间。
  • config_name (str) — 数据集的配置名称。默认为 “default”。
  • set_default (bool, 可选) — 是否将此配置设置为默认配置。否则,默认配置是名称为“default”的配置。
  • data_dir (str, 可选) — 将包含上传的数据文件的目录名称。如果不同于“default”,则默认为 config_name,否则为“data”。

    Added in 2.17.0

  • commit_message (str, 可选) — 推送时提交的消息。默认为 "Upload dataset"
  • commit_description (str, 可选) — 创建提交时使用的描述。如果创建了 PR (create_pr 为 True),则也是 PR 的描述。

    Added in 2.16.0

  • private (bool, 可选) — 是否将仓库设为私有。如果为 None(默认值),仓库将公开,除非组织默认设置为私有。如果仓库已存在,则忽略此值。
  • token (str, 可选) — 用于 Hugging Face Hub 的可选身份验证令牌。如果未传递令牌,将默认为使用 huggingface-cli login 登录时本地保存的令牌。如果未传递令牌且用户未登录,将引发错误。
  • revision (str, 可选) — 要上传到的分支。默认为 "main" 分支。

    Added in 2.15.0

  • create_pr (bool, 可选, defaults to False) — 是否创建 PR 来包含上传的文件,还是直接提交。

    Added in 2.15.0

  • max_shard_size (intstr, 可选, defaults to "500MB") — 要上传到 hub 的数据集分片的最大大小。如果表示为字符串,则需要是数字后跟一个单位(例如 "500MB""1GB")。
  • num_shards (Dict[str, int], 可选) — 要写入的分片数量。默认情况下,分片数量取决于 max_shard_size。使用字典为每个分片定义不同的 num_shards。

    Added in 2.8.0

  • embed_external_files (bool, defaults to True) — 在默认情况下,是否在分片中嵌入文件字节。具体来说,这将对以下类型的字段在推送前执行以下操作:

    • AudioImage 将删除本地路径信息,并将文件内容嵌入 Parquet 文件中。
  • num_proc (int, 可选, defaults to None) — 准备和上传数据集时使用的进程数。如果数据集由许多样本或媒体文件组成,这会很有帮助。默认情况下禁用多进程。

    Added in 4.0.0

DatasetDict 作为 Parquet 数据集推送到 hub。 DatasetDict 使用 HTTP 请求推送,不需要安装 git 或 git-lfs。

每个数据集分片将独立推送。推送的数据集将保留原始的分片名称。

默认情况下,生成的 Parquet 文件是自包含的:如果您的数据集包含 ImageAudio 数据,Parquet 文件将存储图像或音频文件的字节。通过将 embed_external_files 设置为 False,可以禁用此功能。

示例

>>> dataset_dict.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", num_shards={"train": 1024, "test": 8})

如果您想为数据集添加新的配置(或子集)(例如,如果数据集有多个任务/版本/语言)

>>> english_dataset.push_to_hub("<organization>/<dataset_id>", "en")
>>> french_dataset.push_to_hub("<organization>/<dataset_id>", "fr")
>>> # later
>>> english_dataset = load_dataset("<organization>/<dataset_id>", "en")
>>> french_dataset = load_dataset("<organization>/<dataset_id>", "fr")

save_to_disk

< >

( dataset_dict_path: typing.Union[str, bytes, os.PathLike] max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[dict[str, int]] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None )

参数

  • dataset_dict_path (类路径) — 要保存 dataset dict 的数据集词典目录的路径(例如 "dataset/train")或远程 URI(例如 "s3://my-bucket/dataset/train")。
  • max_shard_size (intstr, 可选, defaults to "500MB") — 要保存到文件系统的分片的最大大小。如果表示为字符串,则需要是数字后跟一个单位(例如 "50MB")。
  • num_shards (Dict[str, int], 可选) — 要写入的分片数量。默认情况下,分片数量取决于 max_shard_sizenum_proc。您需要为数据集词典中的每个数据集提供分片数量。使用字典为每个分片定义不同的 num_shards。

    Added in 2.8.0

  • num_proc (int, 可选, default None) — 在本地下载和生成数据集时使用的进程数。默认情况下禁用多进程。

    Added in 2.8.0

  • storage_options (dict, 可选) — 传递给文件系统后端的键/值对(如果有)。

    Added in 2.8.0

使用 fsspec.spec.AbstractFileSystem 将 dataset dict 保存到文件系统。

对于 ImageAudioVideo 数据

所有 Image()、Audio() 和 Video() 数据都存储在 arrow 文件中。如果想存储路径或 URL,请使用 Value("string") 类型。

示例

>>> dataset_dict.save_to_disk("path/to/dataset/directory")
>>> dataset_dict.save_to_disk("path/to/dataset/directory", max_shard_size="1GB")
>>> dataset_dict.save_to_disk("path/to/dataset/directory", num_shards={"train": 1024, "test": 8})

load_from_disk

< >

( dataset_dict_path: typing.Union[str, bytes, os.PathLike] keep_in_memory: typing.Optional[bool] = None storage_options: typing.Optional[dict] = None )

参数

  • dataset_dict_path (类路径) — 要从中加载 dataset dict 的数据集词典目录的路径(例如 "dataset/train")或远程 URI(例如 "s3//my-bucket/dataset/train")。
  • keep_in_memory (bool, defaults to None) — 是否将数据集复制到内存中。如果为 None,除非明确设置 datasets.config.IN_MEMORY_MAX_SIZE 为非零值来启用,否则数据集不会被复制到内存中。有关更多详细信息,请参阅 提高性能 部分。
  • storage_options (dict, 可选) — 传递给文件系统后端的键/值对(如果有)。

    Added in 2.8.0

从文件系统加载先前使用 save_to_disk 保存的数据集(使用 fsspec.spec.AbstractFileSystem)。

示例

>>> ds = load_from_disk('path/to/dataset/directory')

from_csv

< >

( path_or_paths: dict features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False **kwargs )

参数

  • path_or_paths (dict 路径类) — CSV 文件的路径。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • **kwargs (附加关键字参数) — 要传递给 pandas.read_csv 的关键字参数。

从 CSV 文件创建 DatasetDict

示例

>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_csv({'train': 'path/to/dataset.csv'})

from_json

< >

( path_or_paths: dict features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False **kwargs )

参数

  • path_or_paths (path-likepath-like 列表) — JSON Lines 文件的路径。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • **kwargs (附加关键字参数) — 要传递给 JsonConfig 的关键字参数。

从 JSON Lines 文件创建 DatasetDict

示例

>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_json({'train': 'path/to/dataset.json'})

from_parquet

< >

( path_or_paths: dict features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False columns: typing.Optional[list[str]] = None **kwargs )

参数

  • path_or_paths (dict 路径类) — CSV 文件的路径。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • columns (list[str], 可选) — 如果不为 None,则只从文件中读取这些列。列名可以是嵌套字段的前缀,例如 'a' 将选择 'a.b'、'a.c' 和 'a.d.e'。
  • **kwargs (附加关键字参数) — 要传递给 ParquetConfig 的关键字参数。

从 Parquet 文件创建 DatasetDict

示例

>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_parquet({'train': 'path/to/dataset/parquet'})

from_text

< >

( path_or_paths: dict features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False **kwargs )

参数

  • path_or_paths (dict 路径类) — 文本文件的路径。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • **kwargs (附加关键字参数) — 要传递给 TextConfig 的关键字参数。

从文本文件创建 DatasetDict

示例

>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_text({'train': 'path/to/dataset.txt'})

IterableDataset

基类 IterableDataset 实现了一个由 python 生成器支持的可迭代数据集。

class datasets.IterableDataset

< >

( ex_iterable: _BaseExamplesIterable info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None formatting: typing.Optional[datasets.iterable_dataset.FormattingConfig] = None shuffling: typing.Optional[datasets.iterable_dataset.ShufflingConfig] = None distributed: typing.Optional[datasets.iterable_dataset.DistributedConfig] = None token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

一个由可迭代对象支持的数据集。

from_generator

< >

( generator: typing.Callable features: typing.Optional[datasets.features.features.Features] = None gen_kwargs: typing.Optional[dict] = None split: NamedSplit = NamedSplit('train') ) IterableDataset

参数

  • generator (Callable) — 一个生成器函数,它yields示例。
  • features (Features, 可选) — 数据集的特征。
  • gen_kwargs(dict, 可选) — 要传递给 generator 可调用对象的关键字参数。您可以将分片列表传递给 gen_kwargs 来定义一个分片的可迭代数据集。这可以用于改进随机打乱以及使用多个工作进程迭代数据集。
  • split (NamedSplit, 默认为 Split.TRAIN) — 分配给数据集的拆分名称。

    Added in 2.21.0

返回

IterableDataset

从生成器创建可迭代数据集。

示例

>>> def gen():
...     yield {"text": "Good", "label": 0}
...     yield {"text": "Bad", "label": 1}
...
>>> ds = IterableDataset.from_generator(gen)
>>> def gen(shards):
...     for shard in shards:
...         with open(shard) as f:
...             for line in f:
...                 yield {"line": line}
...
>>> shards = [f"data{i}.txt" for i in range(32)]
>>> ds = IterableDataset.from_generator(gen, gen_kwargs={"shards": shards})
>>> ds = ds.shuffle(seed=42, buffer_size=10_000)  # shuffles the shards order + uses a shuffle buffer
>>> from torch.utils.data import DataLoader
>>> dataloader = DataLoader(ds.with_format("torch"), num_workers=4)  # give each worker a subset of 32/4=8 shards

remove_columns

< >

( column_names: typing.Union[str, list[str]] ) IterableDataset

参数

  • column_names (Union[str, List[str]]) — 要移除的列的名称。

返回

IterableDataset

一个不包含要删除的列的数据集对象副本。

在数据集中移除一个或多个列及其关联的特征。移除是迭代数据集时实时进行的。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1}
>>> ds = ds.remove_columns("label")
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

select_columns

< >

( column_names: typing.Union[str, list[str]] ) IterableDataset

参数

  • column_names (Union[str, List[str]]) — 要选择的列的名称。

返回

IterableDataset

带有选定列的数据集对象的副本。

在数据集中选择一个或多个列及其关联的特征。选择是迭代数据集时实时进行的。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1}
>>> ds = ds.select_columns("text")
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

cast_column

< >

( column: str feature: typing.Union[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.LargeList, datasets.features.features.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf, datasets.features.nifti.Nifti] ) IterableDataset

参数

  • column (str) — 列名。
  • feature (Feature) — 目标特征。

返回

IterableDataset

用于解码的列特征转换。

示例

>>> from datasets import load_dataset, Audio
>>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train", streaming=True)
>>> ds.features
{'audio': Audio(sampling_rate=8000, mono=True, decode=True, id=None),
 'english_transcription': Value('string'),
 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan',  'card_issues', 'cash_deposit', 'direct_debit', 'freeze', 'high_value_payment', 'joint_account', 'latest_transactions', 'pay_bill']),
 'lang_id': ClassLabel(num_classes=14, names=['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR',  'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN']),
 'path': Value('string'),
 'transcription': Value('string')}
>>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
>>> ds.features
{'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None),
 'english_transcription': Value('string'),
 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan',  'card_issues', 'cash_deposit', 'direct_debit', 'freeze', 'high_value_payment', 'joint_account', 'latest_transactions', 'pay_bill']),
 'lang_id': ClassLabel(num_classes=14, names=['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR',  'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN']),
 'path': Value('string'),
 'transcription': Value('string')}

cast

< >

( features: Features ) IterableDataset

参数

  • features (Features) — 要转换到的新特征。特征中的字段名必须与当前列名匹配。数据类型也必须可以从一种类型转换为另一种类型。对于非平凡转换,例如 string <-> ClassLabel,您应该使用 map() 来更新数据集。

返回

IterableDataset

一个具有转换后特征的数据集副本。

将数据集转换为一组新特征。

示例

>>> from datasets import load_dataset, ClassLabel, Value
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> ds.features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> new_features = ds.features.copy()
>>> new_features["label"] = ClassLabel(names=["bad", "good"])
>>> new_features["text"] = Value("large_string")
>>> ds = ds.cast(new_features)
>>> ds.features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('large_string')}

decode

< >

( enable: bool = True num_threads: int = 0 ) IterableDataset

参数

  • enable (bool, 默认为 True) — 启用或禁用特征解码。
  • num_threads (int, 默认为 0) — 启用特征解码的多线程。

返回

IterableDataset

一个具有转换后特征的数据集副本。

启用或禁用音频、图像、视频的数据集特征解码。

启用时(默认),媒体类型将被解码

  • audio -> 包含“array”、“sampling_rate”和“path”的字典
  • image -> PIL.Image
  • video -> torchvision.io.VideoReader

您可以使用 num_threads 启用多线程。这对于加快远程数据流传输特别有用。但是,对于快速磁盘上的本地数据,它可能比 num_threads=0 慢。

禁用解码对于您想迭代媒体文件的路径或字节而不实际解码其内容的情况很有用。要禁用解码,您可以使用 .decode(False),这等同于使用所有 Audio、Image 和 Video 类型设置为 decode=False 来调用 .cast().cast_column()

示例

禁用解码

>>> from datasets import load_dataset
>>> ds = load_dataset("sshh12/planet-textures", split="train", streaming=True)
>>> next(iter(ds))
{'image': <PIL.PngImagePlugin.PngImageFile image mode=RGB size=2048x1024>,
'text': 'A distant celestial object with an icy crust, displaying a light blue shade, covered with round pits and rugged terrains.'}
>>> ds = ds.decode(False)
>>> ds.features
{'image': Image(mode=None, decode=False, id=None),
'text': Value('string')}
>>> next(iter(ds))
{
  'image': {
    'path': 'hf://datasets/sshh12/planet-textures@69dc4cef7a5c4b2cfe387727ec8ea73d4bff7302/train/textures/0000.png',
    'bytes': None
  },
  'text': 'A distant celestial object with an icy crust, displaying a light blue shade, covered with round pits and rugged terrains.'
}

使用多线程加速流式传输

>>> import os
>>> from datasets import load_dataset
>>> from tqdm import tqdm
>>> ds = load_dataset("sshh12/planet-textures", split="train", streaming=True)
>>> num_threads = min(32, (os.cpu_count() or 1) + 4)
>>> ds = ds.decode(num_threads=num_threads)
>>> for _ in tqdm(ds):  # 20 times faster !
...     ...

__iter__

< >

( )

iter

< >

( batch_size: int drop_last_batch: bool = False )

参数

  • batch_size (int) — 要 yield 的每个 batch 的大小。
  • drop_last_batch (bool, 默认为 False) — 是否应丢弃小于 batch_size 的最后一个 batch

遍历大小为 batch_size 的批次。

map

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None features: typing.Optional[datasets.features.features.Features] = None fn_kwargs: typing.Optional[dict] = None )

参数

  • function (Callable, 可选, 默认为 None) — 在迭代数据集时实时应用于示例的函数。它必须具有以下签名之一:

    • function(example: Dict[str, Any]) -> Dict[str, Any] 如果 batched=Falsewith_indices=False
    • function(example: Dict[str, Any], idx: int) -> Dict[str, Any] 如果 batched=Falsewith_indices=True
    • function(batch: Dict[str, List]) -> Dict[str, List] 如果 batched=Truewith_indices=False
    • function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List] 如果 batched=Truewith_indices=True

    对于高级用法,函数还可以返回 pyarrow.Table。如果函数是异步的,则 map 将并行运行您的函数。此外,如果您的函数不返回任何内容(None),则 map 将运行您的函数并返回未更改的数据集。如果未提供函数,则默认为标识函数:lambda x: x

  • with_indices (bool, 默认为 False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx[, rank]): ...
  • input_columns (Optional[Union[str, List[str]]], 默认为 None) — 要作为位置参数传递给 function 的列。如果为 None,则将映射到所有格式化列的字典作为单个参数传递。
  • batched (bool, 默认为 False) — 将示例批次提供给 function
  • batch_size (int, 可选, 默认为 1000) — 如果 batched=True,则提供给 function 的每个批次的示例数。batch_size <= 0batch_size == None 则将整个数据集作为单个批次提供给 function
  • drop_last_batch (bool, 默认为 False) — 是否丢弃比 batch_size 小的最后一个 batch。
  • remove_columns ([List[str]], 可选, 默认为 None) — 在映射时移除选定的列。列将在使用 function 的输出来更新示例之前被移除,即如果 function 添加了与 remove_columns 中同名的列,这些列将被保留。
  • features ([Features], 可选, 默认为 None) — 结果数据集的特征类型。
  • fn_kwargs (Dict, 可选, 默认为 None) — 要传递给 function 的关键字参数。

对可迭代数据集中的所有示例(单个或批量)应用一个函数并更新它们。如果您的函数返回一个已存在的列,则会覆盖它。该函数在迭代数据集时按需应用。

You can specify whether the function should be batched or not with the batched parameter

  • If batched is False, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. {"text": "Hello there !"}.
  • 如果 batched 为 Truebatch_size 为 1,则函数接收一个包含 1 个示例的批次作为输入,并可以返回一个包含 1 个或多个示例的批次。批次是字典,例如,包含 1 个示例的批次是 {“text”: [“Hello there !”]}。
  • 如果 batched 为 Truebatch_sizen > 1,则函数接收一个包含 n 个示例的批次作为输入,并可以返回一个包含 n 个示例或任意数量示例的批次。请注意,最后一个批次可能少于 n 个示例。批次是字典,例如,包含 n 个示例的批次是 {"text": ["Hello there !"] * n}

如果函数是异步的,则 map 将以最多一千个并发调用来并行运行您的函数。建议在函数中使用 asyncio.Semaphore 来设置同时运行的最大操作数。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'Review: the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'Review: effective but too-tepid biopic'}]

rename_column

< >

( original_column_name: str new_column_name: str ) IterableDataset

参数

  • original_column_name (str) — 要重命名的列名。
  • new_column_name (str) — 列的新名称。

返回

IterableDataset

一个具有重命名列的数据集副本。

重命名数据集中的列,并将与原始列关联的特征移动到新列名下。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
>>> ds = ds.rename_column("text", "movie_review")
>>> next(iter(ds))
{'label': 1,
 'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

过滤器

< >

( function: typing.Optional[typing.Callable] = None with_indices = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 fn_kwargs: typing.Optional[dict] = None )

参数

  • function (Callable) — 具有以下签名之一的可调用对象:

    • function(example: Dict[str, Any]) -> bool 如果 with_indices=False, batched=False
    • function(example: Dict[str, Any], indices: int) -> bool 如果 with_indices=True, batched=False
    • function(example: Dict[str, List]) -> List[bool] 如果 with_indices=False, batched=True
    • function(example: Dict[str, List], indices: List[int]) -> List[bool] 如果 with_indices=True, batched=True

    如果函数是异步的,则 filter 将并行运行您的函数。如果未提供函数,则默认为始终返回 True 的函数:lambda x: True

  • with_indices (bool, 默认为 False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx): ...
  • input_columns (strList[str], 可选) — 将作为位置参数传递给 function 的列。如果为 None,则将映射到所有格式化列的字典作为单个参数传递。
  • batched (bool, 默认为 False) — 向 function 提供示例批次。
  • batch_size (int, 可选, 默认为 1000) — 如果 batched=True,则提供给 function 的批次中的示例数量。
  • fn_kwargs (Dict, 可选, 默认为 None) — 要传递给 function 的关键字参数。

应用一个过滤函数到所有元素,以便数据集只包含符合过滤函数的示例。过滤按需在迭代数据集时完成。

如果函数是异步的,则 filter 将以最多一千个并发调用(可配置)来并行运行您的函数。建议在函数中使用 asyncio.Semaphore 来设置同时运行的最大操作数。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> ds = ds.filter(lambda x: x["label"] == 0)
>>> list(ds.take(3))
[{'label': 0, 'movie_review': 'simplistic , silly and tedious .'},
 {'label': 0,
 'movie_review': "it's so laddish and juvenile , only teenage boys could possibly find it funny ."},
 {'label': 0,
 'movie_review': 'exploitative and largely devoid of the depth or sophistication that would make watching such a graphic treatment of the crimes bearable .'}]

shuffle

< >

( seed = None generator: typing.Optional[numpy.random._generator.Generator] = None buffer_size: int = 1000 )

参数

  • seed (int, 可选, 默认为 None) — 用于打乱数据集的随机种子。它用于从打乱缓冲区采样以及打乱数据分片。
  • generator (numpy.random.Generator, 可选) — 用于计算数据集行排列的 numpy 随机生成器。如果 generator=None (默认),则使用 np.random.default_rng (NumPy 的默认 BitGenerator (PCG64))。
  • buffer_size (int, 默认为 1000) — 缓冲区的尺寸。

随机打乱此数据集的元素。

此数据集将一个大小为 buffer_size 的缓冲区填满元素,然后从该缓冲区中随机采样元素,用新元素替换所选的元素。为了完美地打乱,需要一个大于或等于数据集完整大小的缓冲区大小。

例如,如果您的数据集包含 10,000 个元素但 buffer_size 设置为 1000,则 shuffle 最初只会从缓冲区的前 1000 个元素中随机选择一个。一旦选择了一个元素,它在缓冲区中的位置就会被下一个(即第 1001 个)元素替换,从而保持 1000 个元素的缓冲区。

如果数据集由多个分片组成,它还会打乱分片的顺序。但是,如果顺序已经通过使用 skip()take() 固定,则分片的顺序将保持不变。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]
>>> shuffled_ds = ds.shuffle(seed=42)
>>> list(shuffled_ds.take(3))
[{'label': 1,
 'text': "a sports movie with action that's exciting on the field and a story you care about off it ."},
 {'label': 1,
 'text': 'at its best , the good girl is a refreshingly adult take on adultery . . .'},
 {'label': 1,
 'text': "sam jones became a very lucky filmmaker the day wilco got dropped from their record label , proving that one man's ruin may be another's fortune ."}]

batch

< >

( batch_size: int drop_last_batch: bool = False )

参数

  • batch_size (int) — 每个批次中的样本数。
  • drop_last_batch (bool, 默认为 False) — 是否丢弃最后一个不完整的批次。

将数据集中的样本分组到批次中。

示例

>>> ds = load_dataset("some_dataset", streaming=True)
>>> batched_ds = ds.batch(batch_size=32)

skip

< >

( n: int )

参数

  • n (int) — 要跳过的元素数量。

创建一个新的 IterableDataset,它跳过前 n 个元素。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]
>>> ds = ds.skip(1)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'},
 {'label': 1,
 'text': 'if you sometimes like to go to the movies to have fun , wasabi is a good place to start .'}]

take

< >

( n: int )

参数

  • n (int) — 要取的元素数量。

创建一个新的 IterableDataset,只包含前 n 个元素。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> small_ds = ds.take(2)
>>> list(small_ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'}]

shard

< >

( num_shards: int index: int contiguous: bool = True )

参数

  • num_shards (int) — 要将数据集拆分成多少个分片。
  • index (int) — 要选择并返回的分片索引。
  • contiguous — (bool, 默认为 True):是否选择连续的索引块进行分片。

从数据集中返回 index-nth 片,该数据集被分成 num_shards 份。

此分片是确定性的。dataset.shard(n, i) 将数据集拆分成连续的块,因此可以在处理后轻松地将其重新连接在一起。如果 dataset.num_shards % n == l,则前 l 个数据集各有 (dataset.num_shards // n) + 1 个分片,其余数据集有 (dataset.num_shards // n) 个分片。datasets.concatenate_datasets([dset.shard(n, i) for i in range(n)]) 返回一个与原始数据集顺序相同的数据集。特别地,dataset.shard(dataset.num_shards, i) 返回一个具有 1 个分片的数据集。

注意:n 应小于或等于数据集中分片的数量 dataset.num_shards

另一方面,dataset.shard(n, i, contiguous=False) 包含所有分片索引模 n 等于 i 的数据集。

确保在使用任何随机化运算符(如 shuffle)之前进行分片。最好在数据集管道的早期使用分片运算符。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("fancyzhx/amazon_polarity", split="train", streaming=True)
>>> ds
Dataset({
    features: ['label', 'title', 'content'],
    num_shards: 4
})
>>> ds.shard(num_shards=2, index=0)
Dataset({
    features: ['label', 'title', 'content'],
    num_shards: 2
})

repeat

< >

( num_times: typing.Optional[int] )

参数

  • num_times (int or (None)) — 重复数据集的次数。如果为 None,则数据集将无限重复。

创建一个新的 IterableDataset,该数据集将底层数据集重复 num_times 次。

注意:调用 shuffle 后 repeat 的效果很大程度上取决于 buffer_size。当 buffer_size 为 1 时,即使在 shuffle 之后,重复的数据也不会在同一次迭代中出现:ds.repeat(n).shuffle(seed=42, buffer_size=1) 等同于 ds.shuffle(seed=42, buffer_size=1).repeat(n),并且只 shuffle 每次迭代中分片的顺序。当 buffer_size 大于等于(数据集中样本的数量 * 重复次数)时,我们将获得对重复数据的完全 shuffle,即我们可以在同一次迭代中观察到重复项。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> ds = ds.take(2).repeat(2)
>>> list(ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'},
 {'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]

to_csv

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **to_csv_kwargs ) int

参数

  • path_or_buf (PathLikeFileOrBuffer) — 要保存数据集的文件的路径(例如 file.csv)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.csv)或 BinaryIO。
  • batch_size (int, optional) — 一次加载到内存并写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • storage_options (dict, optional) — 传递给文件系统后端的键/值对(如果有)。
  • **to_csv_kwargs (其他关键字参数) — 传递给 pandas 的 pandas.DataFrame.to_csv 的参数。如果未指定 index,则默认为 False。如果您想写入索引,请传递 index=True,并通过传递 index_label 为索引列设置名称。

返回

int

写入的字符数或字节数。

将数据集导出为 csv。

这会迭代数据集并将其完全加载到内存中,然后再进行写入。

示例

>>> ds.to_csv("path/to/dataset/directory")

to_pandas

< >

( batch_size: typing.Optional[int] = None batched: bool = False )

参数

  • batch_size (int, optional) — 如果 batchedTrue,则返回的批次大小(行数)。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • batched (bool) — 设置为 True 以返回一个生成器,该生成器按 batch_size 行的批次产生数据集。默认为 False(一次返回整个数据集)。

将数据集返回为 pandas.DataFrame。对于大型数据集,也可以返回一个生成器。

示例

>>> ds.to_pandas()

to_dict

< >

( batch_size: typing.Optional[int] = None batched: bool = False )

参数

  • batch_size (int, optional) — 如果 batchedTrue,则返回的批次大小(行数)。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE

将数据集返回为 Python 字典。对于大型数据集,也可以返回一个生成器。

示例

>>> ds.to_dict()

to_json

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **to_json_kwargs ) int

参数

  • path_or_buf (PathLikeFileOrBuffer) — 要保存数据集的文件的路径(例如 file.json)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.json)或 BinaryIO。
  • batch_size (int, optional) — 一次加载到内存并写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • storage_options (dict, optional) — 传递给文件系统后端的键/值对(如果有)。
  • **to_json_kwargs (其他关键字参数) — 传递给 pandas 的 pandas.DataFrame.to_json 的参数。默认参数为 lines=Trueorient="records"。如果 orient“split”“table”,则 index参数默认为False。如果您想写入索引,请传递 index=True

返回

int

写入的字符数或字节数。

将数据集导出到 JSON Lines 或 JSON。

这会迭代数据集并将其完全加载到内存中,然后再进行写入。

默认的输出格式是 JSON Lines。要导出到 JSON,请传递 lines=False 参数和所需的 orient

示例

>>> ds.to_json("path/to/dataset/directory/filename.jsonl")
>>> num_shards = dataset.num_shards
>>> for index in range(num_shards):
...     shard = dataset.shard(index, num_shards)
...     shard.to_json(f"path/of/my/dataset/data-{index:05d}.jsonl")

to_parquet

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **parquet_writer_kwargs ) int

参数

  • path_or_buf (PathLikeFileOrBuffer) — 要保存数据集的文件的路径(例如 file.parquet)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.parquet)或 BinaryIO。
  • batch_size (int, optional) — 一次加载到内存并写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • storage_options (dict, optional) — Key/value pairs to be passed on to the file-system backend, if any.

    Added in 2.19.0

  • **parquet_writer_kwargs (additional keyword arguments) — Parameters to pass to PyArrow’s pyarrow.parquet.ParquetWriter.

返回

int

写入的字符数或字节数。

将数据集导出到 parquet

示例

>>> ds.to_parquet("path/to/dataset/directory")
>>> num_shards = dataset.num_shards
>>> for index in range(num_shards):
...     shard = dataset.shard(index, num_shards)
...     shard.to_parquet(f"path/of/my/dataset/data-{index:05d}.parquet")

to_sql

< >

( name: str con: typing.Union[str, ForwardRef('sqlalchemy.engine.Connection'), ForwardRef('sqlalchemy.engine.Engine'), ForwardRef('sqlite3.Connection')] batch_size: typing.Optional[int] = None **sql_writer_kwargs ) int

参数

  • name (str) — Name of SQL table.
  • con (str or sqlite3.Connection or sqlalchemy.engine.Connection or sqlalchemy.engine.Connection) — A URI string or a SQLite3/SQLAlchemy connection object used to write to a database.
  • batch_size (int, optional) — Size of the batch to load in memory and write at once. Defaults to datasets.config.DEFAULT_MAX_BATCH_SIZE.
  • **sql_writer_kwargs (additional keyword arguments) — Parameters to pass to pandas’s pandas.DataFrame.to_sql. The parameter index defaults to False if not specified. If you would like to write the index, pass index=True and also set a name for the index column by passing index_label.

返回

int

写入的记录数。

将数据集导出到 SQL 数据库。

示例

>>> # con provided as a connection URI string
>>> ds.to_sql("data", "sqlite:///my_own_db.sql")
>>> # con provided as a sqlite3 connection object
>>> import sqlite3
>>> con = sqlite3.connect("my_own_db.sql")
>>> with con:
...     ds.to_sql("data", con)

push_to_hub

< >

( repo_id: str config_name: str = 'default' set_default: typing.Optional[bool] = None split: typing.Optional[str] = None data_dir: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = False num_shards: typing.Optional[int] = None embed_external_files: bool = True num_proc: typing.Optional[int] = None )

参数

  • repo_id (str) — The ID of the repository to push to in the following format: <user>/<dataset_name> or <org>/<dataset_name>. Also accepts <dataset_name>, which will default to the namespace of the logged-in user.
  • config_name (str, defaults to “default”) — The configuration name (or subset) of a dataset. Defaults to “default”.
  • set_default (bool, optional) — Whether to set this configuration as the default one. Otherwise, the default configuration is the one named “default”.
  • split (str, optional) — The name of the split that will be given to that dataset. Defaults to self.split.
  • data_dir (str, optional) — Directory name that will contain the uploaded data files. Defaults to the config_name if different from “default”, else “data”.
  • commit_message (str, optional) — Message to commit while pushing. Will default to "Upload dataset".
  • commit_description (str, optional) — Description of the commit that will be created. Additionally, description of the PR if a PR is created (create_pr is True).
  • private (bool, optional) — Whether to make the repo private. If None (default), the repo will be public unless the organization’s default is private. This value is ignored if the repo already exists.
  • token (str, optional) — An optional authentication token for the Hugging Face Hub. If no token is passed, will default to the token saved locally when logging in with huggingface-cli login. Will raise an error if no token is passed and the user is not logged-in.
  • revision (str, optional) — Branch to push the uploaded files to. Defaults to the "main" branch.
  • create_pr (bool, optional, defaults to False) — Whether to create a PR with the uploaded files or directly commit.
  • num_shards (int, optional) — Number of shards to write. Equals to this dataset’s .num_shards by default.
  • embed_external_files (bool, defaults to True) — Whether to embed file bytes in the shards. In particular, this will do the following before the push for the fields of type:

    • Audio and Image: remove local path information and embed file content in the Parquet files.
  • num_proc (int, optional, defaults to None) — Number of processes when preparing and uploading the dataset. This is helpful if the dataset is made of many samples and transformations. Multiprocessing is disabled by default.

将数据集作为 Parquet 数据集推送到 hub。数据集使用 HTTP 请求推送,无需安装 git 或 git-lfs。

默认情况下,生成的 Parquet 文件是自包含的。如果您的数据集包含 ImageAudioVideo 数据,Parquet 文件将存储您的图像或音频文件的字节。您可以通过将 embed_external_files 设置为 False 来禁用此功能。

示例

>>> dataset.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset.push_to_hub("<organization>/<dataset_id>", num_shards=1024)

如果您的数据集有多个分割(例如 train/validation/test)

>>> train_dataset.push_to_hub("<organization>/<dataset_id>", split="train")
>>> val_dataset.push_to_hub("<organization>/<dataset_id>", split="validation")
>>> # later
>>> dataset = load_dataset("<organization>/<dataset_id>")
>>> train_dataset = dataset["train"]
>>> val_dataset = dataset["validation"]

如果您想为数据集添加新的配置(或子集)(例如,如果数据集有多个任务/版本/语言)

>>> english_dataset.push_to_hub("<organization>/<dataset_id>", "en")
>>> french_dataset.push_to_hub("<organization>/<dataset_id>", "fr")
>>> # later
>>> english_dataset = load_dataset("<organization>/<dataset_id>", "en")
>>> french_dataset = load_dataset("<organization>/<dataset_id>", "fr")

load_state_dict

< >

( state_dict: dict )

Load the state_dict of the dataset. The iteration will restart at the next example it yielded.

Resuming returns exactly where the checkpoint was saved except in two cases

  1. examples from shuffle buffers are lost when resuming and the buffers are refilled with new data
  2. combinations of .with_format(arrow) and batched .map() may skip one batch.

示例

>>> from datasets import Dataset, concatenate_datasets
>>> ds = Dataset.from_dict({"a": range(6)}).to_iterable_dataset(num_shards=3)
>>> for idx, example in enumerate(ds):
...     print(example)
...     if idx == 2:
...         state_dict = ds.state_dict()
...         print("checkpoint")
...         break
>>> ds.load_state_dict(state_dict)
>>> print(f"restart from checkpoint")
>>> for example in ds:
...     print(example)

which returns

{'a': 0}
{'a': 1}
{'a': 2}
checkpoint
restart from checkpoint
{'a': 3}
{'a': 4}
{'a': 5}
>>> from torchdata.stateful_dataloader import StatefulDataLoader
>>> ds = load_dataset("deepmind/code_contests", streaming=True, split="train")
>>> dataloader = StatefulDataLoader(ds, batch_size=32, num_workers=4)
>>> # checkpoint
>>> state_dict = dataloader.state_dict()  # uses ds.state_dict() under the hood
>>> # resume from checkpoint
>>> dataloader.load_state_dict(state_dict)  # uses ds.load_state_dict() under the hood

state_dict

< >

( ) dict

返回

字典

Get the current state_dict of the dataset. It corresponds to the state at the latest example it yielded.

Resuming returns exactly where the checkpoint was saved except in two cases

  1. examples from shuffle buffers are lost when resuming and the buffers are refilled with new data
  2. combinations of .with_format(arrow) and batched .map() may skip one batch.

示例

>>> from datasets import Dataset, concatenate_datasets
>>> ds = Dataset.from_dict({"a": range(6)}).to_iterable_dataset(num_shards=3)
>>> for idx, example in enumerate(ds):
...     print(example)
...     if idx == 2:
...         state_dict = ds.state_dict()
...         print("checkpoint")
...         break
>>> ds.load_state_dict(state_dict)
>>> print(f"restart from checkpoint")
>>> for example in ds:
...     print(example)

which returns

{'a': 0}
{'a': 1}
{'a': 2}
checkpoint
restart from checkpoint
{'a': 3}
{'a': 4}
{'a': 5}
>>> from torchdata.stateful_dataloader import StatefulDataLoader
>>> ds = load_dataset("deepmind/code_contests", streaming=True, split="train")
>>> dataloader = StatefulDataLoader(ds, batch_size=32, num_workers=4)
>>> # checkpoint
>>> state_dict = dataloader.state_dict()  # uses ds.state_dict() under the hood
>>> # resume from checkpoint
>>> dataloader.load_state_dict(state_dict)  # uses ds.load_state_dict() under the hood

info

< >

( )

DatasetInfo 对象,包含数据集中的所有元数据。

split

< >

( )

NamedSplit 对象,对应一个命名的数据集分片。

builder_name

< >

( )

引用

< >

( )

config_name

< >

( )

dataset_size

< >

( )

description

< >

( )

download_checksums

< >

( )

download_size

< >

( )

features

< >

( )

homepage

< >

( )

许可证

< >

( )

size_in_bytes

< >

( )

supervised_keys

< >

( )

版本

< >

( )

class datasets.IterableColumn

< >

( source: typing.Union[ForwardRef('IterableDataset'), ForwardRef('IterableColumn')] column_name: str )

An iterable for a specific column of an IterableDataset.

示例

迭代数据集“text”列的文本

for text in dataset["text"]:
    ...

它也适用于嵌套列

for source in dataset["metadata"]["source"]:
    ...

IterableDatasetDict

Dictionary with split names as keys (‘train’, ‘test’ for example), and IterableDataset objects as values.

class datasets.IterableDatasetDict

< >

( )

map

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_split: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: int = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None fn_kwargs: typing.Optional[dict] = None )

参数

  • function (Callable, optional, defaults to None) — Function applied on-the-fly on the examples when you iterate on the dataset. It must have one of the following signatures:

    • function(example: Dict[str, Any]) -> Dict[str, Any] if batched=False and with_indices=False
    • function(example: Dict[str, Any], idx: int) -> Dict[str, Any] if batched=False and with_indices=True
    • function(batch: Dict[str, list]) -> Dict[str, list] if batched=True and with_indices=False
    • function(batch: Dict[str, list], indices: list[int]) -> Dict[str, list] if batched=True and with_indices=True

    For advanced usage, the function can also return a pyarrow.Table. If the function is asynchronous, then map will run your function in parallel. Moreover if your function returns nothing (None), then map will run your function and return the dataset unchanged. If no function is provided, default to identity function: lambda x: x.

  • with_indices (bool, defaults to False) — Provide example indices to function. Note that in this case the signature of function should be def function(example, idx[, rank]): ....
  • input_columns ([Union[str, list[str]]], optional, defaults to None) — The columns to be passed into function as positional arguments. If None, a dict mapping to all formatted columns is passed as one argument.
  • batched (bool, defaults to False) — Provide batch of examples to function.
  • batch_size (int, optional, defaults to 1000) — Number of examples per batch provided to function if batched=True.
  • drop_last_batch (bool, defaults to False) — Whether a last batch smaller than the batch_size should be dropped instead of being processed by the function.
  • remove_columns ([list[str]], optional, defaults to None) — Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of function, i.e. if function is adding columns with names in remove_columns, these columns will be kept.
  • fn_kwargs (Dict, optional, defaults to None) — Keyword arguments to be passed to function

Apply a function to all the examples in the iterable dataset (individually or in batches) and update them. If your function returns a column that already exists, then it overwrites it. The function is applied on-the-fly on the examples when iterating over the dataset. The transformation is applied to all the datasets of the dataset dictionary.

You can specify whether the function should be batched or not with the batched parameter

  • If batched is False, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. {"text": "Hello there !"}.
  • If batched is True and batch_size is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is {"text": ["Hello there !"]}.
  • 如果 batched 为 Truebatch_sizen > 1,则函数接收一个包含 n 个示例的批次作为输入,并可以返回一个包含 n 个示例或任意数量示例的批次。请注意,最后一个批次可能少于 n 个示例。批次是字典,例如,包含 n 个示例的批次是 {"text": ["Hello there !"] * n}

If the function is asynchronous, then map will run your function in parallel, with up to one thousand simultaneous calls. It is recommended to use a asyncio.Semaphore in your function if you want to set a maximum number of operations that can run at the same time.

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> next(iter(ds["train"]))
{'label': 1,
 'text': 'Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

过滤器

< >

( function: typing.Optional[typing.Callable] = None with_indices = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 fn_kwargs: typing.Optional[dict] = None )

参数

  • function (Callable) — 具有以下签名之一的可调用对象:

    • function(example: Dict[str, Any]) -> bool if with_indices=False, batched=False
    • function(example: Dict[str, Any], indices: int) -> bool if with_indices=True, batched=False
    • function(example: Dict[str, list]) -> list[bool] if with_indices=False, batched=True
    • function(example: Dict[str, list], indices: list[int]) -> list[bool] if with_indices=True, batched=True

    如果未提供函数,则默认为始终返回 true 的函数:lambda x: True

  • with_indices (bool, defaults to False) — 为 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx): ...
  • input_columns (str or list[str], optional) — 要作为位置参数传递给 function 的列。如果为 None,则将所有格式化列的字典作为单个参数传递。
  • batched (bool, defaults to False) — 为 function 提供示例批次
  • batch_size (int, optional, defaults to 1000) — 如果 batched=True,则提供给 function 的每批示例数。
  • fn_kwargs (Dict, optional, defaults to None) — 要传递给 function 的关键字参数

应用过滤器函数来过滤所有元素,以便数据集仅包含符合过滤器函数的示例。过滤是在迭代数据集时即时进行的。过滤应用于数据集字典中的所有数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.filter(lambda x: x["label"] == 0)
>>> list(ds["train"].take(3))
[{'label': 0, 'text': 'Review: simplistic , silly and tedious .'},
 {'label': 0,
 'text': "Review: it's so laddish and juvenile , only teenage boys could possibly find it funny ."},
 {'label': 0,
 'text': 'Review: exploitative and largely devoid of the depth or sophistication that would make watching such a graphic treatment of the crimes bearable .'}]

shuffle

< >

( seed = None generator: typing.Optional[numpy.random._generator.Generator] = None buffer_size: int = 1000 )

参数

  • seed (int, optional, defaults to None) — 用于对数据集进行随机排序的随机种子。它用于从排序缓冲区中采样以及对数据分片进行排序。
  • generator (numpy.random.Generator, optional) — 用于计算数据集行排列的 NumPy 随机生成器。如果 generator=None(默认),则使用 np.random.default_rng(NumPy 的默认 BitGenerator (PCG64))。
  • buffer_size (int, defaults to 1000) — 缓冲区的尺寸。

随机打乱此数据集的元素。打乱应用于数据集字典中的所有数据集。

此数据集将缓冲区填充 buffer_size 个元素,然后从中随机采样元素,用新元素替换选定的元素。为了完美打乱,需要一个大于或等于数据集总大小的缓冲区。

例如,如果您的数据集包含 10,000 个元素但 buffer_size 设置为 1000,则 shuffle 最初只会从缓冲区的前 1000 个元素中随机选择一个。一旦选择了一个元素,它在缓冲区中的位置就会被下一个(即第 1001 个)元素替换,从而保持 1000 个元素的缓冲区。

如果数据集由多个分片组成,它还会对分片的顺序进行 shuffle。但是,如果顺序已通过使用 skip()take() 固定,则分片的顺序保持不变。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> list(ds["train"].take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]
>>> ds = ds.shuffle(seed=42)
>>> list(ds["train"].take(3))
[{'label': 1,
 'text': "a sports movie with action that's exciting on the field and a story you care about off it ."},
 {'label': 1,
 'text': 'at its best , the good girl is a refreshingly adult take on adultery . . .'},
 {'label': 1,
 'text': "sam jones became a very lucky filmmaker the day wilco got dropped from their record label , proving that one man's ruin may be another's fortune ."}]

with_format

< >

( type: typing.Optional[str] = None )

参数

  • type (str, optional) — 在 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中选择的输出类型。None 表示返回 Python 对象(默认)。

返回具有指定格式的数据集。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation", streaming=True)
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds = ds.with_format("torch")
>>> next(iter(ds))
{'text': 'compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 'label': tensor(1),
 'input_ids': tensor([  101, 18027, 16310, 16001,  1103,  9321,   178, 11604,  7235,  6617,
        1742,  2165,  2820,  1206,  6588, 22572, 12937,  1811,  2153,  1105,
        1147, 12890, 19587,  6463,  1105, 15026,  1482,   119,   102,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
 'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])}

cast

< >

( features: Features ) IterableDatasetDict

参数

  • features (Features) — 要将数据集转换为的新功能。功能中的字段名称必须与当前列名匹配。数据类型也必须可以从一种类型转换为另一种类型。对于非平凡转换,例如 string <-> ClassLabel,您应使用 map 更新数据集。

返回

IterableDatasetDict

一个具有转换后特征的数据集副本。

将数据集转换为一组新功能。类型转换应用于数据集字典中的所有数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> new_features = ds["train"].features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('large_string')}

cast_column

< >

( column: str feature: typing.Union[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.LargeList, datasets.features.features.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf, datasets.features.nifti.Nifti] )

参数

  • column (str) — 列名。
  • feature (Feature) — 目标功能。

将列转换为用于解码的功能。类型转换应用于数据集字典中的所有数据集。

示例

>>> from datasets import load_dataset, ClassLabel
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('string')}

remove_columns

< >

( column_names: typing.Union[str, list[str]] ) IterableDatasetDict

参数

  • column_names (Union[str, list[str]]) — 要删除的列名。

返回

IterableDatasetDict

一个不包含要删除的列的数据集对象副本。

从数据集中删除一个或多个列以及与之关联的功能。删除是在迭代数据集时即时在示例上进行的。删除应用于数据集字典中的所有数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.remove_columns("label")
>>> next(iter(ds["train"]))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

rename_column

< >

( original_column_name: str new_column_name: str ) IterableDatasetDict

参数

  • original_column_name (str) — 要重命名的列名。
  • new_column_name (str) — 列的新名称。

返回

IterableDatasetDict

一个具有重命名列的数据集副本。

重命名数据集中的列,并将与原始列关联的功能移动到新列名下。重命名应用于数据集字典中的所有数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.rename_column("text", "movie_review")
>>> next(iter(ds["train"]))
{'label': 1,
 'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

rename_columns

< >

( column_mapping: dict ) IterableDatasetDict

参数

  • column_mapping (Dict[str, str]) — 要重命名的列及其新名称的映射。

返回

IterableDatasetDict

重命名列后的数据集的副本

重命名数据集中的多个列,并将与原始列关联的功能移动到新列名下。重命名应用于数据集字典中的所有数据集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.rename_columns({"text": "movie_review", "label": "rating"})
>>> next(iter(ds["train"]))
{'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',
 'rating': 1}

select_columns

< >

( column_names: typing.Union[str, list[str]] ) IterableDatasetDict

参数

  • column_names (Union[str, list[str]]) — 要保留的列名。

返回

IterableDatasetDict

要仅选择列的 dataset 对象副本。

在 dataset 中选择一个或多个列及其关联的特征。选择是在迭代 dataset 时即时进行的。选择将应用于 dataset 字典中的所有 dataset。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.select("text")
>>> next(iter(ds["train"]))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

push_to_hub

< >

( repo_id config_name: str = 'default' set_default: typing.Optional[bool] = None data_dir: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = False num_shards: typing.Optional[dict[str, int]] = None embed_external_files: bool = True num_proc: typing.Optional[int] = None )

参数

  • repo_id (str) — 要推送到的仓库 ID,格式如下:<user>/<dataset_name><org>/<dataset_name>。也可以接受 <dataset_name>,这将默认为已登录用户的命名空间。
  • config_name (str) — dataset 的配置名称。默认为 “default”。
  • set_default (bool, optional) — 是否将此配置设置为默认配置。否则,默认配置是名为“default”的配置。
  • data_dir (str, optional) — 将包含已上传数据文件的目录名称。如果与“default”不同,则默认为 config_name,否则为“data”。

    Added in 2.17.0

  • commit_message (str, optional) — 推送时要提交的消息。默认为 "Upload dataset"
  • commit_description (str, optional) — 将要创建的 commit 的描述。如果 create_pr 为 True,也是 PR 的描述。

    Added in 2.16.0

  • private (bool, optional) — 是否使仓库私有。如果为 None(默认),仓库将公开,除非该组织的默认设置为私有。如果仓库已存在,则忽略此值。
  • token (str, optional) — Hugging Face Hub 的可选身份验证令牌。如果未传递令牌,将默认为使用 huggingface-cli login 登录时本地保存的令牌。如果未传递令牌且用户未登录,将引发错误。
  • revision (str, optional) — 推送已上传文件到的分支。默认为 "main" 分支。
  • create_pr (bool, optional, defaults to False) — 是否创建带有已上传文件的 PR 或直接提交。
  • num_shards (Dict[str, int], optional) — 要写入的分片数量。默认为此 dataset 的 .num_shards。使用字典为每个拆分定义不同的 num_shards。
  • embed_external_files (bool, defaults to True) — 是否将文件字节嵌入分片中。特别是,在推送用于以下字段类型的操作之前,它将执行以下操作:

    • AudioImage 将删除本地路径信息,并将文件内容嵌入 Parquet 文件中。
  • num_proc (int, optional, defaults to None) — 准备和上传 dataset 时的进程数。如果 dataset 包含许多样本或媒体文件要嵌入,这将很有帮助。多进程默认禁用。

    Added in 4.0.0

DatasetDict 作为 Parquet 数据集推送到 hub。 DatasetDict 使用 HTTP 请求推送,不需要安装 git 或 git-lfs。

每个数据集分片将独立推送。推送的数据集将保留原始的分片名称。

默认情况下,生成的 Parquet 文件是自包含的:如果您的数据集包含 ImageAudio 数据,Parquet 文件将存储图像或音频文件的字节。通过将 embed_external_files 设置为 False,可以禁用此功能。

示例

>>> dataset_dict.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", num_shards={"train": 1024, "test": 8})

如果您想为数据集添加新的配置(或子集)(例如,如果数据集有多个任务/版本/语言)

>>> english_dataset.push_to_hub("<organization>/<dataset_id>", "en")
>>> french_dataset.push_to_hub("<organization>/<dataset_id>", "fr")
>>> # later
>>> english_dataset = load_dataset("<organization>/<dataset_id>", "en")
>>> french_dataset = load_dataset("<organization>/<dataset_id>", "fr")

Features

class datasets.Features

< >

( *args **kwargs )

一个定义 dataset 内部结构的特殊字典。

使用 dict[str, FieldType] 类型的字典进行实例化,其中键是所需的列名,值是该列的类型。

FieldType 可以是以下之一

  • Value 特征指定单个数据类型值,例如 int64string
  • ClassLabel 特征指定一组预定义的类,这些类可以与标签关联,并在 dataset 中存储为整数。
  • Python dict 指定一个复合特征,包含子字段到子特征的映射。可以以任意方式拥有嵌套字段的嵌套字段。
  • ListLargeList 指定一个复合特征,包含一系列相同特征类型的子特征。
  • Array2DArray3DArray4DArray5D 多维数组特征。
  • Audio 特征用于存储音频文件的绝对路径或一个字典,其中包含音频文件的相对路径(“path”键)及其字节内容(“bytes”键)。此特征使用解码器惰性加载音频。
  • Image 特征用于存储图像文件的绝对路径、np.ndarray 对象、PIL.Image.Image 对象或一个字典,其中包含图像文件的相对路径(“path”键)及其字节内容(“bytes”键)。此特征提取图像数据。
  • Video 特征用于存储视频文件的绝对路径、torchcodec.decoders.VideoDecoder 对象或一个字典,其中包含视频文件的相对路径(“path”键)及其字节内容(“bytes”键)。此特征使用解码器惰性加载视频。
  • Pdf 特征用于存储 PDF 文件的绝对路径、pdfplumber.pdf.PDF 对象或一个字典,其中包含 PDF 文件的相对路径(“path”键)及其字节内容(“bytes”键)。此特征使用 PDF 阅读器惰性加载 PDF。
  • Nifti 特征用于存储 NIfTI 神经影像文件的绝对路径、nibabel.Nifti1Image 对象或一个字典,其中包含 NIfTI 文件的相对路径(“path”键)及其字节内容(“bytes”键)。此特征使用 nibabel 惰性加载 NIfTI 文件。
  • TranslationTranslationVariableLanguages 特征,专门用于机器翻译。

复制

< >

( )

Features 进行深拷贝。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> copy_of_features = ds.features.copy()
>>> copy_of_features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}

decode_batch

< >

( batch: dict token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

参数

  • batch (dict[str, list[Any]]) — Dataset batch 数据。
  • token_per_repo_id (dict, optional) — 要从私有仓库访问和解码音频或图像文件,您可以传递一个字典 repo_id (str) -> token (bool or str)

使用自定义特征解码批次。

decode_column

< >

( column: list column_name: str token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

参数

  • column (list[Any]) — Dataset column data.
  • column_name (str) — Dataset column name.

使用自定义特征解码来解码列。

decode_example

< >

( example: dict token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

参数

  • example (dict[str, Any]) — Dataset row data.
  • token_per_repo_id (dict, optional) — To access and decode audio or image files from private repositories on the Hub, you can pass a dictionary repo_id (str) -> token (bool or str).

使用自定义特征解码来解码示例。

encode_batch

< >

( batch )

参数

  • batch (dict[str, list[Any]]) — Data in a Dataset batch.

将批次编码为 Arrow 的格式。

encode_column

< >

( column column_name: str )

参数

  • column (list[Any]) — Data in a Dataset column.
  • column_name (str) — Dataset column name.

将列编码为 Arrow 的格式。

encode_example

< >

( example )

参数

  • example (dict[str, Any]) — Data in a Dataset row.

将示例编码为 Arrow 的格式。

flatten

< >

( max_depth = 16 ) Features

返回

功能

平展后的 Features。

平展 Features。所有字典列都会被移除,并替换为它们包含的所有子字段。新字段的命名方式是将原始列名和子字段名连接起来,格式为:<original>.<subfield>

如果一个列包含嵌套字典,那么所有较低级别的子字段名也会被连接起来,形成新的列:<original>.<subfield>.<subsubfield>,依此类推。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad", split="train")
>>> ds.features.flatten()
{'answers.answer_start': List(Value('int32'), id=None),
 'answers.text': List(Value('string'), id=None),
 'context': Value('string'),
 'id': Value('string'),
 'question': Value('string'),
 'title': Value('string')}

from_arrow_schema

< >

( pa_schema: Schema )

参数

  • pa_schema (pyarrow.Schema) — Arrow Schema.

从 Arrow Schema 构建 Features。它还会检查 Hugging Face Datasets features 的 schema metadata。不支持非可空字段,并将它们设置为可空。

此外,pa.dictionary 不受支持,它会使用其底层类型。因此,datasets 会将 DictionaryArray 对象转换为其实际值。

from_dict

< >

( dic ) Features

参数

  • dic (dict[str, Any]) — Python dictionary.

返回

功能

从 dict 构建 [Features]。

从反序列化的 dict 重建嵌套的 feature 对象。我们使用 _type 键来推断 feature FieldType 的数据类名称。

它允许使用方便的构造函数语法从反序列化的 JSON 字典定义 Features。此函数特别用于反序列化转储到 JSON 对象的 [DatasetInfo]。它充当 [Features.from_arrow_schema] 的类似功能,并处理递归的逐字段实例化,但不需要与 pyarrow 之间的任何映射,除了它利用了 [Value] 自动执行的 pyarrow 原始数据类型映射。

示例

>>> Features.from_dict({'_type': {'dtype': 'string', 'id': None, '_type': 'Value'}})
{'_type': Value('string')}

reorder_fields_as

< >

( other: Features )

参数

  • other ([Features]) — The other [Features] to align with.

重新排序 Features 字段以匹配其他 [Features] 的字段顺序。

字段的顺序很重要,因为它会影响底层的 arrow 数据。重新排序字段可以使底层的 arrow 数据类型匹配。

示例

>>> from datasets import Features, List, Value
>>> # let's say we have two features with a different order of nested fields (for a and b for example)
>>> f1 = Features({"root": {"a": Value("string"), "b": Value("string")}})
>>> f2 = Features({"root": {"b": Value("string"), "a": Value("string")}})
>>> assert f1.type != f2.type
>>> # re-ordering keeps the base structure (here List is defined at the root level), but makes the fields order match
>>> f1.reorder_fields_as(f2)
{'root': List({'b': Value('string'), 'a': Value('string')})}
>>> assert f1.reorder_fields_as(f2).type == f2.type

Scalar

class datasets.Value

< >

( dtype: str id: typing.Optional[str] = None )

参数

  • dtype (str) — Name of the data type.

特定数据类型的标量特征值。

Value 的可能数据类型如下:

  • null
  • 布尔值
  • int8
  • int16
  • int32
  • int64
  • uint8
  • uint16
  • uint32
  • uint64
  • float16
  • float32 (别名 float)
  • float64 (别名 double)
  • time32[(s|ms)]
  • time64[(us|ns)]
  • timestamp[(s|ms|us|ns)]
  • timestamp[(s|ms|us|ns), tz=(tzstring)]
  • date32
  • date64
  • duration[(s|ms|us|ns)]
  • decimal128(precision, scale)
  • decimal256(precision, scale)
  • binary
  • large_binary
  • binary_view
  • 字符串
  • large_string
  • string_view

示例

>>> from datasets import Features
>>> features = Features({'stars': Value('int32')})
>>> features
{'stars': Value('int32')}

class datasets.ClassLabel

< >

( num_classes: dataclasses.InitVar[typing.Optional[int]] = None names: list = None names_file: dataclasses.InitVar[typing.Optional[str]] = None id: typing.Optional[str] = None )

参数

  • num_classes (int, optional) — 类的数量。所有标签都必须小于 num_classes
  • names (list of str, optional) — 整数类的字符串名称。提供的名称顺序得以保留。
  • names_file (str, optional) — 整数类的名称文件路径,每行一个。

整数类标签的特征类型。

定义 ClassLabel 有 3 种方式,对应于 3 个参数

  • num_classes:创建 0 到 (num_classes-1) 的标签。
  • names:标签字符串列表。
  • names_file:包含标签列表的文件。

在底层,标签存储为整数。您可以使用负整数来表示未知/缺失的标签。

示例

>>> from datasets import Features, ClassLabel
>>> features = Features({'label': ClassLabel(num_classes=3, names=['bad', 'ok', 'good'])})
>>> features
{'label': ClassLabel(names=['bad', 'ok', 'good'])}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.IntegerArray] ) pa.Int64Array

参数

  • storage (Union[pa.StringArray, pa.IntegerArray]) — 要转换的 PyArrow 数组。

返回

pa.Int64Array

ClassLabel arrow 存储类型中的数组。

将 Arrow 数组转换为 ClassLabel arrow 存储类型。可以转换为 ClassLabel pyarrow 存储类型的 Arrow 类型有

  • pa.string()
  • pa.int()

int2str

< >

( values: typing.Union[int, collections.abc.Iterable] )

转换 integer => 类名 string

关于未知/缺失标签:传入负整数会引发 ValueError

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> ds.features["label"].int2str(0)
'neg'

str2int

< >

( values: typing.Union[str, collections.abc.Iterable] )

转换类名 string => integer

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> ds.features["label"].str2int('neg')
0

组合

class datasets.LargeList

< >

( feature: typing.Any id: typing.Optional[str] = None )

参数

  • feature (FeatureType) — 大列表内每个项目的子特征数据类型。

由子特征数据类型组成的大列表的特征类型。

它由 pyarrow.LargeListType 支持,它类似于 pyarrow.ListType,但具有 64 位偏移量而不是 32 位。

class datasets.List

< >

( feature: typing.Any length: int = -1 id: typing.Optional[str] = None )

参数

  • feature (FeatureType) — 大列表内每个项目的子特征数据类型。
  • length (optional int, default to -1) — 如果列表是固定的,则为列表的长度。默认值为 -1,表示任意长度。

由子特征数据类型组成的大列表的特征类型。

它由 pyarrow.ListType 支持,该类型使用 32 位偏移量或固定长度。

class datasets.Sequence

< >

( feature = None length = -1 **kwargs )

参数

  • feature (FeatureType) — 大列表内每个项目的子特征数据类型。
  • length (optional int, default to -1) — 如果列表是固定的,则为列表的长度。默认值为 -1,表示任意长度。

Sequence 是一个实用程序,可自动将内部字典特征转换为列表字典。此行为实现是为了与 TensorFlow Datasets 库兼容,但在某些情况下可能不需要。如果您不希望此行为,可以使用 ListLargeList 而不是 Sequence

翻译

class datasets.Translation

< >

( languages: list id: typing.Optional[str] = None )

参数

  • languages (dict) — 每个示例的字典,将字符串语言代码映射到字符串翻译。

每个示例具有固定语言的“Translation”功能。此处是为了与 tfds 兼容。

示例

>>> # At construction time:
>>> datasets.features.Translation(languages=['en', 'fr', 'de'])
>>> # During data generation:
>>> yield {
...         'en': 'the cat',
...         'fr': 'le chat',
...         'de': 'die katze'
... }

flatten

< >

( )

将 Translation 功能展平成一个字典。

class datasets.TranslationVariableLanguages

< >

( languages: typing.Optional[list] = None num_languages: typing.Optional[int] = None id: typing.Optional[str] = None )

  • languagetranslation (可变长度一维 tf.Tensor of tf.string)

参数

  • languages (dict) — 每个示例的字典,将字符串语言代码映射到一个或多个字符串翻译。不同示例的语言可能不同。

返回

  • languagetranslation (可变长度一维 tf.Tensor of tf.string)

按升序排序的语言代码或纯文本翻译,按语言代码对齐排序。

每个示例具有可变语言的“Translation”功能。此处是为了与 tfds 兼容。

示例

>>> # At construction time:
>>> datasets.features.TranslationVariableLanguages(languages=['en', 'fr', 'de'])
>>> # During data generation:
>>> yield {
...         'en': 'the cat',
...         'fr': ['le chat', 'la chatte,']
...         'de': 'die katze'
... }
>>> # Tensor returned :
>>> {
...         'language': ['en', 'de', 'fr', 'fr'],
...         'translation': ['the cat', 'die katze', 'la chatte', 'le chat'],
... }

flatten

< >

( )

将 TranslationVariableLanguages 功能展平成一个字典。

数组

class datasets.Array2D

< >

( shape: tuple dtype: str id: typing.Optional[str] = None )

参数

  • shape (tuple) — 各维度的尺寸。
  • dtype (str) — 数据类型的名称。

创建一个二维数组。

示例

>>> from datasets import Features
>>> features = Features({'x': Array2D(shape=(1, 3), dtype='int32')})

class datasets.Array3D

< >

( shape: tuple dtype: str id: typing.Optional[str] = None )

参数

  • shape (tuple) — 各维度的尺寸。
  • dtype (str) — 数据类型的名称。

创建一个三维数组。

示例

>>> from datasets import Features
>>> features = Features({'x': Array3D(shape=(1, 2, 3), dtype='int32')})

class datasets.Array4D

< >

( shape: tuple dtype: str id: typing.Optional[str] = None )

参数

  • shape (tuple) — 各维度的尺寸。
  • dtype (str) — 数据类型的名称。

创建一个四维数组。

示例

>>> from datasets import Features
>>> features = Features({'x': Array4D(shape=(1, 2, 2, 3), dtype='int32')})

class datasets.Array5D

< >

( shape: tuple dtype: str id: typing.Optional[str] = None )

参数

  • shape (tuple) — 各维度的尺寸。
  • dtype (str) — 数据类型的名称。

创建一个五维数组。

示例

>>> from datasets import Features
>>> features = Features({'x': Array5D(shape=(1, 2, 2, 3, 3), dtype='int32')})

Audio

class datasets.Audio

< >

( sampling_rate: typing.Optional[int] = None decode: bool = True num_channels: typing.Optional[int] = None stream_index: typing.Optional[int] = None id: typing.Optional[str] = None )

参数

  • sampling_rate (int, optional) — 目标采样率。如果为 None,则使用原始采样率。
  • num_channels (int, optional) — 样本所需的通道数。默认情况下,使用源的通道数。音频解码将返回形状为 (num_channels, num_samples) 的样本。目前支持 None(源的通道数,默认)、1(单声道)或 2(立体声)通道。num_channels 参数将传递给 torchcodec.decoders.AudioDecoder

    Added in 4.4.0

  • decode (bool, defaults to True) — 是否解码音频数据。如果为 False,则返回基础字典,格式为 {"path": audio_path, "bytes": audio_bytes}
  • stream_index (int, optional) — 要从文件中使用的流索引。如果为 None,则默认为“最佳”索引。

Audio Feature 用于从音频文件中提取音频数据。

输入:Audio feature 接受的输入

  • 一个 str:音频文件的绝对路径(允许随机访问)。

  • 一个 pathlib.Path:音频文件的路径(允许随机访问)。

  • 一个 dict,键为

    • path:音频文件相对于存档文件的相对路径的字符串。
    • bytes:音频文件的字节内容。

    这对于嵌入音频文件的 parquet 或 webdataset 文件很有用。

  • 一个 dict,键为

    • array:包含音频样本的数组
    • sampling_rate:与音频样本采样率对应的整数。
  • 一个 torchcodec.decoders.AudioDecoder:torchcodec 音频解码器对象。

输出:Audio feature 将数据作为 torchcodec.decoders.AudioDecoder 对象输出,并附带附加键

  • array:包含音频样本的数组
  • sampling_rate:与音频样本采样率对应的整数。

示例

>>> from datasets import load_dataset, Audio
>>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=44100, num_channels=2))
>>> ds[0]["audio"]
<datasets.features._torchcodec.AudioDecoder object at 0x11642b6a0>
>>> audio = ds[0]["audio"]
>>> audio.get_samples_played_in_range(0, 10)
AudioSamples:
    data (shape): torch.Size([2, 110592])
    pts_seconds: 0.0
    duration_seconds: 2.507755102040816
    sample_rate: 44100

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray] token_per_repo_id = None ) pa.StructArray

参数

  • storage (Union[pa.StringArray, pa.StructArray]) — 要转换的 PyArrow 数组。

返回

pa.StructArray

Audio arrow 存储类型的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将 Arrow 数组转换为 Audio pyarrow 存储类型。可以转换为 Audio pyarrow 存储类型的 Arrow 类型是

  • pa.string() - 它必须包含“path”数据
  • pa.binary() - 它必须包含音频字节
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 顺序无关

decode_example

< >

( value: dict token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

参数

  • value (dict) — 包含键的字典:

    • path:相对音频文件路径的字符串。
    • bytes:音频文件的字节。
  • token_per_repo_id (dict, optional) — 要访问和解码 Hub 上的私有存储库的音频文件,您可以传递一个字典 repo_id (str) -> token (boolstr)

将示例音频文件解码为音频数据。

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

参数

  • storage (pa.StructArray) — 要嵌入的 PyArrow 数组。

返回

pa.StructArray

Audio arrow 存储类型的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将音频文件嵌入到 Arrow 数组中。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, ForwardRef('AudioDecoder')] ) dict

参数

  • value (str, bytes,bytearray,dict, AudioDecoder) — 输入到 Audio 特征的数据。

返回

字典

将示例编码为 Arrow 的格式。

flatten

< >

( )

如果处于可解码状态,则引发错误,否则将特征展平成字典。

Image

class datasets.Image

< >

( mode: typing.Optional[str] = None decode: bool = True id: typing.Optional[str] = None )

参数

  • mode (str, optional) — The mode to convert the image to. If None, the native mode of the image is used.
  • decode (bool, defaults to True) — Whether to decode the image data. If False, returns the underlying dictionary in the format {"path": image_path, "bytes": image_bytes}.

Image Feature to read image data from an image file.

Input: The Image feature accepts as input

  • A str: Absolute path to the image file (i.e. random access is allowed).

  • A pathlib.Path: path to the image file (i.e. random access is allowed).

  • 一个 dict,键为

    • path: String with relative path of the image file to the archive file.
    • bytes: Bytes of the image file.

    This is useful for parquet or webdataset files which embed image files.

  • An np.ndarray: NumPy array representing an image.

  • A PIL.Image.Image: PIL image object.

Output: The Image features output data as PIL.Image.Image objects.

示例

>>> from datasets import load_dataset, Image
>>> ds = load_dataset("AI-Lab-Makerere/beans", split="train")
>>> ds.features["image"]
Image(decode=True, id=None)
>>> ds[0]["image"]
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x500 at 0x15E52E7F0>
>>> ds = ds.cast_column('image', Image(decode=False))
{'bytes': None,
 'path': '/root/.cache/huggingface/datasets/downloads/extracted/b0a21163f78769a2cf11f58dfc767fb458fc7cea5c05dccc0144a2c0f0bc1292/train/healthy/healthy_train.85.jpg'}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray, pyarrow.lib.ListArray] ) pa.StructArray

参数

  • storage (Union[pa.StringArray, pa.StructArray, pa.ListArray]) — PyArrow 数组需要转换。

返回

pa.StructArray

Image arrow 存储类型中的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将 Arrow 数组转换为 Image arrow 存储类型。可以转换为 Image pyarrow 存储类型的 Arrow 类型为

  • pa.string() - 它必须包含“path”数据
  • pa.large_string() - 必须包含“path”数据(如果可能,将转换为字符串)
  • pa.binary() - 必须包含图像字节
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 顺序无关
  • pa.list(*) - 必须包含图像数组数据

decode_example

< >

( value: dict token_per_repo_id = None )

参数

  • value (str or dict) — A string with the absolute image file path, a dictionary with keys:

    • path: String with absolute or relative image file path.
    • bytes: The bytes of the image file.
  • token_per_repo_id (dict, optional) — To access and decode image files from private repositories on the Hub, you can pass a dictionary repo_id (str) -> token (bool or str).

Decode example image file into image data.

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

参数

  • storage (pa.StructArray) — PyArrow 数组将被嵌入。

返回

pa.StructArray

Image arrow 存储类型中的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将图像文件嵌入 Arrow 数组。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, numpy.ndarray, ForwardRef('PIL.Image.Image')] )

参数

  • value (str, np.ndarray, PIL.Image.Image or dict) — 输入到 Image 特征的数据。

将示例编码为 Arrow 的格式。

flatten

< >

( )

如果处于可解码状态,则返回特征本身,否则将特征展平成字典。

Video

class datasets.Video

< >

( decode: bool = True stream_index: typing.Optional[int] = None dimension_order: typing.Literal['NCHW', 'NHWC'] = 'NCHW' num_ffmpeg_threads: int = 1 device: typing.Union[str, ForwardRef('torch.device'), NoneType] = 'cpu' seek_mode: typing.Literal['exact', 'approximate'] = 'exact' id: typing.Optional[str] = None )

参数

  • decode (bool, defaults to True) — Whether to decode the video data. If False, returns the underlying dictionary in the format {"path": video_path, "bytes": video_bytes}.
  • stream_index (int, optional) — The streaming index to use from the file. If None defaults to the “best” index.
  • dimension_order (str, defaults to NCHW) — The dimension order of the decoded frames. where N is the batch size, C is the number of channels, H is the height, and W is the width of the frames.
  • num_ffmpeg_threads (int, defaults to 1) — The number of threads to use for decoding the video. (Recommended to keep this at 1)
  • device (str or torch.device, defaults to cpu) — The device to use for decoding the video.
  • seek_mode (str, defaults to exact) — Determines if frame access will be “exact” or “approximate”. Exact guarantees that requesting frame i will always return frame i, but doing so requires an initial scan of the file. Approximate is faster as it avoids scanning the file, but less accurate as it uses the file’s metadata to calculate where i probably is. read more here

Video Feature to read video data from a video file.

Input: The Video feature accepts as input

  • A str: Absolute path to the video file (i.e. random access is allowed).

  • A pathlib.Path: path to the video file (i.e. random access is allowed).

  • 一个 dict,键为

    • path: String with relative path of the video file in a dataset repository.
    • bytes: Bytes of the video file.

    This is useful for parquet or webdataset files which embed video files.

  • A torchcodec.decoders.VideoDecoder: torchcodec video decoder object.

Output: The Video features output data as torchcodec.decoders.VideoDecoder objects.

示例

>>> from datasets import Dataset, Video
>>> ds = Dataset.from_dict({"video":["path/to/Screen Recording.mov"]}).cast_column("video", Video())
>>> ds.features["video"]
Video(decode=True, id=None)
>>> ds[0]["video"]
<torchcodec.decoders._video_decoder.VideoDecoder object at 0x14a61e080>
>>> video = ds[0]["video"]
>>> video.get_frames_in_range(0, 10)
FrameBatch:
data (shape): torch.Size([10, 3, 50, 66])
pts_seconds: tensor([0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333,
        0.4333], dtype=torch.float64)
duration_seconds: tensor([0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167,
        0.0167], dtype=torch.float64)
>>> ds.cast_column('video', Video(decode=False))[0]["video]
{'bytes': None,
 'path': 'path/to/Screen Recording.mov'}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray, pyarrow.lib.ListArray] ) pa.StructArray

参数

  • storage (Union[pa.StringArray, pa.StructArray, pa.ListArray]) — PyArrow 数组,用于转换。

返回

pa.StructArray

Video Arrow 存储类型中的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将 Arrow 数组转换为 Video Arrow 存储类型。可以转换为 Video PyArrow 存储类型的 Arrow 类型是

  • pa.string() - 它必须包含“path”数据
  • pa.binary() - 它必须包含视频字节
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 顺序无关
  • pa.list(*) - 它必须包含视频数组数据

decode_example

< >

( value: typing.Union[str, datasets.features.video.Example] token_per_repo_id: typing.Optional[dict[str, typing.Union[bool, str]]] = None )

参数

  • value (strdict) — 包含绝对视频文件路径的字符串,或包含以下键的字典:

    • path: 视频文件的绝对或相对路径。
    • bytes: 视频文件的字节。
  • token_per_repo_id (dict, optional) — 要从 Hub 上的私有存储库访问和解码视频文件,您可以传递一个字典 repo_id (str) -> token (boolstr)。

解码示例视频文件为视频数据。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, datasets.features.video.Example, numpy.ndarray, ForwardRef('VideoDecoder')] )

参数

  • value (str, np.ndarray, bytes, bytearray, VideoDecoderdict) — 输入到 Video feature 的数据。

将示例编码为 Arrow 的格式。

flatten

< >

( )

如果处于可解码状态,则返回特征本身,否则将特征展平成字典。

Pdf

class datasets.Pdf

< >

( decode: bool = True id: typing.Optional[str] = None )

参数

  • decode (bool, 默认为 True) — 是否解码 pdf 数据。如果为 False,则返回格式为 {"path": pdf_path, "bytes": pdf_bytes} 的底层字典。

Experimental. Pdf Feature,用于从 pdf 文件读取 pdf 文档。

输入: Pdf feature 接受的输入为

  • 一个 str: pdf 文件的绝对路径(即允许随机访问)。

  • 一个 pathlib.Path: pdf 文件的路径(即允许随机访问)。

  • 一个 dict,键为

    • path: 数据集存储库中 pdf 文件的相对路径字符串。
    • bytes: pdf 文件的字节。这对于存档的顺序访问文件很有用。
  • 一个 pdfplumber.pdf.PDF: pdfplumber pdf 对象。

示例

>>> from datasets import Dataset, Pdf
>>> ds = Dataset.from_dict({"pdf": ["path/to/pdf/file.pdf"]}).cast_column("pdf", Pdf())
>>> ds.features["pdf"]
Pdf(decode=True, id=None)
>>> ds[0]["pdf"]
<pdfplumber.pdf.PDF object at 0x7f8a1c2d8f40>
>>> ds = ds.cast_column("pdf", Pdf(decode=False))
>>> ds[0]["pdf"]
{'bytes': None,
'path': 'path/to/pdf/file.pdf'}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray, pyarrow.lib.ListArray] ) pa.StructArray

参数

  • storage (Union[pa.StringArray, pa.StructArray, pa.ListArray]) — PyArrow 数组,用于转换。

返回

pa.StructArray

Pdf Arrow 存储类型中的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将 Arrow 数组转换为 Pdf Arrow 存储类型。可以转换为 Pdf PyArrow 存储类型的 Arrow 类型是

  • pa.string() - 它必须包含“path”数据
  • pa.binary() - 必须包含图像字节
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 顺序无关
  • pa.list(*) - 它必须包含 pdf 数组数据

decode_example

< >

( value: dict token_per_repo_id = None )

参数

  • value (strdict) — 包含绝对 pdf 文件路径的字符串,或包含以下键的字典:

    • path: pdf 文件的绝对或相对路径。
    • bytes: pdf 文件的字节。
  • token_per_repo_id (dict, optional) — 要从 Hub 上的私有存储库访问和解码 pdf 文件,您可以传递一个字典 repo_id (str) -> token (boolstr)。

解码示例 pdf 文件为 pdf 数据。

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

参数

  • storage (pa.StructArray) — PyArrow 数组,用于嵌入。

返回

pa.StructArray

PDF Arrow 存储类型中的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将 PDF 文件嵌入 Arrow 数组。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, ForwardRef('pdfplumber.pdf.PDF')] )

参数

  • value (str, bytes, pdfplumber.pdf.PDFdict) — 输入到 Pdf feature 的数据。

将示例编码为 Arrow 的格式。

flatten

< >

( )

如果处于可解码状态,则返回特征本身,否则将特征展平成字典。

Nifti

class datasets.Nifti

< >

( decode: bool = True id: typing.Optional[str] = None )

参数

  • decode (bool, 默认为 True) — 是否解码 NIfTI 数据。如果为 False,则返回包含字节的字符串。decode=False 在解码示例时不被支持。

Experimental. Nifti Feature,用于读取 NIfTI 神经影像文件。

输入: Nifti feature 接受的输入为

  • 一个 str: NIfTI 文件的绝对路径(即允许随机访问)。

  • 一个 pathlib.Path: NIfTI 文件的路径(即允许随机访问)。

  • 一个 dict,键为

    • path: 数据集存储库中 NIfTI 文件的相对路径字符串。
    • bytes: NIfTI 文件的字节。这对于存档的顺序访问文件很有用。
  • 一个 nibabel 图像对象(例如,nibabel.nifti1.Nifti1Image)。

示例

>>> from datasets import Dataset, Nifti
>>> ds = Dataset.from_dict({"nifti": ["path/to/file.nii.gz"]}).cast_column("nifti", Nifti())
>>> ds.features["nifti"]
Nifti(decode=True, id=None)
>>> ds[0]["nifti"]
<nibabel.nifti1.Nifti1Image object at 0x7f8a1c2d8f40>
>>> ds = ds.cast_column("nifti", Nifti(decode=False))
>>> ds[0]["nifti"]
{'bytes': None,
'path': 'path/to/file.nii.gz'}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray, pyarrow.lib.BinaryArray] ) pa.StructArray

参数

  • storage (Union[pa.StringArray, pa.StructArray, pa.BinaryArray]) — PyArrow 数组,用于转换。

返回

pa.StructArray

Nifti Arrow 存储类型中的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将 Arrow 数组转换为 Nifti Arrow 存储类型。可以转换为 Nifti PyArrow 存储类型的 Arrow 类型是

  • pa.string() - 它必须包含“path”数据
  • pa.binary() - 它必须包含 NIfTI 字节
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 顺序无关

decode_example

< >

( value: dict token_per_repo_id = None )

参数

  • value (strdict) — NIfTI 文件绝对路径的字符串,或包含以下键的字典:

    • path: NIfTI 文件路径的绝对或相对字符串。
    • bytes: NIfTI 文件的字节。
  • token_per_repo_id (dict, 可选) — 要访问和解码 Hub 私有仓库中的 NIfTI 文件,您可以传递一个字典 repo_id (str) -> token (boolstr)。

将示例 NIfTI 文件解码为 nibabel 图像对象。

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

参数

  • storage (pa.StructArray) — 要嵌入的 PyArrow 数组。

返回

pa.StructArray

NIfTI Arrow 存储类型的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将 NIfTI 文件嵌入到 Arrow 数组中。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, ForwardRef('nib.Nifti1Image')] )

参数

  • value (str, bytes, nibabel.Nifti1Imagedict) — 作为 Nifti 特征输入的传入数据。

将示例编码为 Arrow 的格式。

flatten

< >

( )

如果处于可解码状态,则返回特征本身,否则将特征展平成字典。

文件系统

datasets.filesystems.is_remote_filesystem

< >

( fs: AbstractFileSystem )

参数

  • fs (fsspec.spec.AbstractFileSystem) — 一个 Pythonic 文件系统的抽象超类,例如 fsspec.filesystem('file')s3fs.S3FileSystem

检查 fs 是否是远程文件系统。

指纹

class datasets.fingerprint.Hasher

< >

( )

接受 Python 对象作为输入的 Hasher。

在 GitHub 上更新

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