使用tf.keras.Sequential.pop()移除最后一层时出现图断开错误求助
问题:tf.keras.Sequential.pop() 调用报错原因分析
测试代码
import tensorflow as tf if (__name__== "__main__"): x= tf.ones((3, 3)) x= tf.cast(x, tf.float32) #################################################################### layer1= tf.keras.layers.Dense(2, activation= "relu", name= "nlayer1") layer2= tf.keras.layers.Dense(3, activation="relu", name= "nlayer2") layer3= tf.keras.layers.Dense(4, name= 'nlayer3') #################################################################### model_1= tf.keras.Sequential([layer1, layer2, layer3]) y1= model_1(x) #################################################################### #################################################################### model_2= tf.keras.Sequential(name= 'model_2') model_2.add(layer1) model_2.add(layer2) model_2.add(layer3) y2= model_2(x) #################################################################### print('y1= ', y1) print('y2= ', y2) input('Press Enter to continue...') #################################################################### print('<<<<<<<<<<<<<<<<<<<<<<The summary of model_5>>>>>>>>>>>>>>>>>>>>>>') model_2.summary() print('*****************Removing the last layer of model_5******************') model_2.pop() model_2.summary()
报错信息
ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor(type_spec=TensorSpec(shape=(3, 3), dtype=tf.float32, name='nlayer1_input'), name='nlayer1_input', description="created by layer 'nlayer1_input'") at layer "nlayer1". The following previous layers were accessed without issue: []
原因分析
- Keras层是带状态的实例,不支持跨模型共享:你创建的
layer1、layer2、layer3是同一个对象,同时被model_1和model_2添加。当model_1先执行model_1(x)时,这些层已经完成构建,生成了权重参数和输入输出的张量关联,状态已经和model_1绑定。 - pop()操作触发了模型结构的重新校验:给
model_2添加这些已被构建的层后,调用pop()移除最后一层,Keras会尝试重新构建model_2的计算图,但这些层的输入依赖已经被model_1占用,导致model_2无法找到layer1对应的输入张量,最终抛出计算图断开的错误。
总结:同一个层实例不能被多个Keras模型同时使用,共享层会导致模型状态混乱,触发计算图关联断裂的错误。
内容的提问来源于stack exchange,提问作者Gabriele
相关产品推荐
相关产品推荐

