I'm trying to write a MCC Loss Function. I draft out the layout but it has to be done in a Matrix manipulation form as shown in the Reference 1 (This is not a school HW). So the following code is a pseudo code of what I'm trying to do.
class MCCLoss(Loss):
def __init__(self, weight=None, batch_axis=0, **kwargs):
super(MCCLoss, self).__init__(weight, batch_axis, **kwargs)
@staticmethod
def compute_confusion_matrix_values(y_true, y_pred):
tp = 0
fp = 0
tn = 0
fn = 0
for i in range(len(y_pred)):
if y_true[i] == y_pred[i] == 1:
tp += 1
if y_pred[i] == 1 and y_true[i] != y_pred[i]:
fp += 1
if y_true[i] == y_pred[i] == 0:
tn += 1
if y_pred[i] == 0 and y_true[i] != y_pred[i]:
fn += 1
return tp, fp, tn, fn
@staticmethod
def matthews_corrcoef(F, tp, fp, tn, fn):
# https://stackoverflow.com/a/56875660/992687
x = (tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)
epsilon = np.finfo(np.float64).eps
return ((tp * tn) - (fp * fn)) / F.sqrt(x + epsilon)
def hybrid_forward(self, F, y_pred, y_true, sample_weight=None):
tp, fp, tn, fn = self.compute_confusion_matrix_values(y_true, y_pred)
loss = 1 - self.matthews_corrcoef(F, tp, fp, tn, fn)
return loss
I found some resources that are quite useful, especially an example implementation using Keras in the following Reference 1 link .
I'm not sure if I can use MakeLoss at Reference 2 to simplify the whole thing.
Reference:
Multiple Classification for MCC (Matthews Correlation Coefficient implementation) in Keras https://github.com/vlainic/matthews-correlation-coefficient/blob/master/multi_mcc_loss.py
Custom Loss Function by using MakeLoss http://beta.mxnet.io/r/api/mx.symbol.MakeLoss.html https://blog.csdn.net/u013381011/article/details/79141680
MXNet MCC metric https://github.com/apache/incubator-mxnet/blob/56e79853ad5cf98baf84454eb595c7658bef6ee6/python/mxnet/metric.py#L838
Would any tech expert help me to implement this? Need a good hands
Much appreciatedMuch appreciated