code
stringlengths
17
6.64M
class Node(Common): "\n Provide methods for calculating 'Plan Points' and 'Actual Points'.\n " def __init__(self, regression=False, log_level=Log.error): self.LogLevel = log_level self.regression = regression def __O_N(self, n): return n def __O_1(self, n): ret...
class CalcNode(Node): "\n Provide methods to estimate the progress of the query.\n\n Estimation Outline:\n\n To estimate the progress of the query, this module defines a concept internally\n called 'point'. It is a non-dimensional value, and it is like the concept of\n cost in the optimizer in the ...
class QueryProgress(MergePlan, Replace, Rules, CalcNode): def __init__(self, base_dir='.', log_level=Log.error): self.set_base_dir(base_dir) self.LogLevel = log_level def _progress(self, merged_plan, serverId=None, queryid=None, planid=None): '\n Estimate the progress of merge...
class CalcRegression(): '\n Functions to calculate the regression params.\n ' def set_log_level(self, log_level): self.LogLevel = log_level def __rss(self, X, Y): assert (len(X) != 0) return (math.sqrt(sum(list(map((lambda x: (x ** 2)), list(map(operator.sub, X, Y)))))) / l...
class Regression(Repository, CalcRegression): def __init__(self, base_dir='.', log_level=Log.error): self.ServerId = '' self.Level = 0 self.set_base_dir(base_dir) self.LogLevel = log_level def __set_serverId(self, serverId): self.ServerId = serverId '\n Handle ...
class Replace(Common): def __init__(self, log_level=Log.info): self.__numNode = 0 self.__ar = [] self.LogLevel = log_level def __calc(self, plan, param, queryid, planid, depth): def get_children_plan_rows(plan): _X = [[], []] _NP = [[], []] ...
class Repository(Common): def __init__(self, base_dir='.', log_level=Log.error): self.set_base_dir(base_dir) self.LogLevel = log_level DEFAULT_DIR_MODE = 504 DEFAULT_HOSTS_CONF_MODE = 416 def secure_check(self, path, ref_mode): if (os.path.exists(path) == False): ...
class Rules(Common): def __init__(self, log_level=Log.error): self.LogLevel = log_level '\n All rules are heuristics; there is no theoretical background.\n ' def __rule1(self, plan): if ((plan['CurrentState'] == State.RUNNING) and (plan['Node Type'] == 'Hash Join') and ('Join Filte...
class NN(): def __init__(self, base_dir='.', log_level=Log.error): self.ServerId = '' self.LogLevel = log_level 'For Neural Net' NN_DIR = 'nn' NN_THRESHOLD = 3 def store_params(self, serverId, queryid, planid, depth, node_type, xouter, xinner, y): _keys = ['Depth', 'Node ...
class ExtendedStatistics(): def __init__(self, base_dir='.', log_level=Log.error): self.ServerId = '' self.LogLevel = log_level ES_FILE_PREFIX = 'es_' ES_THRESHOLD = 10 COND_LIST = ('Index Cond', 'Recheck Cond', 'TID Cond', 'Merge Cond', 'Hash Cond', 'Filter', 'Join Filter') def ...
class Histogram(): def __init__(self, base_dir='.', log_level=Log.error): self.ServerId = '' self.LogLevel = log_level HIST_FILE_PREFIX = 'hist_' HIST_THRESHOLD = 0.025 DIFF_THRESHOLD = 0.001 RANGE_THRESHOLD = 1.75 COND_LIST = ('Index Cond', 'Recheck Cond', 'TID Cond', 'Merge ...
class Analyze(Repository, ExtendedStatistics, NN, Histogram): def __init__(self, base_dir='.', log_level=Log.error): self.ServerId = '' self.Level = 0 self.set_base_dir(base_dir) self.LogLevel = log_level def __set_serverId(self, serverId): self.ServerId = serverId ...
def stylize(): device = ('cuda' if torch.cuda.is_available() else 'cpu') net = transformer.TransformerNetwork() net.load_state_dict(torch.load(STYLE_TRANSFORM_PATH)) net = net.to(device) with torch.no_grad(): while 1: torch.cuda.empty_cache() print('Stylize Image~ P...
def stylize_folder_single(style_path, content_folder, save_folder): '\n Reads frames/pictures as follows:\n\n content_folder\n pic1.ext\n pic2.ext\n pic3.ext\n ...\n\n and saves as the styled images in save_folder as follow:\n\n save_folder\n pic1.ext\n pic2.e...
def stylize_folder(style_path, folder_containing_the_content_folder, save_folder, batch_size=1): 'Stylizes images in a folder by batch\n If the images are of different dimensions, use transform.resize() or use a batch size of 1\n IMPORTANT: Put content_folder inside another folder folder_containing_the_con...
class TransformerNetwork(nn.Module): 'Feedforward Transformation Network without Tanh\n reference: https://arxiv.org/abs/1603.08155 \n exact architecture: https://cs.stanford.edu/people/jcjohns/papers/fast-style/fast-style-supp.pdf\n ' def __init__(self): super(TransformerNetwork, self).__in...
class TransformerNetworkTanh(TransformerNetwork): "A modification of the transformation network that uses Tanh function as output \n This follows more closely the architecture outlined in the original paper's supplementary material\n his model produces darker images and provides retro styling effect\n Re...
class ConvLayer(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, norm='instance'): super(ConvLayer, self).__init__() padding_size = (kernel_size // 2) self.reflection_pad = nn.ReflectionPad2d(padding_size) self.conv_layer = nn.Conv2d(in_channels, out_...
class ResidualLayer(nn.Module): '\n Deep Residual Learning for Image Recognition\n\n https://arxiv.org/abs/1512.03385\n ' def __init__(self, channels=128, kernel_size=3): super(ResidualLayer, self).__init__() self.conv1 = ConvLayer(channels, channels, kernel_size, stride=1) s...
class DeconvLayer(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, output_padding, norm='instance'): super(DeconvLayer, self).__init__() padding_size = (kernel_size // 2) self.conv_transpose = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride,...
def gram(tensor): (B, C, H, W) = tensor.shape x = tensor.view(B, C, (H * W)) x_t = x.transpose(1, 2) return (torch.bmm(x, x_t) / ((C * H) * W))
def load_image(path): img = cv2.imread(path) return img
def show(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = np.array((img / 255)).clip(0, 1) plt.figure(figsize=(10, 5)) plt.imshow(img) plt.show()
def saveimg(img, image_path): img = img.clip(0, 255) cv2.imwrite(image_path, img)
def itot(img, max_size=None): if (max_size == None): itot_t = transforms.Compose([transforms.ToTensor(), transforms.Lambda((lambda x: x.mul(255)))]) else: (H, W, C) = img.shape image_size = tuple([int(((float(max_size) / max([H, W])) * x)) for x in [H, W]]) itot_t = transforms....
def ttoi(tensor): tensor = tensor.squeeze() img = tensor.cpu().numpy() img = img.transpose(1, 2, 0) return img
def transfer_color(src, dest): '\n Transfer Color using YIQ colorspace. Useful in preserving colors in style transfer.\n This method assumes inputs of shape [Height, Width, Channel] in BGR Color Space\n ' (src, dest) = (src.clip(0, 255), dest.clip(0, 255)) (H, W, _) = src.shape dest = cv2.res...
def plot_loss_hist(c_loss, s_loss, total_loss, title='Loss History'): x = [i for i in range(len(total_loss))] plt.figure(figsize=[10, 6]) plt.plot(x, c_loss, label='Content Loss') plt.plot(x, s_loss, label='Style Loss') plt.plot(x, total_loss, label='Total Loss') plt.legend() plt.xlabel('E...
class ImageFolderWithPaths(datasets.ImageFolder): 'Custom dataset that includes image file paths. \n Extends torchvision.datasets.ImageFolder()\n Reference: https://discuss.pytorch.org/t/dataloader-filenames-in-each-batch/4212/2\n ' def __getitem__(self, index): original_tuple = super(ImageF...
class VGG19(nn.Module): def __init__(self, vgg_path='models/vgg19-d01eb7cb.pth'): super(VGG19, self).__init__() vgg19_features = models.vgg19(pretrained=False) vgg19_features.load_state_dict(torch.load(vgg_path), strict=False) self.features = vgg19_features.features for pa...
class VGG16(nn.Module): def __init__(self, vgg_path='models/vgg16-00b39a1b.pth'): super(VGG16, self).__init__() vgg16_features = models.vgg16(pretrained=False) vgg16_features.load_state_dict(torch.load(vgg_path), strict=False) self.features = vgg16_features.features for pa...
def video_transfer(video_path, style_path): print('OpenCV {}'.format(cv2.__version__)) starttime = time.time() (H, W, fps) = getInfo(video_path) print('Height: {} Width: {} FPS: {}'.format(H, W, fps)) print('Extracting video frames') getFrames(video_path) print('Performing style transfer o...
def getInfo(video_path): '\n Extracts the height, width,\n and fps of a video\n ' vidcap = cv2.VideoCapture(video_path) width = vidcap.get(cv2.CAP_PROP_FRAME_WIDTH) height = vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT) fps = vidcap.get(cv2.CAP_PROP_FPS) return (height, width, fps)
def getFrames(video_path): '\n Extracts the frames of a video\n and saves in specified path\n ' vidcap = cv2.VideoCapture(video_path) (success, image) = vidcap.read() count = 1 success = True while success: cv2.imwrite('{}{}{}{}'.format((FRAME_SAVE_PATH + FRAME_CONTENT_FOLDER)...
def makeVideo(frames_path, save_name, fps, height, width): base_name_len = len(FRAME_BASE_FILE_NAME) filetype_len = len(FRAME_BASE_FILE_TYPE) images = [img for img in sorted(os.listdir(frames_path), key=(lambda x: int(x[base_name_len:(- filetype_len)]))) if img.endswith('.jpg')] fourcc = cv2.VideoWrit...
def webcam(style_transform_path, width=1280, height=720): '\n Captures and saves an image, perform style transfer, and again saves the styled image.\n Reads the styled image and show in window. \n ' device = ('cuda' if torch.cuda.is_available() else 'cpu') print('Loading Transformer Network') ...
def pretty(d, indent=0): for (key, value) in d.items(): print((('\t' * indent) + str(key))) if isinstance(value, dict): pretty(value, (indent + 1)) else: print((('\t' * (indent + 1)) + str(value)))
def get_record(output_dir): print('Loading records from:', output_dir) records = reporting.load_records(output_dir) print('Total records:', len(records)) return records
def get_results(out_dir, selection_method): 'Given all records, print a results table for each dataset.' records = get_record(out_dir) grouped_records = reporting.get_grouped_records(records, group_test_envs=True).map((lambda group: {**group, 'sweep_acc': selection_method.sweep_acc(group['records'], retur...
def get_result(setup): result_dict = {} for dataset in dataset_all: result_dict[dataset] = {} sub_result_dict = result_dict[dataset] basedir = f'{base_output_dir}/{dataset}/{setup}' for (alg_name, alg_name_long) in algorithm_all.items(): if (alg_name in ['CLIPPretra...
def plot_result(result_dict, plot_dataset, plot_y='acc_tgt', include=None, exclude=None, plot_std=False): plt.figure() sub_result_dict = result_dict[plot_dataset] plt_xs = [] plt_ys = [] plt_errs = [] for (k, v) in sub_result_dict.items(): subsub_result_dict = sub_result_dict[k] ...
def pretty(d, indent=0): for (key, value) in d.items(): print((('\t' * indent) + str(key))) if isinstance(value, dict): pretty(value, (indent + 1)) else: print((('\t' * (indent + 1)) + str(value)))
def get_record(output_dir): print('Loading records from:', output_dir) records = reporting.load_records(output_dir) print('Total records:', len(records)) return records
def get_results_per_domain(out_dir, selection_method, num_envs, env_names=None): 'Given all records, get averaged results of each setup for each test domain.' records = get_record(out_dir) grouped_records = reporting.get_grouped_records(records, group_test_envs=True).map((lambda group: {**group, 'sweep_ac...
def get_result(setup): result_dict = {} for dataset in dataset_all: result_dict[dataset] = {} sub_result_dict = result_dict[dataset] basedir = f'{base_output_dir}/{dataset}/{setup}' env_names = datasets.get_dataset_class(dataset).ENVIRONMENTS num_envs = len(env_names) ...
def pretty(d, indent=0): for (key, value) in d.items(): print((('\t' * indent) + str(key))) if isinstance(value, dict): pretty(value, (indent + 1)) else: print((('\t' * (indent + 1)) + str(value)))
def get_record(output_dir): print('Loading records from:', output_dir) records = reporting.load_records(output_dir) print('Total records:', len(records)) return records
def get_results(out_dir, selection_method): 'Given all records, print a results table for each dataset.' records = get_record(out_dir) grouped_records = reporting.get_grouped_records(records, group_test_envs=True).map((lambda group: {**group, 'sweep_acc': selection_method.sweep_acc(group['records'], retur...
def get_result(setup): result_dict = {} for dataset in dataset_all: result_dict[dataset] = {} sub_result_dict = result_dict[dataset] basedir = f'{base_output_dir}/{dataset}/{setup}' for (alg_name, alg_name_long) in algorithm_all.items(): if (alg_name in ['CLIPPretra...
def plot_result(result_dict, plot_dataset, plot_y='acc_tgt', include=None, exclude=None, plot_std=False): plt.figure() sub_result_dict = result_dict[plot_dataset] plt_xs = [] plt_ys = [] plt_errs = [] for (k, v) in sub_result_dict.items(): subsub_result_dict = sub_result_dict[k] ...
class AbstractBottleneck(torch.nn.Module): 'Domain Bottleneck (abstract class)' def __init__(self, feature_dim, num_classes, num_domains, hparams): super(AbstractBottleneck, self).__init__() self.hparams = hparams def forward(self, z): return z def loss(self, z, y, dom_label...
class DummyBottleneck(AbstractBottleneck): 'Dummy Bottleneck (without bottleneck)' def __init__(self, feature_dim, num_classes, num_domains, hparams): super(DummyBottleneck, self).__init__(feature_dim, num_classes, num_domains, hparams) def loss(self, z, y, dom_labels): dummy_loss = torc...
class DiscreteEntropyBottleneck(AbstractBottleneck): 'Entropy Bottleneck (with discretization)\n Introduced by J. Ballé, et al., in “Variational image compression with a scale hyperprior”.\n\n Properties:\n - Minimize H(Z)\n - Require no access to domain labels and task labels\n ' def __init__...
class AbstractContrastBottleneck(AbstractBottleneck): 'Contrastive based bottlenecks (abstract class)\n The implementation is based on the supervised contrastive loss (SupCon) introduced by\n P. Khosla, et al., in “Supervised Contrastive Learning“.\n ' def __init__(self, feature_dim, num_classes,...
class CADBottleneck(AbstractContrastBottleneck): 'Contrastive Adversarial Domain (CAD) bottleneck\n Introduced in Sec 4.2.1 in our paper.\n\n Properties:\n - Minimize I(D;Z)\n - Require access to domain labels but not task labels\n ' def __init__(self, feature_dim, num_classes, num_domains, hp...
class CondCADBottleneck(AbstractContrastBottleneck): 'Conditional Contrastive Adversarial Domain (CAD) bottleneck\n Introduced in Appx C.4 in our paper.\n\n Properties:\n - Minimize I(D;Z|Y)\n - Require access to both domain labels and task labels\n ' def __init__(self, feature_dim, num_classe...
class SupConLoss(nn.Module): 'Supervised Contrastive (SupCon) loss\n Introduced by P. Khosla, et al., in “Supervised Contrastive Learning“.\n Modified from https://github.com/HobbitLong/SupContrast/blob/8d0963a7dbb1cd28accb067f5144d61f18a77588/losses.py#L11\n ' def __init__(self, feature_dim, num_d...
class AbstractCLIPAlgorithm(Algorithm): 'CLIP based algorithms (abstract class)' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(AbstractCLIPAlgorithm, self).__init__(feature_dim, num_classes, num_domains, hparams) self.clip_model = pretrained ...
class CLIPPretrained(AbstractCLIPAlgorithm): 'Pretrained CLIP model' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(CLIPPretrained, self).__init__(feature_dim, num_classes, num_domains, hparams, pretrained, idx2class) self.transform = (lambda ...
class AbstractCLIPBottleneck(AbstractCLIPAlgorithm): 'CLIP based algorithms with an additional bottleneck (abstract class)' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class, bottleneck_class, use_clip_contrast=False): '\n Args:\n feature_dim: ...
class SupCLIPBottleneckBase(AbstractCLIPBottleneck): 'CLIP finetuned with supervised cross-entropy loss but no bottleneck' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(SupCLIPBottleneckBase, self).__init__(feature_dim, num_classes, num_domains, hpar...
class SupCLIPBottleneckEnt(AbstractCLIPBottleneck): 'CLIP finetuned with supervised cross-entropy loss and entropy bottleneck' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(SupCLIPBottleneckEnt, self).__init__(feature_dim, num_classes, num_domains, h...
class SupCLIPBottleneckCAD(AbstractCLIPBottleneck): 'CLIP finetuned with supervised cross-entropy loss and CAD bottleneck' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(SupCLIPBottleneckCAD, self).__init__(feature_dim, num_classes, num_domains, hpara...
class SupCLIPBottleneckCondCAD(AbstractCLIPBottleneck): 'CLIP finetuned with supervised cross-entropy loss and conditional CAD bottleneck' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(SupCLIPBottleneckCondCAD, self).__init__(feature_dim, num_classes...
class ContrastCLIPBottleneckBase(AbstractCLIPBottleneck): 'CLIP finetuned with text-image contrastive loss but no bottleneck' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(ContrastCLIPBottleneckBase, self).__init__(feature_dim, num_classes, num_domai...
class ContrastCLIPBottleneckEnt(AbstractCLIPBottleneck): 'CLIP finetuned with text-image contrastive loss and entropy bottleneck (no need to access to domain labels)' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(ContrastCLIPBottleneckEnt, self).__in...
class ContrastCLIPBottleneckCAD(AbstractCLIPBottleneck): 'CLIP finetuned with text-image contrastive loss and CAD bottleneck (require access to domain labels)' def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class): super(ContrastCLIPBottleneckCAD, self).__init__(fe...
def local_launcher(commands): 'Launch commands serially on the local machine.' for cmd in commands: subprocess.call(cmd, shell=True)
def dummy_launcher(commands): "\n Doesn't run anything; instead, prints each command.\n Useful for testing.\n " for cmd in commands: print(f'Dummy launcher: {cmd}')
def multi_gpu_launcher(commands): '\n Launch commands on the local machine, using all GPUs in parallel.\n ' print('WARNING: using experimental multi_gpu_launcher.') n_gpus = torch.cuda.device_count() procs_by_gpu = ([None] * n_gpus) while (len(commands) > 0): for gpu_idx in range(n_g...
def slurm_launcher(commands): '\n Parallel job launcher for computationnal cluster using SLURM workload manager.\n An example of SBATCH options:\n #!/bin/bash\n #SBATCH --job-name=<job_name>\n #SBATCH --output=<job_name>.out\n #SBATCH --error=<job_name>_error.out\n #SBATCH...
def _define_hparam(hparams, hparam_name, default_val, random_val_fn): hparams[hparam_name] = (hparams, hparam_name, default_val, random_val_fn)
def _hparams(algorithm, dataset, random_seed, larger_batch=False): '\n Global registry of hyperparams. Each entry is a (default, random) tuple.\n New algorithms / networks / etc. should add entries here.\n ' SMALL_IMAGES = ['Debug28', 'RotatedMNIST', 'ColoredMNIST'] hparams = {} def _hparam(...
def default_hparams(algorithm, dataset, larger_batch=False): return {a: b for (a, (b, c)) in _hparams(algorithm, dataset, 0, larger_batch=larger_batch).items()}
def random_hparams(algorithm, dataset, seed, larger_batch=False): return {a: c for (a, (b, c)) in _hparams(algorithm, dataset, seed, larger_batch=larger_batch).items()}
class _InfiniteSampler(torch.utils.data.Sampler): 'Wraps another Sampler to yield an infinite stream.' def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: for batch in self.sampler: (yield batch)
class InfiniteDataLoader(): def __init__(self, dataset, weights, batch_size, num_workers): super().__init__() if (weights is not None): sampler = torch.utils.data.WeightedRandomSampler(weights, replacement=True, num_samples=batch_size) else: sampler = torch.utils.d...
class FastDataLoader(): 'DataLoader wrapper with slightly improved speed by not respawning worker\n processes at every epoch.' def __init__(self, dataset, batch_size, num_workers): super().__init__() batch_sampler = torch.utils.data.BatchSampler(torch.utils.data.RandomSampler(dataset, repl...
def make_weights_for_balanced_classes(dataset): counts = Counter() classes = [] for (_, y) in dataset: y = int(y) counts[y] += 1 classes.append(y) n_classes = len(counts) weight_per_class = {} for y in counts: weight_per_class[y] = (1 / (counts[y] * n_classes)) ...
def pdb(): sys.stdout = sys.__stdout__ import pdb print("Launching PDB, enter 'n' to step to parent function.") pdb.set_trace()
def seed_hash(*args): '\n Derive an integer hash from all args, for use as a random seed.\n ' args_str = str(args) return (int(hashlib.md5(args_str.encode('utf-8')).hexdigest(), 16) % (2 ** 31))
def print_separator(): print(('=' * 80))
def print_row(row, colwidth=10, latex=False): if latex: sep = ' & ' end_ = '\\\\' else: sep = ' ' end_ = '' def format_val(x): if np.issubdtype(type(x), np.floating): x = '{:.5f}'.format(x) return str(x).ljust(colwidth)[:colwidth] print(sep...
class _SplitDataset(torch.utils.data.Dataset): 'Used by split_dataset' def __init__(self, underlying_dataset, keys): super(_SplitDataset, self).__init__() self.underlying_dataset = underlying_dataset self.keys = keys def __getitem__(self, key): return self.underlying_data...
def split_dataset(dataset, n, seed=0): '\n Return a pair of datasets corresponding to a random split of the given\n dataset, with n datapoints in the first dataset and the rest in the last,\n using the given random seed\n ' assert (n <= len(dataset)) keys = list(range(len(dataset))) np.ran...
def random_pairs_of_minibatches(minibatches): perm = torch.randperm(len(minibatches)).tolist() pairs = [] for i in range(len(minibatches)): j = ((i + 1) if (i < (len(minibatches) - 1)) else 0) (xi, yi) = (minibatches[perm[i]][0], minibatches[perm[i]][1]) (xj, yj) = (minibatches[per...
def accuracy(network, loader, weights, device): correct = 0 total = 0 weights_offset = 0 network.eval() with torch.no_grad(): for (x, y) in loader: x = x.to(device) y = y.to(device) p = network.predict(x) if (weights is None): ...
def loss(network, loader, device): total_loss = 0 total_num = 0 network.eval() with torch.no_grad(): for (x, y, d) in loader: x = x.to(device) y = y.to(device) d = d.to(device) loss = network.loss(x, y, d)['total_loss'] total_loss += ...
class Tee(): def __init__(self, fname, mode='a'): self.stdout = sys.stdout self.file = open(fname, mode) self.encoding = sys.stdout.encoding def write(self, message): self.stdout.write(message) self.file.write(message) self.flush() def flush(self): ...
class ParamDict(OrderedDict): 'Code adapted from https://github.com/Alok/rl_implementations/tree/master/reptile.\n A dictionary where the values are Tensors, meant to represent weights of\n a model. This subclass lets you perform arithmetic on weights directly.' def __init__(self, *args, **kwargs): ...
def str2bool(v): if isinstance(v, bool): return v if (v.lower() in ('yes', 'true', 't', 'y', '1')): return True elif (v.lower() in ('no', 'false', 'f', 'n', '0')): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
def make_selector_fn(selector): "\n If selector is a function, return selector.\n Otherwise, return a function corresponding to the selector string. Examples\n of valid selector strings and the corresponding functions:\n x lambda obj: obj['x']\n x.y lambda obj: obj['x']['y']\n ...
def hashable(obj): try: hash(obj) return obj except TypeError: return json.dumps({'_': obj}, sort_keys=True)
class Q(object): def __init__(self, list_): super(Q, self).__init__() self._list = list_ def __len__(self): return len(self._list) def __getitem__(self, key): return self._list[key] def __eq__(self, other): if isinstance(other, self.__class__): r...
def load_records(path): records = [] for (i, subdir) in tqdm.tqdm(list(enumerate(os.listdir(path))), ncols=80, leave=False): results_path = os.path.join(path, subdir, 'results.jsonl') try: with open(results_path, 'r') as f: for line in f: records...
def get_grouped_records(records, group_test_envs=True): 'Group records by (trial_seed, dataset, algorithm, test_env). Because\n records can have multiple test envs, a given record may appear in more than\n one group.' result = collections.defaultdict((lambda : [])) if group_test_envs: for r ...
def get_test_records(records): 'Given records with a common test env, get the test records (i.e. the\n records with *only* that single test env and no other test envs)' return records.filter((lambda r: (len(r['args']['test_envs']) == 1)))
class SelectionMethod(): 'Abstract class whose subclasses implement strategies for model\n selection across hparams and timesteps.' def __init__(self): raise TypeError @classmethod def run_acc(self, run_records): '\n Given records from a run, return a {val_acc, test_acc} di...
class OracleSelectionMethod(SelectionMethod): 'Like Selection method which picks argmax(test_out_acc) across all hparams\n and checkpoints, but instead of taking the argmax over all\n checkpoints, we pick the last checkpoint, i.e. no early stopping.' name = 'test-domain validation set (oracle)' @cl...
class IIDAccuracySelectionMethod(SelectionMethod): 'Picks argmax(mean(env_out_acc for env in train_envs))' name = 'training-domain validation set' @classmethod def _step_acc(self, record): 'Given a single record, return a {val_acc, test_acc} dict.' test_env = record['args']['test_envs...