Datasets 文档

主要类

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

主类

DatasetInfo

class datasets.DatasetInfo

< >

( description: str = <factory> citation: str = <factory> homepage: str = <factory> license: str = <factory> features: typing.Optional[datasets.features.features.Features] = None post_processed: typing.Optional[datasets.info.PostProcessedInfo] = None supervised_keys: typing.Optional[datasets.info.SupervisedKeysData] = None builder_name: typing.Optional[str] = None dataset_name: typing.Optional[str] = None config_name: typing.Optional[str] = None version: typing.Union[str, datasets.utils.version.Version, NoneType] = None splits: typing.Optional[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, 可选) — 下载数据集校验和的 URL 与相应元数据之间的映射。
  • download_size (int, 可选) — 生成数据集需要下载的文件大小,以字节为单位。
  • post_processing_size (int, 可选) — 数据集在后处理后的大小,以字节为单位(如果进行了后处理)。
  • dataset_size (int, 可选) — 所有数据集划分的 Arrow 表的总大小,以字节为单位。
  • size_in_bytes (int, 可选) — 与数据集相关的所有文件的总大小,以字节为单位(下载的文件 + Arrow 文件)。
  • **config_kwargs (额外的关键字参数) — 将传递给 BuilderConfig 并在 DatasetBuilder 中使用的关键字参数。

关于数据集的信息。

DatasetInfo 记录了数据集的各种信息,包括其名称、版本和特征。完整的列表请参见构造函数参数和属性。

并非所有字段在构建时都是已知的,可能会在之后更新。

from_directory

< >

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

参数

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

    在 2.9.0 版本中新增

从 `dataset_info_dir` 中的 JSON 文件创建 DatasetInfo

此函数会更新 DatasetInfo 的所有动态生成字段(例如,示例数量、哈希值、创建时间等)。

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

示例

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

write_to_directory

< >

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

参数

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

    在 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 表支持的数据集。

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 表支持的数据集。

add_column

< >

( name: str column: typing.Union[list, numpy.ndarray] 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.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf, NoneType] = None )

参数

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

向数据集中添加列。

在 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) — 要添加的项目数据。

向数据集中添加项目。

在 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, 可选) — 数据集信息,如描述、引用等。
  • split (NamedSplit, 可选) — 数据集划分的名称。
  • indices_filename (str, 可选) — 索引的文件名。
  • in_memory (bool, 默认为 False) — 是否将数据复制到内存中。

实例化一个由位于指定文件名的 Arrow 表支持的数据集。

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 缓冲区支持的数据集。

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, optional) — 数据集特征。
  • info (DatasetInfo, optional) — 数据集信息,如描述、引用等。
  • split (NamedSplit, optional) — 数据集拆分的名称。
  • preserve_index (bool, optional) — 是否将索引作为额外的一列存储在生成的数据集中。默认值 `None` 会将索引存储为一列,但 `RangeIndex` 除外,它仅作为元数据存储。使用 `preserve_index=True` 强制将其存储为一列。

将 `pandas.DataFrame` 转换为 `pyarrow.Table` 以创建一个 Dataset

生成的 Arrow Table 中的列类型是根据 DataFrame 中 `pandas.Series` 的 dtypes 推断的。对于非对象 Series,NumPy dtype 会被转换为其等效的 Arrow 类型。对于 `object` 类型,我们需要通过查看该 Series 中的 Python 对象来猜测数据类型。

请注意,`object` 类型的 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, optional) — 数据集特征。
  • info (DatasetInfo, optional) — 数据集信息,如描述、引用等。
  • split (NamedSplit, optional) — 数据集拆分的名称。

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

    2.7.0 版本新增

  • split (NamedSplit, defaults to Split.TRAIN) — 分配给数据集的拆分名称。

    2.21.0 版本新增

  • **kwargs (附加关键字参数) — 将传递给 :`GeneratorConfig` 的关键字参数。

从生成器创建数据集。

示例

>>> 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, optional) — 转换后数据集的新指纹。如果为 `None`,则新指纹将使用前一个指纹的哈希值和转换参数计算。

返回

数据集

一份列已展平的数据集副本。

展平表格。每个具有结构类型的列都将展平为每个结构字段一个列。其他列保持不变。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad", split="train")
>>> ds.features
{'id': Value('string'),
 'title': Value('string'),
 'context': Value('string'),
 'question': Value('string'),
 'answers': {'text': List(Value('string')),
 'answer_start': List(Value('int32'))}}
>>> ds.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() 来更新数据集。
  • batch_size (int, defaults to 1000) — 提供给 cast 的每批样本数。如果 `batch_size <= 0` 或 `batch_size == None`,则将整个数据集作为一个批次提供给 cast。
  • keep_in_memory (bool, defaults to False) — 是否将数据复制到内存中。
  • load_from_cache_file (bool, defaults to True if caching is enabled) — 如果可以识别存储当前 `function` 计算结果的缓存文件,则使用它而不是重新计算。
  • cache_file_name (str, optional, defaults to None) — 提供缓存文件的路径名称。它用于存储计算结果,而不是使用自动生成的缓存文件名。
  • writer_batch_size (int, defaults to 1000) — 缓存文件写入器的每次写入操作的行数。此值在处理过程中的内存使用和处理速度之间是一个很好的权衡。较高的值使处理过程中的查找次数减少,较低的值在运行 map() 时消耗较少的临时内存。
  • num_proc (int, optional, defaults to None) — 多进程处理的进程数。默认情况下不使用多进程处理。

返回

数据集

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

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

示例

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

cast_column

< >

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

参数

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

将列转换为特征以进行解码。

示例

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

remove_columns

< >

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

参数

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

返回

数据集

移除了指定列的数据集对象副本。

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

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

示例

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

rename_column

< >

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

参数

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

返回

数据集

一列已重命名的数据集副本。

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

示例

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

rename_columns

< >

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

参数

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

返回

数据集

列已重命名的数据集副本

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

示例

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

select_columns

< >

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

参数

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

返回

数据集

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

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

示例

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

class_encode_column

< >

( column: str include_nulls: bool = False )

参数

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

    1.14.2 版本新增

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

示例

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

