tf.keras.backend.set_learning_phase设置某些层的参数是否可变

介绍

将某些层的参数设置成固定值,或者是 通过学习会改变的

tf.keras.layers.BatchNormalization()会受此影响
详见:
https://www.malaoshi.top/show_1EF5JUYBib4t.html

语法

tf.keras.backend.set_learning_phase(
    value
)
参数
  • value:学习阶段的值
    • 0:表示 测试(预测),某些层的参数是固定的
    • 1:表示 训练,某些层的参数是通过学习会改变的

例子

K.set_learning_phase(0)

base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False,
                                  input_shape=(img_resize, img_resize, 3), )

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)
plt.plot(history.epoch,history.history["acc"],label="acc")
plt.plot(history.epoch,history.history["val_acc"],label="val_acc")
plt.legend()


plt.plot(history.epoch,history.history["loss"],label="loss")
plt.plot(history.epoch,history.history["val_loss"],label="val_loss")
plt.legend()

原文出处:/show_1EF5JTbvJ50y.html