数据集文档

主要类别

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[dict] = 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) — 数据集的描述。
  • citation (str) — 数据集的 BibTeX 引用。
  • homepage (str) — 数据集官方主页的 URL。
  • license (str) — 数据集的许可证。可以是许可证的名称,也可以是包含许可证条款的段落。
  • features (Features, 可选) — 用于指定数据集列类型的功能。
  • post_processed (PostProcessedInfo, 可选) — 关于数据集可能进行后处理的资源信息。例如,它可以包含索引的信息。
  • supervised_keys (SupervisedKeysData, 可选) — 如果数据集适用于监督学习,则指定输入特征和标签(TFDS 的遗留功能)。
  • builder_name (str, 可选) — 用于创建数据集的 GeneratorBasedBuilder 子类的名称。通常与相应的脚本名称匹配。它也是数据集构建器类名称的 snake_case 版本。
  • config_name (str, 可选) — 从 BuilderConfig 派生的配置名称。
  • version (strVersion, 可选) — 数据集的版本。
  • splits (dict, 可选) — 拆分名称和元数据之间的映射。
  • download_checksums (dict, optional) — 用于下载数据集校验和的 URL 与相应元数据之间的映射。
  • download_size (int, optional) — 生成数据集需要下载的文件大小,以字节为单位。
  • post_processing_size (int, optional) — 如果有,后处理后数据集的大小,以字节为单位。
  • dataset_size (int, optional) — 所有拆分 Arrow 表的总大小,以字节为单位。
  • size_in_bytes (int, optional) — 与数据集关联的所有文件(下载的文件 + 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, optional) — 要传递给文件系统后端的键/值对(如果有)。

    在 2.9.0 中添加

dataset_info_dir 中的 JSON 文件创建 DatasetInfo

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

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

示例

>>> 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, 默认为 False) — 如果为 True,JSON 将以缩进级别为 4 进行美观打印。
  • storage_options (dict, optional) — 要传递给文件系统后端的键/值对(如果有)。

    在 2.9.0 中添加

DatasetInfo 和许可证(如果存在)作为 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, <built-in function array>] new_fingerprint: 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.Sequence, 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, NoneType] = None )

参数

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

向 Dataset 添加列。

在 1.7 中添加

示例

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

add_item

< >

( item: dict new_fingerprint: str )

参数

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

向 Dataset 添加项目。

在 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, 默认为 False) — 是否将数据复制到内存中。

实例化一个由文件名处的 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, 可选) — 数据集信息,例如描述、引用等。
  • split (NamedSplit, 可选) — 数据集拆分的名称。
  • indices_buffer (pyarrow.Buffer, 可选) — 索引 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 表格中的列类型是从 DataFrame 中 pandas.Series 的 dtypes 推断出来的。 对于非对象 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') **kwargs )

参数

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

    在 2.7.0 中添加

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

    在 2.21.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,则使用先前指纹的哈希值和转换参数计算新指纹。

返回值

Dataset

具有扁平化列的数据集副本。

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

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad", split="train")
>>> ds.features
{'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None),
 'context': Value(dtype='string', id=None),
 'id': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None),
 'title': Value(dtype='string', id=None)}
>>> ds.flatten()
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() 来更新 Dataset。
  • 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) — 用于多进程处理的进程数。默认情况下不使用多进程处理。

返回值

Dataset

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

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

示例

>>> 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'], id=None),
 'text': Value(dtype='string', id=None)}
>>> 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'], id=None),
 'text': Value(dtype='large_string', id=None)}

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.Sequence, 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] 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'], id=None),
 'text': Value(dtype='string', id=None)}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds.features
{'label': ClassLabel(names=['bad', 'good'], id=None),
 'text': Value(dtype='string', id=None)}

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, optional) — 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.

返回值

Dataset

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

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

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

示例

>>> 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) — Name of the column to rename.
  • new_column_name (str) — New name for the column.
  • new_fingerprint (str, optional) — 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.

返回值

Dataset

数据集的一个副本,其中一列已重命名。

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

示例

>>> 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]) — A mapping of columns to rename to their new names
  • new_fingerprint (str, optional) — 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.

返回值

Dataset

数据集的一个副本,其中列已重命名。

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

示例

>>> 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]]) — Name of the column(s) to keep.
  • new_fingerprint (str, optional) — 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.

返回值

Dataset

数据集对象的一个副本,仅包含选定的列。

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

示例

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

class_encode_column

< >

( column: str include_nulls: bool = False )

参数

  • column (str) — The name of the column to cast (list all the column names with column_names)
  • include_nulls (bool, defaults to False) — Whether to include null values in the class labels. If True, the null values will be encoded as the "None" class label.

    Added in 1.14.2

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

示例

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

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

< >

( )

遍历示例。

如果使用 Dataset.set_format() 设置了格式,则将以选定的格式返回行。

iter

< >

( batch_size: int drop_last_batch: bool = False )

参数

  • batch_size (int) — size of each batch to yield.
  • drop_last_batch (bool, default False) — Whether a last batch smaller than the batch_size should be dropped

遍历大小为 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) — Either output type selected in [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars']. None means `getitem“ returns python objects (default).
  • columns (List[str], optional) — Columns to format in the output. None means __getitem__ returns all columns (default).
  • output_all_columns (bool, defaults to False) — Keep un-formatted columns as well in the output (as python objects).
  • **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, 可选) — 在 [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__ 时格式化批次。

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

在调用 set_format 后可以调用 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}

会被更新。在这种情况下,如果您在数据集上应用 map 以添加新列,则此列将被格式化为

set_transform

< >

参数

  • ( transform: typing.Optional[typing.Callable] columns: typing.Optional[list] = None output_all_columns: bool = False )
  • transform (Callable, 可选) — 用户定义的格式化转换,替换由 set_format() 定义的格式。格式化函数是一个可调用对象,它接受一个批次(作为 dict)作为输入并返回一个批次。此函数在 __getitem__ 中返回对象之前立即应用。
  • columns (List[str], 可选) — 要在输出中格式化的列。如果指定,则转换的输入批次仅包含这些列。

output_all_columns (bool, 默认为 False) — 在输出中保留未格式化的列(作为 Python 对象)。如果设置为 True,则其他未格式化的列将与转换的输出一起保留。

示例

>>> 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])}

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

reset_format

( )

< >

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

示例

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

self.set_format() 相同

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

示例

>>> 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])}

set_format() 相反,with_format 返回一个新的 Dataset 对象。

with_transform

< >

参数

  • < >
  • transform (Callable, optional) — 用户定义的格式化转换,替换由 set_format() 定义的格式。格式化函数是一个可调用对象,它接受一个批次(作为 dict)作为输入并返回一个批次。此函数在 __getitem__ 中返回对象之前立即应用。
  • columns (List[str], optional) — 要在输出中格式化的列。如果指定,则转换的输入批次仅包含这些列。

output_all_columns (bool, 默认为 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-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])}

set_transform() 相反,with_transform 返回一个新的 Dataset 对象。

