如何在 tensorflow 或 keras 中使用 scipy.optimize.linear_sum_assignment?

Yel*_*Kyu 5 python keras tensorflow

第一次在这里发帖!如果我的问题缺少任何内容,请告诉我,我会解决它!

Facebook 最近发布了 DETR,一个使用 Transformer 的对象检测模型!该模型是用 Pytorch 实现的,我正在尝试实现包含匈牙利算法的损失函数,但使用 Keras 和 Tensorflow 作为 Keras 模型的自定义损失函数。在 Facebook 的原始实现中,它是https://github.com/facebookresearch/detr/blob/master/models/matcher.py 中的第 81-82 行

为了使用 numpy 和经典的 python 函数,我使用了:

    def hungarian_loss(losses):
        row_ind, col_ind = linear_sum_assignment(losses)
        idx = [[i, j] for i, j in zip(row_ind, col_ind)]
        return idx

    # dist loss is a 5x5 matrix, and idx is 5x2 indexes
    idx = tf.py_function(func=hungarian_loss, inp=[dist_loss], Tout=tf.int32)
    min_val = tf.gather_nd(dist_loss, idx)
    return K.mean(min_val)
Run Code Online (Sandbox Code Playgroud)

但我得到了:

tensorflow.python.framework.errors_impl.InvalidArgumentError:  Inner dimensions of output shape must match inner dimensions of updates shape. Output: [5,5] updates: [5]
Run Code Online (Sandbox Code Playgroud)

是因为我试图使用不是 tf.Tensor 的东西作为 loss 吗?

小智 6

这对你有用吗?请参阅:https://www.tensorflow.org/api_docs/python/tf/numpy_function

@tf.function
def tf_linear_sum_assignment(cost_matrix):
    return tf.numpy_function(func=linear_sum_assignment,inp=[cost_matrix],Tout=[tf.int64,tf.int64])
Run Code Online (Sandbox Code Playgroud)

  • 这让算法为我运行,但当我尝试训练时,我收到“无梯度”错误。我怀疑它是在我的损失函数中使用的“线性求和分配”,但我知道我之前见过在损失中使用匈牙利算法的例子。知道如何解决这个问题吗? (3认同)