连接错误:添加的层必须是类Lay的实例

2024-09-29 01:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Keras中做了一个片段,我有两个顺序模型需要合并到第三个模型中,这是我的最终模型。代码片段是用Keras的一个版本构建的,其中允许使用Merge方法,所以现在我尝试用concatenate method with axis = 0替换它,因此行为与Merge()相同。尽管进行了所有这些修改,我还是收到了以下stacktrace作为输出:

Traceback (most recent call last):
  File ".\CaptionGenerator.py", line 738, in <module>
    caption.BeamPredictor('image.PNG')
  File ".\CaptionGenerator.py", line 485, in BeamPredictor
    self.SetNeuralNetworksWithoutApi()
  File ".\CaptionGenerator.py", line 433, in SetNeuralNetworksWithoutApi
    Activation('softmax')
  File "D:\Anaconda\lib\site-packages\keras\engine\sequential.py", line 92, in __init__
    self.add(layer)
  File "D:\Anaconda\lib\site-packages\keras\engine\sequential.py", line 131, in add
    'Found: ' + str(layer))
TypeError: The added layer must be an instance of class Layer. Found: Tensor("concatenate_1/concat:0", shape=(?, 40, 300), dtype=float32)

代码段代码是:

^{pr2}$

我无法理解concatenate()的结果不应该是Layer类的实例的原因,因为从函数返回的对象中没有一个Layer属性,根据文档,该属性是张量。有没有办法在不切换到API的情况下解决这个问题?谢谢。在


Tags: 代码inpy模型selflayerlinemerge
1条回答
网友
1楼 · 发布于 2024-09-29 01:31:25

至少对于最终的模型,您需要切换到functional API,因为Sequential被设计成具有一个单一的输入,因此您在其中强制使用2个张量,这是行不通的。这是因为Sequential为其输入创建了一个占位符。大致如下:

image_model = Sequential([
Dense(embedding_size, input_shape=(2048,), activation='relu'),
RepeatVector(self.MaxCaptionLength)
])

caption_model = Sequential([
Embedding(self.numberOfWords, embedding_size, input_length=self.MaxCaptionLength),
LSTM(256, return_sequences=True),
TimeDistributed(Dense(300))
])

image_in = Input(shape=(2048,))
caption_in = Input(shape=(MaxCaptionLength, numberOfWords))
merged = concatenate([image_model(image_in), caption_model(caption_in)], axis=0)
latent = Bidirectional(LSTM(256, return_sequences=False))(merged)
out = Dense(self.numberOfWords, activation='softmax')(latent)
final_model = Model([image_in, caption_in], out)

final_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])
final_model.summary()

您仍然可以将图像和标题模型分开,但是即使有一个解决方法可以使用2个输入顺序连接,我也不推荐它,因为它不是API的预期用途。在

相关问题 更多 >