gpt4 book ai didi

python-3.x - tf.metrics.accuracy 未按预期工作

转载 作者:行者123 更新时间:2023-11-30 08:59:06 25 4
gpt4 key购买 nike

我的线性回归模型似乎运行良好,但我想显示模型的准确性。

首先,我初始化变量和占位符...

X_train, X_test, Y_train, Y_test = train_test_split(
X_data,
Y_data,
test_size=0.2
)

n_rows = X_train.shape[0]

X = tf.placeholder(tf.float32, [None, 89])
Y = tf.placeholder(tf.float32, [None, 1])

W_shape = tf.TensorShape([89, 1])
b_shape = tf.TensorShape([1])

W = tf.Variable(tf.random_normal(W_shape))
b = tf.Variable(tf.random_normal(b_shape))

pred = tf.add(tf.matmul(X, W), b)

cost = tf.reduce_sum(tf.pow(pred-Y, 2)/(2*n_rows-1))

optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(cost)

X_train 的形状为 (6702, 89)Y_train 的形状为 (6702, 1)。接下来,我运行 session 并显示每个周期的成本以及总 MSE...

init = tf.global_variables_initializer()

with tf.Session() as sess:

sess.run(init)

for epoch in range(FLAGS.training_epochs):

avg_cost = 0

for (x, y) in zip(X_train, Y_train):

x = np.reshape(x, (1, 89))
y = np.reshape(y, (1,1))
sess.run(optimizer, feed_dict={X:x, Y:y})

# display logs per epoch step
if (epoch + 1) % FLAGS.display_step == 0:

c = sess.run(
cost,
feed_dict={X:X_train, Y:Y_train}
)

y_pred = sess.run(pred, feed_dict={X:X_test})
test_error = r2_score(Y_test, y_pred)
print(test_error)

print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(c))

print("Optimization Finished!")

pred_y = sess.run(pred, feed_dict={X:X_test})
mse = tf.reduce_mean(tf.square(pred_y - Y_test))

print("MSE: %4f" % sess.run(mse))

这一切似乎都工作正常。但是,现在我想查看模型的准确性,因此我想实现 tf.metrics.accuracy。文档说它有 2 个参数,标签和预测。我接下来添加了以下内容...

accuracy, accuracy_op = tf.metrics.accuracy(labels=Y_test, predictions=pred)

init_local = tf.local_variables_initializer()

sess.run(init_local)

print(sess.run(accuracy))

显然我需要初始化本地变量,但是我认为我做错了什么,因为打印出来的准确性结果是0.0

我到处搜索工作示例,但无法让它适用于我的模型,实现它的正确方法是什么?

最佳答案

我认为您正在学习回归模型tf.metrics.accuracy 应该针对分类模型运行。

当您的模型预测为 1.2 但您的目标值为 1.15 时,使用准确度来衡量这是否是正确的预测是没有意义的。 准确率适用于分类问题(例如,mnist),当您的模型预测数字为“9”并且您的目标图像也是“9”时:这是正确的预测,您将获得满分;或者,当您的模型预测数字为“9”但您的目标图像为“6”时:这是错误的预测,您不会获得任何荣誉。

对于您的回归问题,我们通过绝对误差 - |目标 - 预测|均方误差来衡量预测值与目标值之间的差异code> - 您在 MSE 计算中使用的代码。因此,您应该使用 tf.metrics.mean_squared_errortf.metrics.mean_absolute_error 来衡量回归模型的预测误差。

关于python-3.x - tf.metrics.accuracy 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com