Datasets 文档
主要类
并获得增强的文档体验
开始使用
主类
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 (
str
或 Version, 可选) — 数据集的版本。 - 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` 中的 JSON 文件创建 DatasetInfo。
此函数会更新 DatasetInfo 的所有动态生成字段(例如,示例数量、哈希值、创建时间等)。
这将覆盖所有先前的元数据。
write_to_directory
< 来源 >( dataset_info_dir pretty_print = False storage_options: typing.Optional[dict] = None )
将 `DatasetInfo` 和许可证(如果存在)作为 JSON 文件写入 `dataset_info_dir`。
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 )
向数据集中添加列。
在 1.7 版本中新增
向数据集中添加项目。
在 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 )
实例化一个由位于指定文件名的 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 )
实例化一个由 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 重新加载。
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 toFalse
) — 是否将数据复制到内存中。 - gen_kwargs(
dict
, optional) — 将传递给 `generator` 可调用对象的关键字参数。您可以通过在 `gen_kwargs` 中传递分片列表并将 `num_proc` 设置为大于 1 的值来定义分片数据集。 - num_proc (
int
, optional, defaults toNone
) — 在本地下载和生成数据集时的进程数。如果数据集由多个文件组成,这会很有帮助。多进程处理默认是禁用的。如果 `num_proc` 大于 1,则 `gen_kwargs` 中的所有列表值必须具有相同的长度。这些值将在对生成器的调用之间进行分割。分片的数量将是 `gen_kwargs` 中最短列表的长度与 `num_proc` 之间的最小值。2.7.0 版本新增
- split (NamedSplit, defaults to
Split.TRAIN
) — 分配给数据集的拆分名称。2.21.0 版本新增
- **kwargs (附加关键字参数) — 将传递给 :`GeneratorConfig` 的关键字参数。
从生成器创建数据集。
支持该数据集的 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]]
包含支持该数据集的 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'}]
数据集中的列数。
数据集中的行数(与 Dataset.len() 相同)。
数据集中的列名。
数据集的形状(列数,行数)。
flatten
< 源码 >( new_fingerprint: typing.Optional[str] = None max_depth = 16 ) → Dataset
参数
返回
一份列已展平的数据集副本。
展平表格。每个具有结构类型的列都将展平为每个结构字段一个列。其他列保持不变。
示例
>>> 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 to1000
) — 提供给 cast 的每批样本数。如果 `batch_size <= 0` 或 `batch_size == None`,则将整个数据集作为一个批次提供给 cast。 - keep_in_memory (
bool
, defaults toFalse
) — 是否将数据复制到内存中。 - load_from_cache_file (
bool
, defaults toTrue
if caching is enabled) — 如果可以识别存储当前 `function` 计算结果的缓存文件,则使用它而不是重新计算。 - cache_file_name (
str
, optional, defaults toNone
) — 提供缓存文件的路径名称。它用于存储计算结果,而不是使用自动生成的缓存文件名。 - writer_batch_size (
int
, defaults to1000
) — 缓存文件写入器的每次写入操作的行数。此值在处理过程中的内存使用和处理速度之间是一个很好的权衡。较高的值使处理过程中的查找次数减少,较低的值在运行 map() 时消耗较少的临时内存。 - num_proc (
int
, optional, defaults toNone
) — 多进程处理的进程数。默认情况下不使用多进程处理。
返回
一份具有转换后特征的数据集副本。
将数据集转换为一组新的特征。
示例
>>> 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 )
将列转换为特征以进行解码。
示例
>>> 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
移除数据集中的一列或多列以及与之相关的特征。
您也可以使用带有 `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
重命名数据集中的一列,并将与原始列关联的特征移动到新的列名下。
rename_columns
< 源码 >( column_mapping: dict new_fingerprint: typing.Optional[str] = None ) → Dataset
重命名数据集中的多个列,并将与原始列关联的特征移动到新的列名下。
select_columns
< 源码 >( column_names: typing.Union[str, list[str]] new_fingerprint: typing.Optional[str] = None ) → Dataset
选择数据集中的一列或多列以及与之相关的特征。
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')}
数据集中的行数。
iter
< source >( batch_size: int drop_last_batch: bool = False )
按批次大小 batch_size 遍历。
如果使用 [~datasets.Dataset.set_format] 设置了格式,将返回所选格式的行。
formatted_as
< source >( 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.array
、torch.tensor
或tensorflow.ragged.constant
。
在 with
语句中使用。设置 __getitem__
返回格式(类型和列)。
set_format
< source >( 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.array
、torch.tensor
或tensorflow.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
< source >( 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])}
将 __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
< source >( 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.array
、torch.tensor
或tensorflow.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
< source >( 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])}
可用于索引列(通过字符串名称)或行(通过整数索引、索引的可迭代对象或布尔值)。
清理数据集缓存目录中的所有缓存文件,但当前使用的缓存文件(如果有)除外。
运行此命令时要小心,确保没有其他进程当前正在使用其他缓存文件。
map
< source >( 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=False
且with_indices=False
且with_rank=False
function(example: Dict[str, Any], *extra_args) -> Dict[str, Any]
如果batched=False
且with_indices=True
和/或with_rank=True
(每个对应一个额外参数)function(batch: Dict[str, List]) -> Dict[str, List]
如果batched=True
且with_indices=False
且with_rank=False
function(batch: Dict[str, List], *extra_args) -> Dict[str, List]
如果batched=True
且with_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 <= 0
或batch_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=1
和num_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)
过滤器
< source >( 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=False
且with_indices=False
且with_rank=False
function(example: Dict[str, Any], *extra_args) -> bool
如果batched=False
且with_indices=True
和/或with_rank=True
(每个对应一个额外参数)function(batch: Dict[str, List]) -> List[bool]
如果batched=True
且with_indices=False
且with_rank=False
function(batch: Dict[str, List], *extra_args) -> List[bool]
如果batched=True
且with_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 (
str
或List[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`。
选择
< source >( indices: Iterable keep_in_memory: bool = False indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 new_fingerprint: typing.Optional[str] = None )
参数
- indices (
range
,list
,iterable
,ndarray
或Series
) — 用于索引的整数索引的范围、列表或一维数组。如果索引对应一个连续范围,Arrow 表将被简单地切片。然而,传递一个不连续的索引列表会创建索引映射,这效率要低得多,但仍然比重新创建一个由所请求行组成的 Arrow 表要快。 - keep_in_memory (
bool
, 默认为False
) — 将索引映射保留在内存中,而不是写入缓存文件。 - indices_cache_file_name (
str
, *可选*, 默认为None
) — 提供缓存文件的路径名称。它用于存储索引映射,而不是使用自动生成的缓存文件名。 - writer_batch_size (
int
, 默认为1000
) — 缓存文件写入器的每次写入操作的行数。此值是在处理过程中的内存使用和处理速度之间的一个良好权衡。较高的值使处理过程中的查找次数减少,较低的值在运行 `map` 时消耗更少的临时内存。 - new_fingerprint (
str
, *可选*, 默认为None
) — 转换后数据集的新指纹。如果为 `None`,则使用前一个指纹的哈希值和转换参数计算新指纹。
根据索引列表/数组创建一个新的数据集,其中包含选定的行。
sort
< source >( 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
< source >( 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
创建一个新的 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 .'}]
创建一个新的 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
< source >( 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)(train
和 test
Dataset
拆分)。拆分是根据 test_size
、train_size
和 shuffle
从数据集中创建的。
此方法类似于 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`)之前,请务必进行分片。最好在数据集管道的早期使用分片操作符。
创建一个新的 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`。
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 (
int
或str
,可选,默认为 `"500MB"`) — 要上传到 hub 的数据集分片的最大大小。如果以字符串形式表示,需要是数字后跟一个单位(例如 `"5MB"`)。 - num_shards (
int
,可选) — 要写入的分片数。默认情况下,分片数取决于 `max_shard_size`。在 2.8.0 中添加
- embed_external_files (
bool
,默认为 `True`) — 是否在分片中嵌入文件字节。特别是,在推送之前,这将对以下类型的字段执行以下操作: - num_proc (
int
,可选,默认为 `None`) — 准备和上传数据集时的进程数。如果数据集由许多样本或要嵌入的媒体文件组成,这会很有帮助。默认情况下禁用多进程。在 4.0.0 中添加
将数据集作为 Parquet 数据集推送到 Hub。数据集使用 HTTP 请求推送,不需要安装 git 或 git-lfs。
默认情况下,生成的 Parquet 文件是自包含的。如果您的数据集包含 Image、Audio 或 Video 数据,Parquet 文件将存储您的图像或音频文件的字节。您可以通过将 `embed_external_files` 设置为 `False` 来禁用此功能。
示例
>>> dataset.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB")
>>> dataset.push_to_hub("<organization>/<dataset_id>", num_shards=1024)
如果您的数据集有多个拆分(例如 train/validation/test)
>>> train_dataset.push_to_hub("<organization>/<dataset_id>", split="train")
>>> val_dataset.push_to_hub("<organization>/<dataset_id>", split="validation")
>>> # later
>>> dataset = load_dataset("<organization>/<dataset_id>")
>>> train_dataset = dataset["train"]
>>> val_dataset = dataset["validation"]
如果您想向数据集添加新的配置(或子集)(例如,如果数据集有多个任务/版本/语言)
>>> english_dataset.push_to_hub("<organization>/<dataset_id>", "en")
>>> french_dataset.push_to_hub("<organization>/<dataset_id>", "fr")
>>> # later
>>> english_dataset = load_dataset("<organization>/<dataset_id>", "en")
>>> french_dataset = load_dataset("<organization>/<dataset_id>", "fr")
save_to_disk
< 源代码 >( dataset_path: typing.Union[str, bytes, os.PathLike] max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[int] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None )
参数
- dataset_path (
path-like
) — 数据集目录的路径(例如 `dataset/train`)或远程 URI(例如 `s3://my-bucket/dataset/train`),数据集将保存到此处。 - max_shard_size (
int
或str
,可选,默认为 `"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` 的任何实现保存到文件系统中。
所有的 Image()、Audio() 和 Video() 数据都存储在 arrow 文件中。如果您想存储路径或 url,请使用 Value(“string”) 类型。
load_from_disk
< 源代码 >( dataset_path: typing.Union[str, bytes, os.PathLike] keep_in_memory: typing.Optional[bool] = None storage_options: typing.Optional[dict] = None ) → Dataset 或 DatasetDict
参数
- 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 中添加
返回
- 如果 `dataset_path` 是数据集目录的路径,则返回请求的数据集。
- 如果 `dataset_path` 是数据集字典目录的路径,则返回一个包含每个拆分的 `datasets.DatasetDict`。
从数据集目录加载先前使用 `save_to_disk` 保存的数据集,或使用 `fsspec.spec.AbstractFileSystem` 的任何实现从文件系统中加载。
flatten_indices
< source >( 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
< source >( 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
orFileOrBuffer
) — 文件路径(例如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 文件。
to_pandas
< source >( batch_size: typing.Optional[int] = None batched: bool = False )
将数据集作为 pandas.DataFrame
返回。对于大型数据集,也可以返回一个生成器。
to_dict
< source >( batch_size: typing.Optional[int] = None batched: bool = False )
将数据集作为 Python 字典返回。对于大型数据集,也可以返回一个生成器。
to_json
< source >( 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
orFileOrBuffer
) — 文件路径(例如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
。
to_parquet
< source >( 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
orFileOrBuffer
) — 文件路径(例如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 文件。
to_sql
< source >( 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
orsqlite3.Connection
orsqlalchemy.engine.Connection
orsqlalchemy.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 数据库。
to_iterable_dataset
< source >( 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()
>>> 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
add_faiss_index
< source >( 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_PRODUCT
或faiss.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
< source >( 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_PRODUCT
或faiss.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 上运行,可以指定 device
(device
必须是 GPU 索引)。您可以在此处找到有关 Faiss 的更多信息。
- 对于 字符串工厂
save_faiss_index
< source >( index_name: str file: typing.Union[str, pathlib.PurePath] storage_options: typing.Optional[dict] = None )
将 FaissIndex 保存到磁盘。
load_faiss_index
< source >( 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
< source >( 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 添加一个文本索引以实现快速检索。此操作是原地执行的。
load_elasticsearch_index
< source >( 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_nearest
或search
的索引名称。 - 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 加载现有文本索引以实现快速检索。
列出所有附加索引的 colindex_nameumns
/标识符。
列出所有附加索引的 index_name
/标识符。
删除指定列的索引。
search
< source >( 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
< source >( 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
< source >( index_name: str query: typing.Union[str, <built-in function array>] k: int = 10 **kwargs ) → (scores, examples)
在数据集中查找与查询最接近的样本。
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]
):每个查询检索到的样本
在数据集中查找与查询最接近的样本。
包含数据集中所有元数据的 DatasetInfo 对象。
对应于命名数据集拆分的 NamedSplit 对象。
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-like
或path-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 文件创建数据集。
from_json
< 源 >( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False field: typing.Optional[str] = None num_proc: typing.Optional[int] = None **kwargs )
参数
- path_or_paths (
path-like
或path-like
列表) — JSON 或 JSON Lines 文件的路径。 - split (NamedSplit, 可选) — 要分配给数据集的拆分名称。
- features (Features, 可选) — 数据集特征。
- cache_dir (
str
, 可选, 默认为"~/.cache/huggingface/datasets"
) — 缓存数据的目录。 - keep_in_memory (
bool
, 默认为False
) — 是否将数据复制到内存中。 - field (
str
, 可选) — 包含数据集的 JSON 文件的字段名。 - num_proc (
int
, 可选, 默认为None
) — 在本地下载和生成数据集时使用的进程数。如果数据集由多个文件组成,此参数会很有帮助。默认禁用多进程。2.8.0 版本新增
- **kwargs (附加关键字参数) — 传递给 `JsonConfig` 的关键字参数。
从 JSON 或 JSON Lines 文件创建数据集。
from_parquet
< 源 >( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False columns: typing.Optional[list[str]] = None num_proc: typing.Optional[int] = None **kwargs )
参数
- path_or_paths (
path-like
或path-like
列表) — Parquet 文件的路径。 - split (
NamedSplit
, 可选) — 要分配给数据集的拆分名称。 - features (
Features
, 可选) — 数据集特征。 - cache_dir (
str
, 可选, 默认为"~/.cache/huggingface/datasets"
) — 缓存数据的目录。 - keep_in_memory (
bool
, 默认为False
) — 是否将数据复制到内存中。 - columns (
List[str]
, 可选) — 如果不为 `None`,则仅从文件中读取这些列。列名可以是嵌套字段的前缀,例如,“a”将选择“a.b”、“a.c”和“a.d.e”。 - num_proc (
int
, 可选, 默认为None
) — 在本地下载和生成数据集时使用的进程数。如果数据集由多个文件组成,此参数会很有帮助。默认禁用多进程。2.8.0 版本新增
- **kwargs (附加关键字参数) — 传递给 `ParquetConfig` 的关键字参数。
从 Parquet 文件创建数据集。
from_text
< 源 >( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False num_proc: typing.Optional[int] = None **kwargs )
参数
- path_or_paths (
path-like
或path-like
列表) — 文本文件的路径。 - split (
NamedSplit
, 可选) — 要分配给数据集的拆分名称。 - features (
Features
, 可选) — 数据集特征。 - cache_dir (
str
, 可选, 默认为"~/.cache/huggingface/datasets"
) — 缓存数据的目录。 - keep_in_memory (
bool
, 默认为False
) — 是否将数据复制到内存中。 - num_proc (
int
, 可选, 默认为None
) — 在本地下载和生成数据集时使用的进程数。如果数据集由多个文件组成,此参数会很有帮助。默认禁用多进程。2.8.0 版本新增
- **kwargs (附加关键字参数) — 传递给 `TextConfig` 的关键字参数。
从文本文件创建数据集。
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 (
str
或sqlalchemy.sql.Selectable
) — 要执行的 SQL 查询或表名。 - con (
str
或sqlite3.Connection
或sqlalchemy.engine.Connection
或sqlalchemy.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 )
将数据集的标签 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 )
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' ) → Dataset 或 IterableDataset
参数
- 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_exhausted
和all_exhausted
。默认情况下,first_exhausted
是一种欠采样策略,即一旦某个数据集的样本耗尽,数据集的构建就停止。如果策略是all_exhausted
,我们使用过采样策略,即一旦每个数据集的每个样本都至少被添加过一次,数据集的构建就停止。请注意,如果策略是all_exhausted
,交错后的数据集大小可能会变得非常大:- 没有概率时,结果数据集将有
max_length_datasets*nb_dataset
个样本。 - 有给定概率时,如果某些数据集的访问概率非常低,结果数据集的样本会更多。
- 没有概率时,结果数据集将有
返回
返回类型取决于输入的 datasets
参数。如果输入是 Dataset
列表,则返回 Dataset
;如果输入是 IterableDataset
列表,则返回 IterableDataset
。
将多个数据集(源)交错成单个数据集。新数据集通过在源之间交替获取示例来构建。
您可以在 Dataset 对象列表上或在 IterableDataset 对象列表上使用此函数。
- 如果
probabilities
为None
(默认),新数据集通过在每个源之间循环获取示例来构建。 - 如果
probabilities
不为None
,新数据集通过根据提供的概率从随机源中获取示例来构建。
当其中一个源数据集耗尽示例时,结果数据集结束,除非 oversampling
为 True
,在这种情况下,当所有数据集都至少耗尽一次示例时,结果数据集才结束。
可迭代数据集注意事项
在分布式设置或 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 ) → Dataset 或 IterableDataset
参数
- dataset (Dataset 或 IterableDataset) — 按节点拆分的数据集。
- rank (
int
) — 当前节点的排名。 - world_size (
int
) — 节点总数。
返回
在排名为 rank
的节点上使用的数据集。
在一个大小为 world_size
的节点池中,为排名为 rank
的节点拆分一个数据集。
对于映射样式的数据集
每个节点被分配一个数据块,例如,排名 0 的节点被给予数据集的第一个数据块。为了最大化数据加载吞吐量,如果可能,数据块由磁盘上的连续数据组成。
对于可迭代的数据集
如果数据集的分片数是 world_size
的因子(即 dataset.num_shards % world_size == 0
),那么分片将在节点之间均匀分配,这是最优化的。否则,每个节点从 world_size
个示例中保留 1 个示例,跳过其他示例。
在对数据集应用转换时,数据存储在缓存文件中。缓存机制允许在已计算过的情况下重新加载现有的缓存文件。
重新加载数据集是可能的,因为缓存文件是使用数据集指纹命名的,该指纹在每次转换后都会更新。
如果禁用,该库在对数据集应用转换时将不再重新加载缓存的数据集文件。更确切地说,如果禁用了缓存:
- 缓存文件总是被重新创建
- 缓存文件被写入一个临时目录,该目录在会话关闭时被删除
- 缓存文件使用随机哈希命名,而不是数据集指纹
- 使用 save_to_disk() 来保存转换后的数据集,否则它将在会话关闭时被删除
- 缓存不影响 load_dataset()。如果你想从头开始重新生成一个数据集,你应该在 load_dataset() 中使用
download_mode
参数。
在对数据集应用转换时,数据存储在缓存文件中。缓存机制允许在已计算过的情况下重新加载现有的缓存文件。
重新加载数据集是可能的,因为缓存文件是使用数据集指纹命名的,该指纹在每次转换后都会更新。
如果禁用,该库在对数据集应用转换时将不再重新加载缓存的数据集文件。更确切地说,如果禁用了缓存:
- 缓存文件总是被重新创建
- 缓存文件被写入一个临时目录,该目录在会话关闭时被删除
- 缓存文件使用随机哈希命名,而不是数据集指纹
- 使用 save_to_disk() 来保存转换后的数据集,否则它将在会话关闭时被删除
- 缓存不影响 load_dataset()。如果你想从头开始重新生成一个数据集,你应该在 load_dataset() 中使用
download_mode
参数。
在对数据集应用转换时,数据存储在缓存文件中。缓存机制允许在已计算过的情况下重新加载现有的缓存文件。
重新加载数据集是可能的,因为缓存文件是使用数据集指纹命名的,该指纹在每次转换后都会更新。
如果禁用,该库在对数据集应用转换时将不再重新加载缓存的数据集文件。更确切地说,如果禁用了缓存:
- 缓存文件总是被重新创建
- 缓存文件被写入一个临时目录,该目录在会话关闭时被删除
- 缓存文件使用随机哈希命名,而不是数据集指纹
- 使用 save_to_disk() 来保存转换后的数据集,否则它将在会话关闭时被删除
- 缓存不影响 load_dataset()。如果你想从头开始重新生成一个数据集,你应该在 load_dataset() 中使用
download_mode
参数。
class datasets.Column
< 源 >( source: typing.Union[ForwardRef('Dataset'), ForwardRef('Column')] column_name: str )
用于 Dataset 特定列的可迭代对象。
示例
DatasetDict
以拆分名称(例如‘train’、‘test’)为键,Dataset
对象为值的字典。它还具有数据集转换方法,如 map 或 filter,可一次处理所有拆分。
一个具有数据集转换方法(map、filter 等)的字典(dict of str: datasets.Dataset)。
支持每个拆分的 Apache Arrow 表。
包含支持每个拆分的 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'}]}
数据集中每个拆分的列数。
数据集中每个拆分的行数。
数据集中每个拆分的列名。
数据集中每个拆分的形状(行数,列数)。
清理数据集缓存目录中的所有缓存文件,但当前正在使用的缓存文件(如果有的话)除外。运行此命令时要小心,确保没有其他进程正在使用其他缓存文件。
map
< 源 >( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False with_split: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 features: typing.Optional[datasets.features.features.Features] = None disable_nullable: bool = False fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None desc: typing.Optional[str] = None try_original_type: typing.Optional[bool] = True )
参数
- function (
callable
) — 具有以下签名之一:function(example: Dict[str, Any]) -> Dict[str, Any]
如果batched=False
且with_indices=False
function(example: Dict[str, Any], indices: int) -> Dict[str, Any]
如果batched=False
且with_indices=True
function(batch: Dict[str, list]) -> Dict[str, list]
如果batched=True
且with_indices=False
function(batch: Dict[str, list], indices: list[int]) -> Dict[str, list]
如果batched=True
且with_indices=True
对于高级用法,该函数还可以返回一个
pyarrow.Table
。如果函数是异步的,那么map
将并行运行您的函数。此外,如果您的函数不返回任何内容(None
),那么map
将运行您的函数并返回未更改的数据集。如果没有提供函数,则默认为恒等函数:lambda x: x
。 - with_indices (
bool
, 默认为False
) — 向function
提供示例索引。请注意,在这种情况下,function
的签名应为def function(example, idx): ...
。 - with_rank (
bool
, 默认为False
) — 向function
提供进程排名。请注意,在这种情况下,function
的签名应为def function(example[, idx], rank): ...
。 - with_split (
bool
, 默认为False
) — 向function
提供进程拆分。请注意,在这种情况下,function
的签名应为def function(example[, idx], split): ...
。 - input_columns (
[Union[str, list[str]]]
, 可选, 默认为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 (
[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=False
且with_indices=False
且with_rank=False
时:function(example: Dict[str, Any]) -> bool
- 当
batched=False
且with_indices=True
和/或with_rank=True
时(每项一个额外参数):function(example: Dict[str, Any], *extra_args) -> bool
- 当
batched=True
且with_indices=False
且with_rank=False
时:function(batch: Dict[str, list]) -> list[bool]
- 当
batched=True
且with_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 <= 0
或batch_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_start
或first
,则将None
值放在开头;如果是at_end
或last
,则放在末尾。 - 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
,则会从操作系统中获取全新的、不可预测的熵。如果传递一个int
或array_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)。
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.array
、torch.tensor
或tensorflow.ragged.constant
。
设置 __getitem__
的返回格式(类型和列)。该格式将为数据集字典中的每个数据集设置。
可以在调用 set_format
后调用 map
。由于 map
可能会添加新列,格式化列的列表会随之更新。在这种情况下,如果你对数据集应用 map
来添加一个新列,那么这个新列将被格式化。
新的格式化列 = (所有列 - 先前未格式化的列)
示例
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True)
>>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds["train"].format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
'format_kwargs': {},
'output_all_columns': False,
'type': 'numpy'}
将 __getitem__
的返回格式重置为 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.array
、torch.tensor
或tensorflow.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.array
、torch.tensor
或tensorflow.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])}
展平每个数据分割的 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
< source >( features: Features )
将数据集转换为一组新的特征。该转换将应用于数据集字典的所有数据集。
示例
>>> 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')}
将列转换为特征以进行解码。
示例
>>> 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
< source >( column_names: typing.Union[str, list[str]] ) → DatasetDict
从数据集的每个分割中移除一个或多个列以及与这些列相关的特征。
该转换将应用于数据集字典的所有分割。
您也可以使用带有 remove_columns
的 map() 来移除列,但本方法不会复制剩余列的数据,因此速度更快。
示例
>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds = ds.remove_columns("label")
DatasetDict({
train: Dataset({
features: ['text'],
num_rows: 8530
})
validation: Dataset({
features: ['text'],
num_rows: 1066
})
test: Dataset({
features: ['text'],
num_rows: 1066
})
})
rename_column
< source >( original_column_name: str new_column_name: str )
重命名数据集中的列,并将与原始列关联的特征移动到新列名下。该转换将应用于数据集字典的所有数据集。
您也可以使用带有 remove_columns
的 map() 来重命名列,但本方法
- 负责将原始特征移动到新列名下。
- 不会将数据复制到新数据集中,因此速度更快。
示例
>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds = ds.rename_column("label", "label_new")
DatasetDict({
train: Dataset({
features: ['text', 'label_new'],
num_rows: 8530
})
validation: Dataset({
features: ['text', 'label_new'],
num_rows: 1066
})
test: Dataset({
features: ['text', 'label_new'],
num_rows: 1066
})
})
rename_columns
< source >( column_mapping: dict ) → 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
< source >( column_names: typing.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
< source >( column: str include_nulls: bool = False )
将给定列转换为 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
< source >( 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 (
int
或str
, 可选, 默认为"500MB"
) — 要上传到 Hub 的数据集分片的最大大小。如果表示为字符串,需要是数字后跟一个单位(如"500MB"
或"1GB"
)。 - num_shards (
Dict[str, int]
, 可选) — 要写入的分片数量。默认情况下,分片数量取决于max_shard_size
。使用字典为每个分割定义不同的 num_shards。2.8.0 版本新增
- embed_external_files (
bool
, 默认为True
) — 是否在分片中嵌入文件字节。特别是,在推送之前,这将对以下类型的字段执行以下操作: - num_proc (
int
, 可选, 默认为None
) — 准备和上传数据集时的进程数。如果数据集由许多样本或要嵌入的媒体文件组成,这会很有帮助。多进程默认禁用。4.0.0 版本新增
将 DatasetDict 作为 Parquet 数据集推送到 Hub。DatasetDict 使用 HTTP 请求推送,不需要安装 git 或 git-lfs。
每个数据集分割将独立推送。推送的数据集将保留原始的分割名称。
默认情况下,生成的 Parquet 文件是自包含的:如果您的数据集包含 Image 或 Audio 数据,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
< source >( 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 (
int
或str
, 可选, 默认为"500MB"
) — 要保存到文件系统的数据集分片的最大大小。如果表示为字符串,需要是数字后跟一个单位(如"50MB"
)。 - num_shards (
Dict[str, int]
, 可选) — 要写入的分片数量。默认情况下,分片数量取决于max_shard_size
和num_proc
。您需要为数据集字典中的每个数据集提供分片数量。使用字典为每个分割定义不同的 num_shards。2.8.0 版本新增
- num_proc (
int
, 可选, 默认None
) — 在本地下载和生成数据集时的进程数。多进程默认禁用。2.8.0 版本新增
- storage_options (
dict
, 可选) — 要传递给文件系统后端的键/值对(如果有)。2.8.0 版本新增
使用 fsspec.spec.AbstractFileSystem
将数据集字典保存到文件系统。
所有的 Image()、Audio() 和 Video() 数据都存储在 arrow 文件中。如果您想存储路径或 url,请使用 Value(“string”) 类型。
load_from_disk
< source >( 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
保存的数据集。
from_csv
< source >( 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_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-like
或path-like
列表) — JSON Lines 文件的路径。 - features (Features, optional) — 数据集特征。
- cache_dir (str, optional, 默认为
"~/.cache/huggingface/datasets"
) — 缓存数据的目录。 - keep_in_memory (
bool
, 默认为False
) — 是否将数据复制到内存中。 - **kwargs (附加关键字参数) — 传递给
JsonConfig
的关键字参数。
从 JSON Lines 文件创建 DatasetDict。
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_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。
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
移除数据集中的一个或多个列以及与之相关的特征。在迭代数据集时,移除操作是在样本上动态执行的。
示例
>>> 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
选择数据集中的一个或多个列以及与之相关的特征。在迭代数据集时,选择操作是在样本上动态执行的。
示例
>>> 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
将列转换为特征以进行解码。
示例
>>> 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
将数据集转换为一组新的特征。
示例
>>> 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
启用或禁用对音频、图像、视频的数据集特征解码。
启用时(默认),媒体类型会被解码
- 音频 -> 包含 "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
< 来源 >( batch_size: int drop_last_batch: bool = False )
按批次大小 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=False
且with_indices=False
function(example: Dict[str, Any], idx: int) -> Dict[str, Any]
如果batched=False
且with_indices=True
function(batch: Dict[str, List]) -> Dict[str, List]
如果batched=True
且with_indices=False
function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List]
如果batched=True
且with_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 为
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="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
重命名数据集中的一列,并将与原始列关联的特征移动到新的列名下。
示例
>>> 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 (
str
或List[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 )
随机打乱此数据集的元素。
此数据集用 `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 )
将数据集中的样本分组为批次。
创建一个新的 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 .'}]
创建一个新的 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
份后的第 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`)之前,请务必进行分片。最好在数据集管道的早期使用分片操作符。
repeat
< 源 >( num_times: typing.Optional[int] )
创建一个新的 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
orFileOrBuffer
) — 文件路径(例如 `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。
这会迭代数据集并在写入之前将其完全加载到内存中。
to_pandas
< 源 >( batch_size: typing.Optional[int] = None batched: bool = False )
将数据集作为 pandas.DataFrame
返回。对于大型数据集,也可以返回一个生成器。
to_dict
< 源 >( batch_size: typing.Optional[int] = None batched: bool = False )
将数据集作为 Python 字典返回。对于大型数据集,也可以返回一个生成器。
to_json
< source >( 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
orFileOrBuffer
) — 文件路径(例如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=True
和orient="records"
。如果orient
是"split"
或"table"
,参数index
默认为False
。如果你想写入索引,请传递index=True
。
返回
int
写入的字符或字节数。
将数据集导出为 JSON Lines 或 JSON。
这会迭代数据集并在写入之前将其完全加载到内存中。
默认输出格式是 JSON Lines。要导出为 JSON,请传递 lines=False
参数和所需的 orient
。
to_parquet
< source >( 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
orFileOrBuffer
) — 文件路径(例如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 文件。
to_sql
< source >( 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
orsqlite3.Connection
orsqlalchemy.engine.Connection
orsqlalchemy.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 数据库。
push_to_hub
< source >( 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
) — 是否在分片中嵌入文件字节。特别是,在推送之前,对于以下类型的字段,它将执行以下操作: - num_proc (
int
, optional, 默认为None
) — 准备和上传数据集时的进程数。如果数据集包含许多样本和转换,这将很有帮助。默认禁用多进程。
将数据集作为 Parquet 数据集推送到 Hub。数据集使用 HTTP 请求推送,不需要安装 git 或 git-lfs。
默认情况下,生成的 Parquet 文件是自包含的。如果您的数据集包含 Image、Audio 或 Video 数据,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")
加载数据集的 state_dict。迭代将从状态保存时的下一个示例重新开始。
恢复时会准确地返回到检查点保存的位置,但有两种情况例外
- 恢复时,随机缓冲区中的示例会丢失,缓冲区会用新数据重新填充
.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)
>>> 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。它对应于它产出的最后一个示例的状态。
恢复时会准确地返回到检查点保存的位置,但有两种情况例外
- 恢复时,随机缓冲区中的示例会丢失,缓冲区会用新数据重新填充
.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)
>>> 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
包含数据集中所有元数据的 DatasetInfo 对象。
对应于命名数据集拆分的 NamedSplit 对象。
class datasets.IterableColumn
< source >( source: typing.Union[ForwardRef('IterableDataset'), ForwardRef('IterableColumn')] column_name: str )
IterableDataset 特定列的可迭代对象。
示例
IterableDatasetDict
以拆分名称(例如 'train'、'test')为键,以 IterableDataset
对象为值的字典。
map
< source >( 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=False
且with_indices=False
function(example: Dict[str, Any], idx: int) -> Dict[str, Any]
如果batched=False
且with_indices=True
function(batch: Dict[str, list]) -> Dict[str, list]
如果batched=True
且with_indices=False
function(batch: Dict[str, list], indices: list[int]) -> Dict[str, list]
如果batched=True
且with_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 为
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", 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 (
str
或list[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 )
随机打乱此数据集的元素。该打乱操作会应用于数据集字典中的所有数据集。
此数据集首先用 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 )
返回一个具有指定格式的数据集。
示例
>>> 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
将数据集转换为一组新的特征。类型转换会应用于数据集字典中的所有数据集。
示例
>>> 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] )
将列转换为特征以进行解码。类型转换会应用于数据集字典中的所有数据集。
示例
>>> 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
移除数据集中的一列或多列以及与之相关的特征。移除操作在迭代数据集时动态地对样本进行。该移除会应用于数据集字典中的所有数据集。
示例
>>> 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
参数
一列已重命名的数据集副本。
重命名数据集中的一列,并将与原始列关联的特征移到新列名下。重命名操作会应用于数据集字典中的所有数据集。
示例
>>> 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
重命名数据集中的多列,并将与原始列关联的特征移到新列名下。重命名操作会应用于数据集字典中的所有数据集。
示例
>>> 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
选择数据集中的一列或多列以及与之相关的特征。选择操作在迭代数据集时动态地对样本进行。该选择会应用于数据集字典中的所有数据集。
示例
>>> 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
) — 是否在分片中嵌入文件字节。特别是,这将在推送前对以下类型的字段执行以下操作: - num_proc (
int
, 可选, 默认为None
) — 准备和上传数据集时的进程数。如果数据集由许多样本或要嵌入的媒体文件组成,这将很有帮助。默认情况下禁用多进程。4.0.0 版本中新增
将 DatasetDict 作为 Parquet 数据集推送到 Hub。DatasetDict 使用 HTTP 请求推送,不需要安装 git 或 git-lfs。
每个数据集分割将独立推送。推送的数据集将保留原始的分割名称。
默认情况下,生成的 Parquet 文件是自包含的:如果您的数据集包含 Image 或 Audio 数据,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")
特征
一种特殊的字典,用于定义数据集的内部结构。
使用 dict[str, FieldType]
类型的字典进行实例化,其中键是所需的列名,值是该列的类型。
FieldType
可以是以下之一:
- Value 特征指定单个数据类型值,例如
int64
或string
。 - ClassLabel 特征指定一组预定义的类别,这些类别可以有关联的标签,并在数据集中作为整数存储。
- Python
dict
指定一个复合特征,其中包含子字段到子特征的映射。可以以任意方式嵌套字段。 - List 或 LargeList 指定一个复合特征,其中包含一系列相同特征类型的子特征。
- Array2D、Array3D、Array4D 或 Array5D 特征用于多维数组。
- 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。 - Translation 或 TranslationVariableLanguages 特征专用于机器翻译。
对 Features 进行深拷贝。
decode_batch
< 来源 >( batch: dict token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )
使用自定义特征解码来解码批次。
decode_column
< 来源 >( column: list column_name: str token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )
使用自定义特征解码来解码列。
decode_example
< 源码 >( example: dict token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )
使用自定义特征解码来解码样本。
将批次编码为 Arrow 格式。
encode_column
< 源码 >( column column_name: str )
将列编码为 Arrow 格式。
将样本编码为 Arrow 格式。
展平特征。每个字典列都将被移除,并由其包含的所有子字段替换。新字段的命名方式是通过连接原始列名和子字段名,格式为:<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')}
从 Arrow 模式构建 Features。它还会检查模式元数据中是否包含 Hugging Face Datasets 的特征信息。不支持不可为空的字段,并会将其设置为可为空。
此外,不支持 pa.dictionary,而是使用其底层类型。因此,datasets 会将 DictionaryArray 对象转换为它们的实际值。
从字典构建 [Features]。
从反序列化的字典中重新生成嵌套的特征对象。我们使用 _type 键来推断特征 FieldType 的数据类名称。
这允许使用一种方便的构造函数语法,从反序列化的 JSON 字典中定义特征。该函数特别用于反序列化已转储为 JSON 对象的 [DatasetInfo]。它类似于 [Features.from_arrow_schema],处理递归的逐字段实例化,但不需要任何与 pyarrow 的映射,除了它利用了 [Value] 自动执行的 pyarrow 原始数据类型的映射。
重新排序 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 )
特定数据类型的标量特征值。
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
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 )
整数类别标签的特征类型。
有 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
将 Arrow 数组转换为 ClassLabel
Arrow 存储类型。可以转换为 ClassLabel
pyarrow 存储类型的 Arrow 类型有
pa.string()
pa.int()
转换 integer
=> 类别名称 string
。
关于未知/缺失标签:传递负整数会引发 ValueError
。
转换类别名称 string
=> integer
。
复合类型
class datasets.LargeList
< 源码 >( feature: typing.Any id: typing.Optional[str] = None )
由子特征数据类型组成的大列表数据的特征类型。
它由 pyarrow.LargeListType
支持,类似于 pyarrow.ListType
,但使用 64 位偏移量而非 32 位。
class datasets.List
< 源码 >( feature: typing.Any length: int = -1 id: typing.Optional[str] = None )
由子特征数据类型组成的大列表数据的特征类型。
它由 pyarrow.ListType
支持,使用 32 位偏移量或固定长度。
class datasets.Sequence
< 源码 >( feature = None length = -1 **kwargs )
Sequence
是一个实用工具,可自动将内部的字典特征转换为列表的字典。此行为是为了与 TensorFlow Datasets 库兼容而实现的,但在某些情况下可能不需要。如果您不希望有此行为,可以使用 List 或 LargeList 来代替 Sequence。
翻译
class datasets.Translation
< 源码 >( languages: list id: typing.Optional[str] = None )
用于每个样本具有固定语言的翻译的 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'
... }
将 Translation 特征展平为字典。
class datasets.TranslationVariableLanguages
< 源码 >( languages: typing.Optional[list] = None num_languages: typing.Optional[int] = None id: typing.Optional[str] = None ) →
language
或translation
(可变长度的一维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'],
... }
将 TranslationVariableLanguages 特征展平为字典。
数组
class datasets.Array2D
< 源码 >( shape: tuple dtype: str id: typing.Optional[str] = None )
创建一个二维数组。
class datasets.Array3D
< 源码 >( shape: tuple dtype: str id: typing.Optional[str] = None )
创建一个三维数组。
class datasets.Array4D
< 源代码 >( shape: tuple dtype: str id: typing.Optional[str] = None )
创建一个四维数组。
class datasets.Array5D
< 源代码 >( shape: tuple dtype: str id: typing.Optional[str] = None )
创建一个五维数组。
Audio
class datasets.Audio
< 源代码 >( sampling_rate: typing.Optional[int] = None decode: bool = True stream_index: typing.Optional[int] = None id: typing.Optional[str] = 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
将 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 )
将示例音频文件解码为音频数据。
embed_storage
< 源代码 >( storage: StructArray token_per_repo_id = None ) → pa.StructArray
将音频文件嵌入到 Arrow 数组中。
encode_example
< 源代码 >( value: typing.Union[str, bytes, bytearray, dict, ForwardRef('AudioDecoder')] ) → dict
将样本编码为 Arrow 格式。
如果处于可解码状态,则引发错误,否则将特征展平为字典。
Image
class datasets.Image
< 源代码 >( mode: typing.Optional[str] = None decode: bool = True id: typing.Optional[str] = None )
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
将 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 )
将示例图像文件解码为图像数据。
embed_storage
< 源代码 >( storage: StructArray token_per_repo_id = None ) → pa.StructArray
将图像文件嵌入到 Arrow 数组中。
encode_example
< 源代码 >( value: typing.Union[str, bytes, bytearray, dict, numpy.ndarray, ForwardRef('PIL.Image.Image')] )
将样本编码为 Arrow 格式。
如果处于可解码状态,则返回特征本身,否则将特征展平为字典。
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 (
str
或torch.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
将 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 )
将示例视频文件解码为视频数据。
encode_example
< 源代码 >( value: typing.Union[str, bytes, bytearray, datasets.features.video.Example, numpy.ndarray, ForwardRef('VideoDecoder')] )
将样本编码为 Arrow 格式。
如果处于可解码状态,则返回特征本身,否则将特征展平为字典。
class datasets.Pdf
< 源代码 >( decode: bool = True id: typing.Optional[str] = None )
实验性功能。 用于从 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
将 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 )
将示例 pdf 文件解码为 pdf 数据。
embed_storage
< 源代码 >( storage: StructArray token_per_repo_id = None ) → pa.StructArray
将 PDF 文件嵌入到 Arrow 数组中。
encode_example
< 源代码 >( value: typing.Union[str, bytes, bytearray, dict, ForwardRef('pdfplumber.pdf.PDF')] )
将样本编码为 Arrow 格式。
如果处于可解码状态,则返回特征本身,否则将特征展平为字典。
文件系统
datasets.filesystems.is_remote_filesystem
< 源代码 >( fs: AbstractFileSystem )
检查 fs
是否为远程文件系统。
指纹
接受 python 对象作为输入的哈希器。