__len__

< >

( )

数据集中的行数。

示例

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

__iter__

< >

( )

遍历样本。

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

iter

< >

( batch_size: int drop_last_batch: bool = False )

参数

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

按批次大小 batch_size 遍历。

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

formatted_as

< >

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

参数

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

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

set_format

< >

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

参数

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

设置 __getitem__ 返回格式(类型和列)。数据格式化是即时应用的。格式 type(例如 “numpy”)用于在使用 __getitem__ 时格式化批次。也可以使用 set_transform() 使用自定义转换进行格式化。

在调用 set_format 后可以调用 map()。由于 map 可能会添加新列,因此格式化列的列表

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

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

示例

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

set_transform

< >

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

参数

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

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

示例

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

reset_format

< >

( )

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

self.set_format() 相同

示例

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

with_format

< >

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

参数

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

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

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

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

示例

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

with_transform

< >

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

参数

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

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

set_format() 一样,这可以使用 reset_format() 重置。

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

示例

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

__getitem__

< >

( key )

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

cleanup_cache_files

< >

( ) int

返回

int

已删除的文件数。

清理数据集缓存目录中的所有缓存文件,但当前使用的缓存文件(如果有)除外。

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

示例

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

map

< >

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

参数

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

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

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

  • with_indices (bool, 默认为 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, optional, 默认为 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, optional, 默认为 None) — 提供缓存文件的路径名称。它用于存储计算结果,而不是自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器每次写入操作的行数。此值是在处理过程中的内存使用和处理速度之间的一个良好权衡。较高的值使处理过程中的查找次数减少,较低的值在运行 map 时消耗较少的临时内存。
  • features (Optional[datasets.Features], 默认为 None) — 使用特定的 Features 来存储缓存文件,而不是自动生成的。
  • disable_nullable (bool, 默认为 False) — 不允许表中有空值。
  • fn_kwargs (Dict, optional, 默认为 None) — 要传递给 function 的关键字参数。
  • num_proc (int, optional, 默认为 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, optional, 默认为 None) — 转换后数据集的新指纹。如果为 None,则使用先前指纹和转换参数的哈希值计算新指纹。
  • desc (str, optional, 默认为 None) — 有意义的描述,在映射样本时与进度条一起显示。
  • try_original_type (Optional[bool], 默认为 True) — 尝试保留原始列的类型(例如,int32 -> int32)。如果您希望总是推断新类型,请设置为 False。

对表中的所有示例(单个或批量)应用一个函数并更新表。如果您的函数返回一个已存在的列,那么它将被覆盖。

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

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

过滤器

< >

( 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 如果 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(每个对应一个额外参数)

    如果函数是异步的,那么 `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 <= 0` 或 `batch_size == None`,则将整个数据集作为单个批次提供给 `function`。
  • keep_in_memory (bool, 默认为 False) — 将数据集保留在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], 如果启用缓存则默认为 True) — 如果可以识别存储当前 `function` 计算结果的缓存文件,则使用它而不是重新计算。
  • cache_file_name (str, *可选*) — 提供缓存文件的路径名称。它用于存储计算结果,而不是使用自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器的每次写入操作的行数。此值是在处理过程中的内存使用和处理速度之间的一个良好权衡。较高的值使处理过程中的查找次数减少,较低的值在运行 `map` 时消耗更少的临时内存。
  • fn_kwargs (dict, *可选*) — 要传递给 `function` 的关键字参数。
  • num_proc (int, *可选*) — 用于多进程处理的进程数。默认情况下不使用多进程处理。
  • suffix_template (str) — 如果指定了 `cache_file_name`,则此后缀将添加到每个基本名称的末尾。例如,如果 `cache_file_name` 是 `"processed.arrow"`,那么对于 `rank = 1` 和 `num_proc = 4`,对于默认后缀(默认为 `_{rank:05d}_of_{num_proc:05d}`),生成的文件将是 `"processed_00001_of_00004.arrow"`。
  • new_fingerprint (str, *可选*) — 转换后数据集的新指纹。如果为 `None`,则使用前一个指纹的哈希值和转换参数计算新指纹。
  • desc (str, *可选*, 默认为 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
})

选择

< >

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

参数

  • indices (range, list, iterable, ndarraySeries) — 用于索引的整数索引的范围、列表或一维数组。如果索引对应一个连续范围,Arrow 表将被简单地切片。然而,传递一个不连续的索引列表会创建索引映射,这效率要低得多,但仍然比重新创建一个由所请求行组成的 Arrow 表要快。
  • keep_in_memory (bool, 默认为 False) — 将索引映射保留在内存中,而不是写入缓存文件。
  • indices_cache_file_name (str, *可选*, 默认为 None) — 提供缓存文件的路径名称。它用于存储索引映射,而不是使用自动生成的缓存文件名。
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器的每次写入操作的行数。此值是在处理过程中的内存使用和处理速度之间的一个良好权衡。较高的值使处理过程中的查找次数减少,较低的值在运行 `map` 时消耗更少的临时内存。
  • new_fingerprint (str, *可选*, 默认为 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]], 默认为 False) — 如果为 `True`,则按降序而非升序排序。如果提供单个布尔值,则该值将应用于所有列名的排序。否则,必须提供一个与 column_names 长度和顺序相同的布尔值列表。
  • null_placement (str, 默认为 at_end) — 如果为 `at_start` 或 `first`,则将 `None` 值放在开头;如果为 `at_end` 或 `last`,则放在末尾。

    1.14.2 版本新增

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

创建一个新的数据集,其中的行被打乱。

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

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

不过,这可能会花费很多时间,具体取决于您的数据集大小。

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

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

它只打乱分片的顺序,并为您的数据集添加一个打乱缓冲区,这可以保持数据集的最佳速度。

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

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

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

示例

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

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

skip

< >

( n: int )

参数

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

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

示例

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

take

< >

( n: int )

参数

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

创建一个新的 Dataset,其中只包含前 `n` 个元素。

示例

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

train_test_split

< >

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

参数

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

shard

< >

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

参数

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

