Selecting a representative subset of your large image dataset can significantly speed up the training process while maintaining model performance close to that achieved with the full dataset. Below are several strategies to accomplish this, along with Python code examples for implementation:
- Random Sampling
- Stratified Sampling (if labels are available)
- Clustering-Based Selection
1. Random Sampling
Description:
Randomly select a subset of images from the entire dataset. This method is simple and works well when the dataset is uniformly distributed.
Pros:
- Easy to implement.
- No additional computational overhead.
Cons:
- May not capture the diversity of the dataset, especially with imbalanced classes.
Python Implementation:
import os
import random
import shutil
def random_sampling(source_dir, target_dir, subset_size, seed=42):
"""
Randomly samples a subset of images from the source directory to the target directory.
Args:
source_dir (str): Path to the source image directory.
target_dir (str): Path to the target subset directory.
subset_size (int): Number of images to sample.
seed (int): Random seed for reproducibility.
"""
os.makedirs(target_dir, exist_ok=True)
all_images = [f for f in os.listdir(source_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
random.seed(seed)
sampled_images = random.sample(all_images, min(subset_size, len(all_images)))
for img in sampled_images:
shutil.copy(os.path.join(source_dir, img), os.path.join(target_dir, img))
print(f"Copied {len(sampled_images)} images to {target_dir}.")
# Example usage:
# random_sampling('/path/to/full_dataset', '/path/to/subset_dataset', subset_size=10000)
2. Stratified Sampling (When Labels Are Available)
Description:
Ensure that the subset maintains the same class distribution as the full dataset. This is crucial for classification tasks, especially when dealing with imbalanced datasets.
Pros:
- Preserves class distribution, reducing bias.
- Ensures representation from all classes.
Cons:
Python Implementation:
import os
import random
import shutil
from collections import defaultdict
def stratified_sampling(source_dir, target_dir, subset_size, seed=42):
"""
Performs stratified sampling based on class labels.
Args:
source_dir (str): Path to the source image directory with subdirectories as class labels.
target_dir (str): Path to the target subset directory.
subset_size (int): Total number of images to sample.
seed (int): Random seed for reproducibility.
"""
os.makedirs(target_dir, exist_ok=True)
class_dirs = [d for d in os.listdir(source_dir) if os.path.isdir(os.path.join(source_dir, d))]
class_to_images = defaultdict(list)
# Collect images per class
for cls in class_dirs:
cls_path = os.path.join(source_dir, cls)
images = [f for f in os.listdir(cls_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
class_to_images[cls] = images
# Calculate number of samples per class
total_images = sum(len(imgs) for imgs in class_to_images.values())
samples_per_class = {cls: max(1, int(len(imgs) / total_images * subset_size)) for cls, imgs in class_to_images.items()}
random.seed(seed)
for cls, imgs in class_to_images.items():
selected = random.sample(imgs, min(samples_per_class[cls], len(imgs)))
target_cls_dir = os.path.join(target_dir, cls)
os.makedirs(target_cls_dir, exist_ok=True)
for img in selected:
shutil.copy(os.path.join(source_dir, cls, img), os.path.join(target_cls_dir, img))
print(f"Stratified sampling completed. Subset saved to {target_dir}.")
# Example usage:
# stratified_sampling('/path/to/full_dataset', '/path/to/subset_dataset', subset_size=10000)
3. Clustering-Based Selection (Without Labels)
Description:
Use clustering to group similar images and select representative images from each cluster. This approach helps in maintaining diversity in the subset.
Pros:
- Captures diversity in data.
- Doesn't require labels.
Cons:
- Computationally intensive, especially with very large datasets.
- Requires feature extraction, which may require significant memory.
Python Implementation:
Here, we'll use a pre-trained CNN (e.g., ResNet50) from Keras to extract features, perform clustering with KMeans, and select representative images.
import os
import numpy as np
from tqdm import tqdm
from sklearn.cluster import KMeans
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import Model
import shutil
def extract_features(source_dir, batch_size=32, image_size=(224, 224)):
"""
Extracts features from images using a pre-trained ResNet50 model.
Args:
source_dir (str): Path to the image directory.
batch_size (int): Number of images to process in a batch.
image_size (tuple): Target image size for the model.
Returns:
features (np.array): Extracted features.
image_paths (list): List of image file paths.
"""
model = ResNet50(weights='imagenet', include_top=False, pooling='avg')
features = []
image_paths = []
imgs = []
paths = []
all_images = [os.path.join(source_dir, f) for f in os.listdir(source_dir)
if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
for img_path in tqdm(all_images, desc="Extracting features"):
try:
img = image.load_img(img_path, target_size=image_size)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
imgs.append(x)
paths.append(img_path)
if len(imgs) == batch_size:
x_batch = np.vstack(imgs)
feat = model.predict(x_batch)
features.append(feat)
imgs = []
except Exception as e:
print(f"Error processing {img_path}: {e}")
if imgs:
x_batch = np.vstack(imgs)
feat = model.predict(x_batch)
features.append(feat)
features = np.vstack(features)
image_paths = paths
return features, image_paths
def clustering_selection(source_dir, target_dir, subset_size, n_clusters=1000):
"""
Selects a subset of images based on clustering of features.
Args:
source_dir (str): Path to the source image directory.
target_dir (str): Path to save the subset images.
subset_size (int): Total number of images to select.
n_clusters (int): Number of clusters for KMeans.
"""
os.makedirs(target_dir, exist_ok=True)
# Step 1: Extract features
features, image_paths = extract_features(source_dir)
# Step 2: Perform clustering
print("Clustering features...")
kmeans = KMeans(n_clusters=n_clusters, random_state=42, verbose=1)
kmeans.fit(features)
cluster_labels = kmeans.labels_
# Step 3: Select representative images
images_per_cluster = subset_size // n_clusters
selected = []
cluster_to_images = {}
for idx, label in enumerate(cluster_labels):
cluster_to_images.setdefault(label, []).append(image_paths[idx])
for label, imgs in cluster_to_images.items():
selected += random.sample(imgs, min(images_per_cluster, len(imgs)))
# If not enough samples, fill randomly
if len(selected) < subset_size:
remaining = subset_size - len(selected)
remaining_imgs = set(image_paths) - set(selected)
selected += random.sample(list(remaining_imgs), remaining)
# Step 4: Copy selected images
for img_path in selected:
filename = os.path.basename(img_path)
shutil.copy(img_path, os.path.join(target_dir, filename))
print(f"Clustering-based selection completed. {len(selected)} images copied to {target_dir}.")
# Example usage:
# clustering_selection('/path/to/full_dataset', '/path/to/subset_dataset', subset_size=10000, n_clusters=1000)
Notes:
- Feature Extraction: The
extract_features function uses ResNet50 to extract 2048-dimensional feature vectors for each image. You can choose a different pre-trained model based on your requirements.
- Clustering: KMeans clustering groups images into
n_clusters. Adjust n_clusters based on the diversity of your dataset and the desired subset size.
- Subset Size: Ensure that
subset_size is appropriately distributed across clusters to maintain diversity.
Optimizations for Large Datasets:
- Incremental Clustering: For very large datasets, consider using incremental clustering algorithms like
MiniBatchKMeans instead of KMeans.
- Parallel Processing: Utilize multiprocessing to speed up feature extraction.
- Storage Management: Ensure you have sufficient storage for the intermediate feature representations.
Choosing the Right Method
- If you have labeled data and classes are imbalanced, use Stratified Sampling to ensure each class is proportionally represented.
- If you don't have labels, consider Clustering-Based Selection to maintain diversity.
- If the dataset is uniformly distributed and labeled, simple Random Sampling might suffice.
Final Recommendations
- Validate Subset Quality: Before training, visualize samples from the subset to ensure they represent the diversity of the full dataset.
- Iterative Sampling: You can iteratively adjust the subset size and sampling strategy based on validation performance.
- Hybrid Approaches: Combine methods, e.g., perform stratified clustering if labels are partially available.
By selecting an appropriate subset using one of these methods, you can achieve faster training times while maintaining model performance close to training on the full dataset.