code stringlengths 17 6.64M |
|---|
class LeaveOneOutSelectionMethod(SelectionMethod):
'Picks (hparams, step) by leave-one-out cross validation.'
name = 'leave-one-domain-out cross-validation'
@classmethod
def _step_acc(self, records):
'Return the {val_acc, test_acc} for a group of records corresponding\n to a single ste... |
def format_mean(data, latex):
'Given a list of datapoints, return a string describing their mean and\n standard error'
if (len(data) == 0):
return (None, None, 'X')
mean = (100 * np.mean(list(data)))
err = (100 * np.std((list(data) / np.sqrt(len(data)))))
if latex:
return (mean,... |
def print_table(table, header_text, row_labels, col_labels, colwidth=10, latex=True):
'Pretty-print a 2D array of data, optionally with row/col labels'
print('')
if latex:
num_cols = len(table[0])
print('\\begin{center}')
print('\\adjustbox{max width=\\textwidth}{%')
print(... |
def print_results_tables(records, task, selection_method, latex):
'Given all records, print a results table for each dataset.'
grouped_records = reporting.get_grouped_records(records, group_test_envs=(task != 'unsupervised_domain_generalization')).map((lambda group: {**group, 'sweep_acc': selection_method.swe... |
def stage_path(data_dir, name):
full_path = os.path.join(data_dir, name)
if (not os.path.exists(full_path)):
os.makedirs(full_path)
return full_path
|
def download_and_extract(url, dst, remove=True):
gdown.download(url, dst, quiet=False)
if dst.endswith('.tar.gz'):
tar = tarfile.open(dst, 'r:gz')
tar.extractall(os.path.dirname(dst))
tar.close()
if dst.endswith('.tar'):
tar = tarfile.open(dst, 'r:')
tar.extractall(... |
def download_vlcs(data_dir):
full_path = stage_path(data_dir, 'VLCS')
download_and_extract('https://drive.google.com/uc?id=1skwblH1_okBwxWxmRsp9_qi15hyPpxg8', os.path.join(data_dir, 'VLCS.tar.gz'))
|
def download_mnist(data_dir):
full_path = stage_path(data_dir, 'MNIST')
MNIST(full_path, download=True)
|
def download_pacs(data_dir):
full_path = stage_path(data_dir, 'PACS')
download_and_extract('https://drive.google.com/uc?id=0B6x7gtvErXgfbF9CSk53UkRxVzg', os.path.join(data_dir, 'PACS.zip'))
os.rename(os.path.join(data_dir, 'kfold'), full_path)
|
def download_office_home(data_dir):
full_path = stage_path(data_dir, 'office_home')
download_and_extract('https://drive.google.com/uc?id=0B81rNlvomiwed0V1YUxQdC1uOTg', os.path.join(data_dir, 'office_home.zip'))
os.rename(os.path.join(data_dir, 'OfficeHomeDataset_10072016'), full_path)
|
def download_domain_net(data_dir):
full_path = stage_path(data_dir, 'domain_net')
urls = ['http://csr.bu.edu/ftp/visda/2019/multi-source/groundtruth/clipart.zip', 'http://csr.bu.edu/ftp/visda/2019/multi-source/infograph.zip', 'http://csr.bu.edu/ftp/visda/2019/multi-source/groundtruth/painting.zip', 'http://cs... |
def download_terra_incognita(data_dir):
full_path = stage_path(data_dir, 'terra_incognita')
download_and_extract('https://lilablobssc.blob.core.windows.net/caltechcameratraps/eccv_18_all_images_sm.tar.gz', os.path.join(full_path, 'terra_incognita_images.tar.gz'))
download_and_extract('https://lilablobssc.... |
def download_sviro(data_dir):
full_path = stage_path(data_dir, 'sviro')
download_and_extract('https://sviro.kl.dfki.de/?wpdmdl=1731', os.path.join(data_dir, 'sviro_grayscale_rectangle_classification.zip'))
os.rename(os.path.join(data_dir, 'SVIRO_DOMAINBED'), full_path)
|
def todo_rename(records, selection_method, latex):
grouped_records = reporting.get_grouped_records(records).map((lambda group: {**group, 'sweep_acc': selection_method.sweep_acc(group['records'])})).filter((lambda g: (g['sweep_acc'] is not None)))
alg_names = Q(records).select('args.algorithm').unique()
al... |
class Job():
NOT_LAUNCHED = 'Not launched'
INCOMPLETE = 'Incomplete'
DONE = 'Done'
def __init__(self, train_args, sweep_output_dir):
args_str = json.dumps(train_args, sort_keys=True)
args_hash = hashlib.md5(args_str.encode('utf-8')).hexdigest()
self.output_dir = os.path.join(s... |
def all_test_env_combinations(n):
'\n For a dataset with n >= 3 envs, return all combinations of 1 and 2 test\n envs.\n '
assert (n >= 3)
for i in range(n):
(yield [i])
for j in range((i + 1), n):
(yield [i, j])
|
def make_args_list(n_trials, dataset_names, algorithms, n_hparams_from, n_hparams, steps, data_dir, task, holdout_fraction, single_test_envs, hparams):
args_list = []
for trial_seed in range(n_trials):
for dataset in dataset_names:
for algorithm in algorithms:
if single_tes... |
def ask_for_confirmation():
response = input('Are you sure? (y/n) ')
if (not (response.lower().strip()[:1] == 'y')):
print('Nevermind!')
exit(0)
|
class Job():
NOT_LAUNCHED = 'Not launched'
INCOMPLETE = 'Incomplete'
DONE = 'Done'
def __init__(self, train_args, sweep_output_dir, train_script='domainbed.scripts.train'):
args_str = json.dumps(train_args, sort_keys=True)
args_hash = hashlib.md5(args_str.encode('utf-8')).hexdigest()
... |
def all_test_env_combinations(n):
'\n For a dataset with n >= 3 envs, return all combinations of 1 and 2 test\n envs.\n '
assert (n >= 3)
for i in range(n):
(yield [i])
for j in range((i + 1), n):
(yield [i, j])
|
def make_args_list(n_trials, dataset_names, algorithms, n_hparams_from, n_hparams, steps, data_dir, task, holdout_fraction, single_test_envs, wandb_proj, wandb_group, only_eval, always_rerun, warmstart_model_ckpt, hparams):
args_list = []
for trial_seed in range(n_trials):
for dataset in dataset_names... |
def ask_for_confirmation():
response = input('Are you sure? (y/n) ')
if (not (response.lower().strip()[:1] == 'y')):
print('Nevermind!')
exit(0)
|
class CLIPConLoss(nn.Module):
'CLIP text-image contrastive loss'
def __init__(self, feature_dim, temperature=0.07, learnable_temperature=True, is_project=False, is_symmetric=True):
super(CLIPConLoss, self).__init__()
self.temperature = temperature
if learnable_temperature:
... |
def finite_mean(x):
num_finite = torch.isfinite(x).float().sum()
mean = torch.where(torch.isfinite(x), x, torch.tensor(0.0).to(x)).sum()
if (num_finite != 0):
mean = (mean / num_finite)
else:
return torch.tensor(0.0).to(x)
return mean
|
class PLLogisticRegression(pl.LightningModule):
'\n Logistic regression model\n '
def __init__(self, input_dim: int, num_classes: int, bias: bool=True, learning_rate: float=0.0001, optimizer: Optimizer=Adam, l1_strength: float=0.0, l2_strength: float=0.0, is_nonlinear: bool=False, **kwargs):
"\... |
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 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 is_image_file(filename):
return filename.lower().endswith(IMG_EXTENSIONS)
|
def make_dataset(dir, class_to_idx):
images = []
dir = os.path.expanduser(dir)
for target in sorted(class_to_idx.keys()):
d = os.path.join(dir, target)
if (not os.path.isdir(d)):
continue
for (root, _, fnames) in sorted(os.walk(d)):
for fname in sorted(fname... |
def pil_loader(path):
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
|
class CustomImageFolder(VisionDataset):
def __init__(self, root, transform, perturbation_fn=None, idx_subsample_list=None):
super().__init__(root, transform=transform, target_transform=None)
(classes, class_to_idx) = self._find_classes(self.root)
samples = make_dataset(self.root, class_to... |
class DistributedSampler(Sampler):
'Sampler that restricts data loading to a subset of the dataset.\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n and loa... |
class EvalSetting():
def __init__(self, name, dataset, size, perturbation_fn_cpu=None, perturbation_fn_gpu=None, metrics_fn=None, adversarial_attack=None, class_sublist=None, idx_subsample_list=None, parent_eval_setting=None, transform=None):
super().__init__()
self.name = name
self.datas... |
def accuracy_topk(logits, targets, topk=(1, 5)):
maxk = max(topk)
batch_size = targets.size(0)
(_, pred) = logits.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(targets.view(1, (- 1)).expand_as(pred))
res = {}
for k in topk:
correct_k = correct[:k].contiguous().view((-... |
class StandardDataset():
def __init__(self, name=None, path=None):
super().__init__()
assert (bool(name) ^ bool(path)), 'Please specify one (and exactly one) of name or path'
if (name is not None):
assert (name in DATASET_NAMES), f'Dataset {name} is not recognized as an existi... |
def corrupt_greyscale(image):
return greyscale(image)
|
def accuracy_topk_subselected(logits, targets):
targets = torch.tensor([class_sublist.index(x) for x in targets])
return accuracy_topk(logits, targets)
|
def corr_brightness_sev_1(image):
return corruption_dict['brightness'](image, 0)
|
def corr_brightness_sev_2(image):
return corruption_dict['brightness'](image, 1)
|
def corr_brightness_sev_3(image):
return corruption_dict['brightness'](image, 2)
|
def corr_brightness_sev_4(image):
return corruption_dict['brightness'](image, 3)
|
def corr_brightness_sev_5(image):
return corruption_dict['brightness'](image, 4)
|
def corr_contrast_sev_1(image):
return corruption_dict['contrast'](image, 0)
|
def corr_contrast_sev_2(image):
return corruption_dict['contrast'](image, 1)
|
def corr_contrast_sev_3(image):
return corruption_dict['contrast'](image, 2)
|
def corr_contrast_sev_4(image):
return corruption_dict['contrast'](image, 3)
|
def corr_contrast_sev_5(image):
return corruption_dict['contrast'](image, 4)
|
def corr_fog_sev_1(image):
return corruption_dict['fog'](image, 0)
|
def corr_fog_sev_2(image):
return corruption_dict['fog'](image, 1)
|
def corr_fog_sev_3(image):
return corruption_dict['fog'](image, 2)
|
def corr_fog_sev_4(image):
return corruption_dict['fog'](image, 3)
|
def corr_fog_sev_5(image):
return corruption_dict['fog'](image, 4)
|
def corr_frost_sev_1(image):
return corruption_dict['frost'](image, 0)
|
def corr_frost_sev_2(image):
return corruption_dict['frost'](image, 1)
|
def corr_frost_sev_3(image):
return corruption_dict['frost'](image, 2)
|
def corr_frost_sev_4(image):
return corruption_dict['frost'](image, 3)
|
def corr_frost_sev_5(image):
return corruption_dict['frost'](image, 4)
|
def corr_gaussian_blur_sev_1(image):
return corruption_dict['gaussian_blur'](image, 0)
|
def corr_gaussian_blur_sev_2(image):
return corruption_dict['gaussian_blur'](image, 1)
|
def corr_gaussian_blur_sev_3(image):
return corruption_dict['gaussian_blur'](image, 2)
|
def corr_gaussian_blur_sev_4(image):
return corruption_dict['gaussian_blur'](image, 3)
|
def corr_gaussian_blur_sev_5(image):
return corruption_dict['gaussian_blur'](image, 4)
|
def corr_gaussian_noise_sev_1(image):
return corruption_dict['gaussian_noise'](image, 0)
|
def corr_gaussian_noise_sev_2(image):
return corruption_dict['gaussian_noise'](image, 1)
|
def corr_gaussian_noise_sev_3(image):
return corruption_dict['gaussian_noise'](image, 2)
|
def corr_gaussian_noise_sev_4(image):
return corruption_dict['gaussian_noise'](image, 3)
|
def corr_gaussian_noise_sev_5(image):
return corruption_dict['gaussian_noise'](image, 4)
|
def corr_impulse_noise_sev_1(image):
return corruption_dict['impulse_noise'](image, 0)
|
def corr_impulse_noise_sev_2(image):
return corruption_dict['impulse_noise'](image, 1)
|
def corr_impulse_noise_sev_3(image):
return corruption_dict['impulse_noise'](image, 2)
|
def corr_impulse_noise_sev_4(image):
return corruption_dict['impulse_noise'](image, 3)
|
def corr_impulse_noise_sev_5(image):
return corruption_dict['impulse_noise'](image, 4)
|
def corr_jpeg_compression_sev_1(image):
return corruption_dict['jpeg_compression'](image, 0)
|
def corr_jpeg_compression_sev_2(image):
return corruption_dict['jpeg_compression'](image, 1)
|
def corr_jpeg_compression_sev_3(image):
return corruption_dict['jpeg_compression'](image, 2)
|
def corr_jpeg_compression_sev_4(image):
return corruption_dict['jpeg_compression'](image, 3)
|
def corr_jpeg_compression_sev_5(image):
return corruption_dict['jpeg_compression'](image, 4)
|
def corr_pixelate_sev_1(image):
return corruption_dict['pixelate'](image, 0)
|
def corr_pixelate_sev_2(image):
return corruption_dict['pixelate'](image, 1)
|
def corr_pixelate_sev_3(image):
return corruption_dict['pixelate'](image, 2)
|
def corr_pixelate_sev_4(image):
return corruption_dict['pixelate'](image, 3)
|
def corr_pixelate_sev_5(image):
return corruption_dict['pixelate'](image, 4)
|
def corr_saturate_sev_1(image):
return corruption_dict['saturate'](image, 0)
|
def corr_saturate_sev_2(image):
return corruption_dict['saturate'](image, 1)
|
def corr_saturate_sev_3(image):
return corruption_dict['saturate'](image, 2)
|
def corr_saturate_sev_4(image):
return corruption_dict['saturate'](image, 3)
|
def corr_saturate_sev_5(image):
return corruption_dict['saturate'](image, 4)
|
def corr_shot_noise_sev_1(image):
return corruption_dict['shot_noise'](image, 0)
|
def corr_shot_noise_sev_2(image):
return corruption_dict['shot_noise'](image, 1)
|
def corr_shot_noise_sev_3(image):
return corruption_dict['shot_noise'](image, 2)
|
def corr_shot_noise_sev_4(image):
return corruption_dict['shot_noise'](image, 3)
|
def corr_shot_noise_sev_5(image):
return corruption_dict['shot_noise'](image, 4)
|
def corr_spatter_sev_1(image):
return corruption_dict['spatter'](image, 0)
|
def corr_spatter_sev_2(image):
return corruption_dict['spatter'](image, 1)
|
def corr_spatter_sev_3(image):
return corruption_dict['spatter'](image, 2)
|
def corr_spatter_sev_4(image):
return corruption_dict['spatter'](image, 3)
|
def corr_spatter_sev_5(image):
return corruption_dict['spatter'](image, 4)
|
def corr_speckle_noise_sev_1(image):
return corruption_dict['speckle_noise'](image, 0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.