首页 文章

密集层中的Keras错误,预期4维具有形状的数组(1024,2)[重复]

提问于
浏览
0

这个问题在这里已有答案:

我正在尝试使用具有GPU启用的Tensorflow后端的Keras训练3层密集神经网络的模型 .

我拥有的数据集是400万张20x40像素的图像,我将这些图像放在目录中,并带有它们所属类别的名称 .

由于数据量很大,我无法将其全部加载到RAM中并将其提供给我的模型,因此我认为使用Keras's ImageDataGenerator,特别是函数flow_from_directory()可以解决问题 . 这产生了一个(x,y)元组,其中x是图像的numpy数组,y是图像的标签 .

我希望模型知道访问numpy数组作为我的模型的输入,所以我将我的输入形状设置为:(None,20,40,3)其中None是批量大小,20和40是大小图像和3是图像中的通道数 . 这不起作用,因为当我尝试训练我的模型时,我不断收到错误: ValueError: Error when checking target: expected dense_3 to have 4 dimensions, but got array with shape (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')

1 回答

  • 2

    您的输入形状对于密集图层是错误的 .

    密集层期望形状中的输入(无,长度) .

    你需要重塑你的输入,使它们成为矢量:

    imageBatch=imageBatch.reshape((imageBatch.shape[0],20*40*3))
    

    或者使用卷积层,期望输入形状类型(None,nRows,nCols,nChannels),如 tensorflow .

相关问题