具有Conv2D错误的Input_shape

时间:2017-09-19 05:05:01

标签: keras

我想使用Keras Conv2D但出现错误:

model.add(Conv2D(64, (2, 2), padding='valid', data_format='channels_last', input_shape=(1, 4, 4, 1)))

Keras doc告诉我们输入形状是一个4D张量,但它会抛出这个错误:

ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5.

我做了一些调试,发现有topology.py中的参数检查:

if spec.ndim is not None:
            if K.ndim(x) != spec.ndim:
                raise ValueError('Input ' + str(input_index) +
                                 ' is incompatible with layer ' +
                                 self.name + ': expected ndim=' +
                                 str(spec.ndim) + ', found ndim=' +
                                 str(K.ndim(x)))

我发现x = Tensor("conv2d_1_input:0", shape=(?, 1, 4, 4, 1), dtype=float32)是一个带dim=5的张量,spec是带有dim=4的InputSpec的实例,它永远不会相等。如何解决这个问题呢?

代码:

def _build_model(self):
    # Neural Net for Deep-Q learning Model
    model = Sequential()
    model.add(Conv2D(64, (2, 2), padding='valid', data_format='channels_last', input_shape=(1, 4, 4, 1)))
    model.add(Conv2D(128, 3, strides=(1, 1), padding='valid'))
    model.add(Flatten())
    model.add(Dense(16, activation='relu'))
    model.add(Dense(self.action_size, activation='linear'))
    model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))
    return model

1 个答案:

答案 0 :(得分:0)

试试这个:

model.add(Conv2D(64, (2, 2), padding='valid', data_format='channels_last', input_shape=(4, 4, 1)))

Convolutional2D层需要#samples * height * width * channels。从您的model.fit()函数推断样本数量,您可以在其中输入数据。

如果你把MNIST看作最简单的例子,那就可以了:

model = Sequential()

model.add(Conv2D(32, (3, 3), padding='same', input_shape=(28, 28, 1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
...
history = model.fit(X-train, y_train, batch_size=32, epochs=1)