返回将数据集拆分成 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可选) — 一个可选的 `dict`,包含要传递给 `collate_fn` 的关键字参数。
  • label_cols (List[str]str,默认为 None) — 作为标签加载的数据集列。请注意,许多模型在内部计算损失,而不是让 Keras 来做,在这种情况下,只要标签在输入的 `columns` 中,传递标签就是可选的。
  • prefetch (bool,默认为 True) — 是否在单独的线程中运行数据加载器并为训练维护一个小的批次缓冲区。通过允许在模型训练时在后台加载数据来提高性能。
  • num_workers (int,默认为 0) — 用于加载数据集的工作进程数。
  • num_test_batches (int,默认为 20) — 用于推断数据集输出签名的批次数。这个数字越高,签名就越准确,但创建数据集所需的时间就越长。

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

示例

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

push_to_hub

< >

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

参数

  • repo_id (str) — 要推送到的仓库 ID,格式如下:`<user>/<dataset_name>` 或 `<org>/<dataset_name>`。也接受 `<dataset_name>`,这将默认为已登录用户的命名空间。
  • config_name (str,默认为“default”) — 数据集的配置名称(或子集)。默认为“default”。
  • set_default (bool可选) — 是否将此配置设置为默认配置。否则,默认配置是名为“default”的配置。
  • split (str可选) — 将赋予该数据集的拆分名称。默认为 `self.split`。
  • data_dir (str可选) — 包含上传数据文件的目录名称。如果 `config_name` 不同于“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 文件中嵌入文件内容。
  • num_proc (int可选,默认为 `None`) — 准备和上传数据集时的进程数。如果数据集由许多样本或要嵌入的媒体文件组成,这会很有帮助。默认情况下禁用多进程。

    在 4.0.0 中添加

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

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

示例

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

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

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

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

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

save_to_disk

< >

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

参数

  • dataset_path (path-like) — 数据集目录的路径(例如 `dataset/train`)或远程 URI(例如 `s3://my-bucket/dataset/train`),数据集将保存到此处。
  • max_shard_size (intstr可选,默认为 `"500MB"`) — 要保存到文件系统的数据集分片的最大大小。如果以字符串形式表示,需要是数字后跟一个单位(例如 `"50MB"`)。
  • num_shards (int可选) — 要写入的分片数。默认情况下,分片数取决于 `max_shard_size` 和 `num_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`。

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

示例

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

flatten_indices

< >

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

参数

  • keep_in_memory (bool, 默认为 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,则新指纹将使用前一个指纹和转换参数的哈希值计算。

通过扁平化索引映射创建并缓存一个新的数据集。

to_csv

< >

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

参数

  • path_or_buf (PathLike or FileOrBuffer) — 文件路径(例如 file.csv)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.csv)或 BinaryIO,数据集将以指定格式保存到此处。
  • batch_size (int, 可选) — 一次加载到内存并写入的批次大小。默认为 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 )

参数

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

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

示例

>>> ds.to_pandas()

to_dict

< >

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

参数

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

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

示例

>>> ds.to_dict()

to_json

< >

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

参数

  • path_or_buf (PathLike or FileOrBuffer) — 文件路径(例如 file.json)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.json)或 BinaryIO,数据集将以指定格式保存到此处。
  • batch_size (int, 可选) — 一次加载到内存并写入的批次大小。默认为 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 (PathLike or FileOrBuffer) — 文件路径(例如 file.parquet)、远程 URI(例如 hf://datasets/username/my_dataset_name/data.parquet)或 BinaryIO,数据集将以指定格式保存到此处。
  • batch_size (int, 可选) — 一次加载到内存并写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • storage_options (dict, 可选) — 传递给文件系统后端的键/值对(如果有)。

    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 (str or sqlite3.Connection or sqlalchemy.engine.Connection or sqlalchemy.engine.Connection) — 一个 URI 字符串 或 SQLite3/SQLAlchemy 连接对象,用于向数据库写入数据。
  • batch_size (int, 可选) — 一次加载到内存并写入的批次大小。默认为 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) — 实例化可迭代数据集时定义的分片数。这对于大数据集特别有用,可以正确地进行洗牌,并且可以使用 PyTorch DataLoader 或在分布式设置中实现快速并行加载。分片是使用 datasets.Dataset.shard() 定义的:它只是对数据进行切片,而不在磁盘上写入任何内容。

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

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

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

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

示例

基本用法

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

使用惰性筛选和处理

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

使用分片以实现高效洗牌

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

使用 PyTorch DataLoader

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

使用 PyTorch DataLoader 和洗牌

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

在 PyTorch DDP 等分布式设置中使用 PyTorch DataLoader 和洗牌

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

使用洗牌和多个 epoch

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

add_faiss_index

< >

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

参数

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

    2.4.0 版本中新增

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

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

示例

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

    2.4.0 版本新增

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

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

save_faiss_index

< >

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

参数

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

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

    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, 可选) — 索引的 index_name/标识符。这是用于调用 get_nearest_examples()search() 的索引名称。默认情况下,它对应于 column
  • host (str, 可选, 默认为 localhost) — ElasticSearch 运行的主机。
  • port (str, 可选, 默认为 9200) — ElasticSearch 运行的端口。
  • es_client (elasticsearch.Elasticsearch, 可选) — 当 host 和 port 为 None 时,用于创建索引的 elasticsearch 客户端。
  • es_index_name (str, 可选) — 用于创建索引的 elasticsearch 索引名称。
  • es_index_config (dict, 可选) — 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 (List[float]):检索到的样本的分数,来自 FAISS(默认为 `IndexFlatL2`)或 ElasticSearch
  • examples (dict):检索到的样本

在数据集中查找与查询最接近的样本。

get_nearest_examples_batch

< >

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

参数

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

返回

(total_scores, total_examples)

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

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

在数据集中查找与查询最接近的样本。

info

< >

( )

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

split

< >

( )

对应于命名数据集拆分的 NamedSplit 对象。

builder_name

< >

( )

引用

< >

( )

config_name

< >

( )

dataset_size

< >

( )

description

< >

( )

download_checksums

< >

( )

download_size

< >

( )

features

< >

( )

homepage

< >

( )

许可证

< >

( )

size_in_bytes

< >

( )

supervised_keys

< >

( )

版本

