我试图构建一个使用Theano后端的Keras模型,将一个时间分布的VGG16网络连接到LSTM层,最后连接到一系列的全连接层。然而,我遇到了以下错误:
Traceback (most recent call last): File "osr.py", line 341, in <module> osr.generate_osr_model() File "osr.py", line 145, in generate_osr_model cnn_out = GlobalAveragePooling2D()(cnn_base) File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 529, in __call__ self.assert_input_compatibility(x) File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 464, in assert_input_compatibility if K.ndim(x) != spec.ndim: File "/usr/local/lib/python2.7/dist-packages/keras/backend/theano_backend.py", line 142, in ndim return x.ndimAttributeError: 'Model' object has no attribute 'ndim'
这是我用来构建模型的代码部分:
video = Input(shape=(self.frames_per_sequence, 3, self.rows, self.columns)) cnn_base = VGG16(input_shape=(3, self.rows, self.columns), weights="imagenet", include_top=False) cnn_out = GlobalAveragePooling2D()(cnn_base) cnn = Model(input=cnn_base.input, output=cnn_out) cnn.trainable = False encoded_frames = TimeDistributed(cnn)(video) encoded_vid = LSTM(256)(encoded_frames) hidden_layer = Dense(output_dim=1024, activation="relu")(encoded_vid) outputs = Dense(output_dim=class_count, activation="softmax")(hidden_layer) osr = Model(, outputs) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-08, schedule_decay=0.004) osr.compile(loss="categorical_crossentropy", optimizer=optimizer, metrics=["categorical_accuracy"])
回答:
解决方案是将cnn_base.output作为GlobalAveragePooling2D层的输入:
cnn_out = GlobalAveragePooling2D()(cnn_base.output)