Datasets documentation
构建器类
构建器类
构建者
🤗 Datasets 在构建数据集的过程中主要依赖两个类:DatasetBuilder 和 BuilderConfig。
类 datasets.DatasetBuilder
< source >( cache_dir: typing.Optional[str] = Nonedataset_name: typing.Optional[str] = Noneconfig_name: typing.Optional[str] = Nonehash: typing.Optional[str] = Nonebase_path: typing.Optional[str] = Noneinfo: typing.Optional[datasets.info.DatasetInfo] = Nonefeatures: typing.Optional[datasets.features.features.Features] = Nonetoken: typing.Union[bool, str, NoneType] = Nonerepo_id: typing.Optional[str] = Nonedata_files: typing.Union[str, list, dict, datasets.data_files.DataFilesDict, NoneType] = Nonedata_dir: typing.Optional[str] = Nonestorage_options: typing.Optional[dict] = Nonewriter_batch_size: typing.Optional[int] = Noneconfig_id: typing.Optional[str] = None**config_kwargs )
参数
- cache_dir (
str, 可选) — 用于缓存数据的目录。默认为"~/.cache/huggingface/datasets"。 - dataset_name (
str, 可选) — 数据集的名称,如果与构建器名称不同。对于 csv、imagefolder、audiofolder 等打包构建器,此参数可用于区分使用相同打包构建器的不同数据集。 - 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 类型。 例如,可用于更改数据集的 Features 类型。
- token (
str或bool,可选) — 用作 Datasets Hub 上远程文件 Bearer token 的字符串或布尔值。如果为True,则从"~/.huggingface"获取 token。 - repo_id (
str, 可选) — 数据集仓库的 ID。 用于区分同名但来自不同命名空间的构建器,例如 “rajpurkar/squad” 和 “lhoestq/squad” 仓库 ID。在后一种情况下,构建器名称为 “lhoestq___squad”。 - data_files (
str或Sequence或Mapping,可选) — 源数据文件的路径。 适用于需要用户指定数据文件的构建器,例如 “csv” 或 “json”。这些文件可以是本地文件或远程文件。为了方便起见,您可以使用DataFilesDict。 - data_dir (
str, 可选) — 包含源数据文件的目录路径。 仅在未传入data_files时使用,此时其效果等同于将os.path.join(data_dir, "**")作为data_files传入。 对于需要手动下载的 builder,它必须是包含手动下载数据的本地目录路径。 - storage_options (
dict, 可选) — 要传递给数据集文件系统后端的键值对(如果存在)。 - writer_batch_size (
int, 可选) — ArrowWriter 使用的批处理大小。 它定义了写入前在内存中保留的样本数量,同时也决定了 arrow 块(chunks)的长度。 None 表示 ArrowWriter 将使用其默认值。 - **config_kwargs(额外的关键字参数)— 传递给对应构建器配置类(该类设置在类属性 DatasetBuilder.BUILDER_CONFIG_CLASS 上)的关键字参数。构建器配置类为 BuilderConfig 或其子类。
所有数据集的抽象基类。
DatasetBuilder 有 3 个关键方法:
DatasetBuilder.info:记录数据集的文档信息,包括特征名称、类型、形状、版本、数据划分、引用等。- DatasetBuilder.download_and_prepare():下载源数据并将其写入磁盘。
- DatasetBuilder.as_dataset():生成一个 Dataset。
一些 DatasetBuilder 通过定义 BuilderConfig 子类并在构造时接受配置对象(或名称)来公开数据集的多个变体。可配置的数据集会在 DatasetBuilder.builder_configs() 中公开一组预定义的配置。
as_dataset
< source >( split: typing.Union[str, datasets.splits.Split, list[str], list[datasets.splits.Split], NoneType] = Nonein_memory = False )
参数
- split (
datasets.Split) — 要返回的数据子集。 - verification_mode (VerificationMode 或
str, 默认为BASIC_CHECKS) — 验证模式,用于确定在下载/处理后的数据集信息(校验和/大小/分片/…)上运行的检查。2.9.1 版本新增
- in_memory (
bool,默认为False) — 是否将数据复制到内存中。
返回指定 split 的 Dataset。
download_and_prepare
< source >( output_dir: typing.Optional[str] = Nonedownload_config: typing.Optional[datasets.download.download_config.DownloadConfig] = Nonedownload_mode: typing.Union[datasets.download.download_manager.DownloadMode, str, NoneType] = Noneverification_mode: typing.Union[datasets.utils.info_utils.VerificationMode, str, NoneType] = Nonedl_manager: typing.Optional[datasets.download.download_manager.DownloadManager] = Nonebase_path: typing.Optional[str] = Nonefile_format: str = 'arrow'max_shard_size: typing.Union[str, int, NoneType] = Nonenum_proc: typing.Optional[int] = Nonestorage_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() 作为 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")返回此类或其子类的模块路径。
类 datasets.GeneratorBasedBuilder
< source >( cache_dir: typing.Optional[str] = Nonedataset_name: typing.Optional[str] = Noneconfig_name: typing.Optional[str] = Nonehash: typing.Optional[str] = Nonebase_path: typing.Optional[str] = Noneinfo: typing.Optional[datasets.info.DatasetInfo] = Nonefeatures: typing.Optional[datasets.features.features.Features] = Nonetoken: typing.Union[bool, str, NoneType] = Nonerepo_id: typing.Optional[str] = Nonedata_files: typing.Union[str, list, dict, datasets.data_files.DataFilesDict, NoneType] = Nonedata_dir: typing.Optional[str] = Nonestorage_options: typing.Optional[dict] = Nonewriter_batch_size: typing.Optional[int] = Noneconfig_id: typing.Optional[str] = None**config_kwargs )
基于字典生成器进行数据生成的数据集的基类。
GeneratorBasedBuilder 是一个便捷类,它抽象了 DatasetBuilder 中大部分的数据写入和读取操作。它要求子类实现针对数据集各个拆分(_split_generators)的特征字典生成器。有关详细信息,请参阅方法的文档字符串。
类 datasets.ArrowBasedBuilder
< source >( cache_dir: typing.Optional[str] = Nonedataset_name: typing.Optional[str] = Noneconfig_name: typing.Optional[str] = Nonehash: typing.Optional[str] = Nonebase_path: typing.Optional[str] = Noneinfo: typing.Optional[datasets.info.DatasetInfo] = Nonefeatures: typing.Optional[datasets.features.features.Features] = Nonetoken: typing.Union[bool, str, NoneType] = Nonerepo_id: typing.Optional[str] = Nonedata_files: typing.Union[str, list, dict, datasets.data_files.DataFilesDict, NoneType] = Nonedata_dir: typing.Optional[str] = Nonestorage_options: typing.Optional[dict] = Nonewriter_batch_size: typing.Optional[int] = Noneconfig_id: typing.Optional[str] = None**config_kwargs )
基于 Arrow 加载函数(CSV/JSON/Parquet)进行数据生成的数据集基类。
类 datasets.BuilderConfig
< source >( name: str = 'default'version: typing.Union[datasets.utils.version.Version, str, NoneType] = 0.0.0data_dir: typing.Optional[str] = Nonedata_files: typing.Union[datasets.data_files.DataFilesDict, datasets.data_files.DataFilesPatternsDict, NoneType] = Nonedescription: typing.Optional[str] = None )
DatasetBuilder 数据配置的基础类。
带有数据配置选项的 DatasetBuilder 子类应继承 BuilderConfig 并添加自己的属性。
create_config_id
< source >( config_kwargs: dictcustom_features: typing.Optional[datasets.features.features.Features] = None )
config id 用于构建缓存目录。 默认情况下,它等于 config 名称。 然而,config 的名称不足以作为正在生成的数据集的唯一标识符, 因为它没有考虑到:
- 可用于覆盖属性的 config kwargs
- 用于编写数据集的自定义特征
- json/text/csv/pandas 数据集的 data_files
因此,config id 就是 config 名称加上基于这些的可选后缀。
下载
类 datasets.DownloadManager
< source >( dataset_name: typing.Optional[str] = Nonedata_dir: typing.Optional[str] = Nonedownload_config: typing.Optional[datasets.download.download_config.DownloadConfig] = Nonebase_path: typing.Optional[str] = Nonerecord_checksums = False )
下载
< source >( url_or_urls ) → str or list or dict
下载给定的 URL。
默认情况下,仅使用一个进程进行下载。传入自定义的 download_config.num_proc 以更改此行为。
download_and_extract
< source >( url_or_urls ) → extracted_path(s)
下载并解压给定的url_or_urls。
extract
< source >( path_or_paths ) → extracted_path(s)
提取给定的路径。
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
遍历文件路径。
类 datasets.StreamingDownloadManager
< source >( dataset_name: typing.Optional[str] = Nonedata_dir: typing.Optional[str] = Nonedownload_config: typing.Optional[datasets.download.download_config.DownloadConfig] = Nonebase_path: typing.Optional[str] = None )
使用“::”分隔符来导航(可能位于远程的)压缩归档文件的下载管理器。
与常规的DownloadManager不同,download和extract方法实际上并不会下载或解压数据,而是返回一个路径或 URL,该路径或 URL 可以使用xopen函数打开。此函数扩展了内置的open函数,以从远程文件流式传输数据。
下载
< source >( url_or_urls ) → url(s)
规范化用于流式传输数据的文件 URL。
这是 DownloadManager.download 的流式传输惰性版本。
download_and_extract
< source >( url_or_urls ) → url(s)
为给定的 url_or_urls 准备流式传输(添加提取协议)。
这是DownloadManager.download_and_extract的流式处理惰性版本。
extract
< source >( url_or_urls ) → url(s)
为流式处理添加针对给定 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
遍历文件。
类 datasets.DownloadConfig
< source >( cache_dir: typing.Union[str, pathlib.Path, NoneType] = Noneforce_download: bool = Falseresume_download: bool = Falselocal_files_only: bool = Falseproxies: typing.Optional[dict] = Noneuser_agent: typing.Optional[str] = Noneextract_compressed_file: bool = Falseforce_extract: bool = Falsedelete_extracted: bool = Falseextract_on_the_fly: bool = Falseuse_etag: bool = Truenum_proc: typing.Optional[int] = Nonemax_retries: int = 1token: typing.Union[str, bool, NoneType] = Nonestorage_options: dict = <factory>download_desc: typing.Optional[str] = Nonedisable_tqdm: bool = False )
参数
- cache_dir (
str或Path,可选) — 指定用于保存文件的缓存目录(覆盖默认缓存目录)。 - force_download (
bool,默认为False) — 如果为True,即使文件已缓存在缓存目录中,也会重新下载该文件。 - resume_download (
bool,默认为False) — 如果为True,当发现未完整接收的文件时,继续下载。 - proxies (
dict, 可选) — 已弃用且被忽略。请改为设置HTTP_PROXY/HTTPS_PROXY环境变量,或使用 huggingface_hub.set_client_factory 配置 HTTP 客户端。 - user_agent (
str, 可选) — 可选的字符串或字典,将附加到远程请求的 user-agent 中。 - extract_compressed_file (
bool,默认为False) — 如果为True且路径指向 zip 或 tar 文件,则将该压缩文件解压到与归档文件同级的文件夹中。 - force_extract (
bool,默认为False) — 如果True,且extract_compressed_file为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 token。如果为True或未指定,则从~/.huggingface获取 token。 - storage_options (
dict, 可选) — 要传递给数据集文件系统后端的键值对(如果存在)。 - download_desc (
str, 可选) — 在下载文件时,与进度条一同显示的说明。 - disable_tqdm (
bool,默认为False) — 是否禁用单个文件的下载进度条
我们缓存路径管理器的配置。
class datasets.DownloadMode
< source >( valuenames = Nonemodule = Nonequalname = Nonetype = Nonestart = 1 )
Enum,用于指定如何处理已存在的下载和数据。
默认模式为 REUSE_DATASET_IF_EXISTS,如果原始下载文件和已准备好的数据集存在,则会同时复用它们。
生成模式:
| 下载 | 数据集 | |
|---|---|---|
REUSE_DATASET_IF_EXISTS(默认) | 复用 | 复用 |
REUSE_CACHE_IF_EXISTS | 复用 | 新鲜 |
FORCE_REDOWNLOAD | 新鲜 | 新鲜 |
验证
class datasets.VerificationMode
< source >( valuenames = Nonemodule = Nonequalname = Nonetype = Nonestart = 1 )
Enum,用于指定要运行哪些验证检查。
默认模式为 BASIC_CHECKS,该模式仅执行基础检查,以避免在首次生成/下载数据集时造成速度变慢。
验证模式:
| 验证检查 | |
|---|---|
ALL_CHECKS | 拆分检查以及已下载文件的有效性(文件数量、校验和) |
BASIC_CHECKS(默认) | 与 ALL_CHECKS 相同,但不检查已下载的文件 |
NO_CHECKS | 无 |
拆分
类 datasets.SplitGenerator
< source >( name: strgen_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,因此以下操作将会失败:
split = (
datasets.Split.TRAIN.subsplit(datasets.percent[:25]) +
datasets.Split.TRAIN.subsplit(datasets.percent[75:])
) # Error
split = datasets.Split.TEST + datasets.Split.ALL # Error对应于所有已定义数据集分割的并集的分割。
用于数据集的读取指令。
示例:
# The following lines are equivalent:
ds = datasets.load_dataset('ylecun/mnist', split='test[:33%]')
ds = datasets.load_dataset('ylecun/mnist', split=datasets.ReadInstruction.from_spec('test[:33%]'))
ds = datasets.load_dataset('ylecun/mnist', split=datasets.ReadInstruction('test', to=33, unit='%'))
ds = datasets.load_dataset('ylecun/mnist', split=datasets.ReadInstruction(
'test', from_=0, to=33, unit='%'))
# The following lines are equivalent:
ds = datasets.load_dataset('ylecun/mnist', split='test[:33%]+train[1:-1]')
ds = datasets.load_dataset('ylecun/mnist', split=datasets.ReadInstruction.from_spec(
'test[:33%]+train[1:-1]'))
ds = datasets.load_dataset('ylecun/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('ylecun/mnist', split='test[:33%](pct1_dropremainder)')
ds = datasets.load_dataset('ylecun/mnist', split=datasets.ReadInstruction.from_spec(
'test[:33%](pct1_dropremainder)'))
ds = datasets.load_dataset('ylecun/mnist', split=datasets.ReadInstruction(
'test', from_=0, to=33, unit='%', rounding="pct1_dropremainder"))
# 10-fold validation:
tests = datasets.load_dataset(
'ylecun/mnist',
[datasets.ReadInstruction('train', from_=k, to=k+10, unit='%')
for k in range(0, 100, 10)])
trains = datasets.load_dataset(
'ylecun/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.将翻译指令转换为绝对指令列表。
然后,将这些绝对指令相加。
版本
类 datasets.Version
< source >( version_str: strdescription: typing.Optional[str] = Nonemajor: typing.Union[str, int, NoneType] = Noneminor: typing.Union[str, int, NoneType] = Nonepatch: typing.Union[str, int, NoneType] = None )
数据集版本 MAJOR.MINOR.PATCH。