__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 )
  • with_indices (bool, 默认为 False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx[, rank]): ...
  • with_rank (bool, 默认为 False) — 向 function 提供进程排名。请注意,在这种情况下,function 的签名应为 def function(example[, idx], rank): ...
  • input_columns (Optional[Union[str, List[str]]], 默认为 None) — 要作为位置参数传递到 function 中的列。如果为 None,则会将映射到所有格式化列的 dict 作为单个参数传递。
  • batched (bool, 默认为 False) — 向 function 提供示例批次。
  • batch_size (int, 可选, 默认为 1000) — 如果 batched=True,则提供给 function 的每个批次的示例数量。如果 batch_size <= 0batch_size == None,则将完整数据集作为单个批次提供给 function
  • drop_last_batch (bool, 默认为 False) — 是否应丢弃小于 batch_size 的最后一个批次,而不是由函数处理。
  • remove_columns (Optional[Union[str, List[str]]], 默认为 None) — 在执行映射时删除选定的列。列将在使用 function 的输出更新示例之前删除,即,如果 function 添加的列的名称在 remove_columns 中,则这些列将保留。
  • keep_in_memory (bool, 默认为 False) — 将数据集保存在内存中,而不是将其写入缓存文件。
  • load_from_cache_file (Optional[bool], 如果启用了缓存,则默认为 True) — 如果可以识别存储 function 当前计算的缓存文件,则使用它而不是重新计算。
  • cache_file_name (str, 可选, 默认为 None) — 提供缓存文件的路径名称。它用于存储计算结果,而不是自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器的每次写入操作的行数。此值是在处理期间的内存使用量和处理速度之间的良好折衷。较高的值使处理执行较少的查找,较低的值在运行 map 时消耗较少的临时内存。
  • features (Optional[datasets.Features], 默认为 None) — 使用特定的 Features 来存储缓存文件,而不是自动生成的文件。
  • disable_nullable (bool, 默认为 False) — 禁止表中的空值。
  • fn_kwargs (Dict, 可选, 默认为 None) — 要传递给 function 的关键字参数。
  • num_proc (int, 可选, 默认为 None) — 生成缓存时的最大进程数。已缓存的分片按顺序加载。
  • suffix_template (str) — 如果指定了 cache_file_name,则此后缀将添加到每个基本名称的末尾。默认为 "_{rank:05d}_of_{num_proc:05d}"。例如,如果 cache_file_name 是 “processed.arrow”,那么对于 rank=1num_proc=4,默认后缀的结果文件将是 "processed_00001_of_00004.arrow"
  • new_fingerprint (str, 可选, 默认为 None) — 数据集在转换后的新指纹。如果为 None,则使用先前指纹的哈希和转换参数计算新指纹。
  • desc (str, 可选, 默认为 None) — 有意义的描述,在映射示例时与进度条一起显示。

将函数应用于表中的所有示例(单独或分批),并更新表。如果您的函数返回的列已存在,则会覆盖它。

您可以使用 batched 参数指定函数是否应分批处理

  • 如果 batchedFalse,则函数接受 1 个示例输入,并应返回 1 个示例。示例是一个字典,例如 {"text": "Hello there !"}
  • 如果 batchedTruebatch_size 为 1,则函数接受 1 个示例的批次作为输入,并且可以返回包含 1 个或多个示例的批次。批次是一个字典,例如,1 个示例的批次是 {"text": ["Hello there !"]}
  • 如果 batchedTruebatch_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="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)

filter

< >

( 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) — 具有以下签名之一的可调用对象:

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

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

  • with_indices (bool, 默认为 False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx[, rank]): ...
  • with_rank (bool, 默认为 False) — 向 function 提供进程排名。请注意,在这种情况下,function 的签名应为 def function(example[, idx], rank): ...
  • input_columns (strList[str], 可选) — 要作为位置参数传递到 function 中的列。如果为 None,则会将映射到所有格式化列的 dict 作为单个参数传递。
  • batched (bool, 默认为 False) — 向 function 提供示例批次。
  • batch_size (int, 可选, 默认为 1000) — 如果 batched = True,则提供给 function 的每个批次的示例数量。如果 batched = False,则每个批次传递一个示例给 function。如果 batch_size <= 0batch_size == None,则将完整数据集作为单个批次提供给 function
  • keep_in_memory (bool, 默认为 False) — 将数据集保存在内存中,而不是将其写入缓存文件。
  • load_from_cache_file (Optional[bool], 如果启用了缓存,则默认为 True) — 如果可以识别存储 function 当前计算的缓存文件,则使用它而不是重新计算。
  • cache_file_name (str, 可选) — 提供缓存文件的路径名称。它用于存储计算结果,而不是自动生成的缓存文件名。
  • writer_batch_size (int, defaults to 1000) — 缓存文件写入器的每次写入操作的行数。此值是在处理过程中的内存使用量和处理速度之间取得良好平衡。较高的值使处理执行更少的查找,较低的值在运行 map 时消耗更少的临时内存。
  • fn_kwargs (dict, 可选) — 要传递给 function 的关键字参数。
  • num_proc (int, 可选) — 用于多进程处理的进程数。默认情况下不使用多进程处理。
  • suffix_template (str) — 如果指定了 cache_file_name,则此后缀将添加到每个基本名称的末尾。例如,如果 cache_file_name"processed.arrow",那么对于 rank = 1num_proc = 4,默认后缀(默认为 _{rank:05d}_of_{num_proc:05d})的结果文件将是 "processed_00001_of_00004.arrow"
  • new_fingerprint (str, 可选) — 转换后数据集的新指纹。如果为 None,则使用先前指纹的哈希值和转换参数计算新指纹。
  • desc (str, 可选, defaults to None) — 在过滤示例时,与进度条一起显示的有意义的描述。

将过滤器函数批量应用于表中的所有元素,并更新表,以便数据集仅包含符合过滤器函数的示例。

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

示例

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

select

< >

( 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, ndarray or Series) — 用于索引的整数索引的范围、列表或一维数组。如果索引对应于连续范围,则 Arrow 表将被简单切片。但是,传递不连续的索引列表会创建索引映射,这效率较低,但仍然比重新创建由请求的行组成的 Arrow 表更快。
  • keep_in_memory (bool, defaults to False) — 将索引映射保留在内存中,而不是将其写入缓存文件。
  • indices_cache_file_name (str, 可选, defaults to None) — 提供缓存文件的路径名称。它用于存储索引映射,而不是自动生成的缓存文件名。
  • writer_batch_size (int, defaults to 1000) — 缓存文件写入器的每次写入操作的行数。此值是在处理过程中的内存使用量和处理速度之间取得良好平衡。较高的值使处理执行更少的查找,较低的值在运行 map 时消耗更少的临时内存。
  • new_fingerprint (str, 可选, defaults to None) — 转换后数据集的新指纹。如果为 None,则使用先前指纹的哈希值和转换参数计算新指纹。

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

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.select(range(4))
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]], defaults to False) — 如果为 True,则按降序而不是升序排序。如果提供单个布尔值,则该值将应用于所有列名的排序。否则,必须提供与 column_names 长度和顺序相同的布尔值列表。
  • null_placement (str, defaults to at_end) — 如果为 at_startfirst,则将 None 值放在开头;如果为 at_endlast,则放在末尾。

    在 1.14.2 版本中添加

  • keep_in_memory (bool, defaults to False) — 将排序后的索引保留在内存中,而不是将其写入缓存文件。
  • load_from_cache_file (Optional[bool], defaults to True if caching is enabled) — 如果可以识别出存储排序索引的缓存文件,则使用它而不是重新计算。
  • indices_cache_file_name (str, 可选, defaults to None) — 提供缓存文件的路径名称。它用于存储排序后的索引,而不是自动生成的缓存文件名。
  • writer_batch_size (int, defaults to 1000) — 缓存文件写入器的每次写入操作的行数。较高的值会产生较小的缓存文件,较低的值会消耗较少的临时内存。
  • new_fingerprint (str, 可选, defaults to 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, 可选) — 用于初始化默认 BitGenerator 的种子,如果 generator=None。如果为 None,则将从操作系统中提取新的、不可预测的熵。如果传递 intarray_like[ints],则会将其传递给 SeedSequence 以导出初始 BitGenerator 状态。
  • generator (numpy.random.Generator, 可选) — Numpy 随机 Generator,用于计算数据集行的排列。如果 generator=None(默认),则使用 np.random.default_rng(NumPy 的默认 BitGenerator (PCG64))。
  • keep_in_memory (bool, default False) — 将洗牌后的索引保存在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], defaults to True if caching is enabled) — 如果可以找到存储洗牌后索引的缓存文件,则使用它而不是重新计算。
  • indices_cache_file_name (str, optional) — 为缓存文件提供路径名称。它用于存储洗牌后的索引,而不是自动生成的缓存文件名。
  • writer_batch_size (int, defaults to 1000) — 缓存文件写入器的每次写入操作的行数。此值是在处理期间的内存使用量和处理速度之间取得良好平衡。较高的值使处理执行更少的查找,较低的值在运行 map 时消耗更少的临时内存。
  • new_fingerprint (str, optional, defaults to 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]

