Python 图形已断开连接:无法获取tensor KerasTensor()转移学习的值

Python 图形已断开连接:无法获取tensor KerasTensor()转移学习的值,python,tensorflow,machine-learning,keras,deep-learning,Python,Tensorflow,Machine Learning,Keras,Deep Learning,我试图在自己的模型上实现迁移学习,但失败了。我的实现遵循这里的指南 tensoflow 2.4.1 Keras 2.4.3 旧型号(效果非常好): 迁移学习: old_model = load_model('old.model') # removes top 2 activation layers for i in range(2): old_model.pop() # mark loaded layers as not trainable for layer in old_mod

我试图在自己的模型上实现迁移学习,但失败了。我的实现遵循这里的指南

tensoflow 2.4.1

Keras 2.4.3

旧型号(效果非常好):

迁移学习:

old_model = load_model('old.model')

# removes top 2 activation layers
for i in range(2):
  old_model.pop()

# mark loaded layers as not trainable
for layer in old_model.layers:
    layer.trainable = False

# initialize the new model

in_puts = Input(shape=(256, 256, 3))
count = len(old_model.layers)
ll = old_model.layers[count - 1].output
classes = len(lb.classes_)
ll = Dense(classes)(ll)
ll = Activation("softmax", name="activation3_" + NODE)(ll)
model = Model(inputs=in_puts, outputs=ll) # ERROR

opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])

# train the network
H = model.fit(x_train, y_train, validation_data=(x_test, y_test), steps_per_epoch=len(x_train) // BS, epochs=EPOCHS, verbose=1)


# save the model to disk
model.save("new.model")
错误

ValueError: Graph disconnected: cannot obtain value for tensor
KerasTensor(type_spec=TensorSpec(shape=(None, 256, 256, 3), dtype=tf.float32,
name='conv2d_input'), name='conv2d_input', description="created by layer 'conv2d_input'") at
layer "conv2d". The following previous layers were accessed without issue: []

这里有一个简单的方法来操作转移学习与您的模型

classes = 10
sub_old_model = Model(old_model.input, old_model.layers[-3].output)
sub_old_model.trainable = False

ll = Dense(classes)(sub_old_model.output)
ll = Activation("softmax")(ll)

model = Model(inputs=sub_old_model.input, outputs=ll) 
首先,使用要冻结的旧模型中的层创建子模型(
trainable=False
)。在我们的示例中,我们采用所有层,不包括最后一个
密集
Softmax
激活

然后将子模型输出传递到新的可训练层


此时,您只需创建一个新的模型实例来组装所有部件

在@Marco Cerliani的帮助下,我通过更改为
LabelEncoder
sparse\u Category\u crossentropy

classes = 10
sub_old_model = Model(old_model.input, old_model.layers[-3].output)
sub_old_model.trainable = False

ll = Dense(classes)(sub_old_model.output)
ll = Activation("softmax")(ll)

model = Model(inputs=sub_old_model.input, outputs=ll)