天天看點

NLP-準确率、精确率、召回率和F1值

記錄準确率(Accuracy)、精确率(Precision)、召回率(Recall)和F1值(F-Measure)計算公式,和如何使用TensorFlow實作

一、計算公式

  • True Positive(TP):将正類預測為正類數
  • True Negative(TN):将負類預測為負類數
  • False Positive(FP):将負類預測為正類數
  • False Negative(FN):将正類預測為負類數

1.準确率:

A c c u r a c y = T P + T N T P + T N + F P + F N Accuracy= \frac{TP+TN}{TP+TN+FP+FN} Accuracy=TP+TN+FP+FNTP+TN​

2.精确率:

P r e c i s i o n = T P T P + F P Precision= \frac{TP}{TP+FP} Precision=TP+FPTP​

3.召回率:

R e c a l l = T P T P + F N Recall= \frac{TP}{TP+FN} Recall=TP+FNTP​

4.F1值

F 1 = 2 ∗ P r e ∗ R e c P r e + R e c = 2 ∗ T P 2 ∗ T P + F P + F N F1= \frac{2*Pre*Rec}{Pre+Rec}= \frac{2*TP}{2*TP+FP+FN} F1=Pre+Rec2∗Pre∗Rec​=2∗TP+FP+FN2∗TP​

二、TensorFlow實作

  • Accuracy
with tf.name_scope("accuracy"):
      correct_predictions = tf.equal(self.predictions,self.input_y)
      self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
           
  • TN;TP;FN;FP
with tf.name_scope("tn"):
        tn = tf.metrics.true_negatives(labels=self.input_y, predictions=self.predictions)
        self.tn = tf.reduce_sum(tf.cast(tn, "float"), name="tn")
with tf.name_scope("tp"):
        tp = tf.metrics.true_positives(labels=self.input_y, predictions=self.predictions)
        self.tp = tf.reduce_sum(tf.cast(tn, "float"), name="tp")
with tf.name_scope("fp"):
        fp = tf.metrics.false_positives(labels=self.input_y, predictions=self.predictions)
        self.fp = tf.reduce_sum(tf.cast(fp, "float"), name="fp")
with tf.name_scope("fn"):
       fn = tf.metrics.false_negatives(labels=self.input_y, predictions=self.predictions)
       self.fn = tf.reduce_sum(tf.cast(fn, "float"), name="fn")
           
  • Recall;Precision;F1
with tf.name_scope("recall"):
       self.recall = self.tp / (self.tp + self.fn)
with tf.name_scope("precision"):
       self.precision = self.tp / (self.tp + self.fp)
with tf.name_scope("F1"):
       self.F1 = (2 * self.precision * self.recall) / (self.precision + self.recall)