python - 有没有办法使用数据增强来增加带有标签的数据集的大小?
问题描述
我正在尝试在 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
实际上并没有添加行,而是在训练期间插入了增强的数据。是否有任何其他工具可以保存或增加具有相同标签的数据?
解决方案
以下是我最终使用标签保存增强数据的方式。我采样了 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")
推荐阅读
- linux - 如何使用 jmeter 的“OS Sampler”在 ubuntu 上运行终端的任何命令
- typo3 - TYPO3 域存储库临时更改设置
- asp.net - 如何将使用 MediaRecorder 录制的视频保存到 Asp.NET Core 中的文件中?
- hpc - Rattle 不以普通用户身份运行,而是在 HPC 集群中以 root 身份运行
- .net-core - 在 httpclient 中使用作用域服务
- java - Keycloak Java 管理员客户端在触发验证电子邮件时返回 400 错误
- udp - 我可以在 UDP 服务器上为 NAT 后面的客户端使用不同的接收/发送端口吗?
- javascript - 如何在 VueJS 单元测试中触发子组件的点击事件?
- python - Python数据类从父数据类继承部分属性
- react-native - react native socket.io-client 在 Release 构建时未连接到 https 服务器