Skip to content

Instantly share code, notes, and snippets.

@aunsid
Created September 17, 2020 13:49
Show Gist options
  • Save aunsid/b28c87f98983f00163f6e588e3da1191 to your computer and use it in GitHub Desktop.
Save aunsid/b28c87f98983f00163f6e588e3da1191 to your computer and use it in GitHub Desktop.
Binary Class Segmentation Metrics(f1, acc, precision, recall) in Numpy
# https://github.com/Abe404/segmentation_of_roots_in_soil_with_unet/blob/master/src/metrics.py
def get_metrics(y_pred, y_true, loss=float('nan')):
true_positives = np.sum(np.logical_and(y_pred == 1, y_true == 1))
true_negatives = np.sum(np.logical_and(y_pred == 0, y_true == 0))
false_positives = np.sum(np.logical_and(y_pred == 1, y_true == 0))
false_negatives = np.sum(np.logical_and(y_pred == 0, y_true == 1))
accuracy = (true_positives + true_negatives) / len(y_true)
assert not np.isnan(true_negatives)
assert not np.isnan(false_positives)
assert not np.isnan(false_negatives)
assert not np.isnan(true_positives)
if true_positives > 0:
precision = true_positives / (true_positives + false_positives)
recall = true_positives / (true_positives + false_negatives)
f1_score = 2 * ((precision * recall) / (precision + recall))
iou = true_positives / (true_positives + false_positives + false_negatives)
else:
precision = recall = f1_score = iou = float('NaN')
return {
"accuracy": accuracy,
"TN": true_negatives,
"FP": false_positives,
"FN": false_negatives,
"TP": true_positives,
"precision": precision,
"recall": recall,
"f1_score": f1_score,
"iou": iou,
"true_mean": np.mean(y_true),
"pred_mean": np.mean(y_pred),
"loss": loss
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment