code
stringlengths
17
6.64M
@Registry.register('data.dsprites', 'class') class DSpritesData(base.ImageTfdsData): 'Provides the DSprites data set.\n\n DSprites only comes with a training set. Therefore, the training, validation,\n and test set are split out of the original training set.\n\n For additional details and usage, see the base c...
@Registry.register('data.dtd', 'class') class DTDData(base.ImageTfdsData): 'Provides Describable Textures Dataset (DTD) data.\n\n As of version 1.0.0, the train/val/test splits correspond to those of the\n 1st fold of the official cross-validation partition.\n\n For additional details and usage, see the base c...
@Registry.register('data.eurosat', 'class') class EurosatData(base.ImageTfdsData): 'Provides EuroSat dataset.\n\n EuroSAT dataset is based on Sentinel-2 satellite images covering 13 spectral\n bands and consisting of 10 classes with 27000 labeled and\n geo-referenced samples.\n\n URL: https://github.com/phelb...
@Registry.register('data.oxford_flowers102', 'class') class OxfordFlowers102Data(base.ImageTfdsData): 'Provides Oxford 102 categories flowers dataset.\n\n See corresponding tfds dataset for details.\n\n URL: https://www.robots.ox.ac.uk/~vgg/data/flowers/102/\n ' def __init__(self, data_dir=None, train_spl...
@Registry.register('data.oxford_iiit_pet', 'class') class OxfordIIITPetData(base.ImageTfdsData): 'Provides OxfordIIITPet data.\n\n The OxfordIIITPet dataset comes only with a training and test set.\n Therefore, the validation set is split out of the original training set, and\n the remaining examples are used ...
@Registry.register('data.patch_camelyon', 'class') class PatchCamelyonData(base.ImageTfdsData): 'Provides PatchCamelyon data.' def __init__(self, data_dir=None): dataset_builder = tfds.builder('patch_camelyon:2.*.*', data_dir=data_dir) dataset_builder.download_and_prepare() tfds_split...
def partialclass(cls, *base_args, **base_kwargs): 'Builds a subclass with partial application of the given args and keywords.\n\n Equivalent to functools.partial performance, base_args are preprended to the\n positional arguments given during object initialization and base_kwargs are\n updated with the kwargs ...
def parse_name(string_to_parse): 'Parses input to the registry\'s lookup function.\n\n Args:\n string_to_parse: can be either an arbitrary name or function call\n (optionally with positional and keyword arguments).\n e.g. "multiclass", "resnet50_v2(filters_factor=8)".\n\n Returns:\n A tuple of i...
class Registry(object): 'Implements global Registry.' _GLOBAL_REGISTRY = {} @staticmethod def global_registry(): return Registry._GLOBAL_REGISTRY @staticmethod def register(name, item_type): 'Creates a function that registers its input.' if (item_type not in ['functio...
@Registry.register('data.resisc45', 'class') class Resisc45Data(base.ImageTfdsData): 'Provides RESISC-45 dataset.\n\n RESISC45 dataset is a publicly available benchmark for Remote Sensing Image\n Scene Classification (RESISC), created by Northwestern Polytechnical\n University (NWPU). This dataset contains 31,...
@Registry.register('data.smallnorb', 'class') class SmallNORBData(base.ImageTfdsData): 'Provides the SmallNORB data set.\n\n SmallNORB comes only with a training and test set. Therefore, the validation\n set is split out of the original training set, and the remaining examples are\n used as the "train" split. ...
@Registry.register('data.sun397', 'class') class Sun397Data(base.ImageTfdsData): 'Provides Sun397Data data.' def __init__(self, config='tfds', data_dir=None): if (config == 'tfds'): dataset_builder = tfds.builder('sun397/tfds:4.*.*', data_dir=data_dir) dataset_builder.download...
@Registry.register('data.svhn', 'class') class SvhnData(base.ImageTfdsData): 'Provides SVHN data.\n\n The Street View House Numbers (SVHN) Dataset is an image digit recognition\n dataset of over 600,000 color digit images coming from real world data.\n Split size:\n - Training set: 73,257 images\n - Test...
class Evaluator(): '\n An evaluator with below logics:\n\n 1. find which eval module to use.\n 2. store the eval results, pretty print it in log file as well.\n ' def __init__(self) -> None: self.results = defaultdict(dict) self.iteration = (- 1) self.threshold_end = 0.5 ...
class Trainer(): '\n a trainer with below logics:\n\n 1. Build optimizer, scheduler\n 2. Load checkpoints if provided\n 3. Train and eval at each epoch\n ' def __init__(self, cfg: CfgNode, model: nn.Module, evaluator: Evaluator, device: torch.device) -> None: self.cfg = cfg sel...
def build_model(cfg): '\n build model here\n ' assert (cfg.MODEL.TYPE in _MODEL_TYPES.keys()), "Model type '{}' not supported".format(cfg.MODEL.TYPE) assert (cfg.NUM_GPUS <= torch.cuda.device_count()), 'Cannot use more GPU devices than available' train_type = cfg.MODEL.TYPE model = _MODEL_TY...
def log_model_info(model, verbose=False): 'Logs model info' if verbose: logger.info(f'''Classification Model: {model}''') model_total_params = sum((p.numel() for p in model.parameters())) model_grad_params = sum((p.numel() for p in model.parameters() if p.requires_grad)) logger.info('Total...
def get_current_device(): if torch.cuda.is_available(): cur_device = torch.cuda.current_device() else: cur_device = torch.device('cpu') return cur_device
def load_model_to_device(model, cfg): cur_device = get_current_device() if torch.cuda.is_available(): model = model.cuda(device=cur_device) if (cfg.NUM_GPUS > 1): model = torch.nn.parallel.DistributedDataParallel(module=model, device_ids=[cur_device], output_device=cur_device, find...
def build_mae_model(model_type, crop_size, prompt_cfg, model_root, adapter_cfg=None): if (not (model_type in ['mae_vitb16', 'mae_vitl16'])): raise ValueError('Does not support other arch') if (prompt_cfg is not None): model = prompt_mae_vit(model_type, prompt_cfg) else: model = mae...
def build_mocov3_model(model_type, crop_size, prompt_cfg, model_root, adapter_cfg=None): if (not (model_type in ['mocov3_vitb16', 'mocov3_vits16'])): raise ValueError('Does not support other arch') if (prompt_cfg is not None): model = prompt_moco_vit(model_type, prompt_cfg) else: m...
class MLP(nn.Module): def __init__(self, input_dim: int, mlp_dims: List[int], dropout: float=0.1, nonlinearity: Type[nn.Module]=nn.ReLU, normalization: Type[nn.Module]=nn.BatchNorm1d, special_bias: bool=False, add_bn_first: bool=False): super(MLP, self).__init__() projection_prev_dim = input_dim ...
class SSLViT(nn.Module): 'moco-v3 and mae model.' def __init__(self, cfg): super(SSLViT, self).__init__() if ('prompt' in cfg.MODEL.TRANSFER_TYPE): prompt_cfg = cfg.MODEL.PROMPT else: prompt_cfg = None if ((cfg.MODEL.TRANSFER_TYPE != 'end2end') and ('pr...
class SigmoidLoss(nn.Module): def __init__(self, cfg=None): super(SigmoidLoss, self).__init__() def is_single(self): return True def is_local(self): return False def multi_hot(self, labels: torch.Tensor, nb_classes: int) -> torch.Tensor: labels = labels.unsqueeze(1)...
class SoftmaxLoss(SigmoidLoss): def __init__(self, cfg=None): super(SoftmaxLoss, self).__init__() def loss(self, logits, targets, per_cls_weights, kwargs): weight = torch.tensor(per_cls_weights, device=logits.device) loss = F.cross_entropy(logits, targets, weight, reduction='none') ...
def build_loss(cfg): loss_name = cfg.SOLVER.LOSS assert (loss_name in LOSS), f'loss name {loss_name} is not supported' loss_fn = LOSS[loss_name] if (not loss_fn): return None else: return loss_fn(cfg)
def make_scheduler(optimizer: optim.Optimizer, train_params: CfgNode) -> LambdaLR: warmup = train_params.WARMUP_EPOCH total_iters = train_params.TOTAL_EPOCH if (train_params.SCHEDULER == 'cosine'): scheduler = WarmupCosineSchedule(optimizer, warmup_steps=warmup, t_total=total_iters) elif (trai...
class WarmupCosineSchedule(LambdaLR): ' Linear warmup and then cosine decay.\n Linearly increases learning rate from 0 to 1 over `warmup_steps`.\n Decreases learning rate from 1. to 0. over remaining\n `t_total - warmup_steps` steps following a cosine curve.\n If `cycles` (default=...
class WarmupCosineWithHardRestartsSchedule(LambdaLR): ' Linear warmup and then cosine cycles with hard restarts.\n Linearly increases learning rate from 0 to 1 over `warmup_steps`.\n If `cycles` (default=1.) is different from default, learning rate\n follows `cycles` times a cosine decayi...
def make_optimizer(models: List[Any], train_params: CfgNode) -> Optimizer: params = [] for model in models: if train_params.DBG_TRAINABLE: logger.info('Trainable params:') for (key, value) in model.named_parameters(): if value.requires_grad: if train_par...
class AdamW(Optimizer): ' Implements Adam algorithm with weight decay fix.\n Parameters:\n lr (float): learning rate. Default 1e-3.\n betas (tuple of 2 floats): Adams beta parameters (b1, b2). Default: (0.9, 0.999)\n eps (float): Adams epsilon. Default: 1e-6\n weight_decay (float): ...
def get_world_size() -> int: if (not dist.is_available()): return 1 if (not dist.is_initialized()): return 1 return dist.get_world_size()
def get_rank() -> int: if (not dist.is_available()): return 0 if (not dist.is_initialized()): return 0 return dist.get_rank()
def is_master_process(num_gpus=8): '\n Determines if the current process is the master process.\n ' if torch.distributed.is_initialized(): return ((dist.get_rank() % num_gpus) == 0) else: return True
def run(local_rank, num_proc, func, init_method, shard_id, num_shards, backend, cfg, args): "\n Runs a function from a child process.\n Args:\n local_rank (int): rank of the current process on the current machine.\n num_proc (int): number of processes per machine.\n func (function): fun...
def destroy_process_group(): 'Destroys the default process group.' torch.distributed.destroy_process_group()
def scaled_all_reduce(cfg, tensors): 'Performs the scaled all_reduce operation on the provided tensors.\n\n The input tensors are modified in-place. Currently supports only the sum\n reduction operator. The reduced values are scaled by the inverse size of\n the process group (equivalent to cfg.NUM_GPUS)....
def cat_all_gather(tensors): 'Performs the concatenated all_gather operation on the provided tensors.\n ' tensors_gather = [torch.ones_like(tensors) for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(tensors_gather, tensors, async_op=False) output = torch.cat(tensors_g...
def local_cat_all_gather(tensors): 'Performs the concatenated all_gather operation on the provided tensors.\n ' tensors_gather = [torch.ones_like(tensors) for _ in range(get_local_size())] torch.distributed.all_gather(tensors_gather, tensors, async_op=False, group=_LOCAL_PROCESS_GROUP) output = tor...
def get_local_size(): '\n Returns:\n The size of the per-machine process group,\n i.e. the number of processes per machine.\n ' if (not dist.is_available()): return 1 if (not dist.is_initialized()): return 1 return dist.get_world_size(group=_LOCAL_PROCESS_GROUP)
def get_local_rank(): '\n Returns:\n The rank of the current process within the local (per-machine) process group.\n ' if (not dist.is_available()): return 0 if (not dist.is_initialized()): return 0 assert (_LOCAL_PROCESS_GROUP is not None) return dist.get_rank(group=_...
def get_world_size() -> int: if (not dist.is_available()): return 1 if (not dist.is_initialized()): return 1 return dist.get_world_size()
def get_rank() -> int: if (not dist.is_available()): return 0 if (not dist.is_initialized()): return 0 return dist.get_rank()
def is_master_process(num_gpus=8): '\n Determines if the current process is the master process.\n ' if torch.distributed.is_initialized(): return ((dist.get_rank() % num_gpus) == 0) else: return True
def run(local_rank, num_proc, func, init_method, shard_id, num_shards, backend, cfg, args): "\n Runs a function from a child process.\n Args:\n local_rank (int): rank of the current process on the current machine.\n num_proc (int): number of processes per machine.\n func (function): fun...
def destroy_process_group(): 'Destroys the default process group.' torch.distributed.destroy_process_group()
def scaled_all_reduce(cfg, tensors): 'Performs the scaled all_reduce operation on the provided tensors.\n\n The input tensors are modified in-place. Currently supports only the sum\n reduction operator. The reduced values are scaled by the inverse size of\n the process group (equivalent to cfg.NUM_GPUS)....
def cat_all_gather(tensors): 'Performs the concatenated all_gather operation on the provided tensors.\n ' tensors_gather = [torch.ones_like(tensors) for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(tensors_gather, tensors, async_op=False) output = torch.cat(tensors_g...
def local_cat_all_gather(tensors): 'Performs the concatenated all_gather operation on the provided tensors.\n ' tensors_gather = [torch.ones_like(tensors) for _ in range(get_local_size())] torch.distributed.all_gather(tensors_gather, tensors, async_op=False, group=_LOCAL_PROCESS_GROUP) output = tor...
def get_local_size(): '\n Returns:\n The size of the per-machine process group,\n i.e. the number of processes per machine.\n ' if (not dist.is_available()): return 1 if (not dist.is_initialized()): return 1 return dist.get_world_size(group=_LOCAL_PROCESS_GROUP)
def get_local_rank(): '\n Returns:\n The rank of the current process within the local (per-machine) process group.\n ' if (not dist.is_available()): return 0 if (not dist.is_initialized()): return 0 assert (_LOCAL_PROCESS_GROUP is not None) return dist.get_rank(group=_...
def save_or_append_df(out_path, df): if os.path.exists(out_path): previous_df = pd.read_pickle(out_path) df = pd.concat([previous_df, df], ignore_index=True) df.to_pickle(out_path) print(f'Saved output at {out_path}')
class JSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, bytes): return str(obj, encoding='utf-8') elif isinstance(obj, np.integer): return int(obj) elif isinstance(obj...
def write_json(data: Union[(list, dict)], outfile: str) -> None: (json_dir, _) = os.path.split(outfile) if (json_dir and (not os.path.exists(json_dir))): os.makedirs(json_dir) with open(outfile, 'w') as f: json.dump(data, f, cls=JSONEncoder, ensure_ascii=False, indent=2)
def read_json(filename: str) -> Union[(list, dict)]: 'read json files' with open(filename, 'rb') as fin: data = json.load(fin, encoding='utf-8') return data
def pil_loader(path: str) -> Image.Image: 'load an image from path, and suppress warning' ImageFile.LOAD_TRUNCATED_IMAGES = True with open(path, 'rb') as f: img = Image.open(f) return img.convert('RGB')
def _suppress_print(): 'Suppresses printing from the current process.' def print_pass(*objects, sep=' ', end='\n', file=sys.stdout, flush=False): pass builtins.print = print_pass
@functools.lru_cache(maxsize=None) def _cached_log_stream(filename): return PathManager.open(filename, 'a')
@functools.lru_cache() def setup_logging(num_gpu, num_shards, output='', name='visual_prompt', color=True): 'Sets up the logging.' if is_master_process(num_gpu): logging.root.handlers = [] logging.basicConfig(level=logging.INFO, format=_FORMAT, stream=sys.stdout) else: _suppress_pr...
def setup_single_logging(name, output=''): 'Sets up the logging.' logging.root.handlers = [] logging.basicConfig(level=logging.INFO, format=_FORMAT, stream=sys.stdout) if (len(name) == 0): name = __name__ logger = logging.getLogger(name) logger.setLevel(logging.INFO) logger.propaga...
def get_logger(name): 'Retrieves the logger.' return logging.getLogger(name)
def log_json_stats(stats, sort_keys=True): 'Logs json stats.' logger = get_logger(__name__) stats = {k: (decimal.Decimal('{:.6f}'.format(v)) if isinstance(v, float) else v) for (k, v) in stats.items()} json_stats = simplejson.dumps(stats, sort_keys=True, use_decimal=True) if ((stats['_type'] == 't...
class _ColorfulFormatter(logging.Formatter): def __init__(self, *args, **kwargs): self._root_name = (kwargs.pop('root_name') + '.') self._abbrev_name = kwargs.pop('abbrev_name', '') if len(self._abbrev_name): self._abbrev_name = (self._abbrev_name + '.') super(_Colorfu...
def gpu_mem_usage(): 'Computes the GPU memory usage for the current device (GB).' if (not torch.cuda.is_available()): return 0 _B_IN_GB = ((1024 * 1024) * 1024) mem_usage_bytes = torch.cuda.max_memory_allocated() return (mem_usage_bytes / _B_IN_GB)
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(...
def remove_trailing(eval_dict): min_num = min([len(v) for (k, v) in eval_dict.items() if ('top5' not in k)]) new_dict = {} for (k, v) in eval_dict.items(): if ('top5' not in k): new_dict[k] = v[:min_num] return new_dict
def get_meta(job_root, job_path, model_type): j_data = job_path.split('/run')[0].split(((job_root + '/') + model_type))[(- 1)].split('/') (data_name, feat_type, opt_params) = (j_data[1], j_data[2], j_data[3]) lr = float(opt_params.split('_')[0].split('lr')[(- 1)]) wd = float(opt_params.split('_')[1].s...
def update_eval(line, eval_dict, data_name): if (('top1' in line) and ('top' in line.split(': top1:')[(- 1)])): metric = 'top' else: metric = 'rocauc' top1 = float(line.split(': top1:')[(- 1)].split(metric)[0]) eval_type = line.split(' Classification results with ')[(- 1)].split(': top...
def get_nmi(job_path): with open(job_path) as f: lines = f.readlines() nmi_dict = defaultdict(list) num_jobs = 0 log_temp = [] for l in lines: if ('Rank of current process:' in l): num_jobs += 1 if (num_jobs == 2): break if ('Clutering nmi' i...
def get_mean_accuracy(job_path, data_name): val_data = torch.load(job_path.replace('logs.txt', f'val_{data_name}_logits.pth')) test_data = torch.load(job_path.replace('logs.txt', f'val_{data_name}_logits.pth')) v_matrix = confusion_matrix(val_data['targets'], np.argmax(val_data['joint_logits'], 1)) t_...
def get_training_data(job_path, model_type, job_root): (data_name, feat_type, lr, wd) = get_meta(job_root, job_path, model_type) with open(job_path) as f: lines = f.readlines() train_loss = [] eval_dict = defaultdict(list) num_jobs = 0 total_params = (- 1) gradiented_params = (- 1)...
def get_time(file): with open(file) as f: lines = f.readlines() start_time = lines[0].split('[')[1].split(']')[0] start_time = datetime.datetime.strptime(start_time, '%m/%d %H:%M:%S') end_time = lines[(- 1)].split('[')[1].split(']')[0] end_time = datetime.datetime.strptime(end_time, '%m/%d...
def get_df(files, model_type, root, is_best=True, is_last=True, max_epoch=300): pd_dict = defaultdict(list) for job_path in tqdm(files, desc=model_type): (train_loss, eval_results, meta_dict, (v_top1, t_top1)) = get_training_data(job_path, model_type, root) batch_size = meta_dict['batch_size']...
def delete_ckpts(f): (f_dir, _) = os.path.split(f) for f_delete in glob.glob((f_dir + '/*.pth')): os.remove(f_delete) print(f'removed {f_delete}')
def average_df(df, metric_names=['l-val_top1', 'l-val_base_top1'], take_average=True): data_names = set(list(df['data'])) f_names = set(list(df['feature'])) t_names = set(list(df['type'])) hp_names = [c for c in df.columns if (c not in (['data', 'feature', 'type', 'file', 'best_epoch'] + metric_names)...
def filter_df(df, sorted_cols, max_num): data_names = set(list(df['data'])) f_names = set(list(df['feature'])) t_names = set(list(df['type'])) df_list = [] for d_name in data_names: for f_name in f_names: for t_name in t_names: result = df[(df.data == d_name)] ...
def display_results(df, sorted_cols=['data', 'feature', 'type', 'l-val_top1'], max_num=1): cols = [c for c in df.columns if (c not in [])] df = df[cols] if (max_num is not None): df = filter_df(df, sorted_cols[3:], max_num) return df.sort_values(sorted_cols).reset_index(drop=True)
def setup(args): '\n Create configs and perform basic setups.\n ' cfg = get_cfg() cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) output_dir = cfg.OUTPUT_DIR lr = cfg.SOLVER.BASE_LR wd = cfg.SOLVER.WEIGHT_DECAY output_folder = os.path.join(cfg.DATA.NAME, cfg....
def get_loaders(cfg, logger): logger.info('Loading training data (final training data for vtab)...') if cfg.DATA.NAME.startswith('vtab-'): train_loader = data_loader.construct_trainval_loader(cfg) else: train_loader = data_loader.construct_train_loader(cfg) logger.info('Loading validat...
def train(cfg, args): if torch.cuda.is_available(): torch.cuda.empty_cache() if (cfg.SEED is not None): torch.manual_seed(cfg.SEED) np.random.seed(cfg.SEED) random.seed(0) logging_train_setup(args, cfg) logger = logging.get_logger('visual_prompt') (train_loader, val...
def main(args): 'main function to call from workflow' cfg = setup(args) with open(os.path.join(cfg.OUTPUT_DIR, 'configs.yaml'), 'w') as f: f.write(cfg.dump()) train(cfg, args)
def create_gold(json_file, gold_file, db_id_file): with open(db_id_file) as f: database_id_list = f.readlines() database_id_list = [db_id.strip() for db_id in database_id_list] with open(json_file) as f: data = json.load(f) gold_query = {} for (i, interaction) in enumerate(data...
def timeval(string): 'Returns the numeric version of a time.\n\n Inputs:\n string (str): String representing a time.\n\n Returns:\n String representing the absolute time.\n ' if (string.endswith('am') or (string.endswith('pm') and string[:(- 2)].isdigit())): numval = int(string[...
def is_time(string): 'Returns whether a string represents a time.\n\n Inputs:\n string (str): String to check.\n\n Returns:\n Whether the string represents a time.\n ' if (string.endswith('am') or string.endswith('pm')): if string[:(- 2)].isdigit(): return True r...
def deanonymize(sequence, ent_dict, key): 'Deanonymizes a sequence.\n\n Inputs:\n sequence (list of str): List of tokens to deanonymize.\n ent_dict (dict str->(dict str->str)): Maps from tokens to the entity dictionary.\n key (str): The key to use, in this case either natural language or S...
class Anonymizer(): 'Anonymization class for keeping track of entities in this domain and\n scripts for anonymizing/deanonymizing.\n\n Members:\n anonymization_map (list of dict (str->str)): Containing entities from\n the anonymization file.\n entity_types (list of str): All enti...
class UtteranceItem(): def __init__(self, interaction, index): self.interaction = interaction self.utterance_index = index def __str__(self): return str(self.interaction.utterances[self.utterance_index]) def histories(self, maximum): if (maximum > 0): history...
class UtteranceBatch(): def __init__(self, items): self.items = items def __len__(self): return len(self.items) def start(self): self.index = 0 def next(self): item = self.items[self.index] self.index += 1 return item def done(self): ret...
class PredUtteranceItem(): def __init__(self, input_sequence, interaction_item, previous_query, index, available_snippets): self.input_seq_to_use = input_sequence self.interaction_item = interaction_item self.index = index self.available_snippets = available_snippets self....
class InteractionItem(): def __init__(self, interaction, max_input_length=float('inf'), max_output_length=float('inf'), nl_to_sql_dict={}, maximum_length=float('inf')): if (maximum_length != float('inf')): self.interaction = copy.deepcopy(interaction) self.interaction.utterances =...
class InteractionBatch(): def __init__(self, items): self.items = items def __len__(self): return len(self.items) def start(self): self.timestep = 0 self.current_interactions = [] def get_next_utterance_batch(self, snippet_keep_age, use_gold=False): items = ...
class ATISDataset(): ' Contains the ATIS data. ' def __init__(self, params): self.anonymizer = None if params.anonymize: self.anonymizer = anon.Anonymizer(ANONYMIZATION_FILENAME) if (not os.path.exists(params.data_directory)): os.mkdir(params.data_directory) ...
def num_utterances(dataset): 'Returns the total number of utterances in the dataset.' return sum([len(interaction) for interaction in dataset.examples])
class ATISVocabulary(): ' Stores the vocabulary for the ATIS data.\n\n Attributes:\n raw_vocab (Vocabulary): Vocabulary object.\n tokens (set of str): Set of all of the strings in the vocabulary.\n inorder_tokens (list of str): List of all tokens, with a strict and\n unchanging ...
class DatasetSplit(): 'Stores a split of the ATIS dataset.\n\n Attributes:\n examples (list of Interaction): Stores the examples in the split.\n ' def __init__(self, processed_filename, raw_filename, load_function): if os.path.exists(processed_filename): print(('Loading prepr...
class NLtoSQLDict(): '\n Entity dict file should contain, on each line, a JSON dictionary with\n "input" and "output" keys specifying the string for the input and output\n pairs. The idea is that the existence of the key in an input sequence\n likely corresponds to the existence of the value in the ou...
class Schema(): def __init__(self, table_schema, simple=False): if simple: self.helper1(table_schema) else: self.helper2(table_schema) def helper1(self, table_schema): self.table_schema = table_schema column_names = table_schema['column_names'] ...
class Interaction(): ' ATIS interaction class.\n\n Attributes:\n utterances (list of Utterance): The utterances in the interaction.\n snippets (list of Snippet): The snippets that appear through the interaction.\n anon_tok_to_ent:\n identifier (str): Unique identifier for the intera...
def load_function(parameters, nl_to_sql_dict, anonymizer, database_schema=None): def fn(interaction_example): keep = False raw_utterances = interaction_example['interaction'] if ('database_id' in interaction_example): database_id = interaction_example['database_id'] ...
def is_snippet(token): " Determines whether a token is a snippet or not.\n\n Inputs:\n token (str): The token to check.\n\n Returns:\n bool, indicating whether it's a snippet.\n " return token.startswith(SNIPPET_PREFIX)