首页 > 解决方案 > 有没有办法使用数据增强来增加带有标签的数据集的大小?

问题描述

我正在尝试在 Kaggle 的数字识别数据集上实现逻辑回归。训练集中有 42000 行,我想使用数据增强来增加计数。

我尝试使用 keras 的ImageDataGenerator对象

datagen = ImageDataGenerator(  
        rotation_range=30,   
        zoom_range = 0.2,  
        width_shift_range=0.2,         
        height_shift_range=0.2)

datagen.fit(X_train)

但是大小保持不变,后来我发现ImageDataGenerator实际上并没有添加行,而是在训练期间插入了增强的数据。是否有任何其他工具可以保存或增加具有相同标签的数据?

标签: pythontensorflowkeras

解决方案


以下是我最终使用标签保存增强数据的方式。我采样了 5 行以获得观看乐趣。当考虑完整数据集时,for循环可能不是写入数组的最佳方式

#importing data
train = pd.read_csv("train.csv")
X_train = train.drop(labels=["label"], axis=1)
y_train = train.label

#sampling 5 rows and reshaping x to 4D array
x = X_train[0:5].values.reshape(-1,28,28,1)
y = y_train[0:5]

#Augmentation parameters
from keras_preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(  
        rotation_range=30,   
        zoom_range = 0.2,  
        width_shift_range=0.2,  
        height_shift_range=0.2,  
        )  

#using .flow instead of .fit to write to an array
augmented_data = []
num_augmented = 0
batch = 5  # for 5*5 = 25 entries
for X_batch, y_batch in datagen.flow(X_2, y, batch_size=batch, shuffle=False,):
    augmented_data.append(X_batch)
    augmented_labels.append(y_batch)
    num_augmented += 1
    if num_augmented == x.shape[0]:
        break
augmented_data = np.concatenate(augmented_data) #final shape = (25,28,28,1)
augmented_labels = np.concatenate(augmented_labels)


#Lets take a look at augmented images
for index, image in enumerate(augmented_data):
    plt.subplot(5, 5, index + 1)
    plt.imshow(np.reshape(image, (28,28)), cmap=plt.cm.gray)


# reshaping and converting to df
augmented_data_reshaped = augmented_data.reshape(25, 784)
augmented_dataframe = pd.DataFrame(augmented_data_reshaped)
# inserting labels in df
augmented_dataframe.insert(0, "label", augmented_labels)
header = list(train.columns.values)
augmented_dataframe.columns = header
# write
augmented_dataframe.to_csv("augmented.csv")

增强数字数据


推荐阅读