我试图用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"]()]]
我做错什么了?在
错误来自
在这里,您尝试求值
predictions
和targets
张量,而不向会话提供输入。在另外,
model_fn.ModelFnOps
需要一个loss
张量,因此您不应该像以前那样定义损失,而是应该只使用张量运算来定义损失。请看一下这个doc中的定义模型损失的部分(突出显示是我的):当运行}方法时,您将向您的估计器提供}方法,如同一文档中所述:
nn.fit
和{data
和{相关问题 更多 >
编程相关推荐