import torch


def F1_score(y_pred, y, threshold=0.5):
    """ Function used to compute the F1 score of a prediction of a model """
    # get the actual 0-1 labels
    labels = torch.where(y_pred > threshold, 1.0, 0.0)

    # get the number of positives and the number of negatives
    positives = (y == 1.0).sum().item()
    negatives = (y == 0.0).sum().item()

    # get the true positives and true negatives
    true_positives = ((y == 1.0) & (labels == y)).sum().item()
    true_negatives = ((y == 0.0) & (labels == y)).sum().item()

    # get the false positives and false negatives
    false_positives = ((labels == 1.0) & (y == 0.0)).sum().item()
    false_negatives = ((labels == 0.0) & (y == 1.0)).sum().item()

    # compute the F1 score metrics
    precision = true_positives / (true_positives + false_positives) if true_positives != 0 else 0
    recall = true_positives / positives if positives != 0 else 0

    # compute the F1 score
    f1 = (2 * precision * recall) / (precision + recall) if precision + recall != 0 else 0

    # return the score
    return f1