【tensorflow】fine-tuning, 选择性加载ckpt部分权重

来源:互联网 发布:mac 远程vps 编辑:程序博客网 时间:2024/04/30 09:05

在上一篇的转载博客中http://blog.csdn.net/shwan_ma/article/details/78874696中,

我发现用slim可以很方便的选择性的从ckpt文件中加载所要的数据。

以我自己的代码为例:

exclude = ['layer_weight','WD2_conv', 'BD2']variables_to_restore=slim.get_variables_to_restore(exclude=exclude)self.saver = tf.train.Saver(variables_to_restore)self.saver.restore(self.sess, filename)

上述代码指的是除了权重名称为“layer_weight”,”WD2_conv”, “BD2”三种权重外,加载其他的权重。当然我不加载这些权重是为了更好的fine-tuning。

注意:

这是我犯的一个小错误,就是在保存重新训练的权重时,依然使用了之前的代码:

self.saver.save(self.sess, filename)

这会有问题的,之前我们在定义self.saver.save的时候,去除了“layer_weight”,”WD2_conv”, “BD2”三种权重,因此重新保存下来的也不会包含他们。

因此这里需要更改为:

self.saver = tf.train.Saver()self.saver.save(self.sess, filename)

需要重新定义saver,方能将所有训练好的权重进行保存

===============================================================================================分割线====================================

今天发现slim还有一种方法进行选择性加载ckpt部分权重:

exclude = ['layer_weight','WD2_conv', 'BD2']variables_to_restore = slim.get_variables_to_restore(exclude=exclude)init_fn = slim.assign_from_checkpoint_fn(filename, variables_to_restore)init_fn(self.sess)