0

我需要为我的深度网络实现一个新的损失函数,如下所示:

import tensorflow as tf
from tensorflow.python import confusion_matrix
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import array_ops

def gms_loss(targets=None, logits=None, name=None):
    #Shape checking
    try:
        targets.get_shape().merge_with(logits.get_shape())
    except ValueError:
        raise ValueError("logits and targets must have the same shape (%s vs %s)"
                         % (logits.get_shape(), targets.get_shape()))
    #Compute the confusion matrix
    predictions=tf.nn.softmax(logits)
    cm=confusion_matrix(tf.argmax(targets,1),tf.argmax(predictions,1),3)

    def compute_sensitivities(name):
        """Compute the sensitivity per class via the confusion matrix."""
        per_row_sum = math_ops.to_float(math_ops.reduce_sum(cm, 1))
        cm_diag = math_ops.to_float(array_ops.diag_part(cm))
        denominator = per_row_sum

        # If the value of the denominator is 0, set it to 1 to avoid
        # zero division.
        denominator = array_ops.where(
            math_ops.greater(denominator, 0), denominator,
            array_ops.ones_like(denominator))

        accuracies = math_ops.div(cm_diag, denominator)
        return accuracies

    gms = math_ops.reduce_prod(compute_sensitivities('sensitivities'))
    return gms

这是来自图形代码的调用:

test=gms_loss(targets=y,logits=pred)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(test)

最后,已知的错误:

"ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables..."

我找不到问题,如果我使用 softmax_cross_entropy,它可以工作(但无法正确优化,这就是我需要新损失函数的原因)

先感谢您

4

1 回答 1

2

我认为问题在于tf.argmax()函数不可微。因此,优化器将无法计算损失函数相对于您的预测和目标的梯度。我不知道用 argmax 函数处理这个问题的方法,所以我建议避免使用不可微分的函数。

于 2017-05-17T15:18:38.030 回答