def prf1(cm):
    """Returns (precision, recall, f1) from a provided 2x2 confusion matrix.

    We special case a few F1 situations where the F1 score is technically undefined or
    pathological. For example, if there are no 1s to predict, 1.0 is returned for
    p/r/f1.
    """
    # cm: cm[i][j] is number truly in group i but predicted to be in j
    tp = cm[1][1]
    fp = cm[0][1]
    fn = cm[1][0]
    total_1s = tp + fn

    # precision undefined if tp + fp == 0, i.e. no 1s were predicted.
    if tp + fp == 0:
        # precision should not be penalized for not predicting anything.
        precision = 1.0
    else:
        # normal precision
        precision = tp / (tp + fp)

    # recall undefined if tp + fn == total_1s == 0
    if total_1s == 0:
        # couldn't have predicted any 1s because there weren't any. should not
        # penalize recall.
        recall = 1.0
    else:
        # normal recall
        recall = tp / (tp + fn)

    # f1 undefined if precision + recall == 0.
    if precision + recall == 0:
        # if precision and recall are both 0, f1 should just be 0.
        f1 = 0.0
    else:
        f1 = 2 * (precision * recall) / (precision + recall)

    return precision, recall, f1