<p>Gradient computation occurs inside <code>optimizer.minimize</code> function, so, no explicit use inside loss function is needed. However, your implementation simply lacks an optimizable, trainable variable. </p>

<pre><code>iou = get_iou(masks, predictions)
mean_iou_loss = tf.Variable(initial_value=-tf.log(tf.reduce_sum(iou)), name='loss', trainable=True)
train_op = tf.train.AdamOptimizer(0.001).minimize(mean_iou_loss)
</code></pre>

<p>Numerical stability, differentiability and particular implementation aside, this should be enough to use it as a loss function, which will change with iterations.</p>

<p>Also take a look:</p>

<p><a href="https://arxiv.org/pdf/1902.09630.pdf" rel="noreferrer">https://arxiv.org/pdf/1902.09630.pdf</a></p>

<p><a href="https://stackoverflow.com/questions/40475246/why-does-one-not-use-iou-for-training">Why does one not use IOU for training?</a></p>
Implementing Intersection over Union Loss Using Tensorflow
<p>This may be more of a Tensorflow gradient question. I have been attempting to implement Intersection over Union (IoU) as losses and have been running into some problems. To the point, here is the snippet of my code that computes the IoU:</p>

<pre><code>def get_iou(masks, predictions):
    ious = []
    for i in range(batch_size):
        mask = masks[i]
        pred = predictions[i]
        masks_sum = tf.reduce_sum(mask)
        predictions_sum = tf.reduce_mean(pred)
        intersection = tf.reduce_sum(tf.multiply(mask, pred))
        union = masks_sum + predictions_sum - intersection
        iou = intersection / union
        ious.append(iou)
    return ious

iou = get_iou(masks, predictions)
mean_iou_loss = -tf.log(tf.reduce_sum(iou))
train_op = tf.train.AdamOptimizer(0.001).minimize(mean_iou_loss)
</code></pre>

<p>It works as predicted. However, the issue that I am having is the losses do not decrease. The model does train, though the results are less than ideal so I am wondering if I am implementing it correctly. Do I have to compute the gradients myself? I can compute the gradients for this IoU loss derived by <a href="https://arxiv.org/pdf/1608.01471.pdf" rel="noreferrer">this paper</a> using <code>tf.gradients()</code>, though I am not sure how to incorporate that with the <code>tf.train.AdamOptimizer()</code>. Reading the documentation, I feel like <code>compute_gradients</code> and <code>apply_gradients</code> are the commands that I need to use, but I can't find any examples on how to use them. My understanding is that the Tensorflow graph should be able to come up with the gradient itself via chain rule. So is a custom gradient even necessary in this problem? If the custom gradient is not necessary then I may just have an ill-posed problem and need to adjust some hyperparameters.</p>

<p><strong>Note:</strong> I have tried Tensorflow's implementation of the IoU, <code>tf.metrics.mean_iou()</code>, but it spits out <code>inf</code> every time so I have abandoned that.</p>