跳过

< >

( 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 .'}]

获取

< >

( 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 (numpy.random.Generator, optional) — 测试集拆分的大小。如果为 float,则应介于 0.01.0 之间,并表示要包含在测试集拆分中的数据集的比例。如果为 int,则表示测试样本的绝对数量。如果为 None,则该值设置为训练集大小的补集。如果 train_size 也为 None,则将其设置为 0.25
  • train_size (numpy.random.Generator, optional) — 训练集拆分的大小。如果为 float,则应介于 0.01.0 之间,并表示要包含在训练集拆分中的数据集的比例。如果为 int,则表示训练样本的绝对数量。如果为 None,则该值自动设置为测试集大小的补集。
  • shuffle (bool, optional, defaults to True) — 是否在拆分之前对数据进行洗牌。
  • stratify_by_column (str, optional, defaults to 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, defaults to False) — 将拆分索引保存在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], defaults to True if caching is enabled) — 如果可以找到存储拆分索引的缓存文件,则使用它而不是重新计算。
  • train_cache_file_name (str, optional) — 为缓存文件提供路径名称。它用于存储训练集拆分索引,而不是自动生成的缓存文件名。
  • test_cache_file_name (str, optional) — 为缓存文件提供路径名称。它用于存储测试集拆分索引,而不是自动生成的缓存文件名。
  • writer_batch_size (int, defaults to 1000) — 缓存文件写入器的每次写入操作的行数。此值是在处理期间的内存使用量和处理速度之间取得良好平衡。较高的值使处理执行更少的查找,较低的值在运行 map 时消耗更少的临时内存。
  • train_new_fingerprint (str, optional, defaults to None) — 转换后训练集的新指纹。如果为 None,则使用先前指纹的哈希和转换参数计算新指纹
  • test_new_fingerprint (str, optional, defaults to 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("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
    })
})

分片

< >

( 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 时消耗的临时内存越少。

从拆分为 num_shards 块的数据集中返回第 index 个分片。

此分片操作是确定性的。 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.shard(num_shards=2, index=0)
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 仅包含单个键,否则数据集将为输入和标签生成 dicts,在这种情况下,将改为生成原始 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 )

参数

  • 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, 可选) — 将包含上传数据文件的目录名称。如果与“default”不同,则默认为 config_name,否则为“data”。

    添加于 2.17.0

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

    添加于 2.16.0

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

    添加于 2.15.0

  • create_pr (bool, 可选, 默认为 False) — 是否使用上传的文件创建 PR 或直接提交。

    添加于 2.15.0

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

    添加于 2.8.0

  • embed_external_files (bool, 默认为 True) — 是否将文件字节嵌入到分片中。特别是,这将在推送之前对以下类型的字段执行以下操作:

    • AudioImage: 删除本地路径信息并将文件内容嵌入到 Parquet 文件中。

将数据集作为 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 (intstr, 可选, 默认为 "500MB") — 要上传到 hub 的数据集分片的最大大小。如果表示为字符串,则需要是数字后跟单位(如 "50MB")。
  • num_shards (int, 可选) — 要写入的分片数。默认情况下,分片数取决于 max_shard_sizenum_proc

    添加于 2.8.0

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

    添加于 2.8.0

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

    添加于 2.8.0

将数据集保存到数据集目录,或使用任何 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 ) DatasetDatasetDict

参数

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

    添加于 2.8.0

返回值

DatasetDatasetDict

  • 如果 dataset_path 是数据集目录的路径,则为请求的数据集。
  • 如果 dataset_path 是数据集字典目录的路径,则为包含每个拆分的 datasets.DatasetDict

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

示例

>>> 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, 默认为 False) — 将数据集保存在内存中,而不是写入缓存文件。
  • cache_file_name (str, 可选, 默认为 None) — 提供缓存文件的路径名称。它用于存储计算结果,而不是自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器的每次写入操作的行数。此值是在处理过程中的内存使用和处理速度之间取得良好平衡。值越高,处理过程的查找次数越少;值越低,运行 map 时消耗的临时内存越少。
  • features (Optional[datasets.Features], 默认为 None) — 使用特定的 Features 来存储缓存文件,而不是自动生成的文件。
  • disable_nullable (bool, 默认为 False) — 允许表中使用空值。
  • num_proc (int, 可选, 默认为 None) — 生成缓存时使用的最大进程数。已缓存的分片将按顺序加载
  • new_fingerprint (str, 可选, 默认为 None) — 转换后数据集的新指纹。如果为 None,则新指纹通过哈希之前的指纹和转换参数计算得出

创建并缓存一个新的 Dataset,通过扁平化索引映射。

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 (PathLikeFileOrBuffer) — 文件路径 (例如 file.csv)、远程 URI (例如 hf://datasets/username/my_dataset_name/data.csv) 或 BinaryIO,数据集将以指定格式保存到此处。
  • batch_size (int, 可选) — 一次加载到内存并写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • num_proc (int, 可选) — 用于多进程处理的进程数。默认情况下不使用多进程处理。在这种情况下,batch_size 默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE,但如果您有足够的计算能力,可以随意将其设置为默认值的 5 倍或 10 倍。
  • storage_options (dict, 可选) — 传递给文件系统后端的键/值对(如果有)。

    在 2.19.0 版本中添加

  • **to_csv_kwargs (附加关键字参数) — 传递给 pandas 的 pandas.DataFrame.to_csv 的参数。

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

参数

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

pandas.DataFrame 形式返回数据集。也可以为大型数据集返回生成器。

示例

>>> ds.to_pandas()

to_dict

< >

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

参数

  • batch_size (int, 可选) — 如果 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 num_proc: 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, 可选) — 一次加载到内存并写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • num_proc (int, 可选) — 用于多进程处理的进程数。默认情况下,它不使用多进程处理。在这种情况下,batch_size 默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE,但如果您有足够的计算能力,可以随意将其设置为默认值的 5 倍或 10 倍。
  • storage_options (dict, 可选) — 传递给文件系统后端的键/值对(如果有)。

    在 2.19.0 版本中添加

  • **to_json_kwargs (附加关键字参数) — 传递给 pandas 的 pandas.DataFrame.to_json 的参数。默认参数为 lines=True 和 `orient=“records”。

    在 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 (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) — 要传递给文件系统后端的键值对(如果有)。

    在 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 的参数。

    在 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,默认为 1) — 实例化可迭代数据集时要定义的 shard 数量。这对于大型数据集尤其有用,以便能够正确地进行 shuffle,并例如在 PyTorch DataLoader 中或在分布式设置中实现快速并行加载。Shard 是使用 datasets.Dataset.shard() 定义的:它只是对数据进行切片,而不在磁盘上写入任何内容。

从 map-style 的 datasets.Dataset 获取一个 datasets.IterableDataset。这相当于使用 datasets.load_dataset() 在流模式下加载数据集,但速度更快,因为数据是从本地文件流式传输的。

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

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

为了获得最佳速度性能,请确保您的数据集没有索引映射。如果是这种情况,数据不会被连续读取,这有时可能会很慢。您可以使用 `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

