在上一篇文章中,将两个ckpt加载后进行拼接合并,但固化后进行推理时发现结果不对,于是将合并后的模型和之前的模型权重参数进行比对发现合并后的模型中BN参数存在部分值未加载(moving_mean和moving_variance权重参数未加载至模型)如下图:
最后找到问题原因是由于指定op加载ckpt的时候,BN层的两个参数未指定为trainable_variables,因而在未获取到BN中的moving_mean和moving_variance参数,修改前获取op的代码如下图:
解决上述问题只需要将TRAINABLE_VARIABLES改为GLOBAL_VARIABLES
代码:
def _get_variables_to_train(trainable_scopes = None):
"""Returns a list of variables to train.
Returns:
A list of variables to train by the optimizer.
"""
if trainable_scopes is None:
return tf.trainable_variables()
else:
scopes = [scope.strip() for scope in trainable_scopes.split(',')]
#print('scopes:',scopes)
variables_to_train = []
for scope in scopes:
variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope)
# print(scope,':',variables)
variables_to_train.extend(variables)
return variables_to_train
或者在训练模型设置BN层参数时加上 'variables_collections':[tf.GraphKeys.TRAINABLE_VARIABLES]如下图:
最后BN权重便正常加载,推理结果正常: