Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Tensorflow-如何显示线性回归模型的准确率_Python 3.x_Machine Learning_Tensorflow_Linear Regression - Fatal编程技术网

Python 3.x Tensorflow-如何显示线性回归模型的准确率

Python 3.x Tensorflow-如何显示线性回归模型的准确率,python-3.x,machine-learning,tensorflow,linear-regression,Python 3.x,Machine Learning,Tensorflow,Linear Regression,我有一个线性回归模型,似乎是可行的。我首先将数据加载到X中,将目标列加载到Y,然后实现以下操作 X_train, X_test, Y_train, Y_test = train_test_split( X_data, Y_data, test_size=0.2 ) rng = np.random n_rows = X_train.shape[0] X = tf.placeholder("float") Y = tf.placeholder("float")

我有一个线性回归模型,似乎是可行的。我首先将
数据
加载到
X
中,将目标列加载到
Y
,然后实现以下操作

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

rng = np.random

n_rows = X_train.shape[0]

X = tf.placeholder("float")
Y = tf.placeholder("float")


W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

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

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

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



init = tf.global_variables_initializer()
init_local = tf.local_variables_initializer()

with tf.Session() as sess:

    sess.run([init, init_local])

    for epoch in range(FLAGS.training_epochs):

        avg_cost = 0

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

            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}
            )

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

    print("Optimization Finished!")

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

    print(sess.run(accuracy))
accuracy, accuracy_op = tf.metrics.accuracy(labels=tf.argmax(Y_test, 0), predictions=tf.argmax(pred, 0))

print(sess.run(accuracy))
我不知道如何打印出模型的准确度。例如,在
sklearn
中,如果您有一个模型,您只需打印
model.score(X\u测试,Y\u测试)
。但我不知道如何在
tensorflow
中做到这一点,或者这是否可能

我想我能计算出
均方误差。这有什么帮助吗

编辑

我尝试按照评论中的建议实现
tf.metrics.accurity
,但在实现时遇到了问题。文档中说它需要两个参数,
标签
预测
,所以我尝试了以下方法

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

rng = np.random

n_rows = X_train.shape[0]

X = tf.placeholder("float")
Y = tf.placeholder("float")


W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

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

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

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



init = tf.global_variables_initializer()
init_local = tf.local_variables_initializer()

with tf.Session() as sess:

    sess.run([init, init_local])

    for epoch in range(FLAGS.training_epochs):

        avg_cost = 0

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

            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}
            )

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

    print("Optimization Finished!")

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

    print(sess.run(accuracy))
accuracy, accuracy_op = tf.metrics.accuracy(labels=tf.argmax(Y_test, 0), predictions=tf.argmax(pred, 0))

print(sess.run(accuracy))
但这给了我一个错误

FailedPremissionError(回溯见上文):尝试使用未初始化的值精度/计数 [[Node:accurity/count/read=IdentityT=DT_FLOAT,[u class=[“loc:@accurity/count”],[u device=“/job:localhost/replica:0/task:0/device:CPU:0”]


具体如何实现这一点?

我认为Tensorflow文档中根本不清楚这一点,但在运行精度计算之前,您必须声明精度操作,然后初始化所有全局和局部变量:

accuracy, accuracy_op = tf.metrics.accuracy(labels=tf.argmax(Y_test, 0), predictions=tf.argmax(pred, 0))
# ...
init_global = tf.global_variables_initializer
init_local = tf.local_variables_initializer
sess.run([init_global, init_local])
# ...
# run accuracy calculation

我读了一些关于堆栈溢出的关于使用局部变量进行精度计算的内容,这就是为什么需要局部变量初始值设定项的原因

在阅读了您发布的完整代码后,我注意到了另外两件事:

  • 在计算
    pred
    时,使用
    
    pred=tf.add(tf.multiply(X,W),b)
    <代码>tf.multiply
执行元素级乘法,并且不会为您提供神经网络所需的完全连接层(我假设这是您最终的工作方向,因为您使用的是TensorFlow)。要实现完全连接的层,其中每个层i(包括输入和输出层)都有ni节点,您需要为每对连续层提供单独的权重和偏差矩阵。第i个权重矩阵的尺寸(第i层和第i+1层之间的权重)应为(ni,ni+1),第i个偏置矩阵的尺寸应为(ni+1,1)。然后,回到乘法运算——用tf.matmul替换tf.multiply,就可以开始了。我假设,对于单类线性回归问题,您所拥有的可能很好,但如果您计划解决多类回归问题或实现更深层次的网络,这绝对是您想要的方式
  • 你的重量和偏差张量的形状是(1,1)。您为变量提供了
    np.random.randn()
    的初始值,该值在未提供任何参数时生成一个浮点数。权重和偏差张量的尺寸需要作为参数提供给
    np.random.randn()
    。更好的是,您可以在Tensorflow中将这些变量初始化为随机值:
    W=tf.Variable(tf.random\u normal([dim0,dim1],seed=seed)
    (为了再现性,我总是使用种子值初始化随机变量)
  • 请注意,如果您还不知道这一点,但神经网络需要非线性激活函数才能有效。如果您所有的激活都是线性的,那么无论您有多少层,最终都会简化为简单的线性回归。许多人对隐藏层使用relu激活。对于输出层,使用softmax激活用于输出类为独占的多类分类问题(即,对于任何给定输入,只有一个类可以正确),以及sigmoid激活用于输出类不为独占的多类分类问题

  • 事实证明,由于这是一个多类线性回归问题,而不是一个分类问题,
    tf.metrics.accurity
    不是正确的方法

    我没有用百分比来显示模型的准确性,而是专注于降低均方误差(MSE)

    从其他例子来看,
    tf.metrics.accurity
    从未用于线性回归,而仅用于分类。通常
    tf.metric.mean_squared_error
    是正确的方法

    我实现了两种方法来计算测试数据预测的总MSE

    pred = tf.add(tf.matmul(X, W), b)
    ...
    ...
    Y_pred = sess.run(pred, feed_dict={X:X_test})
    mse = tf.reduce_mean(tf.square(Y_pred - Y_test))
    

    它们的作用相同,但显然第二种方法更简洁


    关于如何测量线性回归模型的精度,有一个很好的解释。

    那么
    tf.metrics.accurity
    呢,它返回一个表示
    精度的张量,总值除以计数?MSE不会告诉你精度分数。@Flika205我正在尝试实现它,但我遇到了错误rs.查看我的编辑。我尝试实现了这一点,但仍然存在错误。是的,文档不是最好的,我找不到任何显示模型精度的工作模型示例,我得到的最接近的结果是让模型显示其成本和MSE。在初始化局部变量之前,您是否定义了精度计算?不,之后。初始化后,我在我答案的编辑部分添加了代码。好的,我编辑了我的问题以添加完整的代码。我认为我很可能错误地实现了
    tf.metrics.accurity
    。但是,在初始化变量之前,需要先声明准确性的行。我正在为清晰。