Skip to content

Commit

Permalink
[#179] Create a new core.model_metrics module and move _calc_mcc() there
Browse files Browse the repository at this point in the history
  • Loading branch information
riley-harper committed Dec 11, 2024
1 parent c1f0d8c commit c166ace
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
20 changes: 20 additions & 0 deletions hlink/linking/core/model_metrics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# This file is part of the ISRDI's hlink.
# For copyright and licensing information, see the NOTICE and LICENSE files
# in this project's top-level directory, and also on-line at:
# https://github.com/ipums/hlink
import math


def mcc(tp: int, tn: int, fp: int, fn: int) -> float:
"""
Given the counts of true positives (tp), true negatives (tn), false
positives (fp), and false negatives (fn) for a model run, compute the
Matthews Correlation Coefficient (MCC).
"""
if (math.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))) != 0:
mcc = ((tp * tn) - (fp * fn)) / (
math.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
)
else:
mcc = 0
return mcc
20 changes: 4 additions & 16 deletions hlink/linking/model_exploration/link_step_train_test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from pyspark.sql import DataFrame
from pyspark.sql.functions import col, count, count_if, mean
from functools import reduce
import hlink.linking.core.model_metrics as metrics_core
import hlink.linking.core.threshold as threshold_core
import hlink.linking.core.classifier as classifier_core

Expand Down Expand Up @@ -690,21 +691,6 @@ def _save_training_results(
# )


def _calc_mcc(tp: int, tn: int, fp: int, fn: int) -> float:
"""
Given the counts of true positives (tp), true negatives (tn), false
positives (fp), and false negatives (fn) for a model run, compute the
Matthews Correlation Coefficient (MCC).
"""
if (math.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))) != 0:
mcc = ((tp * tn) - (fp * fn)) / (
math.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
)
else:
mcc = 0
return mcc


def _calc_threshold_matrix(
alpha_threshold: float | list[float], threshold_ratio: float | list[float] | None
) -> list[list[float]]:
Expand Down Expand Up @@ -796,7 +782,9 @@ def _get_aggregate_metrics(
recall = np.nan
else:
recall = true_positives / (true_positives + false_negatives)
mcc = _calc_mcc(true_positives, true_negatives, false_positives, false_negatives)
mcc = metrics_core.mcc(
true_positives, true_negatives, false_positives, false_negatives
)
return precision, recall, mcc


Expand Down

0 comments on commit c166ace

Please sign in to comment.