冻结权重

示例:
这里使用的是tensorflow内置的Xception模型,然后将预训练模型的前100层冻结,训练后32层,加入全局平均池化层和输出层

covn_base = tf.keras.applications.xception.Xception(weights='imagenet',include_top=False)
covn_base.trainable = True

for layers in covn_base.layers[:-32]:
    layers.trainable = False

model = tf.keras.Sequential()
model.add(covn_base)
model.add(tf.keras.layers.GlobalAveragePooling2D())
model.add(tf.keras.layers.Dense(200))

model.summary()

总结:

covn_base.trainable = True
把trainable设置为True,意思就是在训练时,会更新权重。但是如果把它设置成False,就是在训练中不更新权重,也就是我们常说的冻结权重。

covn_base = tf.keras.applications.xception.Xception(weights='imagenet',include_top=False)
covn_base.trainable = True

下面代码的意思就是冻结最后32层之前的网络权重,而只训练最后32层网路的权重

covn_base = tf.keras.applications.xception.Xception(weights='imagenet',include_top=False)
covn_base.trainable = True
for layers in covn_base.layers[:-32]:
    layers.trainable = False

下面应该是创建一个可以存放网络层的一个序列

model = tf.keras.Sequential()

添加原始网络模型

model.add(covn_base)

在原始模型的最后,添加一些我们自己定义的网络层,最后将模型打包。
这便完成了对一个模型的迁移学习

model.add(tf.keras.layers.GlobalAveragePooling2D())
model.add(tf.keras.layers.Dense(200))

model.summary()
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