code stringlengths 17 6.64M |
|---|
class EG(Optimizer):
def __init__(self, params, lr=required, normalize_fn=(lambda x: x)):
if ((lr is not required) and (lr < 0.0)):
raise ValueError('Invalid learning rate: {}'.format(lr))
self.normalize_fn = normalize_fn
defaults = dict(lr=lr)
super(EG, self).__init__... |
def load_image(path):
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
|
def list_blobs(storage_client, bucket_name, prefix=None):
'Lists all the blobs in the bucket.'
blobs = storage_client.list_blobs(bucket_name, prefix=prefix)
return blobs
|
def create_file_dirs(target_path):
destination_dir = target_path[0:target_path.rfind('/')]
if (not os.path.exists(destination_dir)):
try:
os.makedirs(destination_dir)
except:
assert os.path.exists(destination_dir)
pass
|
class ImageNetDataset(Dataset):
def __init__(self, split, bucket_name, streaming=True, data_download_dir=None, transform=None):
'\n Args:\n split: train or validation split to return the right dataset\n directory: root directory for imagenet where "train" and "validation" fol... |
def download_from_s3(s3_bucket, task, download_dir):
s3 = boto3.client('s3')
if (task == 'smnist'):
data_files = ['s2_mnist.gz']
s3_folder = 'spherical'
if (task == 'scifar100'):
data_files = ['s2_cifar100.gz']
s3_folder = 'spherical'
elif (task == 'sEMG'):
data... |
def WarmupWrapper(scheduler_type):
class Wrapped(scheduler_type):
def __init__(self, warmup_epochs, *args):
self.warmup_epochs = warmup_epochs
super(Wrapped, self).__init__(*args)
def get_lr(self):
if (self.last_epoch < self.warmup_epochs):
re... |
class LinearLRScheduler(_LRScheduler):
def __init__(self, optimizer, max_epochs, warmup_epochs, last_epoch=(- 1)):
self.optimizer = optimizer
self.warmup_epochs = warmup_epochs
self.max_epochs = max_epochs
self.last_epoch = last_epoch
super(LinearLRScheduler, self).__init_... |
class EfficientNetScheduler(_LRScheduler):
def __init__(self, optimizer, gamma, decay_every, last_epoch=(- 1)):
self.optimizer = optimizer
self.last_epoch = last_epoch
self.gamma = gamma
self.decay_every = decay_every
super(EfficientNetScheduler, self).__init__(optimizer, ... |
class Cell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev, activation_function=nn.ReLU, drop_prob=0):
super(Cell, self).__init__()
print(C_prev_prev, C_prev, C)
if reduction_prev:
self.preprocess0 = FactorizedReduce(C_prev_prev, C)
... |
class Network(nn.Module):
def __init__(self, C, num_classes, layers, genotype, in_channels, drop_path_prob):
super(Network, self).__init__()
self._layers = layers
self.drop_path_prob = 0.0
stem_multiplier = 3
C_curr = (stem_multiplier * C)
self.stem = nn.Sequential... |
class AuxNetworkCIFAR(nn.Module):
def __init__(self, C, num_classes, layers, auxiliary, genotype):
super(AuxNetworkCIFAR, self).__init__()
self._layers = layers
self._auxiliary = auxiliary
self.drop_path_prob = 0.3
stem_multiplier = 3
C_curr = (stem_multiplier * C)... |
class AuxiliaryHeadCIFAR(nn.Module):
def __init__(self, C, num_classes):
'assuming input size 8x8'
super(AuxiliaryHeadCIFAR, self).__init__()
self.features = nn.Sequential(nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=3, padding=0, count_include_pad=False), nn.Conv2d(C, 128, 1, bias=False... |
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
|
class GAEAEvalTrial(PyTorchTrial):
def __init__(self, context: PyTorchTrialContext) -> None:
self.context = context
self.hparams = AttrDict(context.get_hparams())
self.data_config = context.get_data_config()
self.criterion = nn.BCEWithLogitsLoss().cuda()
download_directory... |
class GAEAEvalTrial(PyTorchTrial):
def __init__(self, context: PyTorchTrialContext) -> None:
self.context = context
self.data_config = context.get_data_config()
self.criterion = nn.CrossEntropyLoss()
self.download_directory = self.download_data_from_s3()
self.last_epoch_id... |
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
|
class GAEAEvalTrial(PyTorchTrial):
def __init__(self, context: PyTorchTrialContext) -> None:
self.context = context
self.hparams = AttrDict(context.get_hparams())
self.data_config = context.get_data_config()
self.criterion = nn.CrossEntropyLoss()
self.download_directory = ... |
def imagenet_policies():
'AutoAugment policies found on ImageNet.\n\n This policy also transfers to five FGVC datasets with image size similar to\n ImageNet including Oxford 102 Flowers, Caltech-101, Oxford-IIIT Pets,\n FGVC Aircraft and Stanford Cars.\n '
policies = [[('Posterize', 0.4, 8), ('Rot... |
def get_trans_list():
trans_list = ['Invert', 'Sharpness', 'AutoContrast', 'Posterize', 'ShearX', 'TranslateX', 'TranslateY', 'ShearY', 'Cutout', 'Rotate', 'Equalize', 'Contrast', 'Color', 'Solarize', 'Brightness']
return trans_list
|
def randaug_policies():
trans_list = get_trans_list()
op_list = []
for trans in trans_list:
for magnitude in range(1, 10):
op_list += [(trans, 0.5, magnitude)]
policies = []
for op_1 in op_list:
for op_2 in op_list:
policies += [[op_1, op_2]]
return poli... |
class BilevelDataset(Dataset):
def __init__(self, dataset):
'\n We will split the data into a train split and a validation split\n and return one image from each split as a single observation.\n\n Args:\n dataset: PyTorch Dataset object\n '
inds = np.arange(... |
class BilevelAudioDataset(Dataset):
def __init__(self, dataset):
'\n We will split the data into a train split and a validation split\n and return one image from each split as a single observation.\n\n Args:\n dataset: PyTorch Dataset object\n '
inds = np.ar... |
def download_from_s3(s3_bucket, task, download_dir):
s3 = boto3.client('s3')
if (task == 'smnist'):
data_files = ['s2_mnist.gz']
s3_folder = 'spherical'
if (task == 'scifar100'):
data_files = ['s2_cifar100.gz']
s3_folder = 'spherical'
elif (task == 'sEMG'):
data... |
class GenotypeCallback(PyTorchCallback):
def __init__(self, context):
self.model = context.models[0]
def on_validation_end(self, metrics):
print(self.model.genotype())
|
class GAEASearchTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = utils.AttrDict(trial_context.get_hparams())
self.last_epoch = 0
self.download_directory = self.download_data_from_s3()
dataset_h... |
class GenotypeCallback(PyTorchCallback):
def __init__(self, context):
self.model = context.models[0]
def on_validation_end(self, metrics):
print(self.model.genotype())
|
class GAEASearchTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = utils.AttrDict(trial_context.get_hparams())
self.last_epoch = 0
self.download_directory = self.download_data_from_s3()
dataset_h... |
class EG(Optimizer):
def __init__(self, params, lr=required, normalize_fn=(lambda x: x)):
if ((lr is not required) and (lr < 0.0)):
raise ValueError('Invalid learning rate: {}'.format(lr))
self.normalize_fn = normalize_fn
defaults = dict(lr=lr)
super(EG, self).__init__... |
def download_from_s3(s3_bucket, task, download_dir):
s3 = boto3.client('s3')
if (task == 'ECG'):
data_files = ['challenge2017.pkl']
s3_folder = 'ECG'
elif (task == 'satellite'):
data_files = ['satellite_train.npy', 'satellite_test.npy']
s3_folder = 'satellite'
elif (tas... |
class ECGDataset(Dataset):
def __init__(self, data, label, pid=None):
self.data = data
self.label = label
self.pid = pid
def __getitem__(self, index):
return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long))
def __len_... |
def load_data(task, path, train=False):
if (task == 'ECG'):
return load_ECG_data(path, train)
elif (task == 'satellite'):
return load_satellite_data(path, train)
elif (task == 'deepsea'):
return load_deepsea_data(path, train)
else:
raise NotImplementedError
|
def load_ECG_data(path, train):
return (read_data_physionet_4_with_val(path) if train else read_data_physionet_4(path))
|
def load_satellite_data(path, train):
train_file = os.path.join(path, 'satellite_train.npy')
test_file = os.path.join(path, 'satellite_test.npy')
(all_train_data, all_train_labels) = (np.load(train_file, allow_pickle=True)[()]['data'], np.load(train_file, allow_pickle=True)[()]['label'])
(test_data, t... |
def read_data_physionet_4(path, window_size=1000, stride=500):
with open(os.path.join(path, 'challenge2017.pkl'), 'rb') as fin:
res = pickle.load(fin)
all_data = res['data']
for i in range(len(all_data)):
tmp_data = all_data[i]
tmp_std = np.std(tmp_data)
tmp_mean = np.mean(... |
def read_data_physionet_4_with_val(path, window_size=1000, stride=500):
with open(os.path.join(path, 'challenge2017.pkl'), 'rb') as fin:
res = pickle.load(fin)
all_data = res['data']
for i in range(len(all_data)):
tmp_data = all_data[i]
tmp_std = np.std(tmp_data)
tmp_mean =... |
def slide_and_cut(X, Y, window_size, stride, output_pid=False, datatype=4):
out_X = []
out_Y = []
out_pid = []
n_sample = X.shape[0]
mode = 0
for i in range(n_sample):
tmp_ts = X[i]
tmp_Y = Y[i]
if (tmp_Y == 0):
i_stride = stride
elif (tmp_Y == 1):
... |
def load_deepsea_data(path, train):
data = np.load(os.path.join(path, 'deepsea_filtered.npz'))
(train_data, train_labels) = (torch.from_numpy(data['x_train']).type(torch.FloatTensor), torch.from_numpy(data['y_train']).type(torch.LongTensor))
train_data = train_data.permute(0, 2, 1)
trainset = data_uti... |
def WarmupWrapper(scheduler_type):
class Wrapped(scheduler_type):
def __init__(self, warmup_epochs, *args):
self.warmup_epochs = warmup_epochs
super(Wrapped, self).__init__(*args)
def get_lr(self):
if (self.last_epoch < self.warmup_epochs):
re... |
class LinearLRScheduler(_LRScheduler):
def __init__(self, optimizer, max_epochs, warmup_epochs, last_epoch=(- 1)):
self.optimizer = optimizer
self.warmup_epochs = warmup_epochs
self.max_epochs = max_epochs
self.last_epoch = last_epoch
super(LinearLRScheduler, self).__init_... |
class EfficientNetScheduler(_LRScheduler):
def __init__(self, optimizer, gamma, decay_every, last_epoch=(- 1)):
self.optimizer = optimizer
self.last_epoch = last_epoch
self.gamma = gamma
self.decay_every = decay_every
super(EfficientNetScheduler, self).__init__(optimizer, ... |
class Cell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev, activation_function=nn.ReLU, drop_prob=0):
super(Cell, self).__init__()
print(C_prev_prev, C_prev, C)
if reduction_prev:
self.preprocess0 = FactorizedReduce(C_prev_prev, C)
... |
class Network(nn.Module):
def __init__(self, C, num_classes, layers, genotype, in_channels, drop_path_prob):
super(Network, self).__init__()
self._layers = layers
self.drop_path_prob = 0.0
stem_multiplier = 3
C_curr = (stem_multiplier * C)
self.stem = nn.Sequential... |
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
|
class GAEAEvalTrial(PyTorchTrial):
def __init__(self, context: PyTorchTrialContext) -> None:
self.context = context
self.hparams = AttrDict(context.get_hparams())
self.data_config = context.get_data_config()
if (self.context.get_hparam('task') == 'deepsea'):
self.crite... |
class BilevelDataset(Dataset):
def __init__(self, dataset):
'\n We will split the data into a train split and a validation split\n and return one image from each split as a single observation.\n\n Args:\n dataset: PyTorch Dataset object\n '
inds = np.arange(... |
def download_from_s3(s3_bucket, task, download_dir):
s3 = boto3.client('s3')
if (task == 'ECG'):
data_files = ['challenge2017.pkl']
s3_folder = 'ECG'
elif (task == 'satellite'):
data_files = ['satellite_train.npy', 'satellite_test.npy']
s3_folder = 'satellite'
elif (tas... |
class ECGDataset(Dataset):
def __init__(self, data, label, pid=None):
self.data = data
self.label = label
self.pid = pid
def __getitem__(self, index):
return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long))
def __len_... |
def load_data(task, path, train=True):
if (task == 'ECG'):
return load_ECG_data(path, True)
elif (task == 'satellite'):
return load_satellite_data(path, True)
elif (task == 'deepsea'):
return load_deepsea_data(path, True)
else:
raise NotImplementedError
|
def load_ECG_data(path, train):
return (read_data_physionet_4_with_val(path) if train else read_data_physionet_4(path))
|
def load_satellite_data(path, train):
train_file = os.path.join(path, 'satellite_train.npy')
test_file = os.path.join(path, 'satellite_test.npy')
(all_train_data, all_train_labels) = (np.load(train_file, allow_pickle=True)[()]['data'], np.load(train_file, allow_pickle=True)[()]['label'])
(test_data, t... |
def read_data_physionet_4(path, window_size=1000, stride=500):
with open(os.path.join(path, 'challenge2017.pkl'), 'rb') as fin:
res = pickle.load(fin)
all_data = res['data']
for i in range(len(all_data)):
tmp_data = all_data[i]
tmp_std = np.std(tmp_data)
tmp_mean = np.mean(... |
def read_data_physionet_4_with_val(path, window_size=1000, stride=500):
with open(os.path.join(path, 'challenge2017.pkl'), 'rb') as fin:
res = pickle.load(fin)
all_data = res['data']
for i in range(len(all_data)):
tmp_data = all_data[i]
tmp_std = np.std(tmp_data)
tmp_mean =... |
def slide_and_cut(X, Y, window_size, stride, output_pid=False, datatype=4):
out_X = []
out_Y = []
out_pid = []
n_sample = X.shape[0]
mode = 0
for i in range(n_sample):
tmp_ts = X[i]
tmp_Y = Y[i]
if (tmp_Y == 0):
i_stride = stride
elif (tmp_Y == 1):
... |
def load_deepsea_data(path, train):
data = np.load(os.path.join(path, 'deepsea_filtered.npz'))
(train_data, train_labels) = (torch.from_numpy(data['x_train']).type(torch.FloatTensor), torch.from_numpy(data['y_train']).type(torch.LongTensor))
train_data = train_data.permute(0, 2, 1)
trainset = data_uti... |
class GenotypeCallback(PyTorchCallback):
def __init__(self, context):
self.model = context.models[0]
def on_validation_end(self, metrics):
print(self.model.genotype())
|
class GAEASearchTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = AttrDict(trial_context.get_hparams())
self.last_epoch = 0
self.download_directory = self.download_data_from_s3()
dataset_hypers ... |
class EG(Optimizer):
def __init__(self, params, lr=required, normalize_fn=(lambda x: x)):
if ((lr is not required) and (lr < 0.0)):
raise ValueError('Invalid learning rate: {}'.format(lr))
self.normalize_fn = normalize_fn
defaults = dict(lr=lr)
super(EG, self).__init__... |
class BilevelDataset(Dataset):
def __init__(self, dataset):
'\n We will split the data into a train split and a validation split\n and return one image from each split as a single observation.\n Args:\n dataset: PyTorch Dataset object\n '
inds = np.arange(le... |
class BilevelCosmicDataset(Dataset):
def __init__(self, dataset):
'\n We will split the data into a train split and a validation split\n and return one image from each split as a single observation.\n Args:\n dataset: PyTorch Dataset object\n '
inds = np.ara... |
class ImageNet12(object):
def __init__(self, trainFolder, testFolder, num_workers=8, pin_memory=True, size_images=224, scaled_size=256, type_of_data_augmentation='rand_scale', data_config=None):
self.data_config = data_config
self.trainFolder = trainFolder
self.testFolder = testFolder
... |
class Datum(object):
def __init__(self, shape=None, image=None, label=None):
self.shape = shape
self.image = image
self.label = label
def SerializeToString(self, img=None):
image_data = self.image.astype(np.uint8).tobytes()
label_data = np.uint16(self.label).tobytes()... |
def create_dataset(output_path, image_folder, image_list, image_size):
image_name_list = [i.strip() for i in open(image_list)]
n_samples = len(image_name_list)
env = lmdb.open(output_path, map_size=1099511627776, meminit=False, map_async=True)
txn = env.begin(write=True)
classes = [d for d in os.l... |
class Datum(object):
def __init__(self, shape=None, image=None, label=None):
self.shape = shape
self.image = image
self.label = label
def SerializeToString(self):
image_data = self.image.astype(np.uint8).tobytes()
label_data = np.uint16(self.label).tobytes()
r... |
class DatasetFolder(data.Dataset):
'\n Args:\n root (string): Root directory path.\n transform (callable, optional): A function/transform that takes in\n a sample and returns a transformed version.\n E.g, ``transforms.RandomCrop`` for images.\n target_transform (calla... |
class ImageFolder(DatasetFolder):
def __init__(self, root, list_path, transform=None, target_transform=None, patch_dataset=False):
super(ImageFolder, self).__init__(root, list_path, transform=transform, target_transform=target_transform, patch_dataset=patch_dataset)
self.imgs = self.samples
|
def get_list(data_path, output_path):
for split in os.listdir(data_path):
split_path = os.path.join(data_path, split)
if (not os.path.isdir(split_path)):
continue
f = open(os.path.join(output_path, (split + '_datalist')), 'a+')
for sub in os.listdir(split_path):
... |
def get_list(data_path, output_path):
for split in os.listdir(data_path):
if (split == 'train'):
split_path = os.path.join(data_path, split)
if (not os.path.isdir(split_path)):
continue
f_train = open(os.path.join(output_path, (split + '_datalist')), 'w'... |
class Lighting(object):
'Lighting noise(AlexNet - style PCA - based noise)'
def __init__(self, alphastd, eigval, eigvec):
self.alphastd = alphastd
self.eigval = eigval
self.eigvec = eigvec
def __call__(self, img):
if (self.alphastd == 0):
return img
al... |
class RandomScale(object):
'ResNet style data augmentation'
def __init__(self, minSize, maxSize):
self.minSize = minSize
self.maxSize = maxSize
def __call__(self, img):
targetSz = int(round(random.uniform(self.minSize, self.maxSize)))
return F.resize(img, targetSz)
|
def generate_arch(task, net_type):
update_cfg_from_cfg(search_cfg, cfg)
if (task == 'pde'):
merge_cfg_from_file('configs/pde_search_cfg_resnet.yaml', cfg)
input_shape = (3, 85, 85)
elif (task == 'protein'):
merge_cfg_from_file('configs/protein_search_cfg_resnet.yaml', cfg)
... |
class MixedOp(nn.Module):
def __init__(self, dropped_mixed_ops, softmax_temp=1.0):
super(MixedOp, self).__init__()
self.softmax_temp = softmax_temp
self._ops = nn.ModuleList()
for op in dropped_mixed_ops:
self._ops.append(op)
def forward(self, x, alphas, branch_in... |
class HeadLayer(nn.Module):
def __init__(self, dropped_mixed_ops, softmax_temp=1.0):
super(HeadLayer, self).__init__()
self.head_branches = nn.ModuleList()
for mixed_ops in dropped_mixed_ops:
self.head_branches.append(MixedOp(mixed_ops, softmax_temp))
def forward(self, in... |
class StackLayers(nn.Module):
def __init__(self, num_block_layers, dropped_mixed_ops, softmax_temp=1.0):
super(StackLayers, self).__init__()
if (num_block_layers != 0):
self.stack_layers = nn.ModuleList()
for i in range(num_block_layers):
self.stack_layers.... |
class Block(nn.Module):
def __init__(self, num_block_layers, dropped_mixed_ops, softmax_temp=1.0):
super(Block, self).__init__()
self.head_layer = HeadLayer(dropped_mixed_ops[0], softmax_temp)
self.stack_layers = StackLayers(num_block_layers, dropped_mixed_ops[1], softmax_temp)
def f... |
class Dropped_Network(nn.Module):
def __init__(self, super_model, alpha_head_index=None, alpha_stack_index=None, softmax_temp=1.0):
super(Dropped_Network, self).__init__()
self.softmax_temp = softmax_temp
self.input_block = super_model.input_block
if hasattr(super_model, 'head_blo... |
class MixedOp(nn.Module):
def __init__(self, C_in, C_out, stride, primitives):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
for primitive in primitives:
op = OPS[primitive](C_in, C_out, stride, affine=False, track_running_stats=True)
self._ops.append... |
class HeadLayer(nn.Module):
def __init__(self, in_chs, ch, strides, config):
super(HeadLayer, self).__init__()
self.head_branches = nn.ModuleList()
for (in_ch, stride) in zip(in_chs, strides):
self.head_branches.append(MixedOp(in_ch, ch, stride, config.search_params.PRIMITIVES... |
class StackLayers(nn.Module):
def __init__(self, ch, num_block_layers, config, primitives):
super(StackLayers, self).__init__()
if (num_block_layers != 0):
self.stack_layers = nn.ModuleList()
for i in range(num_block_layers):
self.stack_layers.append(MixedO... |
class Block(nn.Module):
def __init__(self, in_chs, block_ch, strides, num_block_layers, config):
super(Block, self).__init__()
assert (len(in_chs) == len(strides))
self.head_layer = HeadLayer(in_chs, block_ch, strides, config)
self.stack_layers = StackLayers(block_ch, num_block_la... |
class Conv1_1_Branch(nn.Module):
def __init__(self, in_ch, block_ch):
super(Conv1_1_Branch, self).__init__()
self.conv1_1 = nn.Sequential(nn.Conv2d(in_channels=in_ch, out_channels=block_ch, kernel_size=1, stride=1, padding=0, bias=False), nn.BatchNorm2d(block_ch, affine=False, track_running_stats... |
class Conv1_1_Block(nn.Module):
def __init__(self, in_chs, block_ch):
super(Conv1_1_Block, self).__init__()
self.conv1_1_branches = nn.ModuleList()
for in_ch in in_chs:
self.conv1_1_branches.append(Conv1_1_Branch(in_ch, block_ch))
def forward(self, inputs, betas, block_su... |
class Network(nn.Module):
def __init__(self, init_ch, dataset, config):
super(Network, self).__init__()
self.config = config
self._C_input = init_ch
self._head_dim = self.config.optim.head_dim
self._dataset = dataset
self.initialize()
def initialize(self):
... |
class Network(BaseSearchSpace):
def __init__(self, init_ch, dataset, config):
super(Network, self).__init__(init_ch, dataset, config)
self.input_block = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=self._C_input, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(self._C_input... |
class Network(BaseSearchSpace):
def __init__(self, init_ch, dataset, config, groups=1, base_width=64, dilation=1, norm_layer=None):
super(Network, self).__init__(init_ch, dataset, config)
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
if ((groups != 1) or (base_width != ... |
class BaseArchGenerate(object):
def __init__(self, super_network, config):
self.config = config
self.num_blocks = len(super_network.block_chs)
self.super_chs = super_network.block_chs
self.input_configs = super_network.input_configs
def update_arch_params(self, betas, head_al... |
class ArchGenerate(BaseArchGenerate):
def __init__(self, super_network, config):
super(ArchGenerate, self).__init__(super_network, config)
def derive_archs(self, betas, head_alphas, stack_alphas, if_display=True):
self.update_arch_params(betas, head_alphas, stack_alphas)
derived_arch... |
class ArchGenerate(BaseArchGenerate):
def __init__(self, super_network, config):
super(ArchGenerate, self).__init__(super_network, config)
def derive_archs(self, betas, head_alphas, stack_alphas, if_display=True):
self.update_arch_params(betas, head_alphas, stack_alphas)
derived_arch... |
class Optimizer(object):
def __init__(self, model, criterion, config):
self.config = config
self.weight_sample_num = self.config.search_params.weight_sample_num
self.criterion = criterion
self.Dropped_Network = (lambda model: Dropped_Network(model, softmax_temp=config.search_param... |
class Trainer(object):
def __init__(self, train_data, val_data, optimizer=None, criterion=None, scheduler=None, config=None, report_freq=None):
self.train_data = train_data
self.val_data = val_data
self.optimizer = optimizer
self.criterion = criterion
self.scheduler = sche... |
class SearchTrainer(object):
def __init__(self, train_data, val_data, search_optim, criterion, scheduler, config, args):
self.train_data = train_data
self.val_data = val_data
self.search_optim = search_optim
self.criterion = criterion
self.scheduler = scheduler
sel... |
class AttrDict(dict):
IMMUTABLE = '__immutable__'
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__[AttrDict.IMMUTABLE] = False
def __getattr__(self, name):
if (name in self.__dict__):
return self.__dict__[name]
... |
def load_cfg(cfg_to_load):
'Wrapper around yaml.load used for maintaining backward compatibility'
if isinstance(cfg_to_load, IOBase):
cfg_to_load = ''.join(cfg_to_load.readlines())
return yaml.load(cfg_to_load)
|
def load_cfg_to_dict(cfg_filename):
with open(cfg_filename, 'r') as f:
yaml_cfg = load_cfg(f)
return yaml_cfg
|
def merge_cfg_from_file(cfg_filename, global_config):
'Load a yaml config file and merge it into the global config.'
with open(cfg_filename, 'r') as f:
yaml_cfg = AttrDict(load_cfg(f))
_merge_a_into_b(yaml_cfg, global_config)
|
def merge_cfg_from_cfg(cfg_other, global_config):
'Merge `cfg_other` into the global config.'
_merge_a_into_b(cfg_other, global_config)
|
def update_cfg_from_file(cfg_filename, global_config):
with open(cfg_filename, 'r') as f:
yaml_cfg = AttrDict(load_cfg(f))
update_cfg_from_cfg(yaml_cfg, global_config)
|
def update_cfg_from_cfg(cfg_other, global_config, stack=None):
assert isinstance(cfg_other, AttrDict), '`a` (cur type {}) must be an instance of {}'.format(type(a), AttrDict)
assert isinstance(global_config, AttrDict), '`b` (cur type {}) must be an instance of {}'.format(type(b), AttrDict)
for (k, v_) in ... |
def merge_cfg_from_list(cfg_list, global_config):
"Merge config keys, values in a list (e.g., from command line) into the\n global config. For example, `cfg_list = ['TEST.NMS', 0.5]`.\n "
assert ((len(cfg_list) % 2) == 0)
for (full_key, v) in zip(cfg_list[0::2], cfg_list[1::2]):
if _key_is_d... |
def _merge_a_into_b(a, b, stack=None):
'Merge config dictionary a into config dictionary b, clobbering the\n options in b whenever they are also specified in a.\n '
assert isinstance(a, AttrDict), '`a` (cur type {}) must be an instance of {}'.format(type(a), AttrDict)
assert isinstance(b, AttrDict),... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.