Implement Micro-F1
Implement Micro-F1
Micro-averaging aggregates the total true positives, false positives, and false negatives across all classes before computing F1:
F1micro=2⋅TP+FP+FN2⋅TPy_true and y_pred are equal-length sequences of integer labels (single-label, multi-class).
Return a float in [0, 1].
Examples
y_true=[0,1,1], y_pred=[0,1,0]
TP=2→F1micro=2⋅2+1+12⋅2=64=32≈0.6667
y_true=[0,1,2,2], y_pred=[0,1,2,2]
Output: 1.0
y_true=[2,2,1,0], y_pred=[1,2,1,0]
TP=3 out of 4 → 0.75
Hint 1
Convert inputs to NumPy arrays first.
Hint 2
Calculate TP by counting element-wise matches between arrays, then derive FP and FN from the total length.
Requirements
- Handle up to 10⁵ items
- Integer labels assumed to be in 0..K-1 (K inferred from data)
- Return a Python float (not NumPy scalar)
Constraints
- len(y_true) == len(y_pred)
- No external ML libraries allowed.
Log in to take notes on this problem
Accepts: array
Accepts: array
Implement Micro-F1
Implement Micro-F1
Micro-averaging aggregates the total true positives, false positives, and false negatives across all classes before computing F1:
F1micro=2⋅TP+FP+FN2⋅TPy_true and y_pred are equal-length sequences of integer labels (single-label, multi-class).
Return a float in [0, 1].
Examples
y_true=[0,1,1], y_pred=[0,1,0]
TP=2→F1micro=2⋅2+1+12⋅2=64=32≈0.6667
y_true=[0,1,2,2], y_pred=[0,1,2,2]
Output: 1.0
y_true=[2,2,1,0], y_pred=[1,2,1,0]
TP=3 out of 4 → 0.75
Hint 1
Convert inputs to NumPy arrays first.
Hint 2
Calculate TP by counting element-wise matches between arrays, then derive FP and FN from the total length.
Requirements
- Handle up to 10⁵ items
- Integer labels assumed to be in 0..K-1 (K inferred from data)
- Return a Python float (not NumPy scalar)
Constraints
- len(y_true) == len(y_pred)
- No external ML libraries allowed.
Log in to take notes on this problem
Accepts: array
Accepts: array