Skip to content
The Chat Archive
mistral-medium-2505· Mistral AI LMArena Human Preference 140K

python How to calculate f1-score using precision and recall

  1. User

    python How to calculate f1-score using precision and recall

  2. Assistant

    To calculate the F1-score using precision and recall, you can use the following formula:

    [ F1 = 2 \times \frac{\text{precision} \times \text{recall}}{\text{precision} + \text{recall}} ]

    Steps:

    1. Compute Precision: [ \text{Precision} = \frac{\text{True Positives (TP)}}{\text{True Positives (TP)} + \text{False Positives (FP)}} ]

    2. Compute Recall: [ \text{Recall} = \frac{\text{True Positives (TP)}}{\text{True Positives (TP)} + \text{False Negatives (FN)}} ]

    3. Calculate F1-Score: [ F1 = 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}} ]

    Python Implementation:

    def calculate_f1(precision, recall):
        if (precision + recall) == 0:
            return 0.0  # Avoid division by zero
        f1 = 2 * (precision * recall) / (precision + recall)
        return f1
    
    # Example usage:
    precision = 0.8
    recall = 0.7
    f1_score = calculate_f1(precision, recall)
    print(f"F1-Score: {f1_score:.2f}")
    

    Explanation:

    • The F1-score is the harmonic mean of precision and recall.
    • It balances both metrics, especially useful when dealing with imbalanced datasets.
    • If either precision or recall is zero, the F1-score will be zero (handled in the code to avoid division by zero).

    Output:

    For the example above (precision = 0.8, recall = 0.7), the output will be:

    F1-Score: 0.75
    

    This means the model has a balanced performance between precision and recall.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.