Skip to content

Instantly share code, notes, and snippets.

@ysl2
Forked from brunodoamaral/_dice.py
Created January 16, 2022 01:53
Show Gist options
  • Save ysl2/5c531ae56fef3a2dee7dcb069f6855ef to your computer and use it in GitHub Desktop.
Save ysl2/5c531ae56fef3a2dee7dcb069f6855ef 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, empty_score=1.0):
"""
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()
if im_sum == 0:
return empty_score
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * intersection.sum() / im_sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment