How do I calculate the matthews correlation coefficient in tensorflow
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Matthews correlation coefficient, or MCC, is a strong binary-classification metric when class imbalance makes accuracy misleading. It uses all four confusion-matrix terms, so it penalizes one-sided predictions much more honestly than plain accuracy. In TensorFlow, the safest implementation is a stateful metric that accumulates confusion counts across batches and computes MCC from the totals.
Start from the MCC Formula
For binary classification:
MCC = ((tp * tn) - (fp * fn)) / sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
The result ranges from -1 to 1:
- '
1means perfect agreement' - '
0is roughly no useful correlation' - '
-1means systematic disagreement'
Because the formula depends on the full confusion matrix, you should not compute MCC independently per batch and then average those batch scores. That produces the wrong answer in general.
Implement MCC as a Stateful Keras Metric
The cleanest TensorFlow pattern is to store running totals of tp, tn, fp, and fn.
This metric expects binary labels and probability-like predictions that can be thresholded.
Test the Metric Before Training
Always verify the metric on a tiny deterministic example before wiring it into a model.
That simple sanity check catches threshold mistakes and shape issues early.
Use It in model.compile
Once the implementation is behaving correctly, you can register it like any other Keras metric.
This is especially useful for imbalanced problems such as fraud detection, anomaly detection, and medical screening.
Threshold Choice Is Part of the Metric Behavior
MCC is computed on binary decisions, not raw probabilities. That means the threshold is not a small implementation detail. It materially changes the score.
A common workflow is:
- train with probabilistic outputs
- evaluate MCC across several thresholds on validation data
- keep the threshold that matches the operating tradeoff you want
If you blindly hard-code 0.5, you may be measuring the model at the wrong operating point.
Handle Degenerate Cases Explicitly
The denominator becomes zero when one side of the confusion matrix is missing entirely, such as all predictions being one class. That is why the metric uses:
Without that guard, you can get NaN results and unstable training logs.
Common Pitfalls
- Averaging per-batch MCC instead of accumulating global confusion counts first.
- Forgetting to threshold probabilistic predictions before computing
tp,tn,fp, andfn. - Ignoring the zero-denominator case and producing
NaN. - Reusing the binary version for multi-class problems without redesigning the metric.
- Treating the threshold as fixed by theory rather than a tunable operating choice.
Summary
- MCC is a useful binary-classification metric for imbalanced datasets.
- In TensorFlow, implement it as a stateful metric that accumulates confusion counts across batches.
- Compute MCC from global
tp,tn,fp, andfn, not from averaged batch scores. - Threshold predicted probabilities before counting outcomes.
- Guard against zero denominators and tune the threshold on validation data when needed.

