Tensorflow Estimator.predict() 失败

Tim*_*opf 1 predict tensorflow-estimator

我正在重新创建 DnCNN,即高斯降噪器,它使用一系列卷积层进行图像到图像的预测。它训练得非常好,但是当我尝试执行列表(model.predict(..))时,出现错误:

标签不能为 none

我实际上将我的 EstimatorSpec 的所有规范参数明确地放在那里,因为它们是根据调用 Estimator 的方法(train/eval/predict)懒惰地评估的。

def DnCNN_model_fn (features, labels, mode):
   # some convolutinons here
   return tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=conv_last + input_layer,
        loss=tf.losses.mean_squared_error(
            labels=labels, 
            predictions=conv_last + input_layer),
        train_op=tf.train.AdamOptimizer(learning_rate=0.001, epsilon=1e-08).minimize(
            loss=tf.losses.mean_squared_error(
                labels=labels,
                predictions=conv_last + input_layer),
            global_step=tf.train.get_global_step()),
        eval_metric_ops={
            "accuracy": tf.metrics.mean_absolute_error(
                labels=labels,
                predictions=conv_last + input_layer)}
      )
Run Code Online (Sandbox Code Playgroud)

将其放入估计器中:

d = datetime.datetime.now()

DnCNN = tf.estimator.Estimator(
    model_fn=DnCNN_model_fn,
    model_dir=root + 'model/' +
              "DnCNN_{}_{}_{}_{}".format(d.month, d.day, d.hour, d.minute),
    config=tf.estimator.RunConfig(save_summary_steps=2,
                                  log_step_count_steps=10)
)
Run Code Online (Sandbox Code Playgroud)

训练模型后,我进行如下预测:

test_input_fn = tf.estimator.inputs.numpy_input_fn(
    x= test_data[0:2,:,:,:],
    y= None,
    batch_size=1,
    num_epochs=1,
    shuffle=False)

predicted = DnCNN.predict(input_fn=test_input_fn) 
list(predicted) # this is where the error occurs
Run Code Online (Sandbox Code Playgroud)

回溯说,tf.losses.mean_squared_error 导致了这种情况。

    Traceback (most recent call last):
      File "<input>", line 16, in <module>
      File "...\venv2\lib\site-packages\tensorflow\python\estimator\estimator.py", line 551, in predict
        features, None, model_fn_lib.ModeKeys.PREDICT, self.config)
      File "...\venv2\lib\site-packages\tensorflow\python\estimator\estimator.py", line 1169, in _call_model_fn
        model_fn_results = self._model_fn(features=features, **kwargs)
      File "<input>", line 95, in DnCNN_model_fn
      File "...\venv2\lib\site-packages\tensorflow\python\ops\losses\losses_impl.py", line 663, in mean_squared_error
        raise ValueError("labels must not be None.")
    ValueError: labels must not be None.
Run Code Online (Sandbox Code Playgroud)

kev*_*vin 5

estimator.predict 引发“ValueError: None values not supported”

“在你的 model_fn 中,你定义了每种模式(训练/评估/预测)的损失。这意味着即使在预测模式下,标签也会被使用并且需要提供。

当您处于预测模式时,您实际上只需要返回预测,以便您可以尽早从函数中返回:”

def model_fn(features, labels, mode):
#...
y = ...
if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode, predictions=y)
#...
Run Code Online (Sandbox Code Playgroud)