我有一个线性回归模型,看起来运行正常,但我希望显示模型的准确率。
首先,我初始化变量和占位符…
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)
。接下来我运行会话,并显示每个周期的成本以及总体 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}) # 每步显示日志 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("优化完成!") 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
。文档说它有两个参数,labels
和 predictions
。我接下来添加了以下内容…
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,使用 accuracy
来衡量这是否是正确预测是没有意义的。accuracy
适用于分类问题(例如,mnist),当你的模型预测一个数字为 ‘9’ 而你的目标图像也是 ‘9’:这是正确预测,你得到满分;或者当你的模型预测一个数字为 ‘9’ 但你的目标图像是 ‘6’:这是错误预测,你得不到分数。
对于你的回归问题,我们通过 绝对误差
– |target - prediction|
或 均方误差
– 你用于 MSE
计算的那个,来衡量预测与目标值之间的差异。因此,你应该使用 tf.metrics.mean_squared_error
或 tf.metrics.mean_absolute_error
来衡量回归模型的预测误差。