首页 文章

Keras维度与ImageDataGenerator不匹配

提问于
浏览
0

我试图用Keras将我的数据“流”到一个神经网络中 . 我正在使用.flow_from_directory方法,这个过程让我适合 . 我正在使用keras文档中的基本示例(我正在使用tensorflow):

ROWS = 64
COLS = 64
CHANNELS = 3

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
    rescale=1./255)

test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
    'train',
    target_size=(64, 64),
    batch_size=32,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    '../tutorial/l1/kaggle_solutions/dogs_vs_cats/valid',
    target_size=(64, 64),
    batch_size=1,
    class_mode='binary')
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import Dense, Activation, Flatten, Dropout, MaxPooling2D
from keras.regularizers import l2

model = Sequential()
model.add(Convolution2D(4, 4, 4, border_mode='same', input_shape=(64, 64,3), activation='relu'))
from keras.utils.np_utils import to_categorical
from keras.optimizers import SGD, RMSprop

model.compile(loss='binary_crossentropy', optimizer=RMSprop(lr=1e-4), metrics=['accuracy'])


model.fit_generator(
    train_generator,  
    samples_per_epoch=2500,
    nb_epoch=20,
    validation_data=validation_generator,
    nb_val_samples=3100)

运行此我得到以下错误:

Exception: Error when checking model target: expected convolution2d_84 to have 4 dimensions, but got array with shape (32, 1)

我已经修了很长时间并找到了以下内容 - 将'model.add'切换为灰度输入model.add(Convolution2D(4,4,4,border_mode ='same',input_shape =(64,64, 3),activation ='relu'))给我以下错误(如预期 - 但似乎确认我的原始输入是正确的):

Error when checking model input: expected convolution2d_input_49 to have shape (None, 64, 64, 1) but got array with shape (32, 64, 64, 3)

所以我传递了(在原文中)原始的32,64,64,3的4维数组,但我得到的错误是我认为意味着预期(1,64,64,3)并得到了(32) ,64,64,3)

因为我正在分批发送数据32.好奇的是,如果我将批处理设置为零(给出0,64,64,3输入),我得到:

Exception: Error when checking model target: expected convolution2d_87 to have 4 dimensions, but got array with shape (0, 1)

根据文档,我无法弄清楚将数据流入模型的正确方法 - 我在使用fit_generator时无法将批量大小传递给模型,并且看起来batch_size(样本数量)是问题所在 .

任何帮助将不胜感激 .

1 回答

  • 1

    ImageDataGenerator 没有问题 . 如错误消息中所述,模型输出的形状与其目标的形状之间存在不匹配 . 您使用 class_mode = 'binary' ,因此模型的预期输出是单个值,但它会产生形状 (batch_size, 64, 64, 4) 的输出,因为您有一个卷积层而模型中没有其他内容 .

    尝试这样的事情:

    model.add(Convolution2D(4, 4, 4, border_mode='same', input_shape=(64, 64,3), activation='relu'))
    model.add(Flatten())
    model.add(Dense(1))
    model.add(Activation('sigmoid'))
    

相关问题