Skip to main content
 首页 » 编程设计

python之使用 Tensorflow CNN 分类器获取精度和召回值

2024年08月22日30wuhuacong

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

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

正如您在 text_cnn.py 的末尾看到的,他实现了一个简单的函数来计算全局精度:

# 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") 

关于我如何做类似的事情以获得不同类别的召回率和准确率值的任何想法?

也许我的问题听起来很愚蠢,但老实说我有点迷茫。感谢您的帮助。

请您参考如下方法:

使用 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"] 

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

如果您不想要累积结果,也可以调用 variables_initializer。