#279 · Machine Learning · Medium
⊣ Solve on deep-ml.comCalculate the Matthews Correlation Coefficient (MCC) for binary classification. MCC is a balanced measure that accounts for true/false positives and negatives, producing a value between -1 and +1.
Compute the confusion matrix components (TP, TN, FP, FN) and apply the MCC formula.
import math
def matthews_correlation_coefficient(
y_true: list[int],
y_pred: list[int],
) -> float:
tp = tn = fp = fn = 0
for true, pred in zip(y_true, y_pred):
if true == 1 and pred == 1:
tp += 1
elif true == 0 and pred == 0:
tn += 1
elif true == 0 and pred == 1:
fp += 1
else:
fn += 1
numerator = tp * tn - fp * fn
denominator = math.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
if denominator == 0:
return 0.0
return round(numerator / denominator, 6)(TP * TN - FP * FN) / sqrt((TP+FP)(TP+FN)(TN+FP)(TN+FN)).