Hub 文件
Hugging Face 資料集上傳決策指南
並獲得增強的文件體驗
開始使用
Hugging Face 資料集上傳決策指南
將資料集上傳到 Hugging Face Hub 的決策指南。針對資料集檢視器相容性和與 Hugging Face 生態系統的整合進行了最佳化。
概述
你的目標是幫助使用者將資料集上傳到 Hugging Face Hub。理想情況下,資料集應與資料集檢視器(以及 `load_dataset` 函式)相容,以確保易於訪問和使用。你應努力滿足以下標準:
標準 | 描述 | 優先順序 |
---|---|---|
遵守儲存庫限制 | 確保資料集符合 Hugging Face 對檔案大小、儲存庫大小和檔案數量的儲存限制。具體限制請參閱下面的關鍵約束部分。 | 必需 |
使用 Hub 相容格式 | 儘可能使用 Parquet 格式(最佳壓縮、豐富型別、支援大型資料集)。對於較小的資料集(<幾 GB),JSON/JSONL 或 CSV 也可以接受。原始檔案在尊重儲存庫限制的情況下適用於較小資料集中的影像/音訊。對於大型媒體集合,請使用 WebDataset (.tar)。當轉換不切實際時,可以使用特定領域格式。 | 期望 |
資料集檢視器相容性 | 構建資料以與自動資料集檢視器配合使用,從而實現預覽和輕鬆探索。這通常意味著使用受支援的格式和適當的檔案組織。本指南後面提供了驗證步驟。 | 期望 |
合理組織資料 | 使用符合 Hub 約定(例如,訓練/測試分割)的邏輯資料夾結構。配置可用於定義資料集的不同配置。這有助於人類理解和自動資料載入。 | 期望 |
使用適當的特徵 | 使用資料集庫時,指定正確的特徵型別(例如,Image()、Audio()、ClassLabel())以確保正確的資料處理和檢視器功能。這可以實現特定型別的最佳化和預覽。 | 必需(使用資料集庫時) |
記錄非標準資料集 | 如果無法轉換為 Hub 相容格式且必須使用自定義格式,請確保嚴格遵守儲存庫限制,並提供有關如何下載和載入資料集的清晰文件。包括使用示例和任何特殊要求。 | 必需(當資料集庫不相容時) |
沒有檔案訪問許可權時的工作
當你無法直接訪問使用者檔案時(例如,Web 介面),請要求使用者執行以下命令以瞭解他們的資料集:
資料集結構:
# Show directory tree (install with: pip install tree or brew install tree)
tree -L 3 --filelimit 20
# Alternative without tree:
find . -type f -name "*.csv" -o -name "*.json" -o -name "*.parquet" | head -20
檢查檔案大小:
# Total dataset size
du -sh .
# Individual file sizes
ls -lh data/
檢視資料格式:
# First few lines of CSV/JSON
head -n 5 data/train.csv
# Check image folder structure
ls -la images/ | head -10
快速檔案計數:
# Count files by type
find . -name "*.jpg" | wc -l
關鍵約束
儲存限制:
# Machine-readable Hub limits
hub_limits:
max_file_size_gb: 50 # absolute hard stop enforced by LFS
recommended_file_size_gb: 20 # best-practice shard size
max_files_per_folder: 10000 # Git performance threshold
max_files_per_repo: 100000 # Repository file count limit
recommended_repo_size_gb: 300 # public-repo soft cap; contact HF if larger
viewer_row_size_mb: 2 # approximate per-row viewer limit
人類可讀摘要:
- 免費:100GB 私有資料集
- Pro(個人)| 團隊或企業(組織):每個席位 1TB+ 私有儲存(參見 定價)
- 公共:300GB(更大容量請聯絡 datasets@huggingface.co)
- 每個檔案:最大 50GB,推薦 20GB
- 每個資料夾:<10k 個檔案
有關儲存庫大小和檔案數量的當前限制和建議,請參閱 https://huggingface.co/docs/hub/storage-limits#repository-limitations-and-recommendations。
按資料型別快速參考
你的資料 | 推薦方法 | 快速命令 |
---|---|---|
CSV/JSON 檔案 | 使用內建載入器(透過記憶體對映處理任何大小) | load_dataset("csv", data_files="data.csv").push_to_hub("username/dataset") |
資料夾中的影像 | 使用 imagefolder 進行自動類檢測 | load_dataset("imagefolder", data_dir="./images").push_to_hub("username/dataset") |
音訊檔案 | 使用 audiofolder 進行自動組織 | load_dataset("audiofolder", data_dir="./audio").push_to_hub("username/dataset") |
影片檔案 | 使用 videofolder 進行自動組織 | load_dataset("videofolder", data_dir="./videos").push_to_hub("username/dataset") |
PDF 文件 | 使用 pdffolder 進行文字提取 | load_dataset("pdffolder", data_dir="./pdfs").push_to_hub("username/dataset") |
超大型資料集(100GB+) | 使用 `max_shard_size` 控制記憶體使用 | dataset.push_to_hub("username/dataset", max_shard_size="5GB") |
許多檔案/目錄(>10k) | 使用 upload_large_folder 避免 Git 限制 | api.upload_large_folder(folder_path="./data", repo_id="username/dataset", repo_type="dataset") |
流式傳輸大型媒體 | WebDataset 格式,實現高效流式傳輸 | 建立 .tar 分片,然後 `upload_large_folder()` |
科學資料(HDF5, NetCDF) | 轉換為具有陣列特徵的 Parquet | 參見 科學資料 部分 |
自定義/專有格式 | 如果無法轉換,請徹底記錄 | 帶有全面 README 的 `upload_large_folder()` |
上傳工作流程
✓ 收集資料集資訊(如果需要)
- 什麼型別的資料?(影像、文字、音訊、CSV 等)
- 如何組織?(資料夾結構、單個檔案、多個檔案)
- 大概多大?
- 檔案是什麼格式?
- 有什麼特殊要求?(例如,流媒體、私有訪問)
- 檢查描述資料集的現有 README 或文件檔案
✓ 認證
- CLI: `hf auth login`
- 或使用令牌:`HfApi(token="hf_...")` 或設定 `HF_TOKEN` 環境變數
✓ 識別您的資料型別:檢視上面的 快速參考 表
✓ 選擇上傳方法
- 小型檔案(<1GB)且相容 Hub 格式:可使用 Hub UI 進行快速上傳
- 內建載入器可用:使用載入器 + `push_to_hub()`(參見快速參考表)
- 大型資料集或檔案數量多:對於大於 100GB 或超過 10k 個檔案的檔案,使用 `upload_large_folder()`
- 自定義格式:如果可能,轉換為 Hub 相容格式;否則,徹底記錄
✓ 本地測試(如果使用內建載入器)
# Validate your dataset loads correctly before uploading dataset = load_dataset("loader_name", data_dir="./your_data") print(dataset)
✓ 上傳到 Hub
# Basic upload dataset.push_to_hub("username/dataset-name") # With options for large datasets dataset.push_to_hub( "username/dataset-name", max_shard_size="5GB", # Control memory usage private=True # For private datasets )
✓ 驗證您的上傳
- 檢查資料集檢視器:`https://huggingface.co/datasets/username/dataset-name`
- 測試載入:`load_dataset("username/dataset-name")`
- 如果檢視器顯示錯誤,請檢視 故障排除 部分
常見轉換模式
當內建載入器不符合您的資料結構時,請使用資料集庫作為相容層。將您的資料轉換為 Dataset 物件,然後使用 `push_to_hub()` 以獲得最大的靈活性和資料集檢視器相容性。
從資料幀
如果您已經擁有在 pandas、polars 或其他資料幀庫中處理的資料,則可以直接轉換
# From pandas DataFrame
import pandas as pd
from datasets import Dataset
df = pd.read_csv("your_data.csv")
dataset = Dataset.from_pandas(df)
dataset.push_to_hub("username/dataset-name")
# From polars DataFrame (direct method)
import polars as pl
from datasets import Dataset
df = pl.read_csv("your_data.csv")
dataset = Dataset.from_polars(df) # Direct conversion
dataset.push_to_hub("username/dataset-name")
# From PyArrow Table (useful for scientific data)
import pyarrow as pa
from datasets import Dataset
# If you have a PyArrow table
table = pa.table({'data': [1, 2, 3], 'labels': ['a', 'b', 'c']})
dataset = Dataset(table)
dataset.push_to_hub("username/dataset-name")
# For Spark/Dask dataframes, see https://huggingface.co/docs/hub/datasets-libraries
自定義格式轉換
當內建載入器不符合您的資料格式時,請遵循以下原則將其轉換為 Dataset 物件:
設計原則
1. 傾向於寬/平結構而非連線
- 將關係資料非規範化為單行,以提高可用性
- 在每個示例中包含所有相關資訊
- 傾向於更大但更可用的資料——Hugging Face 的基礎設施使用高階去重(XetHub)和 Parquet 最佳化來高效處理冗餘
2. 使用配置實現邏輯資料集變體
- 除了訓練/測試/驗證分割之外,還可以使用配置來定義資料的不同子集或檢視
- 每個配置可以具有不同的功能或資料組織
- 示例:特定語言配置、特定任務檢視或資料模態
轉換方法
小型資料集(記憶體可容納)- 使用 `Dataset.from_dict()`:
# Parse your custom format into a dictionary
data_dict = {
"text": ["example1", "example2"],
"label": ["positive", "negative"],
"score": [0.9, 0.2]
}
# Create dataset with appropriate features
from datasets import Dataset, Features, Value, ClassLabel
features = Features({
'text': Value('string'),
'label': ClassLabel(names=['negative', 'positive']),
'score': Value('float32')
})
dataset = Dataset.from_dict(data_dict, features=features)
dataset.push_to_hub("username/dataset")
大型資料集(記憶體高效)- 使用 `Dataset.from_generator()`:
def data_generator():
# Parse your custom format progressively
for item in parse_large_file("data.custom"):
yield {
"text": item["content"],
"label": item["category"],
"embedding": item["vector"]
}
# Specify features for Dataset Viewer compatibility
from datasets import Features, Value, ClassLabel, List
features = Features({
'text': Value('string'),
'label': ClassLabel(names=['cat1', 'cat2', 'cat3']),
'embedding': List(feature=Value('float32'), length=768)
})
dataset = Dataset.from_generator(data_generator, features=features)
dataset.push_to_hub("username/dataset", max_shard_size="1GB")
提示:對於大型資料集,首先透過限制生成器或在建立後使用 `.select(range(100))` 來測試子集。
使用配置進行資料集變體
# Push different configurations of your dataset
dataset_en = Dataset.from_dict(english_data, features=features)
dataset_en.push_to_hub("username/multilingual-dataset", config_name="english")
dataset_fr = Dataset.from_dict(french_data, features=features)
dataset_fr.push_to_hub("username/multilingual-dataset", config_name="french")
# Users can then load specific configs
dataset = load_dataset("username/multilingual-dataset", "english")
多模態示例
文字 + 音訊(語音識別):
def speech_generator():
for audio_file in Path("audio/").glob("*.wav"):
transcript_file = audio_file.with_suffix(".txt")
yield {
"audio": str(audio_file),
"text": transcript_file.read_text().strip(),
"speaker_id": audio_file.stem.split("_")[0]
}
features = Features({
'audio': Audio(sampling_rate=16000),
'text': Value('string'),
'speaker_id': Value('string')
})
dataset = Dataset.from_generator(speech_generator, features=features)
dataset.push_to_hub("username/speech-dataset")
每個示例多張影像:
# Before/after images, medical imaging, etc.
data = {
"image_before": ["img1_before.jpg", "img2_before.jpg"],
"image_after": ["img1_after.jpg", "img2_after.jpg"],
"treatment": ["method_A", "method_B"]
}
features = Features({
'image_before': Image(),
'image_after': Image(),
'treatment': ClassLabel(names=['method_A', 'method_B'])
})
dataset = Dataset.from_dict(data, features=features)
dataset.push_to_hub("username/before-after-images")
注意:對於文字 + 影像,請考慮使用帶 metadata.csv 的 ImageFolder,它會自動處理。
基本特徵
特徵定義資料集列的架構和資料型別。指定正確的特徵可確保:
- 正確的資料處理和型別轉換
- 資料集檢視器功能(例如,影像/音訊預覽)
- 高效儲存和載入
- 清晰的資料結構文件
有關完整特徵文件,請參閱:資料集特徵
特徵型別概述
基本型別:
- `Value`:標量值 - `string`、`int64`、`float32`、`bool`、`binary` 和其他數字型別
- `ClassLabel`:帶命名類別的分類資料
- `Sequence`:任何特徵型別的列表
- `LargeList`:用於超大型列表
媒體型別(啟用資料集檢視器預覽)
- `Image()`:處理各種影像格式,返回 PIL 影像物件
- `Audio(sampling_rate=16000)`:帶陣列資料和可選取樣率的音訊
- `Video()`:影片檔案
- `Pdf()`:帶文字提取的 PDF 文件
陣列型別(用於張量/科學資料)
- `Array2D`、`Array3D`、`Array4D`、`Array5D`:固定或可變長度陣列
- 示例:`Array2D(shape=(224, 224), dtype='float32')`
- 第一維對於可變長度可以是 `None`
翻譯型別:
- `Translation`:用於固定語言的翻譯對
- `TranslationVariableLanguages`:用於不同語言對的翻譯
注意:新功能型別會定期新增。請檢視文件以瞭解最新新增內容。
上傳方法
資料集物件(使用 push_to_hub):當您使用資料集庫載入/轉換資料時使用
dataset.push_to_hub("username/dataset", max_shard_size="5GB")
現有檔案(使用 upload_large_folder):當您已準備好並組織好 Hub 相容檔案(例如 Parquet 檔案)時使用
from huggingface_hub import HfApi
api = HfApi()
api.upload_large_folder(folder_path="./data", repo_id="username/dataset", repo_type="dataset", num_workers=16)
重要提示:在使用 `upload_large_folder` 之前,請驗證檔案是否符合儲存庫限制
- 如果您有檔案訪問許可權,請檢查資料夾結構:確保沒有資料夾包含超過 10k 個檔案
- 請使用者確認:“您的檔案是否為 Hub 相容格式(Parquet/CSV/JSON)且組織得當?”
- 對於非標準格式,請考慮首先轉換為資料集物件以確保相容性
驗證
考慮小幅重構:如果資料接近內建載入器格式,建議進行小幅更改
- 重新命名列(例如,'filename' → 'file_name',用於 ImageFolder)
- 重新組織資料夾(例如,將影像移動到類子資料夾中)
- 重新命名檔案以匹配預期模式(例如,'data.csv' → 'train.csv')
預上傳:
本地測試:`load_dataset("imagefolder", data_dir="./data")`
驗證功能是否正常
# Test first example print(dataset[0]) # For images: verify they load if 'image' in dataset.features: dataset[0]['image'] # Should return PIL Image # Check dataset size before upload print(f"Size: {len(dataset)} examples")
檢查 metadata.csv 是否有“file_name”列
驗證相對路徑,無前導斜槓
確保沒有資料夾超過 10k 個檔案
上傳後:
- 檢視器:`https://huggingface.co/datasets/username/dataset`
- 測試載入:`load_dataset("username/dataset")`
- 驗證特徵是否保留:`print(dataset.features)`
常見問題 → 解決方案
問題 | 解決方案 |
---|---|
“儲存庫未找到” | 執行 `hf auth login` |
記憶體錯誤 | 使用 `max_shard_size="500MB"` |
資料集檢視器無法工作 | 等待 5-10 分鐘,檢查 README.md 配置 |
超時錯誤 | 使用 `multi_commits=True` |
檔案大於 50GB | 分割成更小的檔案 |
“檔案未找到” | 在元資料中使用相對路徑 |
資料集檢視器配置
注意:本節主要適用於直接上傳到 Hub 的資料集(透過 UI 或 `upload_large_folder`)。使用 `push_to_hub()` 上傳的資料集通常會自動配置檢視器。
當自動檢測有效時
資料集檢視器自動檢測標準結構
- 檔案命名:`train.csv`、`test.json`、`validation.parquet`
- 目錄命名:`train/`、`test/`、`validation/`
- 帶分隔符的分割名稱:`test-data.csv` ✓ (而非 `testdata.csv` ✗)
手動配置
對於自定義結構,請在 README.md 中新增 YAML
---
configs:
- config_name: default # Required even for single config!
data_files:
- split: train
path: "data/train/*.parquet"
- split: test
path: "data/test/*.parquet"
---
多個配置示例
---
configs:
- config_name: english
data_files: "en/*.parquet"
- config_name: french
data_files: "fr/*.parquet"
---
常見檢視器問題
- 上傳後無檢視器:請等待 5-10 分鐘進行處理
- “配置名稱錯誤”:新增 `config_name` 欄位(必需!)
- 未檢測到檔案:檢查命名模式(需要分隔符)
- 檢視器已停用:從 README YAML 中刪除 `viewer: false`
快速模板
# ImageFolder with metadata
dataset = load_dataset("imagefolder", data_dir="./images")
dataset.push_to_hub("username/dataset")
# Memory-efficient upload
dataset.push_to_hub("username/dataset", max_shard_size="500MB")
# Multiple CSV files
dataset = load_dataset('csv', data_files={'train': 'train.csv', 'test': 'test.csv'})
dataset.push_to_hub("username/dataset")
文件
核心文件:新增資料集 | 資料集檢視器 | 儲存限制 | 上傳指南
資料集卡
提醒使用者新增包含以下內容的資料集卡(README.md)
- 資料集描述和用法
- 許可證資訊
- 引用詳情
詳情請參閱 資料集卡指南。
附錄:特殊情況
WebDataset 結構
用於流式傳輸大型媒體資料集
- 建立 1-5GB 的 tar 分片
- 一致的內部結構
- 使用 `upload_large_folder` 上傳
科學資料
- HDF5/NetCDF → 轉換為帶陣列特徵的 Parquet
- 時間序列 → Array2D(shape=(None, n))
- 複雜元資料 → 儲存為 JSON 字串
社群資源
對於非常專業或定製的格式
- 在 Hub 上搜索類似資料集:`https://huggingface.co/datasets`
- 在 Hugging Face 論壇 上尋求建議
- 加入 Hugging Face Discord 獲取即時幫助
- 許多特定領域格式在 Hub 上已有示例