使用Tensorflow Hub模块作为自定义tf.Estimator的基础时出现tf.Estimator.predict()问题

时间:2019-02-16 03:50:59

标签: tensorflow tensorflow-hub

我正在尝试创建一个自定义的tensorflow tf.Estimator。在传递给tf.Estimator的model_fn中,我正在从Tensorflow Hub导入Inception_V3模块。

问题:在对模型进行微调(使用tf.Estimator.train)后,使用tf.Estimator.predict获得的结果不如基于tf.Estimator.evaluate预期的结果好(这是针对回归问题的。 )

我是Tensorflow和Tensorflow Hub的新手,所以我可能会犯很多新秀错误。

当我在验证数据上运行tf.Estimator.evaluate()时,报告的损失与tf.Estimator.train()用于训练模型后的损失在同一范围内。当我尝试在同一验证数据上使用tf.Estimator.predict()时,就会出现问题。

tf.Estimator.predict()返回预测,然后使用这些预测来计算由tf.Estimator.evaluate()计算的同一损失指标(mean_squared_error)。我正在使用同一组数据来馈送给预测函数和评估函数。但是,对于mean_squared_error,我没有得到相同的结果-不能远程关闭! (我从预测中计算出的MSE要差得多。)

这就是我所做的(删除了一些详细信息)... 使用Tensorflow Hub模块定义一个model_fn。然后调用tf.Estimator函数进行训练,评估和预测。

def my_model_fun(features, labels, mode, params):
    # Load InceptionV3 Module from Tensorflow Hub
    iv3_module =hub.Module("https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1",trainable=True, tags={'train'})     

    # Gather the variables for fine-tuning
    var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope='CustomeLayer')
    var_list.extend(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope='module/InceptionV3/Mixed_5b'))

    predictions = {"the_prediction" : final_output}
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

    # Define loss, optimizer, and evaluation metrics
    loss = tf.losses.mean_squared_error(labels=labels, predictions=final_output)
    optimizer =tf.train.AdadeltaOptimizer(learning_rate=learn_rate).minimize(loss, 
    var_list=var_list, global_step=tf.train.get_global_step())   
    rms_error = tf.metrics.root_mean_squared_error(labels=labels,predictions=predictions["the_prediction"])
    eval_metric_ops = {"rms_error": rms_error}

    if mode == tf.estimator.ModeKeys.TRAIN:
        return tf.estimator.EstimatorSpec(mode=mode, loss=loss,train_op=optimizer)

    if mode == tf.estimator.ModeKeys.EVAL:
        tf.summary.scalar('rms_error', rms_error)
        return tf.estimator.EstimatorSpec(mode=mode, loss=loss,eval_metric_ops=eval_metric_ops)  


iv3_estimator = tf.estimator.Estimator(model_fn=iv3_model_fn)   
iv3_estimator.train(input_fn=train_input_fn, steps=TRAIN_STEPS) 
iv3_estimator.evaluate(input_fn=val_input_fn)  

ii =0 
for ans in iv3_estimator.predict(input_fn=test_input_fn):
    sqErr = np.square(label[ii] - ans['the_prediction'][0])
    totalSqErr += sqErr
    ii += 1                           
mse = totalSqErr/ii

我希望tf.Estimator.evaluate()报告的mse损失应该与我从已知标签和tf.Estimator.predict()的输出计算mse时的损失相同。

使用预测时,是否需要以其他方式导入Tensorflow Hub模型? (在对hub.Module()的调用中使用trainable = False?

运行tf.Estimator.evaluate()而不是运行tf.Estimator.predict()-时是否使用从训练中获得的权重?

其他?

1 个答案:

答案 0 :(得分:0)

代码段中似​​乎缺少一些东西。如何从final_output计算iv3_module?同样,均方误差是分类问题中损失函数的不常见选择。常见的方法是将图像特征从模块传递到线性输出层,该线性输出层具有每个类别的分数(“ logits”)和“ softmax交叉熵损失”。有关这些术语的说明,您可以查看https://developers.google.com/machine-learning/crash-course/之类的在线教程(一直到多类神经网络)。

关于TF-Hub技术:

  • 集线器模块的变量会自动添加到GLOBAL_VARIABLES和TRAINABLE_VARIABLES集合中(如果已经完成,则为trainable=True)。无需手动扩展这些集合。
  • hub.Module(..., tags=...)对于{"train"}应设置为mode==TRAIN,并应设置为None或否则为空。

通常,在不进行微调作为基准的情况下使解决方案端到端地工作对您很有用,然后添加微调。