xixu-me's picture
Enhance README.md with Quick Start guide, updated dataset statistics, and citation information
4599473
|
raw
history blame
33.9 kB
---
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