< >

( )

from_csv

< >

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

参数

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

    2.8.0 版本新增

  • **kwargs (附加关键字参数) — 传递给 `pandas.read_csv` 的关键字参数。

从 CSV 文件创建数据集。

示例

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

from_json

< >

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

参数

  • path_or_paths (path-likepath-like 列表) — JSON 或 JSON Lines 文件的路径。
  • split (NamedSplit, 可选) — 要分配给数据集的拆分名称。
  • features (Features, 可选) — 数据集特征。
  • cache_dir (str, 可选, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • field (str, 可选) — 包含数据集的 JSON 文件的字段名。
  • num_proc (int, 可选, 默认为 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-likepath-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-likepath-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 查询或数据库表创建数据集。

示例

>>> # 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]) — 要连接的数据集列表。
  • 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,在这种情况下,当所有数据集都至少耗尽一次示例时,结果数据集才结束。

可迭代数据集注意事项

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

示例

对于常规数据集(映射样式)

>>> 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 的节点上使用的数据集。

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

对于映射样式的数据集

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

对于可迭代的数据集

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

datasets.enable_caching

< >

( )

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

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

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

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

datasets.disable_caching

< >

( )

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

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

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

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

datasets.is_caching_enabled

< >

( )

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

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

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

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

class datasets.Column

< >

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

用于 Dataset 特定列的可迭代对象。

示例

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

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

它也适用于嵌套列

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

DatasetDict

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

class datasets.DatasetDict

< >

( )

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

data

< >

( )

支持每个拆分的 Apache Arrow 表。

示例

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

cache_files

< >

( )

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

示例

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

num_columns

< >

( )

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

示例

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

num_rows

< >

( )

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

示例

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

column_names

< >

( )

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

示例

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

shape

< >

( )

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

示例

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

unique

< >

( column: str ) Dict[str, list]

参数

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

返回

Dict[str, list]

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

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

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

示例

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

cleanup_cache_files

< >

( )

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

示例

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

map

< >

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

参数

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

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

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

将一个函数应用于表中的所有示例(单个或批量),并更新表。如果你的函数返回一个已存在的列,那么它将被覆盖。该转换将应用于数据集字典中的所有数据集。

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

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

过滤器

< >

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

参数

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

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

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

  • with_indices (bool, 默认为 False) — 向 function 提供示例索引。请注意,在这种情况下,function 的签名应为 def function(example, idx[, rank]): ...
  • with_rank (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 的每批示例数。如果 batch_size <= 0batch_size == None,则将整个数据集作为单个批次提供给 function
  • keep_in_memory (bool, 默认为 False) — 将数据集保留在内存中,而不是写入缓存文件。
  • load_from_cache_file (Optional[bool], 默认为 True,如果缓存已启用) — 如果可以识别出存储了当前 function 计算结果的缓存文件,则直接使用它而不是重新计算。
  • cache_file_names ([Dict[str, str]], 可选, 默认为 None) — 提供缓存文件的路径名称。它用于存储计算结果,而不是使用自动生成的缓存文件名。您必须为数据集字典中的每个数据集提供一个 cache_file_name
  • writer_batch_size (int, 默认为 1000) — 缓存文件写入器每次写入操作的行数。此值是在处理过程中的内存使用和处理速度之间的一个良好权衡。较高的值会使处理过程中的查找次数减少,较低的值在运行 map 时消耗较少的临时内存。
  • fn_kwargs (Dict, 可选, 默认为 None) — 要传递给 function 的关键字参数。
  • num_proc (int, 可选, 默认为 None) — 用于多进程处理的进程数。默认情况下不使用多进程。
  • desc (str, 可选, 默认为 None) — 在过滤示例时,与进度条一同显示的、有意义的描述。

对表中的所有元素批量应用一个过滤函数,并更新表,使得数据集只包含符合过滤函数的示例。该转换将应用于数据集字典中的所有数据集。

示例

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

sort

< >

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

参数

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

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

示例

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

shuffle

< >

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

参数

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

创建一个新的数据集,其中的行被打乱。

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

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

示例

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

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

set_format

< >

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

参数

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

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

可以在调用 set_format 后调用 map。由于 map 可能会添加新列,格式化列的列表会随之更新。在这种情况下,如果你对数据集应用 map 来添加一个新列,那么这个新列将被格式化。

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

示例

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

reset_format

< >

( )

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

self.set_format() 相同

示例

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

formatted_as

< >

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

参数

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

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

with_format

< >

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

参数

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

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

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

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

示例

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

with_transform

< >

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

参数

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

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

set_format() 一样,这可以使用 reset_format() 重置。

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

示例

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

flatten

< >

( max_depth = 16 )

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

示例

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

cast

< >

( features: Features )

参数

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

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

示例

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

cast_column

< >

( column: str feature )

参数

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

将列转换为特征以进行解码。

示例

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

remove_columns

< >

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

参数

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

返回

DatasetDict

移除了指定列的数据集对象副本。

从数据集的每个分割中移除一个或多个列以及与这些列相关的特征。

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

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

示例

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

rename_column

< >

( original_column_name: str new_column_name: str )

参数

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

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

您也可以使用带有 remove_columnsmap() 来重命名列,但本方法

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

示例

>>> 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('bool'),
 'passage': Value('string'),
 'question': Value('string')}
>>> ds = ds.class_encode_column("answer")
>>> ds["train"].features
{'answer': ClassLabel(num_classes=2, names=['False', 'True']),
 'passage': Value('string'),
 'question': Value('string')}

push_to_hub

< >

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

参数

  • repo_id (str) — 要推送到的仓库 ID,格式为 <user>/<dataset_name><org>/<dataset_name>。也接受 <dataset_name>,此时将默认为已登录用户的命名空间。
  • config_name (str) — 数据集的配置名称。默认为 "default"。
  • set_default (bool, 可选) — 是否将此配置设置为默认配置。否则,默认配置是名为 "default" 的配置。
  • data_dir (str, 可选) — 将包含上传数据文件的目录名称。如果 config_name 不同于 "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 文件中嵌入文件内容。
  • num_proc (int, 可选, 默认为 None) — 准备和上传数据集时的进程数。如果数据集由许多样本或要嵌入的媒体文件组成,这会很有帮助。多进程默认禁用。

    4.0.0 版本新增

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

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

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

示例

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

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

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

save_to_disk

< >

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

参数

  • dataset_dict_path (path-like) — 数据集字典目录的路径(例如 dataset/train)或远程 URI(例如 s3://my-bucket/dataset/train),数据集字典将被保存到该位置。
  • max_shard_size (intstr, 可选, 默认为 "500MB") — 要保存到文件系统的数据集分片的最大大小。如果表示为字符串,需要是数字后跟一个单位(如 "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 设置为非零值来明确启用,否则数据集将不会被复制到内存中。更多详细信息请参见提高性能部分。
  • 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, optional) — 数据集特征。
  • cache_dir (str, optional, 默认为 "~/.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, optional) — 数据集特征。
  • cache_dir (str, optional, 默认为 "~/.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, optional) — 数据集特征。
  • cache_dir (str, optional, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • columns (list[str], optional) — 如果不为 None,则只从文件中读取这些列。列名可以是嵌套字段的前缀,例如,“a”将选择“a.b”、“a.c”和“a.d.e”。
  • **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, optional) — 数据集特征。
  • cache_dir (str, optional, 默认为 "~/.cache/huggingface/datasets") — 缓存数据的目录。
  • keep_in_memory (bool, 默认为 False) — 是否将数据复制到内存中。
  • **kwargs (附加关键字参数) — 传递给 TextConfig 的关键字参数。

从文本文件创建 DatasetDict

示例

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

IterableDataset

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

class datasets.IterableDataset

< >

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

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

from_generator

< >

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

参数

  • generator (Callable) — 一个 `yields` 样本的生成器函数。
  • features (Features, optional) — 数据集特征。
  • gen_kwargs(dict, optional) — 传递给 generator 可调用对象的关键字参数。你可以通过在 gen_kwargs 中传递分片列表来定义一个分片可迭代数据集。这可以用于改善洗牌效果,以及在使用多个工作进程迭代数据集时。
  • split (NamedSplit, 默认为 Split.TRAIN) — 分配给数据集的分割名称。

    2.21.0 版本新增

返回

IterableDataset

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

示例

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

remove_columns

< >

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

参数

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

返回

IterableDataset

移除了指定列的数据集对象副本。

移除数据集中的一个或多个列以及与之相关的特征。在迭代数据集时,移除操作是在样本上动态执行的。

示例

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

select_columns

< >

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

参数

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

返回

IterableDataset

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

选择数据集中的一个或多个列以及与之相关的特征。在迭代数据集时,选择操作是在样本上动态执行的。

示例

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

cast_column

< >

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

参数

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

返回

IterableDataset

将列转换为特征以进行解码。

示例

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

cast

< >

( features: Features ) IterableDataset

参数

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

返回

IterableDataset

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

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

示例

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

decode

< >

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

参数

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

返回

IterableDataset

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

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

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

  • 音频 -> 包含 "array"、"sampling_rate" 和 "path" 的字典
  • 图像 -> PIL.Image
  • 视频 -> torchvision.io.VideoReader

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

如果您想迭代媒体文件的路径或字节,而不实际解码其内容,禁用解码会很有用。要禁用解码,您可以使用 .decode(False),这相当于调用 .cast().cast_column() 并将所有音频、图像和视频类型的 decode=False 设置为 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('string')}
>>> next(iter(ds))
{
  'image': {
    'path': 'hf://datasets/sshh12/planet-textures@69dc4cef7a5c4b2cfe387727ec8ea73d4bff7302/train/textures/0000.png',
    'bytes': None
  },
  'text': 'A distant celestial object with an icy crust, displaying a light blue shade, covered with round pits and rugged terrains.'
}

通过多线程加速流式处理

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

__iter__

< >

( )

iter

< >

( batch_size: int drop_last_batch: bool = False )

参数

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

按批次大小 batch_size 遍历。

map

< >

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

参数

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

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

    对于高级用法,该函数也可以返回一个 `pyarrow.Table`。如果函数是异步的,那么 `map` 将并行运行你的函数。此外,如果你的函数不返回任何内容 (None),那么 `map` 将运行你的函数并返回未经更改的数据集。如果没有提供函数,则默认为恒等函数:`lambda x: x`。

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

对可迭代数据集中的所有样本(单个或批量)应用一个函数并更新它们。如果你的函数返回一个已存在的列,那么它将覆盖该列。该函数在迭代数据集时即时应用于样本。

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

  • 如果 `batched` 为 `False`,则函数接收 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 .'}

过滤器

< >

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

参数

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

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

    如果函数是异步的,那么 `filter` 将并行运行你的函数。如果没有提供函数,则默认为一个始终返回 True 的函数:`lambda x: True`。

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

对所有元素应用一个过滤函数,使数据集只包含符合过滤函数条件的样本。过滤在迭代数据集时即时进行。

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

示例

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

shuffle

< >

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

参数

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

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

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

例如,如果你的数据集包含 10,000 个元素,但 `buffer_size` 设置为 1000,那么 `shuffle` 最初将仅从缓冲区中的前 1000 个元素中随机选择一个元素。一旦一个元素被选中,它在缓冲区中的空间将被下一个(即第 1001 个)元素替换,从而维持 1000 个元素的缓冲区。

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

示例

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

batch

< >

( batch_size: int drop_last_batch: bool = False )

参数

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

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

示例

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

skip

< >

( n: int )

参数

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

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

示例

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

take

< >

( n: int )

参数

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

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

示例

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

shard

< >

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

参数

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

返回将数据集拆分成 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 时,即使在 shuffle 之后,重复数据也永远不会在同一次迭代中出现:ds.repeat(n).shuffle(seed=42, buffer_size=1) 等同于 ds.shuffle(seed=42, buffer_size=1).repeat(n),并且仅在每次迭代内打乱分片顺序。当 buffer size >= (数据集中样本数 * 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'}]

to_csv

< >

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

参数

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

返回

int

写入的字符或字节数。

将数据集导出为 csv。

这会迭代数据集并在写入之前将其完全加载到内存中。

示例

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

to_pandas

< >

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

参数

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

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

示例

>>> ds.to_pandas()

to_dict

< >

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

参数

  • batch_size (int, 可选) — 如果 `batched` 为 `True`,则为批次的大小(行数)。默认为 `datasets.config.DEFAULT_MAX_BATCH_SIZE`。

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

示例

>>> ds.to_dict()

to_json

< >

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

参数

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

返回

int

写入的字符或字节数。

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

这会迭代数据集并在写入之前将其完全加载到内存中。

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

示例

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

to_parquet

< >

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

参数

  • path_or_buf (PathLike or FileOrBuffer) — 文件路径(例如 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")
>>> num_shards = dataset.num_shards
>>> for index in range(num_shards):
...     shard = dataset.shard(index, num_shards)
...     shard.to_parquet(f"path/of/my/dataset/data-{index:05d}.parquet")

to_sql

< >

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

参数

  • name (str) — SQL 表的名称。
  • con (str or sqlite3.Connection or sqlalchemy.engine.Connection or sqlalchemy.engine.Connection) — 用于写入数据库的 URI 字符串 或 SQLite3/SQLAlchemy 连接对象。
  • batch_size (int, optional) — 一次性加载到内存并写入的批次大小。默认为 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • **sql_writer_kwargs (附加关键字参数) — 传递给 pandas 的 pandas.DataFrame.to_sql 的参数。如果未指定,参数 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)

push_to_hub

< >

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

参数

  • repo_id (str) — 要推送到的仓库 ID,格式如下:<user>/<dataset_name><org>/<dataset_name>。也接受 <dataset_name>,它将默认为已登录用户的命名空间。
  • config_name (str, 默认为 “default”) — 数据集的配置名称(或子集)。默认为 “default”。
  • set_default (bool, optional) — 是否将此配置设置为默认配置。否则,默认配置是名为 “default” 的配置。
  • split (str, optional) — 将赋予该数据集的拆分名称。默认为 self.split
  • data_dir (str, optional) — 包含上传的数据文件的目录名称。如果 config_name 不同于 “default”,则默认为 config_name,否则为 “data”。
  • commit_message (str, optional) — 推送时要提交的消息。将默认为 "Upload dataset"
  • commit_description (str, optional) — 将要创建的提交的描述。如果创建了 PR(create_pr 为 True),则也是 PR 的描述。
  • private (bool, optional) — 是否将仓库设为私有。如果为 None (默认),除非组织的默认设置是私有,否则仓库将是公开的。如果仓库已存在,则忽略此值。
  • token (str, optional) — Hugging Face Hub 的可选身份验证令牌。如果未传递令牌,将默认为使用 huggingface-cli login 登录时本地保存的令牌。如果未传递令牌且用户未登录,则会引发错误。
  • revision (str, optional) — 要将上传的文件推送到的分支。默认为 "main" 分支。
  • create_pr (bool, optional, 默认为 False) — 是为上传的文件创建 PR 还是直接提交。
  • num_shards (int, optional) — 要写入的分片数量。默认等于该数据集的 .num_shards
  • embed_external_files (bool, 默认为 True) — 是否在分片中嵌入文件字节。特别是,在推送之前,对于以下类型的字段,它将执行以下操作:

    • AudioImage:移除本地路径信息并在 Parquet 文件中嵌入文件内容。
  • num_proc (int, optional, 默认为 None) — 准备和上传数据集时的进程数。如果数据集包含许多样本和转换,这将很有帮助。默认禁用多进程。

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

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

示例

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

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

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

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

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

load_state_dict

< >

( state_dict: dict )

加载数据集的 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)

它返回

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

返回

字典

获取数据集的当前 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)

它返回

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

info

< >

( )

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

split

< >

( )

对应于命名数据集拆分的 NamedSplit 对象。

builder_name

< >

( )

引用

< >

( )

config_name

< >

( )

dataset_size

< >

( )

description

< >

( )

download_checksums

< >

( )

download_size

< >

( )

features

< >

( )

homepage

< >

( )

许可证

< >

( )

size_in_bytes

< >

( )

supervised_keys

< >

( )

版本

< >

( )

class datasets.IterableColumn

< >

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

IterableDataset 特定列的可迭代对象。

示例

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

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

它也适用于嵌套列

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

IterableDatasetDict

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

class datasets.IterableDatasetDict

< >

( )

map

< >

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

参数

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

对可迭代数据集中的所有样本(单独或批量)应用一个函数并进行更新。如果你的函数返回一个已存在的列,那么它将被覆盖。该函数在迭代数据集时动态地应用于样本。该转换会应用于数据集字典中的所有数据集。

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

  • 如果 `batched` 为 `False`,则函数接收 1 个示例作为输入,并应返回 1 个示例。一个示例是一个字典,例如 `{"text": "Hello there !"}`。
  • 如果 `batched` 为 `True` 且 `batch_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 .'}

过滤器

< >

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

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

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

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

对所有元素应用一个筛选函数,使得数据集只包含符合该筛选函数的样本。筛选在迭代数据集时动态进行。该筛选会应用于数据集字典中的所有数据集。

示例

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

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

此数据集首先用 buffer_size 个元素填充一个缓冲区,然后从该缓冲区中随机抽样元素,并用新元素替换被选中的元素。为了实现完美的打乱效果,缓冲区大小需要大于或等于数据集的完整大小。

例如,如果你的数据集包含 10,000 个元素,但 `buffer_size` 设置为 1000,那么 `shuffle` 最初将仅从缓冲区中的前 1000 个元素中随机选择一个元素。一旦一个元素被选中,它在缓冲区中的空间将被下一个(即第 1001 个)元素替换,从而维持 1000 个元素的缓冲区。

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

示例

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

with_format

< >

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

参数

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

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

示例

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

cast

< >

( features: Features ) IterableDatasetDict

参数

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

返回

IterableDatasetDict

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

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

示例

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

cast_column

< >

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

参数

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

将列转换为特征以进行解码。类型转换会应用于数据集字典中的所有数据集。

示例

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

remove_columns

< >

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

参数

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

返回

IterableDatasetDict

移除了指定列的数据集对象副本。

移除数据集中的一列或多列以及与之相关的特征。移除操作在迭代数据集时动态地对样本进行。该移除会应用于数据集字典中的所有数据集。

示例

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

rename_column

< >

( original_column_name: str new_column_name: str ) IterableDatasetDict

参数

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

返回

IterableDatasetDict

一列已重命名的数据集副本。

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

示例

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

rename_columns

< >

( column_mapping: dict ) IterableDatasetDict

参数

  • column_mapping (Dict[str, str]) — 一个将要重命名的列映射到其新名称的字典。

返回

IterableDatasetDict

列已重命名的数据集副本

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

示例

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

select_columns

< >

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

参数

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

返回

IterableDatasetDict

一个只包含所选列的数据集对象的副本。

选择数据集中的一列或多列以及与之相关的特征。选择操作在迭代数据集时动态地对样本进行。该选择会应用于数据集字典中的所有数据集。

示例

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

push_to_hub

< >

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

参数

  • repo_id (str) — 要推送到的存储库的 ID,格式如下:<user>/<dataset_name><org>/<dataset_name>。也接受 <dataset_name>,它将默认为已登录用户的命名空间。
  • config_name (str) — 数据集的配置名称。默认为“default”。
  • set_default (bool, 可选) — 是否将此配置设置为默认配置。否则,默认配置是名为“default”的配置。
  • data_dir (str, 可选) — 将包含上传数据文件的目录名称。如果 `config_name` 与 “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" 分支。
  • create_pr (bool, 可选, 默认为 False) — 是创建带有上传文件的 PR 还是直接提交。
  • num_shards (Dict[str, int], 可选) — 要写入的分片数量。默认等于此数据集的 .num_shards。使用字典为每个拆分定义不同的 num_shards。
  • embed_external_files (bool, 默认为 True) — 是否在分片中嵌入文件字节。特别是,这将在推送前对以下类型的字段执行以下操作:

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

    4.0.0 版本中新增

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

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

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

示例

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

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

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

特征

class datasets.Features

< >

( *args **kwargs )

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

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

FieldType 可以是以下之一:

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

复制

< >

( )

Features 进行深拷贝。

示例

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

decode_batch

< >

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

参数

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

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

decode_column

< >

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

参数

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

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

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, optional) — 要从 Hub 上的私有仓库访问和解码音频或图像文件,您可以传递一个字典 repo_id (str) -> token (bool or str)

使用自定义特征解码来解码样本。

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

返回

功能

展平后的特征。

展平特征。每个字典列都将被移除,并由其包含的所有子字段替换。新字段的命名方式是通过连接原始列名和子字段名,格式为:<original>.<subfield>

如果一列包含嵌套字典,那么所有更深层次的子字段名也会被连接起来形成新列,例如:<original>.<subfield>.<subsubfield> 等。

示例

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

from_arrow_schema

< >

( pa_schema: Schema )

参数

  • pa_schema (pyarrow.Schema) — Arrow 模式。

从 Arrow 模式构建 Features。它还会检查模式元数据中是否包含 Hugging Face Datasets 的特征信息。不支持不可为空的字段,并会将其设置为可为空。

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

from_dict

< >

( dic ) Features

参数

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

返回

功能

从字典构建 [Features]。

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

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

示例

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

reorder_fields_as

< >

( other: Features )

参数

  • other ([Features]) — 用于对齐的另一个 [Features] 对象。

重新排序 Features 字段以匹配另一个 [Features] 的字段顺序。

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

示例

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

标量

class datasets.Value

< >

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

参数

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

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

Value 可能的数据类型如下

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

示例

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

class datasets.ClassLabel

< >

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

参数

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

整数类别标签的特征类型。

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

cast_storage

< >

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

参数

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

返回

pa.Int64Array

ClassLabel Arrow 存储类型中的数组。

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

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

int2str

< >

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

转换 integer => 类别名称 string

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

示例

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

str2int

< >

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

转换类别名称 string => integer

示例

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

复合类型

class datasets.LargeList

< >

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

参数

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

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

它由 pyarrow.LargeListType 支持,类似于 pyarrow.ListType,但使用 64 位偏移量而非 32 位。

class datasets.List

< >

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

参数

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

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

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

class datasets.Sequence

< >

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

参数

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

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

翻译

class datasets.Translation

< >

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

参数

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

用于每个样本具有固定语言的翻译的 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 (可变长度的一维 tf.Tensor,类型为 tf.string)

参数

  • languages (dict) — 每个样本的字典,将字符串语言代码映射到一个或多个字符串翻译。不同样本中的语言可能会有所不同。

返回

  • languagetranslation (可变长度的一维 tf.Tensor,类型为 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')})

Audio

class datasets.Audio

< >

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

参数

  • sampling_rate (int, 可选) — 目标采样率。如果为 None,则使用原始采样率。
  • mono (bool, 默认为 True) — 是否通过对各通道样本求平均值将音频信号转换为单声道。
  • decode (bool, 默认为 True) — 是否解码音频数据。如果为 False,则返回底层字典,格式为 {"path": audio_path, "bytes": audio_bytes}
  • stream_index (int, 可选) — 要从文件中使用的流索引。如果为 None,则默认为“最佳”索引。

Audio Feature (音频特征) 用于从音频文件中提取音频数据。

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

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

  • 一个包含以下键的 dict

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

    这对于嵌入音频文件的 parquet 或 webdataset 文件很有用。

  • 一个包含以下键的 dict

    • array:包含音频样本的数组
    • sampling_rate:对应音频样本采样率的整数。
  • 一个 torchcodec.decoders.AudioDecoder:torchcodec 音频解码器对象。

输出:音频特征以 torchcodec.decoders.AudioDecoder 对象的形式输出数据,并附带额外的键

  • array:包含音频样本的数组
  • sampling_rate:对应音频样本采样率的整数。

示例

>>> from datasets import load_dataset, Audio
>>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=44100))
>>> ds[0]["audio"]
<datasets.features._torchcodec.AudioDecoder object at 0x11642b6a0>
>>> audio = ds[0]["audio"]
>>> audio.get_samples_played_in_range(0, 10)
AudioSamples:
    data (shape): torch.Size([2, 110592])
    pts_seconds: 0.0
    duration_seconds: 2.507755102040816
    sample_rate: 44100

cast_storage

< >

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

参数

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

返回

pa.StructArray

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

将 Arrow 数组转换为 Audio Arrow 存储类型。可转换为 Audio PyArrow 存储类型的 Arrow 类型包括:

  • pa.string() - 必须包含 "path" 数据
  • pa.binary() - 必须包含音频字节数据
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 顺序无关

decode_example

< >

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

参数

  • value (dict) — 一个包含以下键的字典:

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

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

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

参数

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

返回

pa.StructArray

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

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

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, ForwardRef('AudioDecoder')] ) dict

参数

  • value (str, bytes,bytearray,dict, AudioDecoder) — 作为输入传递给 Audio 特征的数据。

返回

字典

将样本编码为 Arrow 格式。

flatten

< >

( )

如果处于可解码状态,则引发错误,否则将特征展平为字典。

Image

class datasets.Image

< >

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

参数

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

Image Feature (图像特征) 用于从图像文件中读取图像数据。

输入:图像特征接受以下输入

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

  • 一个包含以下键的 dict

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

    这对于嵌入图像文件的 parquet 或 webdataset 文件很有用。

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

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

输出:图像特征以 PIL.Image.Image 对象的形式输出数据。

示例

>>> 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 token_per_repo_id = None ) pa.StructArray

参数

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

返回

pa.StructArray

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

将图像文件嵌入到 Arrow 数组中。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, numpy.ndarray, ForwardRef('PIL.Image.Image')] )

参数

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

将样本编码为 Arrow 格式。

flatten

< >

( )

如果处于可解码状态,则返回特征本身,否则将特征展平为字典。

Video

class datasets.Video

< >

( decode: bool = True stream_index: typing.Optional[int] = None dimension_order: typing.Literal['NCHW', 'NHWC'] = 'NCHW' num_ffmpeg_threads: int = 1 device: typing.Union[str, ForwardRef('torch.device'), NoneType] = 'cpu' seek_mode: typing.Literal['exact', 'approximate'] = 'exact' id: typing.Optional[str] = None )

参数

  • mode (str, 可选) — 视频转换的目标模式。如果为 None,则使用视频的原始模式。
  • decode (bool, 默认为 True) — 是否解码视频数据。如果为 False,则返回底层字典,格式为 {"path": video_path, "bytes": video_bytes}
  • stream_index (int, 可选) — 要从文件中使用的流索引。如果为 None,则默认为“最佳”索引。
  • dimension_order (str, 默认为 NCHW) — 解码帧的维度顺序。其中 N 是批次大小,C 是通道数,H 是高度,W 是帧的宽度。
  • num_ffmpeg_threads (int, 默认为 1) — 用于解码视频的线程数。(建议保持为 1)
  • device (strtorch.device, 默认为 cpu) — 用于解码视频的设备。
  • seek_mode (str, 默认为 exact) — 决定帧访问是“精确”还是“近似”。精确模式保证请求帧 i 总是返回帧 i,但这需要对文件进行初始扫描。近似模式速度更快,因为它避免了扫描文件,但准确性较低,因为它使用文件的元数据来计算 i 可能的位置。更多信息请阅读这里

Video Feature (视频特征) 用于从视频文件中读取视频数据。

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

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

  • 一个包含以下键的 dict

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

    这对于嵌入视频文件的 parquet 或 webdataset 文件很有用。

  • 一个 torchcodec.decoders.VideoDecoder:torchcodec 视频解码器对象。

输出:视频特征以 torchcodec.decoders.VideoDecoder 对象的形式输出数据。

示例

>>> from datasets import Dataset, Video
>>> ds = Dataset.from_dict({"video":["path/to/Screen Recording.mov"]}).cast_column("video", Video())
>>> ds.features["video"]
Video(decode=True, id=None)
>>> ds[0]["video"]
<torchcodec.decoders._video_decoder.VideoDecoder object at 0x14a61e080>
>>> video = ds[0]["video"]
>>> video.get_frames_in_range(0, 10)
FrameBatch:
data (shape): torch.Size([10, 3, 50, 66])
pts_seconds: tensor([0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333,
        0.4333], dtype=torch.float64)
duration_seconds: tensor([0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167,
        0.0167], dtype=torch.float64)
>>> ds.cast_column('video', Video(decode=False))[0]["video]
{'bytes': None,
 'path': 'path/to/Screen Recording.mov'}

cast_storage

< >

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

参数

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

返回

pa.StructArray

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

将 Arrow 数组转换为 Video Arrow 存储类型。可转换为 Video PyArrow 存储类型的 Arrow 类型包括:

  • pa.string() - 必须包含 "path" 数据
  • pa.binary() - 必须包含视频字节数据
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 顺序无关
  • pa.list(*) - 必须包含视频数组数据

decode_example

< >

( value: typing.Union[str, datasets.features.video.Example] token_per_repo_id: typing.Optional[dict[str, typing.Union[bool, str]]] = None )

参数

  • value (strdict) — 包含视频文件绝对路径的字符串,或包含以下键的字典:

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

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

encode_example

< >

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

参数

  • value (str, np.ndarray, bytes, bytearray, VideoDecoderdict) — 传递给视频特征作为输入的数据。

将样本编码为 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 文件中读取 pdf 文档的 Pdf Feature

输入: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 数据。

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

参数

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

返回

pa.StructArray

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

将 PDF 文件嵌入到 Arrow 数组中。

encode_example

< >

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

参数

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

将样本编码为 Arrow 格式。

flatten

< >

( )

如果处于可解码状态,则返回特征本身,否则将特征展平为字典。

文件系统

datasets.filesystems.is_remote_filesystem

< >

( fs: AbstractFileSystem )

参数

  • fs (fsspec.spec.AbstractFileSystem) — Pythonic 文件系统的抽象超类,例如 fsspec.filesystem('file')s3fs.S3FileSystem

检查 fs 是否为远程文件系统。

指纹

class datasets.fingerprint.Hasher

< >

( )

接受 python 对象作为输入的哈希器。

< > 在 GitHub 上更新