使用分片以实现高效的 shuffle

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

>>> 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 DataLoader 和 shuffle 的 PyTorch DDP)

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

使用 shuffle 和多个 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

    在 2.4.0 版本中添加

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

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

  • 对于 string factory

示例

>>> ds = datasets.load_dataset('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('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/标识符。这个 index_name 用于调用 get_nearest_examples()search()
  • device (可选 Union[int, List[int]], optional) — 如果是正整数,则这是要使用的 GPU 的索引。如果是负整数,则使用所有 GPU。如果传入正整数列表,则仅在这些 GPU 上运行。默认情况下使用 CPU。
  • string_factory (str, optional) — 传递给 Faiss 的索引工厂以创建索引。默认索引类是 IndexFlat
  • metric_type (int, optional) — 度量类型。例如:faiss.faiss.METRIC_INNER_PRODUCTfaiss.METRIC_L2
  • custom_index (faiss.Index, optional) — 您已经实例化并配置好的自定义 Faiss 索引,以满足您的需求。
  • batch_size (int, optional) — 向 FaissIndex 添加向量时使用的批次大小。默认值为 1000。

    在 2.4.0 版本中添加

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

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

  • 对于 string factory

save_faiss_index

< >

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

参数

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

    在 2.11.0 版本中添加

在磁盘上保存 FaissIndex。

load_faiss_index

< >

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

参数

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

    在 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, optional) — 索引的 index_name/标识符。这个索引名称用于调用 get_nearest_examples()search()。默认情况下,它对应于 column
  • host (str, optional, 默认为 localhost) — ElasticSearch 运行所在的主机。
  • port (str, optional, 默认为 9200) — ElasticSearch 运行所在的端口。
  • es_client (elasticsearch.Elasticsearch, optional) — 如果 host 和 port 为 None,则用于创建索引的 elasticsearch 客户端。
  • es_index_name (str, optional) — 用于创建索引的 elasticsearch 索引名称。
  • es_index_config (dict, optional) — elasticsearch 索引的配置。默认配置为:

使用 ElasticSearch 添加文本索引以实现快速检索。这是就地完成的。

示例

>>> es_client = elasticsearch.Elasticsearch()
>>> ds = datasets.load_dataset('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, 可选) — 如果 host 和 port 为 None,则用于创建索引的 elasticsearch 客户端。
  • es_index_config (dict, 可选) — elasticsearch 索引的配置。 默认配置为:

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

list_indexes

< >

( )

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

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

< >

( )

citation

< >

( )

config_name

< >

( )

dataset_size

< >

( )

description

< >

( )

download_checksums

< >

( )

download_size

< >

( )

features

< >

( )

homepage

< >

( )

license

< >

( )

size_in_bytes

< >

( )

supervised_keys

< >

( )

version

< >

( )

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) — 本地下载和生成数据集时使用的进程数。如果数据集由多个文件组成,这将很有帮助。默认情况下禁用多进程。

    在 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-like 或 path-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, 可选, 默认为 None) — 本地下载和生成数据集时的进程数。 如果数据集由多个文件组成,这将很有帮助。 默认情况下禁用多进程处理。

    添加于 2.8.0

  • **kwargs (额外的关键字参数) — 要传递给 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-like 或 path-like 列表) — Parquet 文件的路径。
  • split (NamedSplit, 可选) — 要分配给数据集的拆分名称。
  • 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”。
  • num_proc (int, 可选, 默认为 None) — 本地下载和生成数据集时的进程数。 如果数据集由多个文件组成,这将很有帮助。 默认情况下禁用多进程处理。

    添加于 2.8.0

  • **kwargs (额外的关键字参数) — 要传递给 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-like 或 path-like 列表) — 文本文件的路径。
  • split (NamedSplit, 可选) — 要分配给数据集的拆分名称。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 用于缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • num_proc (int, 可选, 默认为 None) — 本地下载和生成数据集时的进程数。 如果数据集由多个文件组成,这将很有帮助。 默认情况下禁用多进程处理。

    添加于 2.8.0

  • **kwargs (额外的关键字参数) — 要传递给 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 (strsqlite3.Connectionsqlalchemy.engine.Connectionsqlalchemy.engine.Connection) — 用于实例化数据库连接的 URI 字符串 或 SQLite3/SQLAlchemy 连接对象。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 用于缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • **kwargs (附加关键字参数) — 要传递给 SqlConfig 的关键字参数。

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

示例

>>> # 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) — 要对齐的标签列的名称。

将数据集的标签 ID 和标签名称映射与输入的 label2id 映射对齐。当您想要确保模型的预测标签与数据集对齐时,这很有用。对齐是使用小写的标签名称完成的。

示例

>>> # 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]) — 要连接的 Dataset 列表。
  • info (DatasetInfo, 可选) — 数据集信息,例如描述、引用等。
  • split (NamedSplit, 可选) — 数据集拆分的名称。
  • axis ({0, 1}, 默认为 0) — 要在其上连接的轴,其中 0 表示按行(垂直)连接,1 表示按列(水平)连接。

    在 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'] = 'first_exhausted' ) DatasetIterableDataset

参数

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

    在 2.4.0 版本中添加

  • split (NamedSplit, 可选) — 数据集拆分的名称。

    在 2.4.0 版本中添加

  • stopping_strategy (str, 默认为 first_exhausted) — 现在提出了两种策略,first_exhaustedall_exhausted。默认情况下,first_exhausted 是一种欠采样策略,即,一旦一个数据集耗尽样本,数据集构建就会停止。如果策略是 all_exhausted,我们使用过采样策略,即,一旦每个数据集的每个样本至少被添加一次,数据集构建就会停止。请注意,如果策略是 all_exhausted,则交错数据集的大小可能会变得非常巨大:
    • 在没有概率的情况下,生成的数据集将具有 max_length_datasets*nb_dataset 个样本。
    • 在给定概率的情况下,如果某些数据集的访问概率非常低,则生成的数据集将具有更多样本。

返回值

DatasetIterableDataset

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

将多个数据集(源)交错成单个数据集。新数据集通过在源之间交替获取示例来构建。

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

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

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

Iterable 数据集注意事项

在分布式设置或 PyTorch DataLoader 工作进程中,停止策略是按进程应用的。因此,在分片的 iterable 数据集上使用 “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) — 要按节点拆分的数据集。
  • rank (int) — 当前节点的排名。
  • world_size (int) — 节点总数。

返回值

DatasetIterableDataset

将在 rank rank 节点上使用的数据集。

在一个大小为 world_size 的节点池中,为 rank rank 的节点拆分数据集。

对于 map-style 数据集

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

对于 iterable 数据集

如果数据集的分片数量是 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 参数。

DatasetDict

字典,其中 split 名称作为键(例如 ‘train’、‘test’),Dataset 对象作为值。它还具有数据集转换方法,如 map 或 filter,可以一次处理所有 split。

class datasets.DatasetDict

< >

( )

一个字典 (dict of str: datasets.Dataset),带有数据集转换方法 (map, filter, 等等)

data

< >

( )

支持每个 split 的 Apache Arrow 表。

示例

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

cache_files

< >

( )

包含支持每个 split 的 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

< >

( )

数据集中每个 split 的列数。

示例

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

< >

( )

数据集中每个 split 的行数。

示例

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

< >

( )

数据集中每个 split 的列名。

示例

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

< >

( )

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

