IoU by tensorflow>

# IoU by tensorflow

What is the best way to calcuate Intersection Over Union value for object detection? I need a simple or fast way to calculate it for detected rectangles.

JO295.00
3

Here is another implementations, which is more useful, when you've got images, not vectors

``````import tensorflow as tf

def IoU(y_pred, y_true):
I = tf.reduce_sum(y_pred * y_true, axis=(1, 2))
U = tf.reduce_sum(y_pred + y_true, axis=(1, 2)) - I
return tf.reduce_mean(I / U)
``````
LP262.00
0

Great. Thank you. It works now.

JW326.00
4

If you've fimilar with true positive, false positive, true negative and false negatives, then here is a code, which will calculate all these. useing these values, you can find a lot of metrics like IoU, precision, recall, F2 score etc.

``````y_pred = tf.nn.sigmoid(_output)
y_pred_class = tf.to_float(y_pred > 0.5)

correct_prediction = tf.equal(y_pred_class, y_true)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

tp = tf.reduce_sum(y_pred_class * y_true)
fp = tf.reduce_sum(tf.nn.relu(y_pred - y_true))
fn = tf.reduce_sum(tf.nn.relu(y_true - y_pred))

iou = tp / (tp + fp + fn)``````