saver.restore的一些问题

tensorflow的保存与训练都知道。

saver = tf.train.Saver()
saver.save(sess, save_file)

恢复呢

saver.restore(sess, save_file)

如果模型一致,自然没什么大问题,麻烦就麻烦在想在全连接后面加几层,恢复就成了问题。保留前面的卷积层。

错误1:Variable-12 not found

这个错误困扰了我好久。其实很简单,因为添加了新的w 和b,原来的模型中自然是没有,所以就选择新加的以及形状有变动的几层w和b选择不恢复。

exclude = ['Variable_12', 'Variable_13','Variable_11','Variable_5']
variables_to_restore = slim.get_variables_to_restore(exclude=exclude)

saver = tf.train.Saver(variables_to_restore)
'Variable_12', 'Variable_13',是新定义的。'Variable_11','Variable_5'是shape有变动的

看到有的说list里面可以列[‘conv1’,‘dense1’],我参看我的checkpoint文件发现我的参数名字都是‘Variable-XX’之类,所以只需要把不想要恢复的列出了,exclude就可以了。

错误2:Assign requires shapes of both tensors to match. lhs shape= [32] rhs shape= [64]

对于我而言,这个就是参数位置不对应的问题。因为我的w是定义在一个list里面,b也是

weights={
    'wc1':tf.Variable(tf.random_normal([3,3,1,64])),
    'wc2':tf.Variable(tf.random_normal([3,3,64,128])),
    'wc3':tf.Variable(tf.random_normal([3,3,128,256])),
    'wd1':tf.Variable(tf.random_normal([4*4*256,1024])),
    'wd2':tf.Variable(tf.random_normal([1024,1024])),
    #‘wa’:tf.Variable(tf.random_normal([1024,48])),
    'out':tf.Variable(tf.random_normal([48,10])),
}

加了一个‘wa’后参数的顺序发生改变,就会出现形状不对应的问题。我的解决办法就是将Wa的定义放到外面,而不影响原本的参数顺序。为什么这么做着,查看你的ckpt文件,看看参数保留的name。

from tensorflow.python import pywrap_tensorflow
import os
checkpoint_path = 'E:\\pycharm\\alexnet2.ckpt1'
reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
var_to_shape_map = reader.get_variable_to_shape_map()
for key in var_to_shape_map:
    print("tensor_name: ", key)
    print(reader.get_tensor(key)) # Remove t
print('end')
可以看到name都是‘Variable-XX’


猜你喜欢

转载自blog.csdn.net/qq_40242410/article/details/80860892
今日推荐