示例

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

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

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

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

示例

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

可用于索引列(通过字符串名称)或行(通过整数索引或索引的可迭代对象或布尔值)。

< >

( )

清理数据集缓存目录中的所有缓存文件,但当前正在使用的缓存文件(如果有)除外。运行此命令时请注意,没有其他进程正在使用其他缓存文件。

示例

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

运行此命令时请注意,没有其他进程正在使用其他缓存文件。

< >

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

参数

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

    • function(example: Dict[str, Any]) -> Dict[str, Any] 如果 batched=Falsewith_indices=False
    • function(example: Dict[str, Any], indices: 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 将运行您的函数并返回未更改的数据集。如果未提供函数,则默认为 identity 函数:lambda x: x

  • with_indices (bool, 默认为 False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx): ...
  • with_rank (bool, 默认为 False) — 向 function 提供进程 rank。请注意,在这种情况下,function 的签名应为 def function(example[, idx], rank): ...
  • with_split (bool, 默认为 False) — 向 function 提供进程 split。请注意,在这种情况下,function 的签名应为 def function(example[, idx], split): ...
  • input_columns ([Union[str, list[str]]], 可选, 默认为 None) — 要作为位置参数传递到 function 中的列。如果为 None,则将映射到所有格式化列的 dict 作为单个参数传递。
  • batched (bool, 默认为 False) — 向 function 提供一批示例。
  • batch_size (int, 可选, 默认为 1000) — 如果 batched=True,则提供给 function 的每个批次的示例数,batch_size <= 0batch_size == None 然后将完整数据集作为单个批次提供给 function
  • drop_last_batch (bool, 默认为 False) — 是否应删除而不是由函数处理小于 batch_size 的最后一个批次。
  • remove_columns ([Union[str, list[str]]], 可选, 默认为 None) — 在执行映射时删除选择的列。列将在使用 function 的输出更新示例之前删除,即,如果 function 正在添加名称在 remove_columns 中的列,则将保留这些列。
  • keep_in_memory (bool, 默认为 False) — 将数据集保存在内存中,而不是将其写入缓存文件。
  • load_from_cache_file (Optional[bool], defaults to True if caching is enabled) — 如果可以找到缓存文件来存储来自 function 的当前计算结果,则使用缓存文件而不是重新计算。
  • 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) — 禁止表格中的空值。
  • fn_kwargs (Dict, optional, defaults to None) — 要传递给 function 的关键字参数
  • num_proc (int, optional, defaults to None) — 用于多进程处理的进程数。默认情况下不使用多进程处理。
  • desc (str, optional, defaults to None) — 在映射示例时,与进度条一起显示的有意义的描述。

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

您可以使用 batched 参数指定函数是否应分批处理

  • 如果 batchedFalse,则函数接受 1 个示例输入,并应返回 1 个示例。示例是一个字典,例如 {"text": "Hello there !"}
  • 如果 batchedTruebatch_size 为 1,则函数接受 1 个示例的批次作为输入,并且可以返回包含 1 个或多个示例的批次。批次是一个字典,例如,1 个示例的批次是 {"text": ["Hello there !"]}
  • 如果 batchedTruebatch_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")
>>> 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)

filter

< >

( 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) — 具有以下签名之一的可调用对象:

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

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

  • with_indices (bool, defaults to False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx[, rank]): ...
  • with_rank (bool, defaults to False) — 向 function 提供进程 rank。请注意,在这种情况下,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) — 如果可以找到缓存文件来存储来自 function 的当前计算结果,则使用缓存文件而不是重新计算。
  • 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) — 用于多进程处理的进程数。默认情况下不使用多进程处理。
  • 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]], defaults to False) — 如果为 True,则按降序而不是升序排序。如果提供单个布尔值,则该值将应用于所有列名的排序。否则,必须提供与 column_names 长度和顺序相同的布尔值列表。
  • null_placement (str, defaults to 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。如果 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'}

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

< >

( )

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

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

示例

>>> 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__ 返回格式(类型和列)。此转换应用于数据集字典中的所有数据集。

self.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__ 返回格式(类型和列)。数据格式化是即时应用的。格式 type(例如 “numpy”)用于在使用 __getitem__ 时格式化批次。格式是为数据集字典中的每个数据集设置的。

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

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])}

set_format() 相反,with_format 返回一个新的 Dataset 对象。

< >

< >

参数

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

使用此转换设置 __getitem__ 返回格式。当调用 __getitem__ 时,转换将即时应用于批次。转换是为数据集字典中的每个数据集设置的

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

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 表(嵌套特征被展平)。每个具有 struct 类型的列都被展平为每个 struct 字段一列。其他列保持不变。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad")
>>> ds["train"].features
{'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None),
 'context': Value(dtype='string', id=None),
 'id': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None),
 'title': Value(dtype='string', id=None)}
>>> 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'], id=None),
 'text': Value(dtype='string', id=None)}
>>> 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'], id=None),
 'text': Value(dtype='large_string', id=None)}

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'], id=None),
 'text': Value(dtype='string', id=None)}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good'], id=None),
 'text': Value(dtype='string', id=None)}

remove_columns

< >

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

参数

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

返回值

DatasetDict

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

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

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

您还可以使用 map()remove_columns 删除列,但本方法不复制剩余列的数据,因此速度更快。

示例

>>> 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) — 列的新名称。

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

您还可以使用 map()remove_columns 重命名列,但本方法

  • 会处理将原始特征移动到新列名下。
  • 不会将数据复制到新数据集,因此速度更快。

示例

>>> 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, 默认为 False) — 是否在类标签中包含空值。如果为 True,则空值将编码为 "None" 类标签。

    在 1.14.2 中添加

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

示例

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

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 )

参数

  • 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”。

    在 2.17.0 中添加

  • commit_message (str, 可选) — 推送时提交的消息。默认为 "Upload dataset"
  • commit_description (str, 可选) — 将要创建的提交的描述。此外,如果创建 PR(create_pr 为 True),则为 PR 的描述。

    在 2.16.0 中添加

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

    在 2.15.0 中添加

  • create_pr (bool, 可选, 默认为 False) — 是否使用上传的文件创建 PR 或直接提交。

    在 2.15.0 中添加

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

    在 2.8.0 中添加

  • embed_external_files (bool, 默认为 True) — 是否将文件字节嵌入到分片中。特别是,这将在推送之前对以下类型的字段执行以下操作:

    • AudioImage 删除本地路径信息并将文件内容嵌入到 Parquet 文件中。

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 (path-like) — 数据集字典目录的路径(例如 dataset/train)或远程 URI(例如 s3://my-bucket/dataset/train),数据集字典将保存到该目录。
  • max_shard_size (intstr, 可选, 默认为 "500MB") — 要上传到 hub 的数据集分片的最大大小。如果表示为字符串,则需要是数字后跟单位(如 "50MB")。
  • num_shards (Dict[str, int], 可选) — 要写入的分片数量。默认情况下,分片数量取决于 max_shard_sizenum_proc。您需要为数据集字典中的每个数据集提供分片数量。使用字典为每个拆分定义不同的 num_shards。

    在 2.8.0 中添加

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

    在 2.8.0 中添加

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

    在 2.8.0 中添加

使用 fsspec.spec.AbstractFileSystem 将数据集字典保存到文件系统。

对于 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 (path-like) — 数据集字典目录的路径(例如 "dataset/train")或远程 URI(例如 "s3//my-bucket/dataset/train"),数据集字典将从该目录加载。
  • keep_in_memory (bool, 默认为 None) — 是否将数据集复制到内存中。如果为 None,则数据集不会复制到内存中,除非通过将 datasets.config.IN_MEMORY_MAX_SIZE 设置为非零值来显式启用。有关更多详细信息,请参阅 improve performance 部分。
  • storage_options (dict, 可选) — 要传递给文件系统后端的键/值对(如果有)。

    在 2.8.0 中添加

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

示例

>>> 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 of path-like) — 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, 可选) — 数据集 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 of path-like) — CSV 文件 的路径。
  • features (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 of path-like) — 文本文件 的路径。
  • features (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 生成器支持的可迭代 Dataset。

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 )

