【问题标题】:Getting a "You must feed a value for placeholder tensor 'input'" error in tensorflow在张量流中出现“您必须为占位符张量'输入'提供一个值”错误
【发布时间】:2017-06-13 20:00:19
【问题描述】:

我正在尝试使用tf.contrib.learn.estimator 在张量流中构建具有加权损失函数的神经网络。运行代码时,我总是遇到同样的错误。 这是估算器的模型:

    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 的方式:

nn = tf.contrib.learn.Estimator(model_fn=model_fn, params=.003)
print("reachedfit")
# Fit model.
#classifier.fit(x=x_train, y=y_train, steps=1000)
nn.fit(x=x_train, y=y_train, steps=1000)
print("reachedpredict")
y = list(nn.predict(x_test))

最后,这是我得到的错误:

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"]()]]

我做错了什么?

【问题讨论】:

  • reachedfit 和reacherpredict 都没有被打印出来。

标签: python numpy tensorflow


【解决方案1】:

错误来自

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

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

您尝试在不向会话提供输入的情况下评估 predictionstargets 张量。

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

model_fn 返回的 ModelFnOps 必须包含损失:一个表示损失值的张量,它量化了模型的预测在训练和评估运行期间反映目标值的程度。 tf.losses 模块提供了使用各种指标计算损失的便捷函数。

在运行同一文档中描述的nn.fitnn.evaluate方法时,您将向估算器提供datatarget

运行 [...] 模型

您已经实例化了一个 Estimator [...] 并在 model_fn 中定义了它的行为;剩下要做的就是训练、评估和做出预测。

将以下代码添加到 main() 的末尾,以使神经网络适应训练数据并评估准确性: 合身 nn.fit(x=training_set.data, y=training_set.target, steps=5000)

得分准确度 ev = nn.evaluate(x=test_set.data, y=test_set.target, steps=1)

【讨论】:

  • 将损失转回 tf.constant 是否可以解决后一个问题?此外,我应该为会话提供哪些输入 - 即占位符是如何格式化的,我的占位符是否必须与特征张量的维度相匹配?
  • 是我上面的nn.fit线不准确(x_train是训练集数据,y_train是训练集目标)?
  • 那应该没问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多