File size: 4,873 Bytes
dee113c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" BERT classification fine-tuning: utilities to work with GLUE tasks """
from __future__ import absolute_import, division, print_function
import csv
import json
import logging
import os
import sys
from io import open
from sklearn.metrics import f1_score, precision_score, recall_score
from torch.utils.data import Dataset
import torch
csv.field_size_limit(sys.maxsize)
logger = logging.getLogger(__name__)
class InputFeatures(object):
"""A single training/test features for a example."""
def __init__(self, code_tokens, code_ids, nl_tokens, nl_ids, label, idx):
self.code_tokens = code_tokens
self.code_ids = code_ids
self.nl_tokens = nl_tokens
self.nl_ids = nl_ids
self.label = label
self.idx = idx
class InputFeaturesTriplet(InputFeatures):
"""A single training/test features for a example. Add docstring seperately. """
def __init__(self, code_tokens, code_ids, nl_tokens, nl_ids, ds_tokens, ds_ids, label, idx):
super(InputFeaturesTriplet, self).__init__(code_tokens, code_ids, nl_tokens, nl_ids, label, idx)
self.ds_tokens = ds_tokens
self.ds_ids = ds_ids
def convert_examples_to_features(js, tokenizer, args):
# label
label = js['label']
# code
code = js['code']
code_tokens = tokenizer.tokenize(code)[:args.max_seq_length-2]
code_tokens = [tokenizer.cls_token]+code_tokens+[tokenizer.sep_token]
code_ids = tokenizer.convert_tokens_to_ids(code_tokens)
padding_length = args.max_seq_length - len(code_ids)
code_ids += [tokenizer.pad_token_id]*padding_length
nl = js['doc'] # query
nl_tokens = tokenizer.tokenize(nl)[:args.max_seq_length-2]
nl_tokens = [tokenizer.cls_token]+nl_tokens+[tokenizer.sep_token]
nl_ids = tokenizer.convert_tokens_to_ids(nl_tokens)
padding_length = args.max_seq_length - len(nl_ids)
nl_ids += [tokenizer.pad_token_id]*padding_length
return InputFeatures(code_tokens, code_ids, nl_tokens, nl_ids, label, js['idx'])
class TextDataset(Dataset):
def __init__(self, tokenizer, args, file_path=None, type=None):
# json file: dict: idx, query, doc, code
self.examples = []
self.type = type
data=[]
with open(file_path, 'r') as f:
data = json.load(f)
# data = data[:114560]
if self.type == 'test':
for js in data:
js['label'] = 0
for js in data:
self.examples.append(convert_examples_to_features(js, tokenizer, args))
if 'train' in file_path:
for idx, example in enumerate(self.examples[:3]):
logger.info("*** Example ***")
logger.info("idx: {}".format(idx))
logger.info("code_tokens: {}".format([x.replace('\u0120','_') for x in example.code_tokens]))
logger.info("code_ids: {}".format(' '.join(map(str, example.code_ids))))
logger.info("nl_tokens: {}".format([x.replace('\u0120','_') for x in example.nl_tokens]))
logger.info("nl_ids: {}".format(' '.join(map(str, example.nl_ids))))
def __len__(self):
return len(self.examples)
def __getitem__(self, i):
""" return both tokenized code ids and nl ids and label"""
return torch.tensor(self.examples[i].code_ids), \
torch.tensor(self.examples[i].nl_ids),\
torch.tensor(self.examples[i].label)
def simple_accuracy(preds, labels):
return (preds == labels).mean()
def acc_and_f1(preds, labels):
acc = simple_accuracy(preds, labels)
f1 = f1_score(y_true=labels, y_pred=preds)
prec = precision_score(y_true=labels, y_pred=preds)
reca = recall_score(y_true=labels, y_pred=preds)
return {
"acc": acc,
"precision": prec,
"recall": reca,
"f1": f1,
"acc_and_f1": (acc + f1) / 2,
}
def compute_metrics(task_name, preds, labels):
assert len(preds) == len(labels)
if task_name == "webquery":
return acc_and_f1(preds, labels)
if task_name == "staqc":
return acc_and_f1(preds, labels)
else:
raise KeyError(task_name)
|