Skip to content

Instantly share code, notes, and snippets.

@kusal1990
Created June 2, 2022 18:35
Show Gist options
  • Save kusal1990/17e6781651cdfd8d9156e474e8f121f1 to your computer and use it in GitHub Desktop.
Save kusal1990/17e6781651cdfd8d9156e474e8f121f1 to your computer and use it in GitHub Desktop.
# Matthews correlation coefficient calculation used inside Keras model
def matthews_correlation(y_true, y_pred):
"""
Calculate Matthews Correlation Coefficient.
References
----------
.. [1] https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
.. [2] https://www.kaggle.com/tarunpaparaju/vsb-competition-attention-bilstm-with-features/notebook?scriptVersionId=10690570
"""
y_pred_positive = K.round(K.clip(y_pred, 0, 1))
y_pred_negative = 1 - y_pred_positive
y_positive = K.round(K.clip(y_true, 0, 1))
y_negative= 1 - y_positive
tp = K.sum(y_positive * y_pred_positive)
tn = K.sum(y_negative * y_pred_negative)
fp = K.sum(y_negative * y_pred_positive)
fn = K.sum(y_positive * y_pred_negative)
numerator = (tp * tn - fp * fn)
denominator = K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
return numerator / (denominator + K.epsilon())
@kusal1990
Copy link
Author

ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment