Datasets:
File size: 2,135 Bytes
485748e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | """PyTorch loading example for Shelly97/multimodal-hate-triplets.
Install: pip install -U datasets pillow torch transformers
The processor is supplied by the caller to match the training model.
"""
import torch
from torch.utils.data import Dataset
def process_image_text(image, text, processor):
processed = processor(
text=text, images=image, max_length=77, padding="max_length",
truncation=True, return_tensors="pt",
)
return {key: processed[key].squeeze(0)
for key in ("pixel_values", "input_ids", "attention_mask")}
def load_and_process(example, processor):
result = {}
for key in ("org", "pos", "neg"):
# Hugging Face Image columns decode directly into PIL images.
with example[f"{key}_img"].convert("RGB") as image:
result[key] = process_image_text(image, example[f"{key}_txt"], processor)
result["label"] = example["org_label"]
return result
class MultimodalDataset(Dataset):
def __init__(self, data, processor):
self.data = data
self.processor = processor
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
# Propagate corrupt data/processor errors so training cannot silently lose rows.
return load_and_process(self.data[idx], self.processor)
def collate_fn(batch):
if not batch:
return None
result = {
key: {field: torch.stack([item[key][field] for item in batch])
for field in ("pixel_values", "input_ids", "attention_mask")}
for key in ("org", "pos", "neg")
}
result["label"] = torch.tensor([item["label"] for item in batch], dtype=torch.long)
return result
# Usage (after publication):
# from datasets import load_dataset
# from transformers import CLIPProcessor
# from torch.utils.data import DataLoader
# processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
# data_pairs = load_dataset("Shelly97/multimodal-hate-triplets", split="train")
# dataset = MultimodalDataset(data_pairs, processor)
# loader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=collate_fn)
|