C.W.K.
Stream
Lesson 05 of 07 · published

Hugging Face Datasets

~12 min · huggingface, datasets, arrow, streaming

Level 0Tensor 호기심
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

한 라이브러리, 만 dataset

datasets (Hugging Face 라이브러리) 가 Hugging Face Hub 의 어떤 dataset 이든 — 그리고 많은 local format 도 — uniform API. 두 큰 feature 가 특별:

  • Apache Arrow backing — dataset 이 disk 에서 memory-mapped. 100GB dataset 로딩이 거의 0 RAM; iterate 하는 것만 read.
  • Streaming mode — download 너무 큰 dataset 위, streaming=True 설정하고 full file download 없이 iterate.

표준 workflow

  1. load_dataset("name") — fetch (또는 stream) 하고 cache.
  2. .map(fn, batched=True) — preprocessing 병렬 적용, result disk 에 cache.
  3. .set_format("torch", columns=[...]) — iterate 시 PyTorch tensor 직접 반환, 수동 변환 없이.
  4. 다른 Dataset 처럼 DataLoader 에 넘김.

왜 너 자신 data 있어도 중요

local data 위에도 Datasets 라이브러리가 줘: disk-backed cache 의 병렬 preprocessing, lossless format 변환 (CSV/JSON/Parquet/Arrow), trivial train/val/test split 관리. 합리적 size 의 NLP / vision project 위 data layer 로 사용 가치.

Code

Hub 에서 로드·python
# pip install datasets
from datasets import load_dataset

# Load IMDB sentiment dataset
ds = load_dataset("imdb")
print(ds)
# DatasetDict({
#     train: Dataset({features: ['text', 'label'], num_rows: 25000})
#     test:  Dataset({features: ['text', 'label'], num_rows: 25000})
# })

train = ds['train']
print(train[0])    # {'text': '...', 'label': 1}
.map 의 preprocessing — 병렬 + cached·python
from datasets import load_dataset
from transformers import AutoTokenizer

ds = load_dataset("imdb")
tok = AutoTokenizer.from_pretrained("distilbert-base-uncased")

def encode(batch):
    return tok(batch['text'], padding='max_length', truncation=True, max_length=512)

# .map runs in parallel by default; result is cached to disk
ds_enc = ds.map(encode, batched=True, num_proc=4)

# Tell datasets to return PyTorch tensors when iterated
ds_enc = ds_enc.with_format('torch', columns=['input_ids', 'attention_mask', 'label'])

print(ds_enc['train'][0])
# {'input_ids': tensor([...]), 'attention_mask': tensor([...]), 'label': tensor(1)}
거대 dataset 의 streaming·python
from datasets import load_dataset

# C4 is hundreds of GB. Stream it instead of downloading.
ds = load_dataset("c4", "en", split="train", streaming=True)

# Iterate without downloading the whole thing
for i, ex in enumerate(ds):
    if i >= 3: break
    print(ex['text'][:80])

# Streaming datasets are IterableDatasets — wrap with DataLoader
from torch.utils.data import DataLoader
loader = DataLoader(ds.with_format('torch'), batch_size=8)
너 파일 로드·python
from datasets import load_dataset

# CSV
csv_ds = load_dataset("csv", data_files="my_data.csv")

# Parquet — fast columnar format, good for large tabular data
pq_ds = load_dataset("parquet", data_files="my_data.parquet")

# JSON Lines
jsonl_ds = load_dataset("json", data_files="my_data.jsonl")

# Even your own image folder, in ImageFolder layout
img_ds = load_dataset("imagefolder", data_dir="./images")

External links

Exercise

어떤 HuggingFace dataset 이든 로드 ('rotten_tomatoes' 가 작은 NLP). distilbert tokenizer 로 .map 통해 tokenize. DataLoader 로 wrap 하고 한 batch iterate — input_ids 와 attention_mask 가 (batch, seq_len) shape 의 tensor 로 돌아오는지 검증.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.