Datasets 文档
Builder 类
并获得增强的文档体验
开始使用
Builder 类
Builders
🤗 Datasets 在数据集构建过程中依赖于两个主要类:DatasetBuilder 和 BuilderConfig。
class datasets.DatasetBuilder
< source >( cache_dir: typing.Optional[str] = None dataset_name: typing.Optional[str] = None config_name: typing.Optional[str] = None hash: typing.Optional[str] = None base_path: typing.Optional[str] = None info: typing.Optional[datasets.info.DatasetInfo] = None features: typing.Optional[datasets.features.features.Features] = None token: typing.Union[bool, str, NoneType] = None repo_id: typing.Optional[str] = None data_files: typing.Union[str, list, dict, datasets.data_files.DataFilesDict, NoneType] = None data_dir: typing.Optional[str] = None storage_options: typing.Optional[dict] = None writer_batch_size: typing.Optional[int] = None **config_kwargs )
参数
- cache_dir (
str
, 可选) — 用于缓存数据的目录。默认为"~/.cache/huggingface/datasets"
。 - dataset_name (
str
, 可选) — 数据集的名称,如果与 builder 名称不同。对于打包的 builder(如 csv、imagefolder、audiofolder 等),用于反映使用相同打包 builder 的数据集之间的差异。 - config_name (
str
, 可选) — 数据集配置的名称。它会影响磁盘上生成的数据。不同的配置将有其自己的子目录和版本。如果未提供,则使用默认配置(如果存在)。在 2.3.0 版本中添加
参数
name
已重命名为config_name
。 - hash (
str
, 可选) — 数据集代码特定的哈希值。用于在数据集加载脚本代码更新时更新缓存目录(以避免重用旧数据)。典型的缓存目录(在self._relative_data_dir
中定义)是name/version/hash/
。 - base_path (
str
, 可选) — 用于下载文件的相对路径的基本路径。这可以是远程 URL。 - features (Features, 可选) — 要用于此数据集的特征类型。例如,可用于更改数据集的 Features 类型。
- token (
str
或bool
, 可选) — 用作 Datasets Hub 上远程文件的 Bearer token 的字符串或布尔值。如果为True
,将从"~/.huggingface"
获取 token。 - repo_id (
str
, 可选) — 数据集仓库的 ID。用于区分具有相同名称但来自不同命名空间的 builder,例如 “rajpurkar/squad” 和 “lhoestq/squad” 仓库 ID。在后者中,builder 名称将为 “lhoestq___squad”。 - data_files (
str
或Sequence
或Mapping
, 可选) — 源数据文件的路径。对于像 “csv” 或 “json” 这样需要用户指定数据文件的 builder。它们可以是本地文件或远程文件。为了方便起见,您可以使用DataFilesDict
。 - data_dir (
str
, 可选) — 包含源数据文件的目录路径。仅当未传递data_files
时使用,在这种情况下,它等效于将os.path.join(data_dir, "**")
作为data_files
传递。对于需要手动下载的 builder,它必须是包含手动下载数据的本地目录的路径。 - storage_options (
dict
, 可选) — 要传递给数据集文件系统后端的键/值对(如果有)。 - writer_batch_size (
int
, 可选) — ArrowWriter 使用的批量大小。它定义了在写入内存之前保存在内存中的样本数以及 arrow 块的长度。None 表示 ArrowWriter 将使用其默认值。 - **config_kwargs (附加的关键字参数) — 要传递给相应 builder 配置类的关键字参数,在类属性 DatasetBuilder.BUILDER_CONFIG_CLASS 上设置。builder 配置类是 BuilderConfig 或其子类。
所有数据集的抽象基类。
DatasetBuilder
具有 3 个关键方法
DatasetBuilder.info
:记录数据集,包括特征名称、类型、形状、版本、分割、引用等。- DatasetBuilder.download_and_prepare():下载源数据并将其写入磁盘。
- DatasetBuilder.as_dataset():生成 Dataset。
一些 DatasetBuilder
通过定义 BuilderConfig 子类并在构造时接受配置对象(或名称)来公开数据集的多个变体。可配置数据集在 DatasetBuilder.builder_configs()
中公开预定义的配置集。
as_dataset
< source >( split: typing.Optional[datasets.splits.Split] = None run_post_process = True verification_mode: typing.Union[datasets.utils.info_utils.VerificationMode, str, NoneType] = None in_memory = False )
参数
- split (
datasets.Split
) — 要返回的数据子集。 - run_post_process (
bool
, 默认为True
) — 是否运行后处理数据集转换和/或添加索引。 - verification_mode (VerificationMode 或
str
, 默认为BASIC_CHECKS
) — 验证模式,决定在下载/处理的数据集信息(校验和/大小/切分/...)上运行的检查。在 2.9.1 中添加
- in_memory (
bool
, 默认为False
) — 是否将数据复制到内存中。
返回指定切分的数据集。
download_and_prepare
< source >( output_dir: typing.Optional[str] = None download_config: typing.Optional[datasets.download.download_config.DownloadConfig] = None download_mode: typing.Union[datasets.download.download_manager.DownloadMode, str, NoneType] = None verification_mode: typing.Union[datasets.utils.info_utils.VerificationMode, str, NoneType] = None dl_manager: typing.Optional[datasets.download.download_manager.DownloadManager] = None base_path: typing.Optional[str] = None file_format: str = 'arrow' max_shard_size: typing.Union[str, int, NoneType] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **download_and_prepare_kwargs )
参数
- output_dir (
str
, 可选) — 数据集的输出目录。默认为此构建器的cache_dir
,默认情况下位于~/.cache/huggingface/datasets
内。在 2.5.0 中添加
- download_config (
DownloadConfig
, 可选) — 特定的下载配置参数。 - download_mode (DownloadMode 或
str
, 可选) — 选择下载/生成模式,默认为REUSE_DATASET_IF_EXISTS
。 - verification_mode (VerificationMode 或
str
, 默认为BASIC_CHECKS
) — 验证模式,决定在下载/处理的数据集信息(校验和/大小/切分/...)上运行的检查。在 2.9.1 中添加
- dl_manager (
DownloadManager
, 可选) — 要使用的特定DownloadManger
。 - base_path (
str
, 可选) — 用于下载文件的相对路径的基本路径。这可以是远程 URL。如果未指定,则将使用base_path
属性 (self.base_path
) 的值。 - file_format (
str
, 可选) — 数据集将写入的数据文件格式。支持的格式:“arrow”、“parquet”。默认为“arrow”格式。如果格式为“parquet”,则图像和音频数据将嵌入到 Parquet 文件中,而不是指向本地文件。在 2.5.0 中添加
- max_shard_size (
Union[str, int]
, 可选) — 每个分片写入的最大字节数,默认为“500MB”。大小基于未压缩的数据大小,因此实际上,由于例如 Parquet 压缩,您的分片文件可能小于max_shard_size
。在 2.5.0 中添加
- num_proc (
int
, 可选, 默认为None
) — 本地下载和生成数据集时使用的进程数。默认情况下禁用多处理。在 2.7.0 中添加
- storage_options (
dict
, 可选) — 要传递到缓存文件系统后端(如果有)的键/值对。在 2.5.0 中添加
- **download_and_prepare_kwargs (附加关键字参数) — 关键字参数。
下载并准备数据集以供读取。
示例
以下载和准备数据集为 Arrow 文件,可以使用 builder.as_dataset()
作为数据集加载
>>> from datasets import load_dataset_builder
>>> builder = load_dataset_builder("cornell-movie-review-data/rotten_tomatoes")
>>> builder.download_and_prepare()
以下载和准备数据集为本地分片 Parquet 文件
>>> from datasets import load_dataset_builder
>>> builder = load_dataset_builder("cornell-movie-review-data/rotten_tomatoes")
>>> builder.download_and_prepare("./output_dir", file_format="parquet")
以下载和准备数据集为云存储中的分片 Parquet 文件
>>> from datasets import load_dataset_builder
>>> storage_options = {"key": aws_access_key_id, "secret": aws_secret_access_key}
>>> builder = load_dataset_builder("cornell-movie-review-data/rotten_tomatoes")
>>> builder.download_and_prepare("s3://my-bucket/my_rotten_tomatoes", storage_options=storage_options, file_format="parquet")
如果不存在,则为空字典
示例
>>> from datasets import load_dataset_builder
>>> ds_builder = load_dataset_builder('vivos')
>>> ds_builder.get_all_exported_dataset_infos()
{'default': DatasetInfo(description='', citation='', homepage='', license='', features={'speaker_id': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None), 'sentence': Value(dtype='string', id=None)}, post_processed=None, supervised_keys=None, builder_name=None, dataset_name=None, config_name='default', version=None, splits={'train': SplitInfo(name='train', num_bytes=1722002133, num_examples=11660, shard_lengths=None, dataset_name=None), 'test': SplitInfo(name='test', num_bytes=86120227, num_examples=760, shard_lengths=None, dataset_name=None)}, download_checksums=None, download_size=1475540500, post_processing_size=None, dataset_size=1808122360, size_in_bytes=None)}
如果不存在,则为空 DatasetInfo
示例
>>> from datasets import load_dataset_builder
>>> ds_builder = load_dataset_builder('cornell-movie-review-data/rotten_tomatoes')
>>> ds_builder.get_exported_dataset_info()
DatasetInfo(description='', citation='', homepage='', license='', features={'speaker_id': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None), 'sentence': Value(dtype='string', id=None)}, post_processed=None, supervised_keys=None, builder_name=None, dataset_name=None, config_name='default', version=None, splits={'train': SplitInfo(name='train', num_bytes=1722002133, num_examples=11660, shard_lengths=None, dataset_name=None), 'test': SplitInfo(name='test', num_bytes=86120227, num_examples=760, shard_lengths=None, dataset_name=None)}, download_checksums=None, download_size=1475540500, post_processing_size=None, dataset_size=1808122360, size_in_bytes=None)
返回此类或子类的模块路径。
class datasets.GeneratorBasedBuilder
< source >( cache_dir: typing.Optional[str] = None dataset_name: typing.Optional[str] = None config_name: typing.Optional[str] = None hash: typing.Optional[str] = None base_path: typing.Optional[str] = None info: typing.Optional[datasets.info.DatasetInfo] = None features: typing.Optional[datasets.features.features.Features] = None token: typing.Union[bool, str, NoneType] = None repo_id: typing.Optional[str] = None data_files: typing.Union[str, list, dict, datasets.data_files.DataFilesDict, NoneType] = None data_dir: typing.Optional[str] = None storage_options: typing.Optional[dict] = None writer_batch_size: typing.Optional[int] = None **config_kwargs )
基于字典生成器的数据集的数据生成基类。
GeneratorBasedBuilder
是一个便捷类,它抽象了 DatasetBuilder
的大部分数据写入和读取操作。它期望子类在数据集拆分 (_split_generators
) 中实现特征字典的生成器。详见方法文档字符串。
class datasets.ArrowBasedBuilder
< source >( cache_dir: typing.Optional[str] = None dataset_name: typing.Optional[str] = None config_name: typing.Optional[str] = None hash: typing.Optional[str] = None base_path: typing.Optional[str] = None info: typing.Optional[datasets.info.DatasetInfo] = None features: typing.Optional[datasets.features.features.Features] = None token: typing.Union[bool, str, NoneType] = None repo_id: typing.Optional[str] = None data_files: typing.Union[str, list, dict, datasets.data_files.DataFilesDict, NoneType] = None data_dir: typing.Optional[str] = None storage_options: typing.Optional[dict] = None writer_batch_size: typing.Optional[int] = None **config_kwargs )
基于 Arrow 加载函数(CSV/JSON/Parquet)进行数据生成的数据集基类。
class datasets.BuilderConfig
< source >( name: str = 'default' version: typing.Union[str, datasets.utils.version.Version, NoneType] = 0.0.0 data_dir: typing.Optional[str] = None data_files: typing.Union[datasets.data_files.DataFilesDict, datasets.data_files.DataFilesPatternsDict, NoneType] = None description: typing.Optional[str] = None )
DatasetBuilder
数据配置的基类。
具有数据配置选项的 DatasetBuilder
子类应继承 BuilderConfig
并添加自己的属性。
create_config_id
< source >( config_kwargs: dict custom_features: typing.Optional[datasets.features.features.Features] = None )
配置 ID 用于构建缓存目录。默认情况下,它等于配置名称。然而,配置名称不足以作为正在生成的数据集的唯一标识符,因为它没有考虑到
- 可用于覆盖属性的配置 kwargs
- 用于写入数据集的自定义特征
- json/text/csv/pandas 数据集的数据文件
因此,配置 ID 只是配置名称,带有一个基于这些内容的可选后缀。
下载
class datasets.DownloadManager
< source >( dataset_name: typing.Optional[str] = None data_dir: typing.Optional[str] = None download_config: typing.Optional[datasets.download.download_config.DownloadConfig] = None base_path: typing.Optional[str] = None record_checksums = True )
download
< source >( url_or_urls ) → str
或 list
或 dict
下载给定的 URL。
默认情况下,下载仅使用一个进程。传递自定义的 download_config.num_proc
可以更改此行为。
download_and_extract
< source >( url_or_urls ) → 提取路径
下载并提取给定的 url_or_urls
。
extract
< source >( path_or_paths ) → 提取路径
提取给定的路径。
iter_archive
< source >( path_or_buf: typing.Union[str, _io.BufferedReader] ) → tuple[str, io.BufferedReader]
迭代处理归档文件中的文件。
iter_files
< source >( paths: typing.Union[str, list[str]] ) → str
迭代处理文件路径。
class datasets.StreamingDownloadManager
< source >( dataset_name: typing.Optional[str] = None data_dir: typing.Optional[str] = None download_config: typing.Optional[datasets.download.download_config.DownloadConfig] = None base_path: typing.Optional[str] = None )
下载管理器,它使用 ”::” 分隔符来导航(可能是远程的)压缩归档文件。与常规 DownloadManager
相反,download
和 extract
方法实际上并不下载或提取数据,而是返回可以使用 xopen
函数打开的路径或 URL,该函数扩展了内置的 open
函数以从远程文件流式传输数据。
download
< source >( url_or_urls ) → URL
规范化用于流式传输数据的文件 URL。这是用于流式传输的 DownloadManager.download
的惰性版本。
download_and_extract
< source >( url_or_urls ) → URL
准备给定的 url_or_urls 以进行流式传输(添加提取协议)。
这是用于流式传输的 DownloadManager.download_and_extract
的惰性版本。
extract
< source >( url_or_urls ) → URL
为给定的 URL 添加提取协议,以便进行流式传输。
这是 DownloadManager.extract
的惰性版本,用于流式传输。
iter_archive
< source >( urlpath_or_buf: typing.Union[str, _io.BufferedReader] ) → tuple[str, io.BufferedReader]
迭代处理归档文件中的文件。
iter_files
< source >( urlpaths: typing.Union[str, list[str]] ) → str
迭代文件。
class datasets.DownloadConfig
< source >( cache_dir: typing.Union[str, pathlib.Path, NoneType] = None force_download: bool = False resume_download: bool = False local_files_only: bool = False proxies: typing.Optional[dict] = None user_agent: typing.Optional[str] = None extract_compressed_file: bool = False force_extract: bool = False delete_extracted: bool = False extract_on_the_fly: bool = False use_etag: bool = True num_proc: typing.Optional[int] = None max_retries: int = 1 token: typing.Union[str, bool, NoneType] = None storage_options: dict = <factory> download_desc: typing.Optional[str] = None disable_tqdm: bool = False )
参数
- cache_dir (
str
或Path
, 可选) — 指定用于保存文件的缓存目录(覆盖默认缓存目录)。 - force_download (
bool
, 默认为False
) — 如果为True
,即使文件已缓存在缓存目录中,也重新下载文件。 - resume_download (
bool
, 默认为False
) — 如果为True
,如果找到未完整接收的文件,则恢复下载。 - proxies (
dict
, 可选) — - user_agent (
str
, 可选) — 可选的字符串或字典,将附加到远程请求的用户代理中。 - extract_compressed_file (
bool
, 默认为False
) — 如果为True
且路径指向 zip 或 tar 文件,则将压缩文件提取到与归档文件同名的文件夹中。 - force_extract (
bool
, 默认为False
) — 如果extract_compressed_file
为True
且归档文件已提取,则当此项为True
时,重新提取归档文件并覆盖其提取到的文件夹。 - delete_extracted (
bool
, 默认为False
) — 是否删除(或保留)提取的文件。 - extract_on_the_fly (
bool
, 默认为False
) — 如果为True
,则在读取压缩文件时对其进行解压缩。 - use_etag (
bool
, 默认为True
) — 是否使用 ETag HTTP 响应标头来验证缓存文件。 - num_proc (
int
, 可选) — 用于并行下载文件的进程数。 - max_retries (
int
, 默认为1
) — HTTP 请求失败时,重试的次数。 - token (
str
或bool
, 可选) — 可选的字符串或布尔值,用作 Datasets Hub 上远程文件的 Bearer 令牌。如果为True
,或未指定,将从~/.huggingface
获取令牌。 - storage_options (
dict
, 可选) — 键/值对,如果存在,将传递到数据集文件系统后端。 - download_desc (
str
, 可选) — 下载文件时,进度条旁边显示的描述。 - disable_tqdm (
bool
, 默认为False
) — 是否禁用单个文件下载进度条
我们缓存路径管理器的配置。
class datasets.DownloadMode
< source >( value names = None module = None qualname = None type = None start = 1 )
Enum
用于说明如何处理预先存在的下载和数据。
默认模式为 REUSE_DATASET_IF_EXISTS
,如果原始下载和准备好的数据集都存在,则都将重用。
生成模式
下载 | 数据集 | |
---|---|---|
REUSE_DATASET_IF_EXISTS (默认) | 重用 | 重用 |
REUSE_CACHE_IF_EXISTS | 重用 | 全新 |
FORCE_REDOWNLOAD | 全新 | 全新 |
验证
class datasets.VerificationMode
< source >( value names = None module = None qualname = None type = None start = 1 )
Enum
,用于指定要运行的验证检查。
默认模式为 BASIC_CHECKS
,它将仅执行基本的检查,以避免在首次生成/下载数据集时减慢速度。
验证模式
验证检查 | |
---|---|
ALL_CHECKS | 拆分检查,在 GeneratorBuilder 的情况下,检查所产生键的唯一性 |
以及下载文件的有效性(文件数、校验和等) | |
BASIC_CHECKS (默认) | 与 ALL_CHECKS 相同,但不检查下载的文件 |
NO_CHECKS | 无 |
拆分
class datasets.SplitGenerator
< source >( name: str gen_kwargs: dict = <factory> )
定义生成器的拆分信息。
这应该用作 GeneratorBasedBuilder._split_generators
的返回值。有关更多信息和用法示例,请参阅 GeneratorBasedBuilder._split_generators
。
数据集拆分的 Enum
。
数据集通常拆分为不同的子集,用于训练和评估的各个阶段。
TRAIN
:训练数据。VALIDATION
:验证数据。 如果存在,则通常在迭代模型时(例如,更改超参数、模型架构等)用作评估数据。TEST
:测试数据。 这是用于报告指标的数据。 通常,您不希望在模型迭代期间使用它,因为您可能会对其过度拟合。ALL
:所有已定义数据集拆分的并集。
所有拆分,包括组合,都继承自 datasets.SplitBase
。
有关更多信息,请参阅关于拆分的指南。
示例
>>> datasets.SplitGenerator(
... name=datasets.Split.TRAIN,
... gen_kwargs={"split_key": "train", "files": dl_manager.download_and extract(url)},
... ),
... datasets.SplitGenerator(
... name=datasets.Split.VALIDATION,
... gen_kwargs={"split_key": "validation", "files": dl_manager.download_and extract(url)},
... ),
... datasets.SplitGenerator(
... name=datasets.Split.TEST,
... gen_kwargs={"split_key": "test", "files": dl_manager.download_and extract(url)},
... )
对应于命名拆分(train、test 等)的描述符。
示例
每个描述符都可以通过加法或切片与其他描述符组合
split = datasets.Split.TRAIN.subsplit(datasets.percent[0:25]) + datasets.Split.TEST
结果拆分将对应于 25% 的训练拆分与 100% 的测试拆分合并。
一个拆分不能被添加两次,所以以下操作将会失败
split = (
datasets.Split.TRAIN.subsplit(datasets.percent[:25]) +
datasets.Split.TRAIN.subsplit(datasets.percent[75:])
) # Error
split = datasets.Split.TEST + datasets.Split.ALL # Error
对应于所有已定义数据集拆分并集的拆分。
class datasets.ReadInstruction
< source >( split_name rounding = None from_ = None to = None unit = None )
数据集的读取指令。
示例
# The following lines are equivalent:
ds = datasets.load_dataset('mnist', split='test[:33%]')
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction.from_spec('test[:33%]'))
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction('test', to=33, unit='%'))
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction(
'test', from_=0, to=33, unit='%'))
# The following lines are equivalent:
ds = datasets.load_dataset('mnist', split='test[:33%]+train[1:-1]')
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction.from_spec(
'test[:33%]+train[1:-1]'))
ds = datasets.load_dataset('mnist', split=(
datasets.ReadInstruction('test', to=33, unit='%') +
datasets.ReadInstruction('train', from_=1, to=-1, unit='abs')))
# The following lines are equivalent:
ds = datasets.load_dataset('mnist', split='test[:33%](pct1_dropremainder)')
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction.from_spec(
'test[:33%](pct1_dropremainder)'))
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction(
'test', from_=0, to=33, unit='%', rounding="pct1_dropremainder"))
# 10-fold validation:
tests = datasets.load_dataset(
'mnist',
[datasets.ReadInstruction('train', from_=k, to=k+10, unit='%')
for k in range(0, 100, 10)])
trains = datasets.load_dataset(
'mnist',
[datasets.ReadInstruction('train', to=k, unit='%') + datasets.ReadInstruction('train', from_=k+10, unit='%')
for k in range(0, 100, 10)])
from_spec
< source >( spec )
从字符串规范创建 ReadInstruction
实例。
示例
test: test split.
test + validation: test split + validation split.
test[10:]: test split, minus its first 10 records.
test[:10%]: first 10% records of test split.
test[:20%](pct1_dropremainder): first 10% records, rounded with the pct1_dropremainder rounding.
test[:-5%]+train[40%:60%]: first 95% of test + middle 20% of train.
将指令转换为绝对指令列表。
这些绝对指令随后将被加在一起。
Version
class datasets.Version
< source >( version_str: str description: typing.Optional[str] = None major: typing.Union[str, int, NoneType] = None minor: typing.Union[str, int, NoneType] = None patch: typing.Union[str, int, NoneType] = None )
数据集版本 MAJOR.MINOR.PATCH
。