You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

加载Keras的VGG16模型时Python内核崩溃,求助解决

排查TensorFlow加载VGG16时内核崩溃问题

问题场景

执行以下代码时出现Python内核崩溃:

model = vgg16.VGG16(input_tensor=input_img, weights='imagenet', include_top=False)

错误信息

WARNING:tensorflow:The following Variables were used in a Lambda layer's call (tf.concat), but are not present in its tracked objects: <tf.Variable 'Variable:0' shape=(1, 474, 712, 3) dtype=float32>
<tf.Variable 'Variable:0' shape=(1, 474, 712, 3) dtype=float32>. This is a strong indication that the Lambda layer should be rewritten as a subclassed Layer.
Canceled future for execute_request message before replies were done
The Kernel crashed while executing code in the the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure. Click here for more info. View Jupyter log for further details.

排查与解决步骤

  • 修正输入张量类型:报错核心是Lambda层引用了未被追踪的Variable,大概率是input_img为tf.Variable类型,而VGG16要求input_tensor传入普通张量。将其转换为张量:

    input_img = tf.convert_to_tensor(input_img)
    

    或直接用tf.keras.Input定义输入:

    input_img = tf.keras.Input(shape=(474, 712, 3))
    
  • 修复Lambda层变量追踪问题:若代码中自定义了Lambda层并引用外部Variable,需让层正确追踪变量:

    • 改用子类化Layer替代Lambda层:
      class ConcatLayer(tf.keras.layers.Layer):
          def __init__(self, external_var, **kwargs):
              super().__init__(**kwargs)
              self.external_var = external_var
          
          def call(self, inputs):
              return tf.concat([inputs, self.external_var], axis=-1)
      
      x = ConcatLayer(external_var)(input)
      
    • 或在Lambda层中显式传递变量:
      x = tf.keras.layers.Lambda(lambda x, var: tf.concat([x, var], axis=-1),
                                 arguments={'var': external_var})(input)
      
  • 清理会话并重启内核:旧会话残留可能导致变量追踪混乱,先清理再重启:

    tf.keras.backend.clear_session()
    

    重启Jupyter内核后重新运行代码。

  • 检查版本兼容性:确保TensorFlow与Keras版本匹配,建议使用TensorFlow 2.x最新稳定版,避免版本不兼容引发底层错误。

内容的提问来源于stack exchange,提问作者Ignacio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:00:58