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

Keras中间层预测疑问:新建模型是否会经过所有前置层(含Dropout)

关于Keras新建模型获取中间层输出的疑问解答

嘿,这个问题我之前也纠结过,给你讲明白哈~

FAQ里提到的第一种方法——新建模型来获取中间层layerN的输出,输入向量是会完整经过从输入层到layerN的所有前置层的,包括你说的Dropout、Dense这些层,最后才输出layerN的计算结果,绝对不会跳过任何一步。

举个实际代码例子你就懂了:
假设我们有这样一个带Dropout的原模型:

from keras.models import Model
from keras.layers import Input, Dense, Dropout

# 构建原模型
input_layer = Input(shape=(100,))
x = Dense(64, activation='relu', name='dense_1')(input_layer)
x = Dropout(0.5, name='dropout_1')(x)
layerN = Dense(32, activation='relu', name='layerN')(x)
x = Dense(10, activation='softmax', name='output_layer')(layerN)
original_model = Model(inputs=input_layer, outputs=x)

如果我们要获取layerN的输出,新建模型的代码是这样的:

# 基于原模型的输入和layerN的输出构建新模型
intermediate_model = Model(inputs=original_model.input, outputs=original_model.get_layer('layerN').output)

当你调用intermediate_model.predict(your_input_data)时,输入数据会按照 输入层 → dense_1 → dropout_1 → layerN 的顺序完整走一遍,最后返回的就是layerN处理后的结果。

另外要注意:在预测阶段(也就是调用predict的时候),Dropout层会自动切换到推理模式,不会随机丢弃神经元,这和原模型执行predict时的行为完全一致,所以你得到的layerN结果和原模型前向传播到这一层的结果是完全匹配的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:49:19