我正在尝试使用 Keras 和启用 GPU 的 Tensorflow 后端来训练 3 层密集神经网络模型。
我拥有的数据集是 400 万张 20x40 像素的图像,我将这些图像放置在目录中,并带有它们所属类别的名称。
由于数据量很大,我不能将其全部加载到 RAM 中并将其提供给我的模型,因此我认为使用Keras 的 ImageDataGenerator,特别是函数 flow_from_directory() 可以解决问题。这会产生一个 (x, y) 元组,其中 x 是图像的 numpy 数组,y 是图像的标签。
我希望模型知道访问作为模型输入的 numpy 数组,因此我将输入形状设置为: (None,20,40,3) 其中 None 是批量大小,20 和 40 是大小图像和 3 是图像中的通道数。然而,这不起作用,因为当我尝试训练我的模型时,我不断收到错误:ValueError:检查目标时出错:预期密集_3 有 4 个维度,但得到了形状为 (1024, 2) 的数组
我知道原因是它从 flow_from_directoy 获取元组,我想我可以更改输入形状以匹配,但是,我担心这会使我的模型无用,因为我将使用图像进行预测而不是预先分类元组。所以我的问题是,我怎样才能让 flow_from_directory 将图像提供给我的模型,并且只使用元组来验证它的训练?我在这里误解了什么吗?
作为参考,这是我的代码:
from keras.models import Model
from keras.layers import *
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import TensorBoard
# Prepare the Image Data Generator.
train_datagen = ImageDataGenerator()
test_datagen = ImageDataGenerator()
train_generator = train_datagen.flow_from_directory(
'/path/to/train_data/',
target_size=(20, 40),
batch_size=1024,
)
test_generator = test_datagen.flow_from_directory(
'/path/to/test_data/',
target_size=(20, 40),
batch_size=1024,
)
# Define input tensor.
input_t = Input(shape=(20,40,3))
# Now create the layers and pass the input tensor to it.
hidden_1 = Dense(units=32, activation='relu')(input_t)
hidden_2 = Dense(units=16)(hidden_1)
prediction = Dense(units=1)(hidden_2)
# Now put it all together and create the model.
model = Model(inputs=input_t, outputs=prediction)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
# Prepare Tensorboard callback and start training.
tensorboard = TensorBoard(log_dir='./graph', histogram_freq=0, write_graph=True, write_images=True)
print(test_generator)
model.fit_generator(
train_generator,
steps_per_epoch=2000,
epochs=100,
validation_data=test_generator,
validation_steps=800,
callbacks=[tensorboard]
)
# Save trained model.
model.save('trained_model.h5')
对于 Dense 层,您的输入形状是错误的。
密集层期望输入形状(无,长度)。
你要么需要重塑你的输入,使它们成为向量:
imageBatch=imageBatch.reshape((imageBatch.shape[0],20*40*3))
或者使用卷积层,它期望像tensorflow那样的输入形状类型 (None,nRows,nCols,nChannels) 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句