简体   繁体   中英

Keras/Theano VGG16 AttributeError: 'Model' object has no attribute 'ndim'

I am trying to build a Keras model with a Theano backend that connects a time-distributed VGG16 network to an LSTM layer, then finally to a series of dense layers. However, I get the following error:

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.ndim
AttributeError: 'Model' object has no attribute 'ndim'

Here is the section of the code I use to build the model:

        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([video], 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM