create an evaluation function for macro f1 score in matlab using the confusion matrix in matlab

To create an evaluation function for macro F1 score in MATLAB using the confusion matrix, you can follow these steps:

  1. Calculate the precision and recall for each class:
main.m
% Assuming you have a confusion matrix named "confusionMatrix"
numClasses = size(confusionMatrix, 1);
precision = zeros(numClasses, 1);
recall = zeros(numClasses, 1);
for i = 1:numClasses
    tp = confusionMatrix(i, i);
    fp = sum(confusionMatrix(:, i)) - tp;
    fn = sum(confusionMatrix(i, :)) - tp;
    precision(i) = tp / (tp + fp);
    recall(i) = tp / (tp + fn);
end
375 chars
12 lines
  1. Calculate the F1 score for each class:
main.m
f1Score = 2 * (precision .* recall) ./ (precision + recall);
61 chars
2 lines
  1. Calculate the macro F1 score by taking the average of F1 scores for all classes:
main.m
macroF1 = mean(f1Score);
25 chars
2 lines

Here is the complete function:

main.m
function macroF1 = calculateMacroF1(confusionMatrix)
    numClasses = size(confusionMatrix, 1);
    precision = zeros(numClasses, 1);
    recall = zeros(numClasses, 1);
    for i = 1:numClasses
        tp = confusionMatrix(i, i);
        fp = sum(confusionMatrix(:, i)) - tp;
        fn = sum(confusionMatrix(i, :)) - tp;
        precision(i) = tp / (tp + fp);
        recall(i) = tp / (tp + fn);
    end
    f1Score = 2 * (precision .* recall) ./ (precision + recall);
    macroF1 = mean(f1Score);
end
503 chars
15 lines

You can now use this function by passing your confusion matrix to it:

main.m
confusionMatrix = ...; % your confusion matrix here
macroF1 = calculateMacroF1(confusionMatrix);
fprintf('Macro F1 Score: %.2f\n', macroF1);
141 chars
4 lines

Make sure to replace ... with your actual confusion matrix. The function will return the macro F1 score, which can be printed using fprintf statement.

Please note that the confusion matrix should be in the form where rows represent the predicted labels and columns represent the true labels.

I hope this helps!

gistlibby LogSnag