用Tensorflow-CNN-classifi获取精度和召回值

2024-05-14 16:50:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一个简单的解决方案来获取分类器类的召回率和精度值?

为了放置一些上下文,我在Denny Britz代码的帮助下使用Tensorflow实现了一个20类CNN分类器:https://github.com/dennybritz/cnn-text-classification-tf

正如你在文末看到的,他实现了一个计算全局精度的简单函数:

# Accuracy
        with tf.name_scope("accuracy"):
            correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
            self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")

有什么想法可以让我做一些类似的事情来获得不同类别的召回率和准确度值吗?

也许我的问题听起来会很愚蠢,但老实说,我有点不知所措。谢谢你的帮助。


Tags: 代码namehttpsself分类器tftensorflow精度
1条回答
网友
1楼 · 发布于 2024-05-14 16:50:42

使用tf.metrics帮了我一把:

#define the method
x = tf.placeholder(tf.int32, )
y = tf.placeholder(tf.int32, )
acc, acc_op = tf.metrics.accuracy(labels=x, predictions=y)
rec, rec_op = tf.metrics.recall(labels=x, predictions=y)
pre, pre_op = tf.metrics.precision(labels=x, predictions=y)

#predict the class using your classifier
scorednn = list(DNNClassifier.predict_classes(input_fn=lambda: input_fn(testing_set)))
scoreArr = np.array(scorednn).astype(int)

#run the session to compare the label with the prediction
sess=tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
v = sess.run(acc_op, feed_dict={x: testing_set["target"],y: scoreArr}) #accuracy
r = sess.run(rec_op, feed_dict={x: testing_set["target"],y: scoreArr}) #recall
p = sess.run(pre_op, feed_dict={x: testing_set["target"],y: scoreArr}) #precision

print("accuracy %f", v)
print("recall %f", r)
print("precision %f", p)

结果:

accuracy %f 0.686667
recall %f 0.978723
precision %f 0.824373

注:为了准确起见,我将使用:

accuracy_score = DNNClassifier.evaluate(input_fn=lambda:input_fn(testing_set),steps=1)["accuracy"]

因为它更简单,并且已经在评估中进行了计算。

如果不需要累积结果,也可以调用变量初始值设定项。

相关问题 更多 >

    热门问题