由可迭代对象支持的 Dataset。

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, 可选) — 数据集 features。
  • gen_kwargs(dict, 可选) — 要传递给 generator 可调用对象的关键字参数。 您可以通过在 gen_kwargs 中传递分片列表来定义分片可迭代数据集。 这可以用于改进洗牌(shuffling)以及在使用多个 worker 迭代数据集时。
  • split (NamedSplit, 默认为 Split.TRAIN) — 要分配给数据集的 split 名称。

    在 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

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

移除数据集中的一个或多个列以及与其关联的 features。 移除操作在迭代数据集中的示例时即时完成。

示例

>>> 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.Sequence, 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] ) 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(dtype='string', id=None),
 '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'], id=None),
 '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'], id=None),
 'path': Value(dtype='string', id=None),
 'transcription': Value(dtype='string', id=None)}
>>> 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(dtype='string', id=None),
 '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'], id=None),
 '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'], id=None),
 'path': Value(dtype='string', id=None),
 'transcription': Value(dtype='string', id=None)}

cast

< >

( features: Features ) IterableDataset

参数

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

返回值

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'], id=None),
 'text': Value(dtype='string', id=None)}
>>> 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'], id=None),
 'text': Value(dtype='large_string', id=None)}

解码

< >

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

参数

  • enable (bool, defaults to True) — 启用或禁用特征解码。
  • num_threads (int, defaults to 0) — 启用多线程进行特征解码。

返回值

IterableDataset

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

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

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

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

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

如果您想迭代媒体文件的路径或字节,而无需实际解码其内容,则禁用解码非常有用。要禁用解码,您可以使用 .decode(False),这等效于调用 .cast().cast_column(),并将所有 Audio、Image 和 Video 类型设置为 decode=False

示例

禁用解码

>>> 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(dtype='string', id=None)}
>>> 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) — 要产生的每个批次的大小。
  • drop_last_batch (bool, default False) — 是否应删除小于 batch_size 的最后一个批次

遍历大小为 batch_size 的批次。

运行此命令时请注意,没有其他进程正在使用其他缓存文件。

< >

( 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, optional, defaults to 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, defaults to False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx[, rank]): ...
  • input_columns (Optional[Union[str, List[str]]], 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
  • drop_last_batch (bool, defaults to False) — 是否应删除而不是由函数处理小于 batch_size 的最后一个批次。
  • remove_columns ([List[str]], optional, defaults to None) — 在执行映射时删除选择的列。列将在使用 function 的输出更新示例之前删除,即,如果 function 正在添加名称在 remove_columns 中的列,则将保留这些列。
  • features ([Features], optional, defaults to None) — 结果数据集的特征类型。
  • fn_kwargs (Dict, optional, default None) — 要传递给 function 的关键字参数。

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

您可以使用 batched 参数指定函数是否应分批处理

  • 如果 batchedFalse,则函数接受 1 个示例输入,并应返回 1 个示例。示例是一个字典,例如 {"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 .'}

filter

< >

( 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, defaults to False) — 向 function 提供示例索引。 请注意,在这种情况下,function 的签名应为 def function(example, idx): ...
  • input_columns (str or List[str], optional) — 要作为位置参数传递到 function 中的列。 如果为 None,则将映射到所有格式化列的 dict 作为一个参数传递。
  • batched (bool, defaults to False) — 向 function 提供一批示例。
  • batch_size (int, optional, default 1000) — 如果 batched=True,则为提供给 function 的每个批次的示例数。
  • fn_kwargs (Dict, optional, default 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, 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 个元素中选择一个随机元素。 一旦选择了元素,它在缓冲区中的空间将被下一个(即第 1,001 个)元素替换,从而保持 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, defaults to False) — 是否删除最后一个不完整的批次。

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

示例

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

跳过

< >

( 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 .'}]

获取

< >

( 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 .'}]

分片

< >

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

参数

  • num_shards (int) — 要将数据集拆分成的分片数。
  • index (int) — 要选择和返回的分片。
  • contiguous — (bool, defaults to True): 是否为分片选择连续的索引块。

从拆分为 num_shards 块的数据集中返回第 index 个分片。

这会确定性地进行分片。 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("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 次。

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

示例

>>> 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'}]

load_state_dict

< >

( state_dict: dict )

加载数据集的 state_dict。 迭代将从保存状态时的下一个示例重新开始。

恢复会返回到检查点保存的确切位置,以下两种情况除外

  1. 从洗牌缓冲区中恢复时,示例会丢失,并且缓冲区会重新填充新数据
  2. .with_format(arrow) 和批量 .map() 的组合可能会跳过一个批次。

示例

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

返回值

dict

获取数据集当前的 state_dict。它对应于其产生的最新示例的状态。

恢复会返回到检查点保存的确切位置,以下两种情况除外

  1. 从洗牌缓冲区中恢复时,示例会丢失,并且缓冲区会重新填充新数据
  2. .with_format(arrow) 和批量 .map() 的组合可能会跳过一个批次。

示例

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

< >

( )

citation

< >

( )

config_name

< >

( )

dataset_size

< >

( )

description

< >

( )

download_checksums

< >

( )

download_size

< >

( )

features

< >

( )

homepage

< >

( )

license

< >

( )

size_in_bytes

< >

( )

supervised_keys

< >

( )

version

< >

( )

IterableDatasetDict

以拆分名称为键(例如 ‘train’, ‘test’),IterableDataset 对象为值的字典。

class datasets.IterableDatasetDict

< >

( )

运行此命令时请注意,没有其他进程正在使用其他缓存文件。

< >

( 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可选,默认为 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 ([Union[str, list[str]]]可选,默认为 None) — 要作为位置参数传递到 function 中的列。 如果为 None,则将映射到所有格式化列的字典作为单个参数传递。
  • batched (bool,默认为 False) — 向 function 提供批量示例。
  • batch_size (int可选,默认为 1000) — 如果 batched=True,则提供给 function 的每个批次的示例数。
  • drop_last_batch (bool,默认为 False) — 是否应丢弃小于 batch_size 的最后一个批次,而不是由函数处理。
  • remove_columns ([list[str]]可选,默认为 None) — 在执行映射时删除选定的列。 列将在使用 function 的输出更新示例之前删除,即,如果 function 添加的列的名称在 remove_columns 中,则这些列将保留。
  • fn_kwargs (Dict, optional, defaults to None) — 要传递给 function 的关键字参数 (Dict 类型,可选,默认为 None)

将函数应用于可迭代数据集中的所有示例(单独或批量),并更新它们。如果您的函数返回的列已存在,则会覆盖它。该函数在迭代数据集中的示例时即时应用。转换应用于数据集字典的所有数据集。

您可以使用 batched 参数指定函数是否应分批处理

  • 如果 batchedFalse,则函数接受 1 个示例输入,并应返回 1 个示例。示例是一个字典,例如 {"text": "Hello there !"}
  • 如果 batchedTruebatch_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", 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 .'}

filter

< >

( 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) — 具有以下签名之一的可调用对象 (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

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

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

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

示例

>>> 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) — 将用于打乱数据集的随机种子。(int 类型,可选,默认为 None) 它用于从洗牌缓冲区中采样,也用于洗牌数据分片。
  • generator (numpy.random.Generator, optional) — 用于计算数据集行排列的 Numpy 随机数生成器。(numpy.random.Generator 类型,可选) 如果 generator=None (默认),则使用 np.random.default_rng (NumPy 的默认 BitGenerator (PCG64))。
  • buffer_size (int, defaults to 1000) — 缓冲区大小。(int 类型,默认为 1000)

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

此数据集使用 buffer_size 元素填充缓冲区,然后从此缓冲区中随机抽取元素,并将选定的元素替换为新元素。为了实现完美洗牌,需要缓冲区大小大于或等于数据集的完整大小。

例如,如果您的数据集包含 10,000 个元素,但 buffer_size 设置为 1000,则 shuffle 最初只会从缓冲区中的前 1000 个元素中选择一个随机元素。 一旦选择了元素,它在缓冲区中的空间将被下一个(即第 1,001 个)元素替换,从而保持 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 ."}]

self.set_format() 相同

< >

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

参数

  • type (str, optional) — 在 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中选择的输出类型。(str 类型,可选) 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) — 要将数据集转换为的新特征。(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'], id=None),
 'text': Value(dtype='string', id=None)}
>>> 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'], id=None),
 'text': Value(dtype='large_string', id=None)}

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.Sequence, 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] )

参数

  • column (str) — 列名。(str 类型)
  • feature (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'], id=None),
 'text': Value(dtype='string', id=None)}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good'], id=None),
 'text': Value(dtype='string', id=None)}

remove_columns

< >

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

参数

  • column_names (Union[str, list[str]]) — 要删除的列的名称。(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) — 要重命名的列的名称。(str 类型)
  • new_column_name (str) — 列的新名称。

返回值

IterableDatasetDict

数据集的一个副本,其中一列已重命名。

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

示例

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

数据集的一个副本,其中列已重命名。

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

示例

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

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

在数据集中选择一个或多个列以及与其关联的 features。选择是在迭代数据集中的示例时即时完成的。选择操作将应用于数据集字典的所有数据集。

示例

>>> 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 .'}

Features

class datasets.Features

< >

( *args **kwargs )

一个特殊的字典,用于定义数据集的内部结构。

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

FieldType 可以是以下类型之一

  • Value feature 指定单个数据类型值,例如 int64string

  • ClassLabel feature 指定一组预定义的类,这些类可以具有与其关联的标签,并将以整数形式存储在数据集中。

  • Python dict 指定一个复合 feature,其中包含子字段到子 feature 的映射。可以任意方式嵌套字段和子字段。

  • Python list, LargeListSequence 指定一个复合 feature,其中包含相同 feature 类型的子 feature 序列。

    具有内部字典 feature 的 Sequence 将自动转换为列表字典。此行为是为了与 TensorFlow Datasets 库具有兼容层而实现的,但在某些情况下可能是不需要的。如果您不希望出现此行为,可以使用 Python listLargeList 而不是 Sequence

  • Array2D, Array3D, Array4DArray5D feature 用于多维数组。

  • Audio feature 用于存储音频文件的绝对路径,或包含音频文件相对路径(“path”键)及其字节内容(“bytes”键)的字典。此 feature 提取音频数据。

  • Image feature 用于存储图像文件的绝对路径、np.ndarray 对象、PIL.Image.Image 对象,或包含图像文件相对路径(“path”键)及其字节内容(“bytes”键)的字典。此 feature 提取图像数据。

  • TranslationTranslationVariableLanguages feature 专门用于机器翻译。

copy

< >

( )

制作 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'], id=None),
 'text': Value(dtype='string', id=None)}

