TensorFlow中pre_trained_model.get_layer()实现迁移学习的原理疑惑
问题
我在做TensorFlow迁移学习时,提取InceptionV3从起始层到mixed7的网络部分,再添加自定义的Flatten、Dense、Dropout和Dense层。代码可正常运行,但我无法理解最终模型为何会包含mixed7之前的所有层。我原以为last_output只是mixed7层的输出,仅关联该层的权重/偏置,就算其计算依赖前面的层,它本身也只代表单个层,后续添加自定义层后,模型应该只包含mixed7和自定义层才对。
from tensorflow.keras.applications.inception_v3 import InceptionV3 from tensorflow.keras import layers local_weights_file = '/tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5' pre_trained_model = InceptionV3(input_shape = (150, 150, 3), include_top = False, weights = None) pre_trained_model.load_weights(local_weights_file) for layer in pre_trained_model.layers: layer.trainable = False pre_trained_model.summary() # Summary of all the layers in InceptionV3 last_layer = pre_trained_model.get_layer('mixed7') print('last layer output shape: ', last_layer.output_shape) last_output = last_layer.output # last layer output shape: (None, 7, 7, 768) x = layers.Flatten()(last_output) x = layers.Dense(1024, activation='relu')(x) x = layers.Dropout(0.2)(x) x = layers.Dense (1, activation='sigmoid')(x) # Append the dense network to the base model model = Model(pre_trained_model.input, x) model.summary() # `InceptionV3` from the beginning up to `mixed7`, plus flatten, dense, dropout and dense layers in the end
解答
这是因为TensorFlow的张量(Tensor)自带计算图依赖关系。你拿到的last_output不是孤立的数值结果,它是一条完整计算链的终点:从pre_trained_model.input出发,经过InceptionV3每一层的计算,最终到mixed7层输出的张量。这个张量内部记录了完整的计算路径:输入→第一层→第二层→……→mixed7。
当你用Model(pre_trained_model.input, x)创建新模型时,TensorFlow会自动追溯从输入到最终输出x的所有计算节点,把这些节点对应的层全部纳入模型中。简单来说:
pre_trained_model.input是整个模型的起点x是基于last_output构建的终点,而last_output的生成依赖前面所有层的计算- 因此TensorFlow会把这条路径上的所有层(从输入到mixed7,再到你添加的自定义层)都整合到新模型里
你可以把张量想象成一条“管道”,last_output是管道的末端,但这条管道是从输入开始,经过前面所有层连通过来的,并非凭空出现的末端。创建模型时,TensorFlow会把整条管道完整打包进去。
内容的提问来源于stack exchange,提问作者lanselibai
相关产品推荐
相关产品推荐

