python - Tensorflow:如何在新图中使用预训练的权重?
问题描述
我正在尝试使用带有 python 框架的 tensorflow 构建一个带有 CNN 的对象检测器。我想训练我的模型首先只进行对象识别(分类),然后使用 pretarined 模型的几个卷积层训练它来预测边界框。我需要替换全连接层,可能还有一些最后的卷积层。因此,出于这个原因,我想知道是否可以仅将用于训练对象分类器的 tensorflow 图中的权重导入我将训练以进行对象检测的新定义图。所以基本上我想做这样的事情:
# here I initialize the new graph
conv_1=tf.nn.conv2d(in, weights_from_old_graph)
conv_2=tf.nn.conv2d(conv_1, weights_from_old_graph)
...
conv_n=tf.nn.nnconv2d(conv_n-1,randomly_initialized_weights)
fc_1=tf.matmul(conv_n, randomly_initalized_weights)
解决方案
Use saver with no arguments to save the entire model.
tf.reset_default_graph()
v1 = tf.get_variable("v1", [3], initializer = tf.initializers.random_normal)
v2 = tf.get_variable("v2", [5], initializer = tf.initializers.random_normal)
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.save(sess, save_path='./test-case.ckpt')
print(v1.eval())
print(v2.eval())
saver = None
v1 = [ 2.1882825 1.159807 -0.26564872]
v2 = [0.11437789 0.5742971 ]
Then in the model you want to restore to certain values, pass a list of variable names you want to restore or a dictionary of {"variable name": variable}
to the Saver
.
tf.reset_default_graph()
b1 = tf.get_variable("b1", [3], initializer= tf.initializers.random_normal)
b2 = tf.get_variable("b2", [3], initializer= tf.initializers.random_normal)
saver = tf.train.Saver(var_list={'v1': b1})
with tf.Session() as sess:
saver.restore(sess, "./test-case.ckpt")
print(b1.eval())
print(b2.eval())
INFO:tensorflow:Restoring parameters from ./test-case.ckpt
b1 = [ 2.1882825 1.159807 -0.26564872]
b2 = FailedPreconditionError: Attempting to use uninitialized value b2
推荐阅读
- python - 取决于熊猫条件的另一列的列值
- docker - 无法在 terraform docker 映像中使用本地构建的提供程序
- odoo - 在 Odoo 中保存使用 new() 方法创建的对象
- javascript - 从firebase实时数据库检查嵌套对象值?
- kubernetes - 无法访问 Kubernetes 集群中的 NodePort ip
- react-native - “_OBJC_CLASS_$_RNPermissionHandlerLocationWhenInUse”,在 libRNPermissions.a(RNPermissions.o) 中引用了 bjc-class-ref
- string - FromStr 和 TryFrom 有什么区别
特质? - html - 如何忽略该表行内按钮中的“表”属性?
- android - 始终运行带有位置更新的 android 应用程序
- c# - 如何更正我的旋转平台脚本并修复 Unity 中的错误纹理?