decode_batch

< >

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

参数

  • batch (dict[str, list[Any]]) — 数据集批次数据。
  • token_per_repo_id (dict, 可选) — 要访问和解码来自 Hub 上私有仓库的音频或图像文件,您可以传递一个字典 repo_id (str) -> token (bool 或 str)

使用自定义 feature 解码来解码批次数据。

decode_column

< >

( column: list column_name: str )

参数

  • column (list[Any]) — 数据集列数据。
  • column_name (str) — 数据集列名。

使用自定义 feature 解码来解码列数据。

decode_example

< >

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

参数

  • example (dict[str, Any]) — 数据集行数据。
  • token_per_repo_id (dict, 可选) — 要访问和解码来自 Hub 上私有仓库的音频或图像文件,您可以传递一个字典 repo_id (str) -> token (bool or str)

使用自定义 feature 解码来解码示例数据。

encode_batch

< >

( batch )

参数

  • batch (dict[str, list[Any]]) — 数据集批次中的数据。

将批次数据编码为 Arrow 格式。

encode_column

< >

( column column_name: str )

参数

  • column (list[Any]) — 数据集列中的数据。
  • column_name (str) — 数据集列名。

将列数据编码为 Arrow 格式。

encode_example

< >

( example )

参数

  • example (dict[str, Any]) — 数据集行中的数据。

将示例数据编码为 Arrow 格式。

flatten

< >

( max_depth = 16 ) Features

返回值

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': Sequence(feature=Value(dtype='int32', id=None), length=-1, id=None),
 'answers.text': Sequence(feature=Value(dtype='string', id=None), length=-1, id=None),
 'context': Value(dtype='string', id=None),
 'id': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None),
 'title': Value(dtype='string', id=None)}

from_arrow_schema

< >

( pa_schema: Schema )

参数

  • pa_schema (pyarrow.Schema) — Arrow Schema.

从 Arrow Schema 构建 Features。 它还会检查模式元数据以获取 Hugging Face Datasets 特征。 不支持非可空字段,并将设置为可空。

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

from_dict

< >

( dic ) Features

参数

  • dic (dict[str, Any]) — Python 字典。

返回值

Features

从字典构建 [Features]。

从反序列化的字典中重新生成嵌套的特征对象。 我们使用 _type 键来推断特征 FieldType 的数据类名称。

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

示例

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

reorder_fields_as

< >

( other: Features )

参数

  • other ([Features]) — 要对齐的其他 [Features]。

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

字段的顺序很重要,因为它对于底层的 arrow 数据至关重要。 重新排序字段可以使底层的 arrow 数据类型匹配。

示例

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

标量

class datasets.Value

< >

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

参数

  • dtype (str) — 数据类型的名称。

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

Value 可能的数据类型如下

  • null
  • bool
  • 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
  • string
  • large_string

示例

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

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, 可选) — 类的数量。 所有标签都必须 < num_classes
  • names (list of str, 可选) — 整数类的字符串名称列表。 提供的名称顺序会被保留。
  • names_file (str, 可选) — 包含整数类的名称的文件路径,每行一个名称。

整数类标签的特征类型。

有 3 种定义 ClassLabel 的方法,分别对应于 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'], id=None)}

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

< >

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

参数

  • feature (FeatureType) — 单个类型特征列表或类型字典。
  • length (int) — 序列的长度。

从单个类型特征或类型字典构建特征列表。 主要用于与 tfds 兼容。

示例

>>> from datasets import Features, Sequence, Value, ClassLabel
>>> features = Features({'post': Sequence(feature={'text': Value(dtype='string'), 'upvotes': Value(dtype='int32'), 'label': ClassLabel(num_classes=2, names=['hot', 'cold'])})})
>>> features
{'post': Sequence(feature={'text': Value(dtype='string', id=None), 'upvotes': Value(dtype='int32', id=None), 'label': ClassLabel(names=['hot', 'cold'], id=None)}, length=-1, id=None)}

Translation

class datasets.Translation

< >

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

参数

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

每个示例具有固定语言的翻译的 Feature。 此处用于与 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 (可变长度的 1D tf.Tensor of tf.string)

