14 KiB
Note
本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
🤗 Datasets 是一个轻量级库,提供 两大 主要功能:
- 一行代码加载众多公开数据集的数据加载器:只需一行代码即可下载并预处理 HuggingFace Datasets Hub. 上提供的任意
个主流公开数据集(图像数据集、音频数据集、涵盖 467 种语言与方言的文本数据集、3D 医学影像、视频数据集、智能体轨迹等)。通过类似
squad_dataset = load_dataset("rajpurkar/squad")的简单命令,即可让这些数据集在用于训练/评估 ML 模型的数据加载器(Numpy/Pandas/PyTorch/TensorFlow/JAX/Polars)中就绪, - 高效数据预处理:对公开数据集以及你本地的 CSV、JSON、JSONL、Parquet、HDF5、XML、文本、PNG、JPEG、WAV、MP3、PDF、NIfTI 等格式数据集,提供简单、快速且可复现的数据预处理。通过类似
processed_dataset = dataset.map(process_example)的简单命令,可高效准备数据集以供检查以及 ML 模型评估与训练。
🎓 文档 🔎 在 Hub 中查找数据集 🌟 在 Hub 上分享数据集
🚀 核心特性
🤗 Datasets 旨在让社区能够轻松添加和分享新数据集,并为数据操作提供强大能力:
| 特性 | 说明 |
|---|---|
| 📦 一行加载数据集 | 通过 load_dataset() 从 Hugging Face Hub 或本地文件加载可直接用于 AI 的数据集 |
| 🔍 多种格式 | 原生支持 CSV、JSON、JSONL、Parquet、Arrow、XML、Text、Webdataset 等 |
| 🖼️ 多模态数据 | 内置支持文本、音频、图像、视频、PDF 及 NIfTI(3D 医学)数据 |
| 🚀 流式模式(Streaming mode) | 无需下载即可流式读取数据集——通过 streaming=True 即时遍历数据(配合 Xet 后端,速度最高可提升 100 倍) |
| 💾 HF Storage Buckets | 直接从 Hugging Face Storage Buckets 读写可变、大规模原始数据 |
| 🧠 AI 智能体轨迹 | 从 Hub 加载并处理 AI 智能体轨迹(提示词、工具调用、响应) |
| ⚡ Apache Arrow 后端 | 零拷贝内存映射存储——数据集天然助你摆脱 RAM 限制 |
| 🔄 智能缓存 | 无需等待数据重复处理——缓存结果会自动复用 |
| 📊 多框架互操作 | 原生支持与 NumPy、Pandas、Polars、Arrow、PyTorch、TensorFlow、JAX 及 Spark 相互转换 |
| 🏎️ 多进程处理 | 通过 map(num_proc=N) 实现快速并行数据处理 |
| 🔎 搜索与索引 | 内置 FAISS 与 Elasticsearch 索引支持,用于相似性搜索 |
| 📦 JSON 类型 | 通过 Json() 特性类型,灵活支持 JSON/结构化数据 |
安装
使用 pip
🤗 Datasets 可从 PyPi 安装,建议在虚拟环境(例如 venv 或 conda)中安装:
pip install datasets
如需最新开发版本:
pip install "datasets @ git+https://github.com/huggingface/datasets.git"
使用 conda
conda install -c huggingface -c conda-forge datasets
可选依赖
🤗 Datasets 通过 extras 支持多种可选功能:
# For audio (torchcodec)
pip install datasets[audio]
# For image/video (Pillow, torchcodec)
pip install datasets[vision]
# For PDFs/NIfTI (pdfplumber, nibabel)
pip install datasets[pdfs,nibabel]
# For PyTorch/TensorFlow/JAX integration
pip install datasets[torch,tensorflow,jax]
有关安装的更多详情,请参阅安装页面.
快速开始
🤗 Datasets 的设计力求极其易用——其 API 围绕单一函数 datasets.load_dataset(dataset_name, **kwargs) 展开,用于实例化数据集。
以下是一个快速示例:
from datasets import load_dataset
# Load a dataset and print the first example in the training set
squad_dataset = load_dataset('rajpurkar/squad')
print(squad_dataset['train'][0])
# Process the dataset - add a column with the length of the context texts
dataset_with_length = squad_dataset.map(lambda x: {"length": len(x["context"])})
# Tokenize the context texts (using a tokenizer from the 🤗 Transformers library)
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')
tokenized_dataset = squad_dataset.map(lambda x: tokenizer(x['context']), batched=True)
# Tokenize chat conversations with a chat template (using a model that supports chat templates)
# This is useful for fine-tuning instruction/chat models
# Load a popular chat dataset (ultrachat_200k contains ~200k AI assistant conversations)
chat_dataset = load_dataset('HuggingFaceH4/ultrachat_200k', split='train_sft')
chat_tokenizer = AutoTokenizer.from_pretrained('Qwen/Qwen2.5-7B-Instruct')
def tokenize_chat(examples):
# Apply the chat template and tokenize in one step
return chat_tokenizer.apply_chat_template(examples["messages"])
tokenized_chat_dataset = chat_dataset.map(tokenize_chat, batched=True)
流式模式
若数据集大于磁盘容量,或你不想等待下载完成,可使用流式模式:
# Stream the dataset without downloading anything
image_dataset = load_dataset('timm/imagenet-1k-wds', streaming=True)
for example in image_dataset["train"]:
print(example["image"])
break
多模态数据
🤗 Datasets 开箱即用地支持多种数据类型:
# Audio dataset
dataset = load_dataset("openslr/librispeech_asr", "clean")
# Image dataset
dataset = load_dataset("ILSVRC/imagenet-1k")
# Video dataset
dataset = load_dataset("Shofo/shofo-tiktok-general-small")
# PDF documents
dataset = load_dataset("pixparse/pdfa-eng-wds")
# NIfTI (3D medical imaging)
dataset = load_dataset("dartbrains/localizer", "betas")
从本地文件
# Load from local CSV
dataset = load_dataset('csv', data_files='my_data.csv')
# Load from local Parquet
dataset = load_dataset('parquet', data_files='data/*.parquet')
# Load from a local directory (auto-detect format)
dataset = load_dataset('./path/to/data')
从 Python 对象
from datasets import Dataset
# From a dictionary
dataset = Dataset.from_dict({"text": ["Hello world", "How are you?"]})
# From a list
dataset = Dataset.from_list([{"text": "Hello world"}, {"text": "How are you?"}])
# From Pandas
import pandas as pd
df = pd.DataFrame({"col1": [1, 2, 3], "col2": ["a", "b", "c"]})
dataset = Dataset.from_pandas(df)
# From a generator
def gen():
for i in range(10):
yield {"value": i}
dataset = Dataset.from_generator(gen)
有关使用该库的更多详情,请参阅 快速入门指南 以及以下专题页面:
核心类
该库提供两个主要的数据集类:
| 类 | 说明 |
|---|---|
Dataset |
基于 Apache Arrow 的内存内/内存映射(memory-mapped)数据集。支持索引、切片、随机访问和缓存。 |
IterableDataset |
用于大规模/核外(out-of-core)处理的惰性、可流式传输数据集。支持流式传输和无限迭代。 |
二者均可封装在 DatasetDict / IterableDatasetDict 中,用于多划分数据集(例如 train/test/val)。
向 Hub 添加新数据集
我们提供了一份非常详细的分步指南,介绍如何向 Hub 添加新数据集;Hub 上 个数据集已发布在 HuggingFace Datasets Hub.
你可以找到:
免责声明
你可以使用 🤗 Datasets 加载基于数据集作者维护的版本化 git 仓库的数据集。出于可复现性考虑,我们要求用户固定(pin)所使用仓库的 revision。
如果你是数据集所有者,希望更新其中的任何部分(描述、引用、许可证等),或不希望你的数据集被收录到 Hugging Face Hub,请通过在数据集页面的 Community 标签页中发起讨论或提交 pull request 与我们联系。感谢你对 ML 社区的贡献!
贡献
我们欢迎贡献!详情请参阅我们的 贡献指南,其中包含:
- 如何提交 issue 和 pull request
- 代码风格指南(我们使用 Ruff)
- 测试要求
- 文档标准
BibTeX
如果你想引用我们的 🤗 Datasets 库,可以使用我们的 论文:
@inproceedings{lhoest-etal-2021-datasets,
title = "Datasets: A Community Library for Natural Language Processing",
author = "Lhoest, Quentin and
Villanova del Moral, Albert and
Jernite, Yacine and
Thakur, Abhishek and
von Platen, Patrick and
Patil, Suraj and
Chaumond, Julien and
Drame, Mariama and
Plu, Julien and
Tunstall, Lewis and
Davison, Joe and
{\v{S}}a{\v{s}}ko, Mario and
Chhablani, Gunjan and
Malik, Bhavitvya and
Brandeis, Simon and
Le Scao, Teven and
Sanh, Victor and
Xu, Canwen and
Patry, Nicolas and
McMillan-Major, Angelina and
Schmid, Philipp and
Gugger, Sylvain and
Delangue, Cl{\'e}ment and
Matussi{\`e}re, Th{\'e}o and
Debut, Lysandre and
Bekman, Stas and
Cistac, Pierric and
Goehringer, Thibault and
Mustar, Victor and
Lagunas, Fran{\c{c}}ois and
Rush, Alexander and
Wolf, Thomas",
booktitle = "Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
month = nov,
year = "2021",
address = "Online and Punta Cana, Dominican Republic",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2021.emnlp-demo.21",
pages = "175--184",
abstract = "The scale, variety, and quantity of publicly-available NLP datasets has grown rapidly as researchers propose new tasks, larger models, and novel benchmarks. Datasets is a community library for contemporary NLP designed to support this ecosystem. Datasets aims to standardize end-user interfaces, versioning, and documentation, while providing a lightweight front-end that behaves similarly for small datasets as for internet-scale corpora. The design of the library incorporates a distributed, community-driven approach to adding datasets and documenting usage. After a year of development, the library now includes more than 650 unique datasets, has more than 250 contributors, and has helped support a variety of novel cross-dataset research projects and shared tasks. The library is available at https://github.com/huggingface/datasets.",
eprint={2109.02846},
archivePrefix={arXiv},
primaryClass={cs.CL},
}
如果你需要为可复现性而引用我们 🤗 Datasets 库的特定版本,可以使用此 列表. 中对应版本的 Zenodo DOI。
