我想将时尚mnist数据集拟合到预先训练的Keras模型。原始数据是具有形状(28、28)的灰度图像。我必须将其转换为形状(224、224、3)以符合模型的要求。但是,对于我的机器的内存/ cpu而言,太大了(对我的机器而言)太大了,使我死机了,我不可能一次转换整个样本集(60K个样本)。我尝试使用Keras数据生成器将32个样本的小批量输入到转换函数,但是会导致ValueError。我的代码如下:
# Get the data
from keras.datasets import fashion_mnist
(x, y), (x_test, y_test) = fashion_mnist.load_data()
# Function to transform data to required shape
def transform_dat(img, lbl):
img = np.array([cv2.merge((idx, idx, idx)) for idx in img])
img = np.array([cv2.resize(idx, (224, 224)) for idx in img])
lbl = to_categorical(lbl, num_classes=10)
return img, lbl
# Fit to a pre-trained model
datagen_train = ImageDataGenerator(rescale=1./255)
datagen_val = ImageDataGenerator(rescale=1./255)
# This will freeze my pc due to the transform function applied to large dataset
history = model.fit_generator(datagen_train.flow(transform_dat(x, y)),
steps_per_epoch=len(x) / 32,
epochs=5,
validation_data=datagen_val.flow(transform_dat(x_test, y_test)),
validation_steps=len(x_test) / 32)
# This will result in error due to wrong shape
history = model.fit_generator(transform_dat(datagen_train.flow(x, y)),
steps_per_epoch=len(x) / 32,
epochs=5, validation_data=transform_dat(datagen_val.flow(x_test, y_test)),
validation_steps=len(x_test) / 32)
ValueError: ('Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape', (32, 28, 28))
您能帮我解决问题吗,也就是说,创建一个生成小批量的生成器,我的机器可以在其中应用转换功能,将数据转换为适合模型的正确形状?
谢谢。