code
stringlengths
17
6.64M
class Coco(BaseDataset): def __init__(self, config, device): super().__init__(config, device) root_dir = Path(os.path.expanduser(config['data_path'])) self._paths = {} train_dir = Path(root_dir, 'train2014') self._paths['train'] = [str(p) for p in list(train_dir.iterdir())...
class _Dataset(Dataset): def __init__(self, paths, config, device): self._paths = paths self._config = config self._angle_lim = (np.pi / 4) self._device = device def __getitem__(self, item): img0 = cv2.imread(self._paths[item]) img0 = cv2.cvtColor(img0, cv2.CO...
class Flashes(BaseDataset): def __init__(self, config, device): super().__init__(config, device) root_dir = Path(os.path.expanduser(config['data_path'])) self._paths = {'train': [], 'val': [], 'test': []} train_dir = Path(root_dir, 'train') train_sequence_paths = [path for...
class _Dataset(Dataset): def __init__(self, paths, config, device): self._paths = paths self._config = config self._angle_lim = (np.pi / 4) self._device = device def __getitem__(self, item): img0 = cv2.imread(self._paths[item][0]) img0 = cv2.cvtColor(img0, cv2...
class MixedDataset(BaseDataset): def __init__(self, config, device): super().__init__(config, device) base_config = {'sizes': {'train': 30000, 'val': 500, 'test': 1000}} base_config.update(self._config) self._config = base_config.copy() self._datasets = [] for (i, ...
class _Dataset(Dataset): def __init__(self, datasets, weights, split, size): self._datasets = [d.get_dataset(split) for d in datasets] self._weights = weights self._size = size def __getitem__(self, item): dataset = self._datasets[np.random.choice(range(len(self._datasets)), ...
class Vidit(BaseDataset): def __init__(self, config, device): super().__init__(config, device) self._root_dir = Path(os.path.expanduser(config['data_path'])) self._paths = {} np.random.seed(config['seed']) files = [str(path) for path in self._root_dir.iterdir()] fi...
class _Dataset(Dataset): def __init__(self, paths, config, device): self._paths = paths self._config = config self._angle_lim = (np.pi / 4) self._device = device def __getitem__(self, item): scene_id = (item // 50) paths = np.random.choice(self._paths[scene_id...
def _train(config, exper_dir, args): with open(os.path.join(exper_dir, 'config.yaml'), 'w') as f: yaml.dump(config, f, default_flow_style=False) checkpoint_dir = os.path.join(exper_dir, 'checkpoints') if (not os.path.exists(checkpoint_dir)): os.makedirs(checkpoint_dir) runs_dir = os.pa...
def _test(config, exper_dir, args): checkpoint_path = args.checkpoint if (not os.path.exists(checkpoint_path)): sys.exit((checkpoint_path + ' not found.')) device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) dataset = get_dataset(config['data']['name'])(config['data'], de...
def _export(config, exper_dir, args): checkpoint_path = args.checkpoint if (not os.path.exists(checkpoint_path)): sys.exit((checkpoint_path + ' not found.')) (exper_path, experiment_name) = os.path.split(exper_dir.rstrip('/')) export_name = (args.export_name if args.export_name else experiment...
def get_model(name): mod = __import__('lisrd.models.{}'.format(name), fromlist=['']) return getattr(mod, _module_to_class(name))
def _module_to_class(name): return ''.join((n.capitalize() for n in name.split('_')))
class NetVLAD(nn.Module): '\n NetVLAD layer implementation\n Credits: https://github.com/lyakaap/NetVLAD-pytorch\n ' def __init__(self, num_clusters=64, dim=128, alpha=100.0, normalize_input=True): '\n Args:\n num_clusters: number of clusters.\n dim: dimension of...
class VGGLikeModule(torch.nn.Module): def __init__(self): super().__init__() self._relu = torch.nn.ReLU(inplace=True) self._pool = torch.nn.AvgPool2d(kernel_size=2, stride=2) self._conv1_1 = torch.nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1) self._bn1_1 = torch.nn....
class Mode(): TRAIN = 'train' VAL = 'validation' TEST = 'test' EXPORT = 'export'
class BaseModel(metaclass=ABCMeta): 'Base model class.\n\n Arguments:\n dataset: A BaseDataset object.\n config: A dictionary containing the configuration parameters.\n The Entry `learning_rate` is required.\n\n Models should inherit from this class and implement the following m...
class LisrdModule(nn.Module): def __init__(self, config, device): super().__init__() self._config = config self.relu = torch.nn.ReLU(inplace=True) self._backbone = VGGLikeModule() self._variances = ['rot_var_illum_var', 'rot_invar_illum_var', 'rot_var_illum_invar', 'rot_in...
class Lisrd(BaseModel): required_config_keys = [] def __init__(self, dataset, config, device): self._device = device super().__init__(dataset, config, device) self._variances = ['rot_var_illum_var', 'rot_invar_illum_var', 'rot_var_illum_invar', 'rot_invar_illum_invar'] self._c...
def matching_score(inputs, descs, meta_descs=None, device='cuda:0'): (b_size, _, Hc, Wc) = descs[0][0].size() img_size = ((Hc * 8), (Wc * 8)) valid_mask = inputs['valid_mask'] n_points = valid_mask.size()[1] n_correct_points = torch.sum(valid_mask.int()).item() if (n_correct_points == 0): ...
def keypoints_to_grid(keypoints, img_size): '\n Convert a tensor [N, 2] or batched tensor [B, N, 2] of N keypoints into\n a grid in [-1, 1]² that can be used in torch.nn.functional.interpolate.\n ' n_points = keypoints.size()[(- 2)] device = keypoints.device grid_points = (((keypoints.float()...
def flush(): 'Try to flush all stdio buffers, both from python and from C.' try: sys.stdout.flush() sys.stderr.flush() except (AttributeError, ValueError, IOError): pass
@contextmanager def capture_outputs(filename): 'Duplicate stdout and stderr to a file on the file descriptor level.' with open(filename, 'a+') as target: original_stdout_fd = 1 original_stderr_fd = 2 target_fd = target.fileno() saved_stdout_fd = os.dup(original_stdout_fd) ...
def plot_mma(config, captions, mma_i, mma_v): models = config['models_name'] n_models = len(models) colors = np.array(brewer2mpl.get_map('Set2', 'qualitative', 8).mpl_colors)[:n_models] linestyles = (['-'] * n_models) plt_lim = [1, config['max_mma_threshold']] plt_rng = np.arange(plt_lim[0], (...
def plot_mma(config, captions, mma_day, mma_night): models = config['models_name'] n_models = len(models) colors = np.array(brewer2mpl.get_map('Set2', 'qualitative', 8).mpl_colors)[:n_models] linestyles = (['-'] * n_models) plt_lim = [1, config['max_mma_threshold']] plt_rng = np.arange(plt_lim...
def get_dataloaders(dataset='mnist', batch_size=128, augmentation_on=False, cuda=False, num_workers=0): kwargs = ({'num_workers': num_workers, 'pin_memory': True} if cuda else {}) if (dataset == 'mnist'): if augmentation_on: transform_train = transforms.Compose([transforms.RandomCrop(28, p...
def get_dataset_details(dataset): if (dataset == 'mnist'): (input_nc, input_width, input_height) = (1, 28, 28) classes = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) elif (dataset == 'cifar10'): (input_nc, input_width, input_height) = (3, 32, 32) classes = ('plane', 'car', 'bird', 'cat', 'de...
class Tree(nn.Module): ' Adaptive Neural Tree module. ' def __init__(self, tree_struct, tree_modules, split=False, node_split=None, child_left=None, child_right=None, extend=False, node_extend=None, child_extension=None, cuda_on=True, breadth_first=True, soft_decision=True): ' Initialise the class.\n...
class Identity(nn.Module): def __init__(self, input_nc, input_width, input_height, **kwargs): super(Identity, self).__init__() self.outputshape = (1, input_nc, input_width, input_height) def forward(self, x): return x
class JustConv(nn.Module): ' 1 convolution ' def __init__(self, input_nc, input_width, input_height, ngf=6, kernel_size=5, stride=1, **kwargs): super(JustConv, self).__init__() if (max(input_width, input_height) < kernel_size): warnings.warn('Router kernel too large, shrink it') ...
class ConvPool(nn.Module): ' 1 convolution + 1 max pooling ' def __init__(self, input_nc, input_width, input_height, ngf=6, kernel_size=5, downsample=True, **kwargs): super(ConvPool, self).__init__() self.downsample = downsample if (max(input_width, input_height) < kernel_size): ...
class ResidualTransformer(nn.Module): ' Bottleneck without batch-norm\n Got the base codes from\n https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\n ' def __init__(self, input_nc, input_width, input_height, ngf=6, stride=1, **kwargs): super(ResidualTransformer, self...
class VGG13ConvPool(nn.Module): ' n convolution + 1 max pooling ' def __init__(self, input_nc, input_width, input_height, ngf=64, kernel_size=3, batch_norm=True, downsample=True, **kwargs): super(VGG13ConvPool, self).__init__() self.downsample = downsample self.batch_norm = batch_norm...
class One(nn.Module): 'Route all data points to the left branch branch ' def __init__(self): super(One, self).__init__() def forward(self, x): return 1.0
class Router(nn.Module): 'Convolution + Relu + Global Average Pooling + Sigmoid' def __init__(self, input_nc, input_width, input_height, kernel_size=28, soft_decision=True, stochastic=False, **kwargs): super(Router, self).__init__() self.soft_decision = soft_decision self.stochastic =...
class RouterGAP(nn.Module): ' Convolution + Relu + Global Average Pooling + FC + Sigmoid ' def __init__(self, input_nc, input_width, input_height, ngf=5, kernel_size=7, soft_decision=True, stochastic=False, **kwargs): super(RouterGAP, self).__init__() self.ngf = ngf self.soft_decision...
class RouterGAPwithDoubleConv(nn.Module): ' 2 x (Convolution + Relu) + Global Average Pooling + FC + Sigmoid ' def __init__(self, input_nc, input_width, input_height, ngf=32, kernel_size=3, soft_decision=True, stochastic=False, **kwargs): super(RouterGAPwithDoubleConv, self).__init__() self.n...
class Router_MLP_h1(nn.Module): ' MLP with 1 hidden layer ' def __init__(self, input_nc, input_width, input_height, kernel_size=28, soft_decision=True, stochastic=False, reduction_rate=2, **kwargs): super(Router_MLP_h1, self).__init__() self.soft_decision = soft_decision self.stochas...
class RouterGAP_TwoFClayers(nn.Module): ' Routing function:\n GAP + fc1 + fc2 \n ' def __init__(self, input_nc, input_width, input_height, kernel_size=28, soft_decision=True, stochastic=False, reduction_rate=2, dropout_prob=0.0, **kwargs): super(RouterGAP_TwoFClayers, self).__init__() s...
class RouterGAPwithConv_TwoFClayers(nn.Module): ' Routing function:\n Conv2D + GAP + fc1 + fc2 \n ' def __init__(self, input_nc, input_width, input_height, ngf=10, kernel_size=3, soft_decision=True, stochastic=False, reduction_rate=2, dropout_prob=0.0, **kwargs): super(RouterGAPwithConv_TwoFCla...
class LR(nn.Module): ' Logistinc regression\n ' def __init__(self, input_nc, input_width, input_height, no_classes=10, **kwargs): super(LR, self).__init__() self.fc = nn.Linear(((input_nc * input_width) * input_height), no_classes) def forward(self, x): x = x.view(x.size(0), (...
class MLP_LeNet(nn.Module): ' The last fully-connected part of LeNet\n ' def __init__(self, input_nc, input_width, input_height, no_classes=10, **kwargs): super(MLP_LeNet, self).__init__() assert (((input_nc * input_width) * input_height) > 120) self.fc1 = nn.Linear(((input_nc * in...
class MLP_LeNetMNIST(nn.Module): ' The last fully connected part of LeNet MNIST:\n https://github.com/BVLC/caffe/blob/master/examples/mnist/lenet.prototxt\n ' def __init__(self, input_nc, input_width, input_height, dropout_prob=0.0, **kwargs): super(MLP_LeNetMNIST, self).__init__() self...
class Solver_GAP_TwoFClayers(nn.Module): ' GAP + fc1 + fc2 ' def __init__(self, input_nc, input_width, input_height, dropout_prob=0.0, reduction_rate=2, **kwargs): super(Solver_GAP_TwoFClayers, self).__init__() self.dropout_prob = dropout_prob self.reduction_rate = reduction_rate ...
class MLP_AlexNet(nn.Module): ' The last fully connected part of LeNet MNIST:\n https://github.com/BVLC/caffe/blob/master/examples/mnist/lenet.prototxt\n ' def __init__(self, input_nc, input_width, input_height, dropout_prob=0.0, **kwargs): super(MLP_AlexNet, self).__init__() self.dropo...
class Solver_GAP_OneFClayers(nn.Module): ' GAP + fc1 ' def __init__(self, input_nc, input_width, input_height, dropout_prob=0.0, reduction_rate=2, **kwargs): super(Solver_GAP_OneFClayers, self).__init__() self.dropout_prob = dropout_prob self.reduction_rate = reduction_rate se...
def weight_init(m): classname = m.__class__.__name__ print(classname) if (classname.find('Conv2d') != (- 1)): nn.init.xavier_normal(m.weight, gain=np.sqrt(2)) if (m.bias is not None): nn.init.constant(m.bias, 0.0) elif (classname.find('Linear') != (- 1)): nn.init.xa...
class ST_Indicator(torch.autograd.Function): ' Straight-through indicator function 1(0.5 =< input):\n rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1},\n using identity for its gradient.\n ' def forward(self, input): return torch.round(input) def backward(self...
class ST_StochasticIndicator(torch.autograd.Function): ' Stochastic version of ST_Indicator:\n indicator function 1(z =< input) where z is drawn from Uniform[0,1]\n with identity for its gradient.\n ' def forward(self, input): '\n Args:\n input (float tensor of values betwe...
def neg_ce_fairflip(p, coeff): ' Compute the negative CE between p and Bernouli(0.5)\n ' nce = (((- 0.5) * coeff) * (torch.log((p + 1e-10)) + torch.log(((1.0 - p) + 1e-10))).mean()) return nce
def weighted_cross_entropy(input, target, weights): ' Compute cross entropy weighted per example\n got most ideas from https://github.com/pytorch/pytorch/issues/563\n\n Args:\n input (torch tensor): (N,C) log probabilities e.g. F.log_softmax(y_hat)\n target (torch tensor): (N) where each value...
def differential_entropy(input, bins=10, min=0.0, max=1.0): ' Approximate dfferential entropy: H(x) = E[-log P(x)]\n Fit a histogram and compute the maximum likelihood estimator of entropy\n i.e. H^{hat}(x) = - \\sum_{i} P(x_i) log(P(x_i))\n\n See https://en.wikipedia.org/wiki/Entropy_estimation\n\n ...
def coefficient_of_variation(input): ' Compute the coefficient of varation std/mean:\n ' epsilon = 1e-10 return (input.std() / (input.mean() + epsilon))
def count_number_transforms(node_idx, tree_struct): ' Get the number of transforms up to and including node_idx \n ' (nodes, _) = get_path_to_root(node_idx, tree_struct) count = 0 for i in nodes: if tree_struct[i]['transformed']: count += 1 return count
def count_number_transforms_after_last_downsample(node_idx, tree_struct): (nodes, _) = get_path_to_root(node_idx, tree_struct) last_idx = 0 for i in nodes: if (tree_struct[i]['transformed'] and tree_struct[i]['downsampled']): last_idx = i count = 0 for i in nodes[last_idx:]: ...
def get_leaf_nodes(struct): ' Get the list of leaf nodes.\n ' leaf_list = [] for (idx, node) in enumerate(struct): if node['is_leaf']: leaf_list.append(idx) return leaf_list
def get_past_leaf_nodes(struct, current_idx): ' Get the list of nodes that were leaves when the specified node is added\n to the tree.\n ' if (current_idx == 0): return [0] leaf_list = [current_idx] node_current = struct[current_idx] parent_idx = struct[current_idx]['parent'] nod...
def get_path_to_root_old(node_idx, struct): ' Get the list of nodes from the current node to the root.\n [0, n1,....., node_idx]\n ' paths_list = [] while (node_idx >= 0): paths_list.append(node_idx) node_idx = get_parent(node_idx, struct) return paths_list[::(- 1)]
def get_path_to_root(node_idx, struct): ' Get two lists:\n First, list of all nodes from the root node to the given node\n Second, list of left-child-status (boolean) of each edge between nodes in the first list\n ' paths_list = [] left_child_status = [] while (node_idx >= 0): if (nod...
def get_parent(node_idx, struct): ' Get index of parent node\n ' return struct[node_idx]['parent']
def get_left_or_right(node_idx, struct): ' Return True if the node is a left child of its parent.\n o/w return false.\n ' parent_node = struct[node_idx]['parent'] return (struct[parent_node]['left_child'] == node_idx)
def node_pred(nodes, edges, tree_modules, input): ' Perform prediction on a given node given its path on the tree.\n e.g.\n nodes = [0, 1, 4, 10]\n edges = [True, False, False]\n ' prob = 1.0 for (node, state) in zip(nodes[:(- 1)], edges): input = tree_modules[node]['transform'](input)...
def node_pred_split(input, nodes, edges, tree_modules, node_left, node_right): ' Perform prediction on a split node given its path on the tree.\n Here, the last node in the list "nodes" is assumed to be split.\n e.g.\n nodes = [0, 1, 4, 10]\n edges = [True, False, False]\n then, node 10 is assumed...
def get_params_node(grow, node_idx, model): 'Get the list of trainable parameters at the given node.\n\n If grow=True, then fetch the local parameters\n (i.e. parent router + 2 children transformers and solvers)\n ' if grow: names = [name for (name, param) in model.named_parameters() if (((('...
class ChunkSampler(sampler.Sampler): " Samples elements sequentially from some offset.\n Args:\n num_samples: # of desired datapoints\n start: offset where we should start selecting from\n\n Source:\n https://github.com/pytorch/vision/issues/168\n\n Examples:\n NUM_TRAIN = 490...
def train(model, data_loader, optimizer, node_idx): ' Train step' model.train() train_loss = 0 no_points = 0 train_epoch_loss = 0 for (batch_idx, (x, y)) in enumerate(data_loader): optimizer.zero_grad() if args.cuda: (x, y) = (x.cuda(), y.cuda()) (x, y) = (V...
def valid(model, data_loader, node_idx, struct): ' Validation step ' model.eval() valid_epoch_loss = 0 correct = 0 for (data, target) in data_loader: if args.cuda: (data, target) = (data.cuda(), target.cuda()) (data, target) = (Variable(data, volatile=True), Variable(ta...
def test(model, data_loader): ' Test step ' model.eval() test_loss = 0 correct = 0 for (data, target) in data_loader: if args.cuda: (data, target) = (data.cuda(), target.cuda()) (data, target) = (Variable(data, volatile=True), Variable(target)) output = model(da...
def _load_checkpoint(model_file_name): save_dir = './experiments/{}/{}/{}/{}'.format(args.dataset, args.experiment, args.subexperiment, 'checkpoints') model = torch.load(((save_dir + '/') + model_file_name)) if args.cuda: model.cuda() return model
def checkpoint_model(model_file_name, struct=None, modules=None, model=None, figname='hist.png', data_loader=None): if (not os.path.exists(os.path.join('./experiments', args.dataset, args.experiment, args.subexperiment))): os.makedirs(os.path.join('./experiments', args.dataset, args.experiment, args.subex...
def checkpoint_msc(struct, data_dict): ' Save structural information of the model and experimental results.\n\n Args:\n struct (list) : list of dictionaries each of which contains\n meta information about each node of the tree.\n data_dict (dict) : data about the experiment (e.g. loss,...
def get_decision(criteria, node_idx, tree_struct): " Define the splitting criteria\n\n Args:\n criteria (str): Growth criteria.\n node_idx (int): Index of the current node.\n tree_struct (list) : list of dictionaries each of which contains\n meta information about each node of t...
def optimize_fixed_tree(model, tree_struct, train_loader, valid_loader, test_loader, no_epochs, node_idx): ' Train a tree with fixed architecture.\n\n Args:\n model (torch.nn.module): tree model\n tree_struct (list): list of dictionaries which contain information\n abou...
def grow_ant_nodewise(): 'The main function for optimising an ANT ' tree_struct = [] tree_modules = [] (root_meta, root_module) = define_node(args, node_index=0, level=0, parent_index=(- 1), tree_struct=tree_struct) tree_struct.append(root_meta) tree_modules.append(root_module) model = Tre...
def define_node(args, node_index, level, parent_index, tree_struct, identity=False): ' Define node operations.\n \n In this function, we assume that 3 building blocks of node operations\n i.e. transformer, solver and router are of fixed complexity. \n ' num_transforms = (0 if (node_index == 0) els...
def define_transformer(version, input_nc, input_width, input_height, **kwargs): if (version == 1): return models.Identity(input_nc, input_width, input_height, **kwargs) elif (version == 2): return models.JustConv(input_nc, input_width, input_height, **kwargs) elif (version == 3): r...
def define_router(version, input_nc, input_width, input_height, **kwargs): if (version == 1): return models.Router(input_nc, input_width, input_height, **kwargs) elif (version == 2): return models.RouterGAP(input_nc, input_width, input_height, **kwargs) elif (version == 3): return ...
def define_solver(version, input_nc, input_width, input_height, **kwargs): if (version == 1): return models.LR(input_nc, input_width, input_height, **kwargs) elif (version == 2): return models.MLP_LeNet(input_nc, input_width, input_height, **kwargs) elif (version == 3): return mode...
def get_scheduler(scheduler_type, optimizer, grow): if (scheduler_type == 'step_lr'): scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[100, 150], gamma=0.1) elif (scheduler_type == 'plateau'): scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.1, patie...
def imshow(img): npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0)))
def plot_hist(data, save_as='./figure'): fig = plt.figure() plt.hist(data, normed=True, bins=150, range=(0, 1.0)) fig.savefig(save_as)
def plot_hist_root(labels, split_status, save_as='./figures/hist_labels_split.png'): ' Plot the distribution of labels of a binary routing function.\n Args:\n labels (np array): labels (N) each entry contains a label\n split_status (np array bool): boolean array (N) where 0 indicates the entry\n ...
def print_performance(jasonfile, model_name='model_1', figsize=(5, 5)): ' Inspect performance of a single model\n ' records = json.load(open(jasonfile, 'r')) print(('\n' + model_name)) print(' train_best_loss: {}'.format(records['train_best_loss'])) print(' valid_best_loss: {}'.fo...
def plot_performance(jasonfiles, model_names=[], figsize=(5, 5), title=''): ' Visualise the results for several models\n\n Args:\n jasonfiles (list): List of jason files\n model_names (list): List of model names\n ' fig = plt.figure(figsize=figsize) color = ['b', 'g', 'r', 'c', 'm', 'y...
def plot_accuracy(jasonfiles, model_names=[], figsize=(5, 5), ymax=100.0, title=''): fig = plt.figure(figsize=figsize) color = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'] if (not model_names): model_names = [str(i) for i in range(len(jasonfiles))] for (i, f) in enumerate(jasonfiles): reco...
def compute_error(model_file, data_loader, cuda_on=False, name=''): 'Load a model and compute errors on a held-out dataset\n Args:\n model_file (str): model parameters\n data_dataloader (torch.utils.data.DataLoader): data loader\n ' model = torch.load(model_file) if cuda_on: mo...
def load_tree_model(model_file, cuda_on=False, soft_decision=True, stochastic=False, breadth_first=False, fast=False): 'Load a tree model. ' map_location = None if (not cuda_on): map_location = 'cpu' tree_tmp = torch.load(model_file, map_location=map_location) (tree_struct, tree_modules) =...
def compute_error_general(model_file, data_loader, cuda_on=False, soft_decision=True, stochastic=False, breadth_first=False, fast=False, task='classification', name=''): 'Load a model and perform stochastic inferenc\n Args:\n model_file (str): model parameters\n data_dataloader (torch.utils.data....
def compute_error_general_ensemble(model_file_list, data_loader, cuda_on=False, soft_decision=True, stochastic=False, breadth_first=False, fast=False, task='classification', name=''): 'Load an ensemble of models and compute the average prediction. ' model_list = [] map_location = None if (not cuda_on)...
def try_different_inference_methods(model_file, dataset, task='classification', augmentation_on=False, cuda_on=True): ' Try different inference methods and compute accuracy \n ' if (dataset == 'cifar10'): if augmentation_on: transform_test = transforms.Compose([transforms.ToTensor(), tr...
def try_different_inference_methods_ensemble(model_file_list, dataset, task='classification', augmentation_on=False, cuda_on=True): ' Try different inference methods and compute accuracy\n ' if (dataset == 'cifar10'): if augmentation_on: transform_test = transforms.Compose([transforms.T...
def get_total_number_of_params(model, print_on=False): tree_struct = model.tree_struct (names, params) = ([], []) for (node_idx, node_meta) in enumerate(tree_struct): for (name, param) in model.named_parameters(): if (((not node_meta['is_leaf']) and ((('.' + str(node_idx)) + '.router')...
def get_number_of_params_path(model, nodes, print_on=False, include_routers=True): (names, params) = ([], []) if include_routers: for (name, param) in model.named_parameters(): if (((('.' + str(nodes[(- 1)])) + '.classifier') in name) or any([((('.' + str(node)) + '.transform') in name) fo...
def get_number_of_params_summary(model, name='', print_on=True, include_routers=True): total_num = get_total_number_of_params(model) paths_list = model.paths_list num_list = [] for (nodes, _) in paths_list: num = get_number_of_params_path(model, nodes, include_routers=include_routers) ...
def round_value(value, binary=False): divisor = (1024.0 if binary else 1000.0) if ((value // (divisor ** 4)) > 0): return (str(round((value / (divisor ** 4)), 2)) + 'T') elif ((value // (divisor ** 3)) > 0): return (str(round((value / (divisor ** 3)), 2)) + 'G') elif ((value // (diviso...
def set_random_seed(seed, cuda): np.random.seed(seed) torch.manual_seed(seed) random.seed(seed) if cuda: torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
def convert_path_to_npy(*, path='train_64x64', outfile='train_64x64.npy'): assert isinstance(path, str), 'Expected a string input for the path' assert os.path.exists(path), "Input path doesn't exist" files = [f for f in listdir(path) if isfile(join(path, f))] print('Number of valid images is:', len(fi...
class Dataset(object): def __init__(self, loc, transform=None, in_mem=True): self.in_mem = in_mem self.dataset = torch.load(loc) if in_mem: self.dataset = self.dataset.float().div(255) self.transform = transform def __len__(self): return self.dataset.size(...
class MNIST(object): def __init__(self, dataroot, train=True, transform=None): self.mnist = vdsets.MNIST(dataroot, train=train, download=True, transform=transform) def __len__(self): return len(self.mnist) @property def ndim(self): return 1 def __getitem__(self, index):...
class CIFAR10(object): def __init__(self, dataroot, train=True, transform=None): self.cifar10 = vdsets.CIFAR10(dataroot, train=train, download=True, transform=transform) def __len__(self): return len(self.cifar10) @property def ndim(self): return 3 def __getitem__(self,...