{"cells":[{"metadata":{"trusted":true,"_uuid":"a44de583e0455943ab8181318faf7f38c59618e5"},"cell_type":"code","source":"import torch","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"def F_score(logit, label, threshold=0.5, beta=2):\n    prob = torch.sigmoid(logit)\n    prob = prob > threshold\n    label = label > threshold\n\n    TP = (prob & label).sum(1).float()\n    TN = ((~prob) & (~label)).sum(1).float()\n    FP = (prob & (~label)).sum(1).float()\n    FN = ((~prob) & label).sum(1).float()\n\n    precision = TP / (TP + FP + 1e-12)\n    recall = TP / (TP + FN + 1e-12)\n    F2 = (1 + beta**2) * precision * recall / (beta**2 * precision + recall + 1e-12)\n    return F2.mean(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a134aacbdc7f087ff3eca589a674c3c16ddfc147"},"cell_type":"code","source":"def label2onehot(label, num_classes=7178):\n    onehot = label.new(label.size(0), num_classes)\n    onehot.zero_()\n    onehot.scatter_(1, label, 1)\n    return onehot","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"967a6a13b5ebf3a2e7db001f87126ec0cf6782cb"},"cell_type":"code","source":"logit = torch.FloatTensor([[0.1,0.2,-0.5,0.8],[-0.3,0.9,-0.1,0.1]])\nlabel = torch.LongTensor([[1,2],[0,3]])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4761bb330f1b0fb5523fb9d875e26f556fe3e190"},"cell_type":"code","source":"onehot = label2onehot(label,4)\nprint(onehot)\nprint(logit)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a50801698a225bc976ad0a816ded160b579a7c85"},"cell_type":"code","source":"fscore = F_score(logit, onehot)\nprint(fscore)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e2f3af5abf3b77d9ba3dc2b70fedab4c6a076720"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}