得到一个“您必须为占位符张量‘input’输入一个值”错误(以十为单位)

2024-10-03 11:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用tf.contrib.learn.estimator在tensorflow中建立一个加权损失函数的神经网络。我在运行代码时总是会遇到相同的错误。 以下是估计器的模型fn:

    def model_fn(features, targets, mode, params):

  """Model function for Estimator."""

  # Connect the first hidden layer to input layer
  # (features) with relu activation
  first_hidden_layer = tf.contrib.layers.relu(features, 20)


  # Connect the second hidden layer to first hidden layer with relu
  second_hidden_layer = tf.contrib.layers.relu(first_hidden_layer, 20)

  third_hidden_layer = tf.contrib.layers.relu(second_hidden_layer, 20)

  # Connect the output layer to second hidden layer (no activation fn)
  output_layer = tf.contrib.layers.linear(second_hidden_layer, 1)

  # Reshape output layer to 1-dim Tensor to return predictions
  predictions = tf.reshape(output_layer, [-1])

  # Calculate loss weighting false negatives up
  sess=tf.InteractiveSession()
  t=tf.constant(0)
  def weightedloss(prediction=[], target=[]):
      losssum = 0.0
      for x in range(len(prediction)):
          if prediction[x] == 1 & target[x] == 0:
              losssum += 1.0
          elif prediction[x] == 0 & target[x] == 1:
              losssum += 9.0
          else:
              losssum += 0.0
      return tf.constant(losssum)
  print(list(predictions.eval(session=sess)))

  loss = weightedloss(list(predictions.eval(session=sess)), list(targets.eval(session=sess)))

  # Calculate root mean squared error as additional eval metric
  eval_metric_ops = {
      "rmse":
          tf.metrics.root_mean_squared_error(
              tf.cast(targets, tf.float64), predictions)
  }

  train_op = tf.contrib.layers.optimize_loss(
      loss=loss,
      global_step=tf.contrib.framework.get_global_step(),
      learning_rate=params["learning_rate"],
      optimizer="SGD")

  return model_fn.ModelFnOps(
      mode=mode,
      predictions=predictions_dict,
      loss=loss,
      train_op=train_op,
      eval_metric_ops=eval_metric_ops)

下面是我如何在代码中使用fn模型:

^{pr2}$

最后,我得到的错误是:

tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input' with dtype double
         [[Node: input = Placeholder[dtype=DT_DOUBLE, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

我做错什么了?在


Tags: tolayeroutputlayerstfevalcontribhidden
1条回答
网友
1楼 · 发布于 2024-10-03 11:24:25

错误来自

 print(list(predictions.eval(session=sess)))

 loss = weightedloss(list(predictions.eval(session=sess)), list(targets.eval(session=sess)))

在这里,您尝试求值predictionstargets张量,而不向会话提供输入。在

另外,model_fn.ModelFnOps需要一个loss张量,因此您不应该像以前那样定义损失,而是应该只使用张量运算来定义损失。请看一下这个doc中的定义模型损失的部分(突出显示是我的):

The ModelFnOps returned by the model_fn must contain loss: a Tensor representing the loss value, which quantifies how well the model's predictions reflect the target values during training and evaluation runs. The tf.losses module provides convenience functions for calculating loss using a variety of metrics.

当运行nn.fit和{}方法时,您将向您的估计器提供data和{}方法,如同一文档中所述:

Running the [...] Model

You've instantiated an Estimator [...] and defined its behavior in model_fn; all that's left to do is train, evaluate, and make predictions.

Add the following code to the end of main() to fit the neural network to the training data and evaluate accuracy: Fit nn.fit(x=training_set.data, y=training_set.target, steps=5000)

Score accuracy ev = nn.evaluate(x=test_set.data, y=test_set.target, steps=1)

相关问题 更多 >