模型的输出张量必须是Keras张量

2024-05-20 14:38:19 发布

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

我试图从两个模型输出的差异中学习到一个模型。所以我做了如下代码。但发生错误读取:

TypeError: Output tensors to a Model must be Keras tensors. Found: Tensor("sub:0", shape=(?, 10), dtype=float32)

我找到了相关的答案,包括lambda,但我无法解决这个问题。 有人知道这个问题吗? 可以看到张量转换为keras的张量。在

提前支付。在

from keras.layers import Dense
from keras.models import Model
from keras.models import Sequential

left_branch = Sequential()
left_branch.add(Dense(10, input_dim=784))

right_branch = Sequential()
right_branch.add(Dense(10, input_dim=784))

diff = left_branch.output - right_branch.output

model = Model(inputs=[left_branch.input, right_branch.input], outputs=[diff])
model.compile(optimizer='rmsprop', loss='binary_crossentropy', loss_weights=[1.])

model.summary(line_length=150)

Tags: from模型importrightaddbranchinputmodel
2条回答

我想我解决了这个问题,但它可能是确切的答案。 我添加了如下代码:

diff = left_branch.output - right_branch.output
setattr(diff, '_keras_history', getattr(right_branch.output, '_keras_history'))
setattr(diff, '_keras_shape', getattr(right_branch.output, '_keras_shape'))
setattr(diff, '_uses_learning_phase', getattr(right_branch.output, '_uses_learning_phase'))

错误发生的原因是diff张量没有名为_keras_history的attr。因此,有意地将它们添加到diff张量中可以避免上述错误。我检查了原始代码的运行和可学习性。在

最好让所有操作都由一个层完成,不要像那样减去输出(我不会因为做的事情与文档期望的不同而冒隐藏错误的风险):

from keras.layers import *

def negativeActivation(x):
    return -x

left_branch = Sequential()
left_branch.add(Dense(10, input_dim=784))

right_branch = Sequential()
right_branch.add(Dense(10, input_dim=784))

negativeRight = Activation(negativeActivation)(right_branch.output) 
diff = Add()([left_branch.output,negativeRight])

model = Model(inputs=[left_branch.input, right_branch.input], outputs=diff)
model.compile(optimizer='rmsprop', loss='binary_crossentropy', loss_weights=[1.])

当连接这样的模型时,我更喜欢使用Model的方式,使用层,而不是使用Sequential

^{2}$

这样,您可以创建具有相同层的其他模型,它们将共享相同的权重:

leftModel = Model(leftInput,left_branch)
rightModel = Model(rightInput,right_branch)
fullModel = Model([leftInput,rightInput],diff)

如果它们共享同一层,训练其中一个会影响其他人。 例如,您可以在编译之前生成left_branch.trainable = False来训练完整模型中正确的部分(或者再次编译以进行训练)。在

相关问题 更多 >