【问题标题】:Tensorflow loss function no gradient providedTensorFlow 损失函数没有提供梯度
【发布时间】:2022-01-07 06:16:52
【问题描述】:

目前我尝试编写自己的损失函数,但是在返回结果(包含损失值列表的张量)时出现以下错误:

ValueError: No gradients provided for any variable: ['conv2d/kernel:0', 'conv2d/bias:0', 'conv2d_1/kernel:0', 'conv2d_1/bias:0', 'dense/kernel:0', 'dense/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0', 'dense_2/kernel:0', 'dense_2/bias:0'].

但是在教程和他们的文档中,他们也使用 tf.recude_mean 并且像他们一样使用它时(他们展示了如何编写 mse 损失函数)我没有收到错误,所以我似乎遗漏了一些东西

我的代码:

gl = tfa.losses.GIoULoss()
def loss(y_true, y_pred):
        batch_size = y_true.shape[0]
        # now contains 32 lists (a batch) of bbxs -> shape is (32, 7876)
        bbx_true = y_true.numpy()

        # now contains 32 lists (a batch) of bbxs here we have to double access [0] in order to get the entry itself 
        # -> shape is (32, 1, 1, 7876)
        bbx_pred = y_pred.numpy()

        losses = []
        curr_true = []
        curr_pred = []
        for i in range(batch_size):
            curr_true = bbx_true[i] 
            curr_pred = bbx_pred[i][0][0]


            curr_true = [curr_true[x:x+4] for x in range(0, len(curr_true), 4)]
            curr_pred = [curr_pred[x:x+4] for x in range(0, len(curr_pred), 4)]

            if len(curr_true) == 0:
                curr_true.append([0., 0.,0.,0.])

            curr_loss = gl(curr_true, curr_pred)

            losses.append(curr_loss)

        return tf.math.reduce_mean(losses, axis=-1)

基本上我想达到bounding box regression,因此我想使用GIoUloss 损失函数。因为我的模型输出了 7896 个神经元(根据我的训练集乘以 4,我想预测的最大边界框数量)并且 gioloss 函数需要将输入作为一个列表数组,每个列表包含 4 个元素,所以我必须执行此转换。

如何更改我的代码才能建立gradient

【问题讨论】:

    标签: tensorflow gradient loss-function loss tensorflow-hub


    【解决方案1】:

    Numpy 不提供 autograd 函数,因此您需要在损失中专门使用 Tensorflow 张量(否则在反向传播期间梯度会丢失)。所以避免使用.numpy(),而是使用 tensorflow 运算符并在 tensorflow 张量上切片。

    【讨论】:

    • 你能帮我一下,把它转换成张量流操作我真的不知道这应该怎么可能,因为我称之为外部损失函数......顺便说一句。我正在以 Eager 模式编译
    • check tf.reshape 我认为这是您在这里错过的主要重要功能。还要检查 tf.concat 以进行连接
    猜你喜欢
    • 2020-08-25
    • 2021-10-26
    • 1970-01-01
    • 2021-05-08
    • 2017-10-16
    • 1970-01-01
    • 2020-04-05
    • 2021-01-08
    • 2022-12-04
    相关资源
    最近更新 更多