Keras Sequential API 中的训练 = False

Mri*_*tyu 7 machine-learning neural-network keras tensorflow

当使用 Keras Function API 时,我们可以training = False在调用预训练模型时传递参数,如教程所示。

如何在 Keras Sequential API 中实现相同的功能?

这是我尝试使用 Sequential API 复制的代码:

inputs = tf.keras.Input( shape = ( TARGET_SIZE[0], TARGET_SIZE[1], 3 ) )
base_model = Xception( include_top = False, pooling = 'avg' )
base_model.trainable = False
x = base_model( inputs, training = False ) 
x = Dense( 512, activation = 'relu' )( x )
x = Dense( 256, activation = 'relu' )( x )
x = Dense( 128, activation = 'relu' )( x )
outputs = Dense( 6, activation = 'softmax' )( x )
Run Code Online (Sandbox Code Playgroud)

下面是在不 使用 Sequential API 的情况下实现整个模型的代码,training = False如下所示:

model = Sequential()
model.add( Xception( include_top = False, pooling = 'avg', input_shape = ( TARGET_SIZE[0], TARGET_SIZE[1], 3 ) ) )
model.add( Dense( units = 512, activation = 'relu' ) )
model.add( Dense( units = 256, activation = 'relu' ) )
model.add( Dense( units = 128, activation = 'relu' ) )
model.add( Dense( 6, activation = 'softmax' ) )
Run Code Online (Sandbox Code Playgroud)

但是,我无法training = False与它进行争论。

小智 0

您可以尝试以下操作,它对我有用:

加载任何基础模型,include_top = False,然后(作为示例):

 flat1 = Flatten()(base_model.layers[-1].output, training=False)
    
 class1 = Dense(5, activation='relu')(flat1)
    
 output = Dense(1, activation='sigmoid')(class1) 

 model = Model(inputs=base_model.inputs, outputs=output) 
Run Code Online (Sandbox Code Playgroud)