SMOTE算法能否应用于图像不平衡数据集?求相关源码
基于SMOTE的方法能否应用于图像数据集?
原生SMOTE确实是为结构化表格数据设计的,但经过适配后完全可以用于图像数据集,主要有两种可行的适配思路:
适配思路
- 特征空间适配(推荐):先通过预训练CNN提取图像的高维特征,在特征空间应用SMOTE生成新的少数类特征,再通过生成模型(如VAE、GAN)将生成的特征映射回图像空间;或者直接用增强后的特征训练分类模型。这种方法避开了图像像素空间的高维稀疏问题,效果更稳定。
- 像素空间适配:将图像展平为一维向量后直接应用SMOTE,但由于图像像素维度极高,生成的新图像往往模糊、缺乏语义信息,实际应用价值较低。
代码示例(特征空间SMOTE实现)
以下是基于PyTorch和imblearn的实现示例,核心是先提取图像特征再应用SMOTE:
import numpy as np import torch from torchvision.models import resnet18 from imblearn.over_sampling import SMOTE from torchvision.transforms import Compose, ToTensor, Normalize # 初始化预训练ResNet18作为特征提取器(去掉分类头) def get_feature_extractor(device): model = resnet18(pretrained=True) feature_extractor = torch.nn.Sequential(*list(model.children())[:-1]) feature_extractor.to(device).eval() return feature_extractor # 批量提取图像特征 def extract_image_features(images, extractor, device): transform = Compose([ ToTensor(), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # 转换图像为模型可接受的张量格式 tensor_imgs = torch.stack([transform(img) for img in images]).to(device) with torch.no_grad(): features = extractor(tensor_imgs) # 展平特征向量 return features.flatten(start_dim=1).cpu().numpy() # 模拟不平衡图像数据集(实际替换为你的数据集) # 100张224x224的RGB图像,少数类20张,多数类80张 sample_count = 100 minority_count = 20 images = np.random.rand(sample_count, 224, 224, 3).astype(np.float32) labels = np.concatenate([np.zeros(minority_count), np.ones(sample_count - minority_count)]) # 设备配置 device = "cuda" if torch.cuda.is_available() else "cpu" # 提取特征 feature_extractor = get_feature_extractor(device) img_features = extract_image_features(images, feature_extractor, device) # 应用SMOTE进行过采样 smote = SMOTE(random_state=42) resampled_features, resampled_labels = smote.fit_resample(img_features, labels) # 可选:若需生成新图像,可训练VAE/GAN将resampled_features映射回图像空间
额外说明
如果需要更贴合图像特性的过采样方法,还可以使用SMOTE的图像专用变体,比如SMOTE-IM(针对图像纹理和结构优化),或是结合GAN的思路:先用SMOTE增强少数类特征,再用GAN基于这些特征生成真实感更强的图像。
内容的提问来源于stack exchange,提问作者Anju Ucok Lubis
相关产品推荐
相关产品推荐

