方案一:
设置bn层参数不可变K.set_learning_phase(0)
base_model = tf.keras.applications.ResNet50(weights=‘imagenet‘, include_top=False,
input_shape=(img_resize, img_resize, 3), )
# 设置bn层参数可变
K.set_learning_phase(1)
model=tf.keras.Sequential()
model.add(base_model)
model.add(tf.keras.layers.GlobalAveragePooling2D())
model.add(tf.keras.layers.Dense(512,activation="relu"))
#model.add(tf.keras.layers.Dense(512,activation="relu",kernel_regularizer=tf.keras.regularizers.l2(0.0001)))
model.add(tf.keras.layers.Dense(1,activation="sigmoid"))
model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.0001),loss="binary_crossentropy",metrics=["acc"])
history=model.fit(train_ds2,epochs=5,validation_data=test_ds2)
方案二:
K.set_learning_phase(0)
base_model = tf.keras.applications.ResNet50(weights=‘imagenet‘, include_top=False,input_shape=(img_resize, img_resize, 3) )
# 不要设置成False,否则会影响训练效果(冻结训练的代码一定要在这个位置写)
base_model.trainable=False
K.set_learning_phase(1)
x=base_model.output
x=tf.keras.layers.GlobalAveragePooling2D()(x)
x=tf.keras.layers.Dense(512,activation="relu")(x)
x=tf.keras.layers.Dense(1,activation="sigmoid")(x)
model = tf.keras.Model(inputs=base_model.input, outputs=x)
?