To select a subset of images from a very large dataset while ensuring that the trained model on this subset performs closely to a model trained on the full dataset, you need to sample your data in a way that captures the diversity and distribution of the entire dataset.
One effective strategy is to leverage feature representations from a pre-trained convolutional neural network (CNN) to capture the intrinsic structure of the data and then perform clustering to select representative images from each cluster.
Here's how you can do it:
-
Feature Extraction: Use a pre-trained CNN (like ResNet50) to extract feature vectors from your images. These features capture high-level representations of the images.
-
Clustering: Apply a clustering algorithm (e.g., MiniBatch KMeans) on the extracted features to group similar images together.
-
Representative Selection: For each cluster, select one or more images that are closest to the cluster centroid. These images are representative of their respective clusters.
By selecting images this way, your subset will cover the diversity of the entire dataset, ensuring that the model trained on this subset can generalize well.
Below is the Python code that implements this method:
import os
import shutil
from PIL import Image
from tqdm import tqdm
import numpy as np
import torch
from torchvision import models, transforms
from torch.utils.data import Dataset, DataLoader
from sklearn.cluster import MiniBatchKMeans
from scipy.spatial.distance import cdist
# Set the device (GPU if available)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class ImageFolderDataset(Dataset):
"""
Custom Dataset to load images from a directory.
"""
def __init__(self, root_dir, transform=None):
self.image_paths = []
supported_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif')
for root, _, files in os.walk(root_dir):
for file in files:
if file.lower().endswith(supported_extensions):
self.image_paths.append(os.path.join(root, file))
self.transform = transform
def __getitem__(self, index):
path = self.image_paths[index]
image = Image.open(path).convert('RGB')
if self.transform:
image = self.transform(image)
return image, path # Return path as well for reference
def __len__(self):
return len(self.image_paths)
def select_representative_images(root_dir, output_dir, num_samples):
"""
Selects a subset of images that are representative of the entire dataset.
Parameters:
- root_dir: Path to the directory containing the images.
- output_dir: Path to the directory where the selected images will be saved.
- num_samples: Desired number of images in the subset.
"""
# Define image transformations
transform = transforms.Compose([
transforms.Resize((224,224)), # Resize to the size expected by the pre-trained model
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], # Normalization for ImageNet pre-trained models
std=[0.229, 0.224, 0.225]),
])
# Create the dataset and dataloader
dataset = ImageFolderDataset(root_dir=root_dir, transform=transform)
data_loader = DataLoader(dataset, batch_size=32, shuffle=False, num_workers=4)
# Load a pre-trained model and set it to evaluation mode
model = models.resnet50(pretrained=True)
model.eval()
model = model.to(device)
# Remove the classification layer to get feature representations
feature_extractor = torch.nn.Sequential(*list(model.children())[:-1])
# Extract features from images
features = []
paths = []
with torch.no_grad():
for images, batch_paths in tqdm(data_loader, desc="Extracting features"):
images = images.to(device)
outputs = feature_extractor(images)
outputs = outputs.view(outputs.size(0), -1) # Flatten features
features.append(outputs.cpu().numpy())
paths.extend(batch_paths)
features = np.vstack(features) # Shape: (num_images, feature_dim)
# Perform clustering on the features
print("Clustering features...")
num_clusters = num_samples
kmeans = MiniBatchKMeans(n_clusters=num_clusters, batch_size=1000)
kmeans.fit(features)
cluster_centers = kmeans.cluster_centers_
labels = kmeans.labels_
# Select the image closest to each cluster center
print("Selecting representative images...")
selected_indices = []
for i in range(num_clusters):
cluster_idx = np.where(labels == i)[0]
cluster_features = features[cluster_idx]
center = cluster_centers[i].reshape(1, -1)
distances = cdist(cluster_features, center)
closest_idx_in_cluster = cluster_idx[np.argmin(distances)]
selected_indices.append(closest_idx_in_cluster)
selected_paths = [paths[i] for i in selected_indices]
# Copy selected images to the output directory
print(f"Copying {len(selected_paths)} images to {output_dir}...")
os.makedirs(output_dir, exist_ok=True)
for path in selected_paths:
shutil.copy(path, output_dir)
print("Done.")
# Example usage:
root_dir = 'path_to_your_large_image_dataset' # Replace with your dataset path
output_dir = 'path_to_output_directory' # Replace with your desired output path
num_samples = 10000 # Number of images you want in the subset
select_representative_images(root_dir, output_dir, num_samples)
Explanation of the Code:
Notes and Considerations:
-
Memory Management: Since the dataset is very large, this code uses batch processing and avoids loading all images into memory at once.
-
Performance: Extracting features and clustering are computationally intensive tasks. Running this code will take time depending on the size of your dataset and your hardware capabilities.
-
Adjustments:
- If you run into memory issues during clustering, consider reducing the batch size in
MiniBatchKMeans or using dimensionality reduction techniques like PCA before clustering.
- You can adjust the
num_samples to control the size of your subset.
-
Dependencies: Ensure that you have the following libraries installed:
torch and torchvision for deep learning and image processing tasks.
scikit-learn for clustering.
numpy, PIL, and tqdm for array operations, image handling, and progress tracking respectively.
Alternative Approach: Stratified Sampling (if Labels are Available):
If your dataset is labeled and you want to maintain the class distribution in your subset, you can perform stratified sampling:
import pandas as pd
# Assume you have a CSV file with image paths and their corresponding labels
data = pd.read_csv('image_labels.csv') # columns: ['image_path', 'label']
# Stratified sampling
from sklearn.model_selection import train_test_split
subset_size = 0.1 # Proportion of data to include in the subset
train_data, _ = train_test_split(data, stratify=data['label'], test_size=(1 - subset_size))
# Copy selected images
for path in train_data['image_path']:
shutil.copy(path, output_dir)
This method is simpler and faster but requires labels for all images. It ensures that the class distribution in your subset resembles that of the full dataset.
Final Thoughts:
By selecting a representative subset using clustering on feature representations, you ensure that your model is trained on data that captures the diversity of the full dataset. This approach helps the model generalize well while reducing training time.
Remember to monitor the model's performance and adjust your subset selection method as needed. In some cases, combining multiple approaches (e.g., combining clustering with stratified sampling) may yield better results.