我编写了以下Tensorflow代码,该代码对自定义数据集执行逻辑回归。
def logi_regression(data, labels, test_data, test_labels, learning_rate,
batch_size, training_epochs, display_step):
x = tf.placeholder(tf.float32, [None, data.shape[1]])
y = tf.placeholder(tf.float32, [None, labels.shape[1]])
# Weights
W = tf.Variable(tf.zeros([data.shape[1], 1]))
b = tf.Variable(tf.zeros([1, 1]))
# Logistic Model
pred = tf.nn.sigmoid(tf.matmul(x, W) + b)
# Error function
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pred,
labels=y))
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
# Initialise global variables
init = tf.global_variables_initializer()
init_l = tf.local_variables_initializer()
# Training
with tf.Session() as sess:
# Run the initializer
sess.run(init)
sess.run(init_l)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(data.shape[0]/batch_size)
# Loop over all batches
for i in range(total_batch):
# The next_data_batch is a custom made function
batch_xs, batch_ys = next_data_batch(batch_size,
data, labels)
# Run optimization op (backprop) and cost op (to get loss value)
_, c = sess.run([optimizer, loss], feed_dict={x: batch_xs,
y: batch_ys})
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
# Test model
prediction = tf.round(tf.sigmoid(pred))
correct = tf.cast(tf.equal(prediction, y), dtype=tf.float32)
_, precision = tf.metrics.precision(y, prediction)
# Calculate accuracy
accuracy = tf.reduce_mean(correct)
avg_prec = tf.reduce_mean(precision)
print("Accuracy:", accuracy.eval({x: test_data, y: test_labels}))
print("Average Precision Score:", avg_prec.eval({x: test_data, y: test_labels}))
但是,即使我从训练(Epoch: xxxx cost= 0.xxxx
)和测试集(Accuracy:0.xxx
)获得了正确的输出。当程序尝试计算精度时,它将返回错误:
FailedPreconditionError(请参阅上面的回溯):尝试使用 未初始化的值precision / true_positives / count [[node precision / true_positives / AssignAdd(定义在 :54)]]
因此,问题出在我添加了({_, precision = tf.metrics.precision(y, prediction)
)的最后几行中。我已经尝试过Stackoverflow帖子中的各种建议,但没有任何效果。这肯定是一个愚蠢的编码错误,但是由于我对Tensorflow的经验不足,所以我无法弄清楚它是什么。
答案 0 :(得分:1)
在tensorflow-graph中创建节点的线应在'tf.global_variables_initializer()'语句之前,作为默认图的一部分。将以下几行移至初始化程序上方,它将起作用:
# Test model
prediction = tf.round(tf.sigmoid(pred))
correct = tf.cast(tf.equal(prediction, y), dtype=tf.float32)
_, precision = tf.metrics.precision(y, prediction)
# Calculate accuracy
accuracy = tf.reduce_mean(correct)
avg_prec = tf.reduce_mean(precision)