参数

  • languages (dict) — 一个字典,用于为每个示例将字符串语言代码映射到一个或多个字符串翻译。存在的语言可能因示例而异。

返回值

  • languagetranslation (可变长度的 1D tf.Tensor of tf.string)

语言代码按升序排列或纯文本翻译,排序以与语言代码对齐。

用于每个示例中具有可变语言的翻译的 Feature。此处为了与 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')})

音频

class datasets.Audio

< >

( sampling_rate: typing.Optional[int] = None mono: bool = True decode: bool = True id: typing.Optional[str] = None )

参数

  • sampling_rate (int, 可选) — 目标采样率。如果为 None,则使用原生采样率。
  • mono (bool, 默认为 True) — 是否通过对跨通道的样本进行平均,将音频信号转换为单声道。
  • decode (bool, 默认为 True) — 是否解码音频数据。如果为 False,则返回格式为 {"path": audio_path, "bytes": audio_bytes} 的底层字典。

音频 Feature,用于从音频文件中提取音频数据。

输入:音频特征接受以下输入

  • 一个 str:音频文件的绝对路径(即允许随机访问)。

  • 一个带有以下键的 dict

    • path:字符串,表示音频文件相对于归档文件的相对路径。
    • bytes:音频文件的字节内容。

    这对于具有顺序访问权限的归档文件非常有用。

  • 一个带有以下键的 dict

    • path:字符串,表示音频文件相对于归档文件的相对路径。
    • 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=16000))
>>> ds[0]["audio"]
{'array': array([ 2.3443763e-05,  2.1729663e-04,  2.2145823e-04, ...,
     3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32),
 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
 'sampling_rate': 16000}

cast_storage

< >

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

参数

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

返回值

pa.StructArray

音频 Arrow 存储类型中的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将 Arrow 数组转换为音频 Arrow 存储类型。可以转换为音频 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 ) dict

参数

  • value (dict) — 具有以下键的字典:

    • path:字符串,表示音频文件相对路径。
    • bytes:音频文件的字节。
  • token_per_repo_id (dict, 可选) — 为了访问和解码 Hub 上私有仓库中的音频文件,您可以传递一个字典 repo_id (str) -> token (boolstr)

返回值

dict

将示例音频文件解码为音频数据。

embed_storage

< >

( storage: StructArray ) pa.StructArray

参数

  • storage (pa.StructArray) — 要嵌入的 PyArrow 数组。

返回值

pa.StructArray

音频 Arrow 存储类型中的数组,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

将音频文件嵌入到 Arrow 数组中。

encode_example

< >

( value: typing.Union[str, bytes, dict] ) dict

参数

  • value (strdict) — 作为输入传递给音频功能的数据。

返回值

dict

将示例数据编码为 Arrow 格式。

flatten

< >

( )

如果在可解码状态,则引发错误,否则将该功能展平为字典。

Image

class datasets.Image

< >

( mode: typing.Optional[str] = None decode: bool = True id: typing.Optional[str] = None )

参数

  • mode (str, 可选) — 转换图像的模式。如果为 None,则使用图像的本机模式。
  • decode (bool, 默认为 True) — 是否解码图像数据。如果为 False,则以 {"path": image_path, "bytes": image_bytes} 格式返回底层字典。

Image Feature 用于从图像文件读取图像数据。

输入:Image 功能接受以下输入

  • str:图像文件的绝对路径(即允许随机访问)。

  • 一个带有以下键的 dict

    • path:字符串,表示图像文件相对于存档文件的相对路径。
    • bytes:图像文件的字节。

    这对于具有顺序访问权限的归档文件非常有用。

  • np.ndarray:表示图像的 NumPy 数组。

  • PIL.Image.Image:PIL 图像对象。

示例

>>> 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.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 (strdict) — 包含绝对图像文件路径的字符串,或包含以下键的字典:

    • path:包含绝对或相对图像文件路径的字符串。
    • bytes:图像文件的字节。
  • token_per_repo_id (dict, 可选) — 要访问和解码 Hub 上私有存储库中的图像文件,您可以传递一个字典 repo_id (str) -> token (boolstr)。

将示例图像文件解码为图像数据。

embed_storage

< >

( storage: StructArray ) 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, dict, numpy.ndarray, ForwardRef('PIL.Image.Image')] )

参数

  • value (str, np.ndarray, PIL.Image.Imagedict) — 作为输入传递给 Image 功能的数据。

将示例数据编码为 Arrow 格式。

flatten

< >

( )

如果在可解码状态,则返回功能本身,否则将该功能展平为字典。

Video

class datasets.Video

< >

( decode: bool = True id: typing.Optional[str] = None )

参数

  • mode (str, 可选) — 转换视频的模式。如果为 None,则使用视频的本机模式。
  • decode (bool, 默认为 True) — 是否解码视频数据。如果为 False,则以 {"path": video_path, "bytes": video_bytes} 格式返回底层字典。

实验性功能。 Video Feature 用于从视频文件读取视频数据。

输入:Video 功能接受以下输入

  • str:视频文件的绝对路径(即允许随机访问)。

  • 一个带有以下键的 dict

    • path:字符串,表示数据集存储库中视频文件的相对路径。
    • bytes:视频文件的字节。

    这对于具有顺序访问权限的归档文件非常有用。

  • torchvision.io.VideoReader:torchvision 视频读取器对象。

示例

>>> 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"]
<torchvision.io.video_reader.VideoReader object at 0x325b1aae0>
>>> ds = ds.cast_column('video', Video(decode=False))
{'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, 可选) — 为了访问和解码 Hub 上私有仓库中的视频文件,您可以传递一个字典 repo_id (str) -> token (boolstr)。

将示例视频文件解码为视频数据。

encode_example

< >

( value: typing.Union[str, bytes, datasets.features.video.Example, numpy.ndarray, ForwardRef('VideoReader')] )

参数

  • value (str, np.ndarray, VideoReaderdict) — 作为输入传递给 Video 特征的数据。

将示例数据编码为 Arrow 格式。

flatten

< >

( )

如果在可解码状态,则返回功能本身,否则将该功能展平为字典。

Pdf

class datasets.Pdf

< >

( decode: bool = True id: typing.Optional[str] = None )

参数

  • mode (str, 可选) — 转换 pdf 的模式。如果为 None,则使用 pdf 的原生模式。
  • decode (bool, 默认为 True) — 是否解码 pdf 数据。如果为 False,则以 {"path": pdf_path, "bytes": pdf_bytes} 格式返回底层字典。

实验性功能。 Pdf Feature 用于从 pdf 文件中读取 pdf 文档。

输入:Pdf 特征接受以下输入

  • 一个 str: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, 可选) — 为了访问和解码 Hub 上私有仓库中的 pdf 文件,您可以传递一个字典 repo_id (str) -> token (boolstr)。

将示例 pdf 文件解码为 pdf 数据。

encode_example

< >

( value: typing.Union[str, bytes, dict, ForwardRef('pdfplumber.pdf.PDF')] )

参数

  • value (str, bytes, pdfplumber.pdf.PDFdict) — 作为输入传递给 Pdf 特征的数据。

将示例数据编码为 Arrow 格式。

encode_pdfplumber_pdf

< >

( pdf: pdfplumber.pdf.PDF ) dict

参数

  • pdf (pdfplumber.pdf.PDF) — 一个 pdfplumber PDF 对象。

返回值

dict

一个包含 “path” 或 “bytes” 字段的字典。

将 pdfplumber.pdf.PDF 对象编码为字典。

如果 PDF 具有关联的文件路径,则返回该路径。否则,将 PDF 内容序列化为字节。

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 上更新