【问题标题】:How to get prediction when computing loss function in convolutional neural network (tensorflow)?在卷积神经网络(张量流)中计算损失函数时如何获得预测?
【发布时间】:2019-02-02 17:45:03
【问题描述】:

我按照以下步骤使用 tensorflow 构建了一个卷积神经网络: https://www.tensorflow.org/tutorials/estimators/cnn

我想用我自己的损失函数计算损失,因此需要在每个训练步骤中获得每个类的预测概率。 从 Tensorflow 教程中,我知道我可以使用“tf.nn.softmax(logits)”获得这些概率,但是这会返回一个张量,我不知道如何从这个张量中提取实际的概率。谁能告诉我如何获得这些概率,以便计算我的损失函数?

【问题讨论】:

    标签: python tensorflow conv-neural-network prediction loss-function


    【解决方案1】:

    这是您计算 softmax 并在之后获得概率的方式:

    # Probabities for each element in the batch for each class.
    softmax = tf.nn.softmax(logits, axis=1)
    # For each element in the batch return the element that has the maximal probability
    predictions = tf.argmax(softmax, axis=1)
    

    但是,请注意,您不需要预测来计算损失函数,您需要实际概率。如果您想计算其他指标,那么您可以使用预测(准确度、精度、召回率等指标)。 softmax 张量包含每个类的实际概率。例如,假设您在一个批次中有 2 个元素,并且您尝试预测三个类别中的一个,softmax 将为您提供以下信息:

    # Logits with random numbers
    logits = np.array([[24, 23, 50], [50, 30, 32]], dtype=np.float32)
    tf.nn.softmax(logits, axis=1)
    # The softmax returns
    # [[5.1090889e-12 1.8795289e-12 1.0000000e+00]
    #  [1.0000000e+00 2.0611537e-09 1.5229979e-08]]
    # If we sum the probabilites for each batch they should sum up to one
    tf.reduce_sum(softmax, axis=1)
    # [1. 1.]
    

    根据您对损失函数的想象,这应该是正确的:

    first_second = tf.nn.l2_loss(softmax[0] - softmax[1])
    first_third = tf.nn.l2_loss(softmax[0] - softmax[2])
    divide_and_add_m = tf.divide(first_second, first_third) + m
    loss = tf.maximum(0.0, 1 - tf.reduce_sum(divide_and_add_m))
    

    【讨论】:

    • 抱歉造成误会,感谢您帮助我。当然,我想获得概率,而不是预测。也许我的问题只是我不知道如何从张量中获取概率。如果我执行“tf.nn.softmax(logits, axis=1)”,它会返回张量而不是数组,但我需要数组来访问概率。
    • 你的损失函数的数学公式是什么?
    • 损失 = max(0,1 - ((||f(x_1)-f(x_2)||^2) / (||f(x_1) - f(x_3)||^ 2 +m)),其中我有三个样本的批次 x_1、x_2、x_3 和 f(x) 是神经网络的输出
    • 非常感谢!现在明白了:)
    猜你喜欢
    • 2018-11-14
    • 2018-07-25
    • 1970-01-01
    • 2020-07-10
    • 2010-11-21
    • 2017-03-18
    • 2016-09-03
    • 2015-04-15
    • 1970-01-01
    相关资源
    最近更新 更多