Tensorflow Hub模块的可训练变量在训练过程中未更新

我的问题与这里提出的问题非常相似:https://github.com/tensorflow/hub/issues/269。但那个问题至今未得到解答,所以我在这里重新提问。重现步骤如下:

tensorflow 1.14.0 tensorflow-hub 0.5.0 Python 3.7.4 Windows 10

以下是重现问题的示例笔记本:https://colab.research.google.com/drive/1PKUyoQRP3othu6cu7v7N7yn8K2pjkuKP

  1. 加载一个可训练的tensor_hub Inception 3模块:
    module_spec = hub.load_module_spec('https://tfhub.dev/google/imagenet/inception_v3/feature_vector/3')    height, width = hub.get_expected_image_size(module_spec)        with tf.Graph().as_default() as graph:            resized_input_tensor =  tf.compat.v1.placeholder(tf.float32, [None, height, width, 3])            module = hub.Module(module_spec, trainable=True, tags={"train"})              bottleneck_tensor = module(inputs=dict(images=resized_input_tensor, batch_norm_momentum=0.997),signature="image_feature_vector_with_bn_hparams")  
  1. 将此时创建的所有可训练/模型/全局变量保存到单独的’基础模型’列表中(3个列表)。变量示例:基础模型可训练变量:188,[‘module/InceptionV3/Conv2d_1a_3x3/weights:0’, ‘module/InceptionV3/Conv2d_1a_3x3/BatchNorm/beta:0’…基础模型模型变量:188,[‘module/InceptionV3/Conv2d_1a_3x3/BatchNorm/moving_mean:0’, ‘module/InceptionV3/Conv2d_1a_3x3/BatchNorm/moving_variance:0’基础模型变量:0,[] #空列表

  2. 在模型顶部添加自定义分类层:

    batch_size, previous_tensor_size = bottleneck_tensor.get_shape().as_list()    ground_truth_input = tf.compat.v1.placeholder(tf.int64, [batch_size], name='GroundTruthInput')    initial_value = tf.random.truncated_normal([previous_tensor_size, class_count], stddev=0.001)    layer_weights = tf.Variable(initial_value, name='final_weights')    layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')    logits = tf.matmul(hidden_layer, layer_weights) + layer_biases    final_tensor = tf.nn.softmax(logits, name=final_tensor_name)
  1. 再次,将所有新添加的变量名称放入3个新的’自定义’列表中:

    自定义可训练变量:2,[‘final_weights:0’, ‘final_biases:0’]自定义模型变量:0,[]自定义变量:0,[]

  2. 添加训练操作。因为基础模型有批量归一化,我们必须注意更新操作。这就是我使用tf.contrib.training.create_train_op的原因:

    cross_entropy_all = tf.compat.v1.losses.sparse_softmax_cross_entropy(labels=ground_truth_input, logits=logits)    optimizer = tf.compat.v1.train.AdamOptimizer()    #更新操作被设置为tf.GraphKeys.UPDATE_OPS集合的内容。    #要训练的变量将默认设置为所有tf.compat.v1.trainable_variables()。    train_step = tf.contrib.training.create_train_op(cross_entropy_mean, optimizer)
    1. 再次,将所有新添加的变量名称放入3个新的’优化器’列表中:优化器可训练变量:0,[]优化器模型变量:0,[]优化器变量:383,[‘global_step:0’, ‘beta1_power:0’, ‘beta2_power:0’, ‘module/InceptionV3/Conv2d_1a_3x3/weights/Adam:0’, ‘module/InceptionV3/Conv2d_1a_3x3/weights/Adam_1:0’, ‘module/InceptionV3/Conv2d_1a_3x3/BatchNorm/beta/Adam:0’, ‘module/InceptionV3/Conv2d_1a_3x3/BatchNorm/beta/Adam_1:0’, ‘module/InceptionV3/Conv2d_2a_3x3/weights/Adam:0’, ‘module/InceptionV3/Conv2d_2a_3x3/weights/Adam_1:0’, ‘module/InceptionV3/Conv2d_2a_3x3/BatchNorm/beta/Adam:0’,…

现在进行常规训练:

    with tf.compat.v1.Session(graph=graph) as sess:        # 初始化所有权重:将模块的权重初始化为预训练值,        # 并将新添加的再训练层初始化为随机初始值。        init = tf.compat.v1.global_variables_initializer()        sess.run(init)        # 导出在构建图形过程中收集的所有变量列表的校验和        for i in range(1000):            # 获取一批输入的调整大小后的图像值,计算新鲜数据            (train_data, train_ground_truth) = get_random_batch_data(sess, image_lists....)            # 导出在构建图形过程中收集的所有变量列表的校验和            # 将输入占位符和真实值输入到图形中,并运行一个训练            # 步骤。            sess.run([train_step], feed_dict = {                resized_input_tensor: train_data,                ground_truth_input: train_ground_truth})            # 再次导出在构建图形过程中收集的所有变量列表的校验和

因此,在每次训练步骤之后,校验和只对两个变量列表发生变化,自定义可训练和优化器全局:

    基础模型可训练变量, 2697202.0, cf4682249fc1f48e9a346149f84e503d 未改变    基础模型模型变量,        2936996.0, 6f995f5f0f032604a49a96ceec576cf7 未改变    基础模型变量, 0, d41d8cd98f00b204e9800998ecf8427e 未改变    自定义可训练变量, -0.7915199408307672, 889c333a56b9496d412eacdcbeb3bef1 **已改变**    自定义模型变量, 0, d41d8cd98f00b204e9800998ecf8427e 未改变    自定义变量, 0, d41d8cd98f00b204e9800998ecf8427e 未改变    优化器可训练变量, 0, d41d8cd98f00b204e9800998ecf8427e 未改变    优化器模型变量, 0, d41d8cd98f00b204e9800998ecf8427e 未改变    优化器变量,        5580902.81437762, d2cb2d4b253a1c12452f560eea35ac42 **已改变**

那么,问题来了,为什么基础模型的可训练变量没有改变?它们是BatchNorm/moving_mean, BatchNorm/moving_variance, Conv2d_1a_3x3/weights,这些变量在训练过程中肯定应该被更新。更重要的是,moving_variance也应该被改变,因为UPDATE_OPS被包含在tf.contrib.training.create_train_op调用中作为训练步骤的依赖。我已经检查了UPDATE_OPS列表,它包含有效的值,如:更新操作:tf.Operation ‘module_apply_image_feature_vector_with_bn_hparams/InceptionV3/InceptionV3/Conv2d_1a_3x3/BatchNorm/AssignMovingAvg/AssignSubVariableOp’ type=AssignSubVariableOp>,


回答:

经过深入调试问题后,我发现问题在于:仅仅从全局变量列表中获取变量并使用eval()获取其值是不够的:它会返回某个值,但这不是当前值(至少对于具有dtype=resource的导入模型的变量来说是这样)。

要计算当前值,我们必须首先使用变量.value()或变量.read_value()获取值张量,然后对其进行eval()操作(对返回的’值’张量进行)。

这解决了问题。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注