【问题标题】:Why is `tf.reduce_mean` used when computing the accuracy of logistic regression?为什么在计算逻辑回归的准确性时使用`tf.reduce_mean`?
【发布时间】:2020-11-21 17:43:33
【问题描述】:

下面的函数是用来计算逻辑回归的准确率的,但是在这个函数中使用reduce_mean函数有什么意义呢?

代码是:

import tensorflow as tf    
def accuracy(y_pred, y_true):
        # Predicted class is the index of the highest score in prediction vector (i.e. argmax).
    
        correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64))
    
        return tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

【问题讨论】:

    标签: python tensorflow machine-learning keras logistic-regression


    【解决方案1】:

    首先,请注意,度量或损失函数通常需要一批预测/真实标签作为输入。现在,如果对应的预测正确,correct_prediction 的每个元素都是True;否则,它是False。然后,tf.cast(correct_prediction, tf.float32) 会将 True 值转换为 1 并将 False 值转换为 0。因此,计算它的平均值(即平均值)将等同于预测的准确性(尽管,作为范围 [0 ,1],而不是百分比)。

    要进一步澄清这一点,请考虑以下内容:

    >>> correct_prediction
    [True, False, False, True, True]    # 3 out of 5 predictions are correct
    
    >>> tf.cast(correct_prediction, tf.float32)
    [1, 0, 0, 1, 1]
    
    >>> tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    0.6    # it means 60% accuracy which is what we expected
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-22
      • 2015-08-10
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多