Datasets:
Tasks:
Image Classification
Sub-tasks:
multi-class-image-classification
Languages:
English
Size:
100K<n<1M
DOI:
License:
File size: 33,883 Bytes
639f152 4599473 639f152 4599473 639f152 26af90a 639f152 26af90a 639f152 26af90a 639f152 4599473 639f152 |
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 |
---
license: mit
viewer: false
task_categories:
- image-classification
task_ids:
- multi-class-image-classification
tags:
- computer-vision
- product-classification
- e-commerce
- retail
- few-shot-learning
- meta-learning
- benchmark
size_categories:
- 100K<n<1M
language:
- en
pretty_name: FSL Product Classification Dataset
configs:
- config_name: default
data_files: "data.tzst"
default: true
dataset_info:
features:
- name: image
dtype: image
- name: label
dtype: int64
- name: class_name
dtype: string
- name: image_id
dtype: string
splits:
- name: train
num_bytes: 9945644054
num_examples: 279747
download_size: 9945644054
dataset_size: 9945644054
---
# Few-Shot Learning (FSL) Product Classification Dataset
## Dataset Description
This dataset is designed for **Few-Shot Learning (FSL)** research in product classification tasks. It contains product images organized into 763 distinct classes, with an average of approximately 367 images per class (279,747 total images), making it ideal for training and evaluating few-shot learning algorithms in e-commerce and retail scenarios. Note that class numbers are not continuous.
### Key Features
- **763 product classes** covering diverse product categories
- **279,747 total images** (average of ~367 images per class)
- **High-quality product images** suitable for computer vision research
- **Variable class distribution** with non-continuous class numbers
- **Efficient tzst compression** for reduced storage and faster transfer
### Dataset Statistics
- **Total Classes**: 763
- **Total Images**: 279,747
- **Images per Class**: ~367 (average, variable distribution)
- **Class Numbers**: Non-continuous (some class numbers may be missing)
- **Image Format**: PNG
- **Typical Image Size**: 50-100 KB per image
- **Compressed Archive Size**: ~9.9 GB (data.tzst)
## Dataset Structure
The dataset is stored in a compressed tzst archive ([`data.tzst`](data.tzst)) with the following structure:
```text
data.tzst
├── class_0/
│ ├── class_0_0.png
│ ├── class_0_1.png
│ └── ...
├── class_1/
│ ├── class_1_0.png
│ ├── class_1_1.png
│ └── ...
└── ... (763 total classes with non-continuous numbers)
```
**Note**: Class numbers are not continuous. For example, you might have class_0, class_2, class_5, etc., but not class_1, class_3, class_4. The total number of classes is 763.
## Quick Start
Get started with the FSL Product Classification dataset in just a few steps:
```python
from datasets import Dataset
import os
from tzst import extract_archive
# 1. Extract the dataset
extract_archive("data.tzst", "extracted_data/")
# 2. Load a few samples
data_dir = "extracted_data"
samples = []
for class_dir in sorted(os.listdir(data_dir))[:3]: # First 3 classes
if class_dir.startswith("class_"):
class_path = os.path.join(data_dir, class_dir)
for img_file in os.listdir(class_path)[:5]: # First 5 images
if img_file.endswith('.png'):
samples.append({
'image': os.path.join(class_path, img_file),
'label': int(class_dir.split("_")[1]),
'class_name': class_dir,
'image_id': img_file.replace('.png', '')
})
print(f"Loaded {len(samples)} sample images from 3 classes")
```
For complete setup and advanced usage, see the sections below.
## Usage
## Installation and Setup
### Quick Start Installation
```bash
# Create a new virtual environment (recommended)
python -m venv fsl-env
# Activate virtual environment
# On Windows:
fsl-env\Scripts\activate
# On macOS/Linux:
# source fsl-env/bin/activate
# Install core dependencies
pip install datasets tzst pillow
# Install additional dependencies for machine learning
pip install torch torchvision numpy scikit-learn matplotlib seaborn tqdm
# For Jupyter notebook users
pip install jupyter ipywidgets
```
### Complete Requirements
Create a `requirements.txt` file with the following dependencies:
```text
# Core dependencies
datasets>=2.14.0
tzst>=1.2.8
pillow>=9.0.0
# Machine learning
torch>=1.9.0
torchvision>=0.10.0
numpy>=1.21.0
scikit-learn>=1.0.0
# Data analysis and visualization
pandas>=1.3.0
matplotlib>=3.4.0
seaborn>=0.11.0
# Progress bars and utilities
tqdm>=4.62.0
pathlib>=1.0.1
# Optional: for advanced few-shot learning
learn2learn>=0.1.7
higher>=0.2.1
# Optional: for notebook usage
jupyter>=1.0.0
ipywidgets>=7.6.0
```
Install all requirements:
```bash
pip install -r requirements.txt
```
### Docker Setup (Optional)
For a containerized environment:
```dockerfile
FROM python:3.9-slim
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
git \
wget \
&& rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Set environment variables
ENV PYTHONPATH=/app
ENV HF_DATASETS_CACHE=/app/cache
# Create cache directory
RUN mkdir -p /app/cache
CMD ["python", "-c", "print('FSL Product Classification environment ready!')"]
```
Build and run:
```bash
docker build -t fsl-product-classification .
docker run -it --rm -v $(pwd)/data:/app/data fsl-product-classification bash
```
### Loading the Dataset
```python
import os
from tzst import extract_archive
from datasets import Dataset, Features, Value, Image, ClassLabel
from PIL import Image as PILImage
# Extract the dataset archive
extract_archive("data.tzst", "extracted_data/")
# Create a custom dataset loader
def load_fsl_dataset(data_dir="extracted_data"):
samples = []
class_names = []
# Scan for class directories
for class_dir in sorted(os.listdir(data_dir)):
if class_dir.startswith("class_"):
class_path = os.path.join(data_dir, class_dir)
if os.path.isdir(class_path):
class_id = int(class_dir.split("_")[1])
class_names.append(class_dir)
# Load images from this class
for img_file in os.listdir(class_path):
if img_file.endswith('.png'):
img_path = os.path.join(class_path, img_file)
image_id = img_file.replace('.png', '')
samples.append({
'image': img_path,
'label': class_id,
'class_name': class_dir,
'image_id': image_id
})
# Create features definition
features = Features({
'image': Image(),
'label': Value('int64'),
'class_name': Value('string'),
'image_id': Value('string')
})
# Create dataset
return Dataset.from_list(samples, features=features)
# Load the dataset
dataset = load_fsl_dataset()
print(f"Loaded {len(dataset)} samples from {len(set(dataset['class_name']))} classes")
```
Streaming mode for memory-efficient processing of large archive:
```python
from tzst import extract_archive
import tempfile
import os
# Use streaming extraction for memory efficiency
with tempfile.TemporaryDirectory() as temp_dir:
# Extract with streaming mode
extract_archive("data.tzst", temp_dir, streaming=True)
# Process extracted data
dataset = load_fsl_dataset(temp_dir)
# ... your processing code here
```
### Data Exploration
```python
from collections import Counter
import matplotlib.pyplot as plt
# Analyze class distribution
class_counts = Counter(dataset['class_name'])
print(f"Number of classes: {len(class_counts)}")
print(f"Average images per class: {len(dataset) / len(class_counts):.1f}")
# Plot class distribution (top 20 classes)
top_classes = class_counts.most_common(20)
classes, counts = zip(*top_classes)
plt.figure(figsize=(12, 6))
plt.bar(range(len(classes)), counts)
plt.xlabel('Class')
plt.ylabel('Number of Images')
plt.title('Top 20 Classes by Image Count')
plt.xticks(range(len(classes)), [c.replace('class_', '') for c in classes], rotation=45)
plt.tight_layout()
plt.show()
# Display sample images
import random
def show_samples(dataset, num_samples=8):
"""Display random samples from the dataset"""
indices = random.sample(range(len(dataset)), num_samples)
fig, axes = plt.subplots(2, 4, figsize=(15, 8))
axes = axes.flatten()
for i, idx in enumerate(indices):
sample = dataset[idx]
axes[i].imshow(sample['image'])
axes[i].set_title(f"{sample['class_name']}\nID: {sample['image_id']}")
axes[i].axis('off')
plt.tight_layout()
plt.show()
# Show sample images
show_samples(dataset)
```
### Few-Shot Learning Setup
#### Basic Few-Shot Episode Creation
```python
import random
from collections import defaultdict
import torch
from torch.utils.data import DataLoader
def create_few_shot_split(dataset, n_way=5, k_shot=5, n_query=15, seed=None):
"""
Create a few-shot learning episode
Args:
dataset: Hugging Face Dataset instance or custom dataset
n_way: Number of classes in the episode
k_shot: Number of support samples per class
n_query: Number of query samples per class
seed: Random seed for reproducibility
Returns:
support_set, query_set: Lists of (image, label) tuples
"""
if seed is not None:
random.seed(seed)
# Group samples by class
class_samples = defaultdict(list)
for i, sample in enumerate(dataset):
class_samples[sample['label']].append(i)
# Filter classes with enough samples
valid_classes = [
class_id for class_id, indices in class_samples.items()
if len(indices) >= k_shot + n_query
]
if len(valid_classes) < n_way:
raise ValueError(f"Not enough classes with {k_shot + n_query} samples. "
f"Found {len(valid_classes)}, need {n_way}")
# Sample n_way classes
episode_classes = random.sample(valid_classes, n_way)
support_set = []
query_set = []
for new_label, original_class in enumerate(episode_classes):
class_indices = random.sample(class_samples[original_class], k_shot + n_query)
# Support samples
for idx in class_indices[:k_shot]:
sample = dataset[idx]
support_set.append((sample['image'], new_label, sample['image_id']))
# Query samples
for idx in class_indices[k_shot:]:
sample = dataset[idx]
query_set.append((sample['image'], new_label, sample['image_id']))
return support_set, query_set
# Create a 5-way 5-shot episode
support_set, query_set = create_few_shot_split(dataset, n_way=5, k_shot=5, n_query=15)
print(f"Support set: {len(support_set)} samples")
print(f"Query set: {len(query_set)} samples")
```
#### Advanced FSL Dataset Class
```python
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from PIL import Image
import numpy as np
class FSLProductDataset(Dataset):
"""
Few-Shot Learning Dataset wrapper for product classification
"""
def __init__(self, hf_dataset, transform=None, target_transform=None):
self.dataset = hf_dataset
self.transform = transform or self.get_default_transform()
self.target_transform = target_transform
# Create label mapping for non-continuous labels
unique_labels = sorted(set(hf_dataset['label']))
self.label_to_idx = {label: idx for idx, label in enumerate(unique_labels)}
self.idx_to_label = {idx: label for label, idx in self.label_to_idx.items()}
def get_default_transform(self):
"""Default image transformations"""
return transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
sample = self.dataset[idx]
image = sample['image']
# Convert to PIL Image if needed
if not isinstance(image, Image.Image):
image = Image.fromarray(image)
# Apply transforms
if self.transform:
image = self.transform(image)
# Map label to continuous indices
label = self.label_to_idx[sample['label']]
if self.target_transform:
label = self.target_transform(label)
return image, label, sample['image_id']
def get_class_samples(self, class_label):
"""Get all samples for a specific class"""
indices = [i for i, sample in enumerate(self.dataset)
if sample['label'] == class_label]
return [self[i] for i in indices]
def create_episode_dataloader(self, n_way=5, k_shot=5, n_query=15,
batch_size=None, shuffle=True):
"""Create a DataLoader for a few-shot episode"""
support_set, query_set = create_few_shot_split(
self.dataset, n_way=n_way, k_shot=k_shot, n_query=n_query
)
# Convert to tensors
support_images = []
support_labels = []
query_images = []
query_labels = []
for image, label, _ in support_set:
if isinstance(image, Image.Image):
image = self.transform(image) if self.transform else image
support_images.append(image)
support_labels.append(label)
for image, label, _ in query_set:
if isinstance(image, Image.Image):
image = self.transform(image) if self.transform else image
query_images.append(image)
query_labels.append(label)
support_data = (torch.stack(support_images), torch.tensor(support_labels))
query_data = (torch.stack(query_images), torch.tensor(query_labels))
return support_data, query_data
# Example usage with PyTorch
transform = transforms.Compose([
transforms.Resize((84, 84)), # Common size for few-shot learning
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
# Load dataset
fsl_dataset = FSLProductDataset(dataset, transform=transform)
# Create episode data
support_data, query_data = fsl_dataset.create_episode_dataloader(
n_way=5, k_shot=1, n_query=15
)
print(f"Support images shape: {support_data[0].shape}")
print(f"Support labels shape: {support_data[1].shape}")
print(f"Query images shape: {query_data[0].shape}")
print(f"Query labels shape: {query_data[1].shape}")
```
#### Meta-Learning Training Loop
```python
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
def train_fsl_model(model, dataset, num_episodes=1000, n_way=5, k_shot=1,
n_query=15, lr=0.001, device='cuda'):
"""
Basic training loop for few-shot learning
Args:
model: Few-shot learning model (e.g., Prototypical Network)
dataset: FSLProductDataset instance
num_episodes: Number of training episodes
n_way, k_shot, n_query: Episode configuration
lr: Learning rate
device: Training device
"""
model.to(device)
optimizer = optim.Adam(model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
model.train()
total_loss = 0
total_acc = 0
for episode in tqdm(range(num_episodes), desc="Training"):
# Create episode
support_data, query_data = dataset.create_episode_dataloader(
n_way=n_way, k_shot=k_shot, n_query=n_query
)
support_images, support_labels = support_data
query_images, query_labels = query_data
# Move to device
support_images = support_images.to(device)
support_labels = support_labels.to(device)
query_images = query_images.to(device)
query_labels = query_labels.to(device)
# Forward pass
optimizer.zero_grad()
logits = model(support_images, support_labels, query_images)
loss = criterion(logits, query_labels)
# Backward pass
loss.backward()
optimizer.step()
# Calculate accuracy
pred = logits.argmax(dim=1)
acc = (pred == query_labels).float().mean()
total_loss += loss.item()
total_acc += acc.item()
if (episode + 1) % 100 == 0:
avg_loss = total_loss / 100
avg_acc = total_acc / 100
print(f"Episode {episode + 1}: Loss = {avg_loss:.4f}, Acc = {avg_acc:.4f}")
total_loss = 0
total_acc = 0
# Example: Simple Prototypical Network
class SimplePrototypicalNetwork(nn.Module):
def __init__(self, backbone):
super().__init__()
self.backbone = backbone
def forward(self, support_images, support_labels, query_images):
# Encode images
support_features = self.backbone(support_images)
query_features = self.backbone(query_images)
# Calculate prototypes
n_way = len(torch.unique(support_labels))
prototypes = []
for class_idx in range(n_way):
class_mask = support_labels == class_idx
class_features = support_features[class_mask]
prototype = class_features.mean(dim=0)
prototypes.append(prototype)
prototypes = torch.stack(prototypes)
# Calculate distances and logits
distances = torch.cdist(query_features, prototypes)
logits = -distances # Negative distance as logits
return logits
```
## Research Applications
This dataset is particularly well-suited for:
### Few-Shot Learning
- **Meta-learning algorithms** (MAML, Prototypical Networks, Relation Networks)
- **Metric learning approaches** (Siamese Networks, Triplet Networks)
- **Gradient-based meta-learning** methods
### Transfer Learning
- **Pre-training** on large-scale product data
- **Domain adaptation** from general images to products
- **Fine-tuning** strategies for product classification
### Computer Vision Research
- **Product recognition** and retrieval
- **E-commerce applications**
- **Retail automation**
- **Visual search** systems
## Benchmark Tasks
### Standard Few-Shot Learning Evaluation
The following benchmarks are recommended for evaluating few-shot learning models on this dataset:
#### Standard Evaluation Protocol
```python
import numpy as np
from sklearn.metrics import accuracy_score, classification_report
import json
def evaluate_fsl_model(model, dataset, num_episodes=600, n_way=5, k_shot=1,
n_query=15, device='cuda'):
"""
Evaluate few-shot learning model using standard protocol
Returns:
dict: Evaluation results with mean accuracy and confidence interval
"""
model.eval()
accuracies = []
with torch.no_grad():
for _ in tqdm(range(num_episodes), desc="Evaluating"):
# Create episode
support_data, query_data = dataset.create_episode_dataloader(
n_way=n_way, k_shot=k_shot, n_query=n_query
)
support_images, support_labels = support_data
query_images, query_labels = query_data
# Move to device
support_images = support_images.to(device)
support_labels = support_labels.to(device)
query_images = query_images.to(device)
query_labels = query_labels.to(device)
# Predict
logits = model(support_images, support_labels, query_images)
pred = logits.argmax(dim=1)
# Calculate episode accuracy
acc = (pred == query_labels).float().mean().item()
accuracies.append(acc)
# Calculate statistics
mean_acc = np.mean(accuracies)
std_acc = np.std(accuracies)
ci_95 = 1.96 * std_acc / np.sqrt(len(accuracies))
results = {
'mean_accuracy': mean_acc,
'std_accuracy': std_acc,
'confidence_interval_95': ci_95,
'num_episodes': num_episodes,
'config': f"{n_way}-way {k_shot}-shot"
}
return results
# Benchmark configurations
benchmark_configs = [
{'n_way': 5, 'k_shot': 1, 'n_query': 15}, # 5-way 1-shot
{'n_way': 5, 'k_shot': 5, 'n_query': 15}, # 5-way 5-shot
{'n_way': 10, 'k_shot': 1, 'n_query': 15}, # 10-way 1-shot
{'n_way': 10, 'k_shot': 5, 'n_query': 15}, # 10-way 5-shot
]
# Run benchmarks
def run_benchmark_suite(model, dataset, num_episodes=600):
"""Run complete benchmark suite"""
results = {}
for config in benchmark_configs:
config_name = f"{config['n_way']}-way_{config['k_shot']}-shot"
print(f"\nEvaluating {config_name}...")
result = evaluate_fsl_model(
model, dataset, num_episodes=num_episodes, **config
)
results[config_name] = result
print(f"Accuracy: {result['mean_accuracy']:.4f} ± {result['confidence_interval_95']:.4f}")
return results
# Example usage
# results = run_benchmark_suite(model, test_dataset)
```
#### Cross-Domain Evaluation
```python
def create_cross_domain_split(dataset, train_ratio=0.6, val_ratio=0.2, test_ratio=0.2, seed=42):
"""
Create train/validation/test splits at the class level for cross-domain evaluation
Args:
dataset: Hugging Face Dataset
train_ratio: Proportion of classes for training
val_ratio: Proportion of classes for validation
test_ratio: Proportion of classes for testing
seed: Random seed
Returns:
dict: Splits with class indices for each set
"""
np.random.seed(seed)
# Get unique classes
unique_classes = sorted(set(dataset['label']))
n_classes = len(unique_classes)
# Calculate split sizes
n_train = int(n_classes * train_ratio)
n_val = int(n_classes * val_ratio)
n_test = n_classes - n_train - n_val
# Shuffle and split classes
shuffled_classes = np.random.permutation(unique_classes)
train_classes = shuffled_classes[:n_train]
val_classes = shuffled_classes[n_train:n_train + n_val]
test_classes = shuffled_classes[n_train + n_val:]
# Create sample indices for each split
train_indices = [i for i, sample in enumerate(dataset) if sample['label'] in train_classes]
val_indices = [i for i, sample in enumerate(dataset) if sample['label'] in val_classes]
test_indices = [i for i, sample in enumerate(dataset) if sample['label'] in test_classes]
return {
'train': {'indices': train_indices, 'classes': train_classes.tolist()},
'validation': {'indices': val_indices, 'classes': val_classes.tolist()},
'test': {'indices': test_indices, 'classes': test_classes.tolist()}
}
# Create cross-domain splits
splits = create_cross_domain_split(dataset)
print(f"Train classes: {len(splits['train']['classes'])}")
print(f"Validation classes: {len(splits['validation']['classes'])}")
print(f"Test classes: {len(splits['test']['classes'])}")
```
### Performance Baselines
Expected performance ranges for different few-shot learning approaches:
| Method | 5-way 1-shot | 5-way 5-shot | 10-way 1-shot | 10-way 5-shot |
|--------|--------------|--------------|----------------|----------------|
| Random Baseline | 20.0% | 20.0% | 10.0% | 10.0% |
| Nearest Neighbor | 35-45% | 55-65% | 25-35% | 45-55% |
| Prototypical Networks | 45-55% | 65-75% | 35-45% | 55-65% |
| MAML | 48-58% | 68-78% | 38-48% | 58-68% |
| Relation Networks | 50-60% | 70-80% | 40-50% | 60-70% |
### Utility Functions
```python
import os
import json
from pathlib import Path
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
def dataset_statistics(dataset):
"""
Generate comprehensive statistics about the dataset
Args:
dataset: Hugging Face Dataset or list of samples
Returns:
dict: Dataset statistics
"""
if hasattr(dataset, '__getitem__') and hasattr(dataset, '__len__'):
# Hugging Face Dataset
labels = dataset['label']
class_names = dataset['class_name']
image_ids = dataset['image_id']
else:
# List of samples
labels = [sample['label'] for sample in dataset]
class_names = [sample['class_name'] for sample in dataset]
image_ids = [sample['image_id'] for sample in dataset]
# Basic statistics
n_samples = len(labels)
n_classes = len(set(labels))
class_counts = Counter(labels)
# Calculate distribution statistics
counts = list(class_counts.values())
stats = {
'total_samples': n_samples,
'total_classes': n_classes,
'avg_samples_per_class': n_samples / n_classes,
'min_samples_per_class': min(counts),
'max_samples_per_class': max(counts),
'std_samples_per_class': np.std(counts),
'class_distribution': dict(class_counts)
}
return stats
def plot_class_distribution(dataset, top_k=50, figsize=(15, 8)):
"""
Plot class distribution
Args:
dataset: Dataset object
top_k: Number of top classes to show
figsize: Figure size
"""
# Get class counts
if hasattr(dataset, '__getitem__'):
class_counts = Counter(dataset['label'])
else:
class_counts = Counter([sample['label'] for sample in dataset])
# Get top k classes
top_classes = class_counts.most_common(top_k)
labels, counts = zip(*top_classes)
# Plot
plt.figure(figsize=figsize)
bars = plt.bar(range(len(labels)), counts)
plt.xlabel('Class ID')
plt.ylabel('Number of Samples')
plt.title(f'Class Distribution (Top {top_k} Classes)')
plt.xticks(range(0, len(labels), max(1, len(labels)//10)),
[str(l) for l in labels[::max(1, len(labels)//10)]], rotation=45)
# Add statistics text
total_samples = sum(counts)
avg_samples = total_samples / len(counts)
plt.text(0.02, 0.98, f'Total Classes: {len(class_counts)}\n'
f'Shown Classes: {len(labels)}\n'
f'Avg Samples/Class: {avg_samples:.1f}',
transform=plt.gca().transAxes, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
plt.tight_layout()
plt.show()
return top_classes
def save_dataset_info(dataset, output_path="dataset_info.json"):
"""
Save dataset information to JSON file
Args:
dataset: Dataset object
output_path: Path to save the info file
"""
stats = dataset_statistics(dataset)
# Add additional metadata
info = {
'dataset_name': 'FSL Product Classification Dataset',
'version': '1.0',
'statistics': stats,
'description': 'Few-shot learning dataset for product classification',
'features': {
'image': 'PIL Image object',
'label': 'Class ID (int64)',
'class_name': 'Class name string',
'image_id': 'Unique image identifier'
}
}
# Save to file
with open(output_path, 'w') as f:
json.dump(info, f, indent=2)
print(f"Dataset info saved to: {output_path}")
return info
def verify_dataset_integrity(dataset_path="data.tzst"):
"""
Verify dataset archive integrity
Args:
dataset_path: Path to the dataset archive
Returns:
bool: True if dataset is valid
"""
from tzst import test_archive
try:
# Test archive integrity
is_valid = test_archive(dataset_path)
if is_valid:
print(f"✅ Dataset archive '{dataset_path}' is valid")
# Get archive info
from tzst import list_archive
contents = list_archive(dataset_path, verbose=True)
print(f"📁 Archive contains {len(contents)} files")
# Check for expected structure
class_dirs = [item['name'] for item in contents
if item['name'].startswith('class_') and item['name'].endswith('/')]
print(f"🏷️ Found {len(class_dirs)} class directories")
return True
else:
print(f"❌ Dataset archive '{dataset_path}' is corrupted")
return False
except Exception as e:
print(f"❌ Error verifying dataset: {e}")
return False
def create_data_splits(dataset, split_ratios={'train': 0.8, 'test': 0.2},
strategy='random', seed=42):
"""
Create train/test splits from the dataset
Args:
dataset: Dataset object
split_ratios: Dictionary with split names and ratios
strategy: 'random' or 'stratified'
seed: Random seed
Returns:
dict: Split datasets
"""
from sklearn.model_selection import train_test_split
np.random.seed(seed)
if strategy == 'random':
# Simple random split
indices = list(range(len(dataset)))
train_size = split_ratios.get('train', 0.8)
train_indices, test_indices = train_test_split(
indices, train_size=train_size, random_state=seed
)
splits = {
'train': dataset.select(train_indices),
'test': dataset.select(test_indices)
}
elif strategy == 'stratified':
# Stratified split maintaining class distribution
labels = dataset['label']
indices = list(range(len(dataset)))
train_size = split_ratios.get('train', 0.8)
train_indices, test_indices = train_test_split(
indices, train_size=train_size, stratify=labels, random_state=seed
)
splits = {
'train': dataset.select(train_indices),
'test': dataset.select(test_indices)
}
# Print split information
for split_name, split_dataset in splits.items():
n_samples = len(split_dataset)
n_classes = len(set(split_dataset['label']))
print(f"{split_name.capitalize()} split: {n_samples} samples, {n_classes} classes")
return splits
```
## Troubleshooting
### Common Issues and Solutions
#### 1. Archive Extraction Issues
**Problem**: Error extracting `data.tzst` file
```text
TzstDecompressionError: Failed to decompress archive
```
**Solution**:
```python
# Verify archive integrity first
from tzst import test_archive
if not test_archive("data.tzst"):
print("Archive is corrupted. Please re-download.")
# Use streaming mode for large archives
from tzst import extract_archive
extract_archive("data.tzst", "output/", streaming=True)
```
#### 2. Non-continuous Class Labels
**Problem**: Class labels are not continuous (0, 1, 2, ...)
**Solution**:
```python
# Create label mapping
unique_labels = sorted(set(dataset['label']))
label_to_idx = {label: idx for idx, label in enumerate(unique_labels)}
# Apply mapping
def map_labels(example):
example['mapped_label'] = label_to_idx[example['label']]
return example
dataset = dataset.map(map_labels)
```
#### 3. CUDA/GPU Issues
**Problem**: CUDA out of memory during training
**Solution**:
```python
# Reduce batch size or use CPU
device = torch.device('cpu') # Force CPU usage
# Or use gradient accumulation
accumulation_steps = 4
for i, (support_data, query_data) in enumerate(dataloader):
loss = model(support_data, query_data) / accumulation_steps
loss.backward()
if (i + 1) % accumulation_steps == 0:
optimizer.step()
optimizer.zero_grad()
```
### Performance Tips
1. **Use appropriate image sizes**: For few-shot learning, 84x84 or 224x224 are common choices
2. **Enable streaming mode**: For memory-efficient processing of large archives
3. **Use data augmentation**: Improve few-shot performance with transforms
4. **Cache preprocessed data**: Save processed episodes to disk for faster iteration
## Citation
If you use this dataset in your research, please cite it as shown on the Hugging Face dataset page:
<https://huggingface.co/datasets/xixu-me/fsl-product-classification?doi=true>
## License
This dataset is released under the MIT License. See the [LICENSE file](LICENSE) for details.
## Data Ethics and Responsible Use
This dataset is intended for academic research and educational purposes in few-shot learning and computer vision. Users should:
- **Respect intellectual property**: Images may be subject to copyright; use only for research purposes
- **Consider bias**: Be aware that product categories may reflect certain demographic or geographic biases
- **Commercial use**: While the license permits it, consider the ethical implications of commercial applications
- **Attribution**: Please cite this dataset in any published work
## Limitations
- **Image quality**: Variable image quality and backgrounds may affect model performance
- **Class imbalance**: Some classes may have significantly fewer images than others
- **Non-continuous labels**: Class numbers are not sequential, which may require label mapping
- **Temporal bias**: Product images reflect trends from the time of collection
|