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

使用summary()查看CNN模型时报错:Undefined shapes are not supported

问题解决:组合模型调用summary()报Undefined shapes错误

问题原因

冻结VGG16部分层后,用Sequential容器组合base_model和top_model时,Keras无法正确推断中间张量的形状,导致top_model无法和base_model的输出正确衔接,触发形状未定义的错误。

解决方案

方法1:改用Functional API组合模型

Functional API对复杂模型的形状推断更可靠,替换Sequential组合方式:

import tensorflow as tf
from tensorflow.keras.applications import VGG16
from tensorflow.keras import layers

base_model = VGG16(weights='imagenet', include_top=False, input_shape=(32, 32, 3))

# 冻结前10层
for layer in base_model.layers[:10]:
    layer.trainable = False

# 用Functional API拼接模型
x = base_model.output
x = layers.Flatten()(x)
output = layers.Dense(10, activation='softmax')(x)
model2 = tf.keras.Model(inputs=base_model.input, outputs=output)

model2.summary()

方法2:通过样例输入明确输出形状

在定义top_model前,先传入一个样例输入让base_model计算输出形状,避免依赖output_shape属性:

import tensorflow as tf
from tensorflow.keras.applications import VGG16
from tensorflow.keras import layers

base_model = VGG16(weights='imagenet', include_top=False, input_shape=(32, 32, 3))

# 传入样例输入,确定base_model的输出形状
sample_input = tf.random.normal((1, 32, 32, 3))
base_output = base_model(sample_input)
top_model = tf.keras.Sequential([
    layers.Flatten(input_shape=base_output.shape[1:]),
    layers.Dense(10, activation='softmax')
])

for layer in base_model.layers[:10]:
    layer.trainable = False

model2 = tf.keras.models.Sequential([
    base_model,
    top_model
])

model2.summary()

额外说明

  • 该问题与Python版本无关,核心是Keras的Sequential容器在处理部分冻结的预训练模型时,形状推断机制存在局限性。
  • 仅使用VGG16前11或15层时,这些层的输出形状在冻结后仍能被Sequential正确推断,因此不会触发错误。

内容的提问来源于stack exchange,提问作者Noah Co Rodriguez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:05:18