Skip to content

Instantly share code, notes, and snippets.

@Feyn-Man
Forked from brunodoamaral/_dice.py
Last active December 14, 2020 14:55
Show Gist options
  • Save Feyn-Man/667c137cebeaa5fdd50b03a91df15134 to your computer and use it in GitHub Desktop.
Save Feyn-Man/667c137cebeaa5fdd50b03a91df15134 to your computer and use it in GitHub Desktop.
Dice coefficient between two boolean NumPy arrays or array-like data. This is commonly used as a set similarity measurement (though note it is not a true metric; it does not satisfy the triangle inequality). The dimensionality of the input is completely arbitrary, but `im1.shape` and `im2.shape` much be equal. This Gist is licensed under the mod…
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Both are empty (sum eq to zero) = empty_score
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
im_sum = im1.sum() + im2.sum()
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return (2. * intersection.sum() + 1) / (im_sum + 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment