code
stringlengths
17
6.64M
def applySoftMax(inputSample, inputSampleShape, numClasses, softmaxTemperature): inputSampleReshaped = inputSample.dimshuffle(0, 2, 3, 4, 1) inputSampleFlattened = inputSampleReshaped.flatten(1) numClassifiedVoxels = ((inputSampleShape[2] * inputSampleShape[3]) * inputSampleShape[4]) firstDimOfinputSa...
def applyBiasToFeatureMaps(bias, featMaps): featMaps = (featMaps + bias.dimshuffle('x', 0, 'x', 'x', 'x')) return featMaps
class parserConfigIni(object): def __init__(_self): _self.networkName = [] def readConfigIniFile(_self, fileName, task): def createModel(): print(' --- Creating model (Reading parameters...)') _self.readModelCreation_params(fileName) def trainModel(): ...
def printUsage(error_type): if (error_type == 1): print(' ** ERROR!!: Few parameters used.') else: print(' ** ERROR!!: Asked to start with an already created network but its name is not specified.') print(' ******** USAGE ******** ') print(' --- argv 1: Name of the configIni file.') ...
def networkSegmentation(argv): if (len(argv) < 2): printUsage(1) sys.exit() configIniName = argv[0] networkModelName = argv[1] startTesting(networkModelName, configIniName) print(' ***************** SEGMENTATION DONE!!! ***************** ')
def arg_parse(): parser = argparse.ArgumentParser(description='GcnInformax Arguments.') parser.add_argument('--DS', dest='DS', help='Dataset') parser.add_argument('--local', dest='local', action='store_const', const=True, default=False) parser.add_argument('--glob', dest='glob', action='store_const', ...
def raise_measure_error(measure): supported_measures = ['GAN', 'JSD', 'JSD_hard', 'X2', 'KL', 'RKL', 'DV', 'H2', 'W1'] raise NotImplementedError('Measure `{}` not supported. Supported: {}'.format(measure, supported_measures))
def get_positive_expectation(p_samples, measure, average=True, tau_plus=0.5): 'Computes the positive part of a divergence / difference.\n\n Args:\n p_samples: Positive samples.\n measure: Measure to compute for.\n average: Average the result over samples.\n\n Returns:\n torch.Ten...
def get_negative_expectation(q_samples, measure, average=True, beta=0, tau_plus=0.5): 'Computes the negative part of a divergence / difference.\n\n Args:\n q_samples: Negative samples.\n measure: Measure to compute for.\n average: Average the result over samples.\n\n Returns:\n t...
def infer_conv_size(w, k, s, p): 'Infers the next size after convolution.\n\n Args:\n w: Input size.\n k: Kernel size.\n s: Stride.\n p: Padding.\n\n Returns:\n int: Output size.\n\n ' x = ((((w - k) + (2 * p)) // s) + 1) return x
class Convnet(nn.Module): 'Basic convnet convenience class.\n\n Attributes:\n conv_layers: nn.Sequential of nn.Conv2d layers with batch norm,\n dropout, nonlinearity.\n fc_layers: nn.Sequential of nn.Linear layers with batch norm,\n dropout, nonlinearity.\n reshape: S...
class FoldedConvnet(Convnet): 'Convnet with strided crop input.\n\n ' def create_layers(self, shape, crop_size=8, conv_args=None, fc_args=None): 'Creates layers\n\n conv_args are in format (dim_h, f_size, stride, pad, batch_norm, dropout, nonlinearity, pool)\n fc_args are in format (...
def create_encoder(Module): class Encoder(Module): 'Encoder used for cortex_DIM.\n\n ' def __init__(self, *args, local_idx=None, multi_idx=None, conv_idx=None, fc_idx=None, **kwargs): '\n\n Args:\n args: Arguments for parent class.\n lo...
class ConvnetEncoder(create_encoder(Convnet)): pass
class FoldedConvnetEncoder(create_encoder(FoldedConvnet)): pass
class ResnetEncoder(create_encoder(ResNet)): pass
class FoldedResnetEncoder(create_encoder(FoldedResNet)): pass
class MIFCNet(nn.Module): 'Simple custom network for computing MI.\n\n ' def __init__(self, n_input, n_units): '\n\n Args:\n n_input: Number of input units.\n n_units: Number of output units.\n ' super().__init__() assert (n_units >= n_input) ...
class MI1x1ConvNet(nn.Module): 'Simple custorm 1x1 convnet.\n\n ' def __init__(self, n_input, n_units): '\n\n Args:\n n_input: Number of input units.\n n_units: Number of output units.\n ' super().__init__() self.block_nonlinear = nn.Sequential(n...
class View(torch.nn.Module): 'Basic reshape module.\n\n ' def __init__(self, *shape): '\n\n Args:\n *shape: Input shape.\n ' super().__init__() self.shape = shape def forward(self, input): 'Reshapes tensor.\n\n Args:\n input: ...
class Unfold(torch.nn.Module): 'Module for unfolding tensor.\n\n Performs strided crops on 2d (image) tensors. Stride is assumed to be half the crop size.\n\n ' def __init__(self, img_size, fold_size): '\n\n Args:\n img_size: Input size.\n fold_size: Crop size.\n ...
class Fold(torch.nn.Module): 'Module (re)folding tensor.\n\n Undoes the strided crops above. Works only on 1x1.\n\n ' def __init__(self, img_size, fold_size): '\n\n Args:\n img_size: Images size.\n fold_size: Crop size.\n ' super().__init__() ...
class Permute(torch.nn.Module): 'Module for permuting axes.\n\n ' def __init__(self, *perm): '\n\n Args:\n *perm: Permute axes.\n ' super().__init__() self.perm = perm def forward(self, input): 'Permutes axes of tensor.\n\n Args:\n ...
class ResBlock(Convnet): 'Residual block for ResNet\n\n ' def create_layers(self, shape, conv_args=None): 'Creates layers\n\n Args:\n shape: Shape of input.\n conv_args: Layer arguments for block.\n ' final_nonlin = conv_args[(- 1)][_nonlin_idx] ...
class ResNet(Convnet): def create_layers(self, shape, conv_before_args=None, res_args=None, conv_after_args=None, fc_args=None): 'Creates layers\n\n Args:\n shape: Shape of the input.\n conv_before_args: Arguments for convolutional layers before residuals.\n res_ar...
class FoldedResNet(ResNet): 'Resnet with strided crop input.\n\n ' def create_layers(self, shape, crop_size=8, conv_before_args=None, res_args=None, conv_after_args=None, fc_args=None): 'Creates layers\n\n Args:\n shape: Shape of the input.\n crop_size: Size of the cro...
class NormalizedDegree(object): def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, data): deg = degree(data.edge_index[0], dtype=torch.float) deg = ((deg - self.mean) / self.std) data.x = deg.view((- 1), 1) return data
class GcnInfomax(nn.Module): def __init__(self, hidden_dim, num_gc_layers, alpha=0.5, beta=1.0, gamma=0.1): super(GcnInfomax, self).__init__() self.alpha = alpha self.beta = beta self.gamma = gamma self.prior = args.prior self.embedding_dim = mi_units = (hidden_dim...
def svc_classify(x, y, search): kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=None) accuracies = [] for (train_index, test_index) in kf.split(x, y): (x_train, x_test) = (x[train_index], x[test_index]) (y_train, y_test) = (y[train_index], y[test_index]) if search: ...
def evaluate_embedding(embeddings, labels, search=True): labels = preprocessing.LabelEncoder().fit_transform(labels) (x, y) = (np.array(embeddings), np.array(labels)) print(x.shape, y.shape) svc_accuracies = [svc_classify(x, y, search) for _ in range(1)] print('svc', np.mean(svc_accuracies)) r...
class Encoder(torch.nn.Module): def __init__(self, num_features, dim, num_gc_layers): super(Encoder, self).__init__() self.num_gc_layers = num_gc_layers self.convs = torch.nn.ModuleList() self.bns = torch.nn.ModuleList() for i in range(num_gc_layers): if i: ...
class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() try: num_features = dataset.num_features except: num_features = 1 dim = 32 self.encoder = Encoder(num_features, dim) self.fc1 = Linear((dim * 5), dim) self.f...
def train(epoch): model.train() if (epoch == 51): for param_group in optimizer.param_groups: param_group['lr'] = (0.5 * param_group['lr']) loss_all = 0 for data in train_loader: data = data.to(device) optimizer.zero_grad() output = model(data.x, data.edge_in...
def test(loader): model.eval() correct = 0 for data in loader: data = data.to(device) output = model(data.x, data.edge_index, data.batch) pred = output.max(dim=1)[1] correct += pred.eq(data.y).sum().item() return (correct / len(loader.dataset))
def local_global_loss_(l_enc, g_enc, edge_index, batch, measure, beta=0): '\n Args:\n l: Local feature map.\n g: Global features.\n measure: Type of f-divergence. For use with mode `fd`\n mode: Loss mode. Fenchel-dual `fd`, NCE `nce`, or Donsker-Vadadhan `dv`.\n Returns:\n ...
def adj_loss_(l_enc, g_enc, edge_index, batch): num_graphs = g_enc.shape[0] num_nodes = l_enc.shape[0] adj = torch.zeros((num_nodes, num_nodes)).cuda() mask = torch.eye(num_nodes).cuda() for (node1, node2) in zip(edge_index[0], edge_index[1]): adj[node1.item()][node2.item()] = 1.0 ...
class GlobalDiscriminator(nn.Module): def __init__(self, args, input_dim): super().__init__() self.l0 = nn.Linear(32, 32) self.l1 = nn.Linear(32, 32) self.l2 = nn.Linear(512, 1) def forward(self, y, M, data): adj = Variable(data['adj'].float(), requires_grad=False).cu...
class PriorDiscriminator(nn.Module): def __init__(self, input_dim): super().__init__() self.l0 = nn.Linear(input_dim, input_dim) self.l1 = nn.Linear(input_dim, input_dim) self.l2 = nn.Linear(input_dim, 1) def forward(self, x): h = F.relu(self.l0(x)) h = F.relu...
class FF(nn.Module): def __init__(self, input_dim): super().__init__() self.block = nn.Sequential(nn.Linear(input_dim, input_dim), nn.ReLU(), nn.Linear(input_dim, input_dim), nn.ReLU(), nn.Linear(input_dim, input_dim), nn.ReLU()) self.linear_shortcut = nn.Linear(input_dim, input_dim) ...
class Model(nn.Module): def __init__(self, feature_dim=128): super(Model, self).__init__() self.f = [] for (name, module) in resnet50().named_children(): if (name == 'conv1'): module = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) ...
class CIFAR10Pair(CIFAR10): def __getitem__(self, index): (img, target) = (self.data[index], self.targets[index]) img = Image.fromarray(img) if (self.transform is not None): pos_1 = self.transform(img) pos_2 = self.transform(img) if (self.target_transform i...
class CIFAR100Pair_true_label(CIFAR100): def __init__(self, root='../data', train=True, transform=None): super().__init__(root=root, train=train, transform=transform) def get_labels(i): return [index for index in range(len(self)) if (self.targets[index] == i)] self.label_inde...
class CIFAR100Pair(CIFAR100): def __getitem__(self, index): (img, target) = (self.data[index], self.targets[index]) img = Image.fromarray(img) if (self.transform is not None): pos_1 = self.transform(img) pos_2 = self.transform(img) if (self.target_transform...
class STL10Pair(STL10): def __getitem__(self, index): (img, target) = (self.data[index], self.labels[index]) img = Image.fromarray(np.transpose(img, (1, 2, 0))) if (self.transform is not None): pos_1 = self.transform(img) pos_2 = self.transform(img) return ...
class GaussianBlur(object): def __init__(self, kernel_size, min=0.1, max=2.0): self.min = min self.max = max self.kernel_size = kernel_size def __call__(self, sample): sample = np.array(sample) prob = np.random.random_sample() if (prob < 0.5): sigm...
def get_dataset(dataset_name, root='../data', pair=True): if pair: if (dataset_name == 'cifar10'): train_data = CIFAR10Pair(root=root, train=True, transform=train_transform) memory_data = CIFAR10Pair(root=root, train=True, transform=test_transform) test_data = CIFAR10Pa...
class CurveBall(Optimizer): 'CurveBall optimizer' def __init__(self, params, lr=None, momentum=None, auto_lambda=True, lambd=10.0, lambda_factor=0.999, lambda_low=0.5, lambda_high=1.5, lambda_interval=5): defaults = dict(lr=lr, momentum=momentum, auto_lambda=auto_lambda, lambd=lambd, lambda_factor=la...
def fmad(ys, xs, dxs): 'Forward-mode automatic differentiation.' v = t.zeros_like(ys, requires_grad=True) g = grad(ys, xs, grad_outputs=v, create_graph=True) return grad(g, v, grad_outputs=dxs)
def train(args, net, device, train_loader, optimizer, epoch, logger): net.train() for (batch_idx, (data, target)) in enumerate(train_loader): start = time() (data, target) = (data.to(device), target.to(device)) model_fn = (lambda : net(data)) loss_fn = (lambda pred: F.cross_ent...
def test(args, net, device, test_loader, logger): net.eval() with torch.no_grad(): for (data, target) in test_loader: start = time() (data, target) = (data.to(device), target.to(device)) predictions = net(data) loss = F.cross_entropy(predictions, target)...
def main(): all_models = [name for name in dir(models) if callable(getattr(models, name))] parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training') parser.add_argument('experiment', nargs='?', default='test') parser.add_argument('-model', choices=all_models, default='BasicNetBN') p...
class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), (- 1))
def onehot(target, like): 'Transforms numeric labels into one-hot regression targets.' out = torch.zeros_like(like) out.scatter_(1, target.unsqueeze(1), 1.0) return out
def train(args, model, device, train_loader, optimizer, epoch, logger): model.train() for (batch_idx, (data, target)) in enumerate(train_loader): start = time() (data, target) = (data.to(device), target.to(device)) model_fn = (lambda : model(data)) loss_fn = (lambda pred: F.cro...
def test(args, model, device, test_loader, logger): model.eval() with torch.no_grad(): for (data, target) in test_loader: start = time() (data, target) = (data.to(device), target.to(device)) predictions = model(data) loss = F.cross_entropy(predictions, t...
def main(): parser = argparse.ArgumentParser() parser.add_argument('experiment', nargs='?', default='test') parser.add_argument('-batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('-test-batch-size', type=int, default=1000, help='in...
class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), (- 1))
def BasicNetBN(): return BasicNet(batch_norm=True)
def BasicNet(batch_norm=False): 'Basic network for CIFAR.' layers = [nn.Conv2d(3, 32, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2, padding=1), nn.Conv2d(32, 32, kernel_size=5, padding=2), nn.ReLU(), nn.AvgPool2d(kernel_size=3, stride=2, padding=1), nn.Conv2d(32, 64, kernel_size=...
def insert_bnorm(layers, init_gain=False, eps=1e-05, ignore_last_layer=True): 'Inserts batch-norm layers after each convolution/linear layer in a list of layers.' last = True for (idx, layer) in reversed(list(enumerate(layers))): if isinstance(layer, (nn.Conv2d, nn.Linear)): if (ignore...
class Bottleneck(nn.Module): def __init__(self, in_planes, growth_rate): super(Bottleneck, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, (4 * growth_rate), kernel_size=1, bias=False) self.bn2 = nn.BatchNorm2d((4 * growth_rate)) sel...
class Transition(nn.Module): def __init__(self, in_planes, out_planes): super(Transition, self).__init__() self.bn = nn.BatchNorm2d(in_planes) self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=False) def forward(self, x): out = self.conv(F.relu(self.bn(x))) ...
class DenseNet(nn.Module): def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=10): super(DenseNet, self).__init__() self.growth_rate = growth_rate num_planes = (2 * growth_rate) self.conv1 = nn.Conv2d(3, num_planes, kernel_size=3, padding=1, bias=False) ...
def DenseNet121(): return DenseNet(Bottleneck, [6, 12, 24, 16], growth_rate=32)
def DenseNet169(): return DenseNet(Bottleneck, [6, 12, 32, 32], growth_rate=32)
def DenseNet201(): return DenseNet(Bottleneck, [6, 12, 48, 32], growth_rate=32)
def DenseNet161(): return DenseNet(Bottleneck, [6, 12, 36, 24], growth_rate=48)
def densenet_cifar(): return DenseNet(Bottleneck, [6, 12, 24, 16], growth_rate=12)
def test(): net = densenet_cifar() x = torch.randn(1, 3, 32, 32) y = net(x) print(y)
class Inception(nn.Module): def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes): super(Inception, self).__init__() self.b1 = nn.Sequential(nn.Conv2d(in_planes, n1x1, kernel_size=1), nn.BatchNorm2d(n1x1), nn.ReLU(True)) self.b2 = nn.Sequential(nn.Conv2d(in_planes...
class GoogLeNet(nn.Module): def __init__(self): super(GoogLeNet, self).__init__() self.pre_layers = nn.Sequential(nn.Conv2d(3, 192, kernel_size=3, padding=1), nn.BatchNorm2d(192), nn.ReLU(True)) self.a3 = Inception(192, 64, 96, 128, 16, 32, 32) self.b3 = Inception(256, 128, 128, 1...
def test(): net = GoogLeNet() x = torch.randn(1, 3, 32, 32) y = net(x) print(y.size())
class LeNet(nn.Module): def __init__(self): super(LeNet, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(((16 * 5) * 5), 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x)...
class Block(nn.Module): 'Depthwise conv + Pointwise conv' def __init__(self, in_planes, out_planes, stride=1): super(Block, self).__init__() self.conv1 = nn.Conv2d(in_planes, in_planes, kernel_size=3, stride=stride, padding=1, groups=in_planes, bias=False) self.bn1 = nn.BatchNorm2d(in...
class MobileNet(nn.Module): cfg = [64, (128, 2), 128, (256, 2), 256, (512, 2), 512, 512, 512, 512, 512, (1024, 2), 1024] def __init__(self, num_classes=10): super(MobileNet, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.Ba...
def test(): net = MobileNet() x = torch.randn(1, 3, 32, 32) y = net(x) print(y.size())
class Block(nn.Module): 'expand + depthwise + pointwise' def __init__(self, in_planes, out_planes, expansion, stride): super(Block, self).__init__() self.stride = stride planes = (expansion * in_planes) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, stride=1, padding...
class MobileNetV2(nn.Module): cfg = [(1, 16, 1, 1), (6, 24, 2, 1), (6, 32, 3, 2), (6, 64, 4, 2), (6, 96, 3, 1), (6, 160, 3, 2), (6, 320, 1, 1)] def __init__(self, num_classes=10): super(MobileNetV2, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False)...
def test(): net = MobileNetV2() x = torch.randn(2, 3, 32, 32) y = net(x) print(y.size())
class SepConv(nn.Module): 'Separable Convolution.' def __init__(self, in_planes, out_planes, kernel_size, stride): super(SepConv, self).__init__() self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding=((kernel_size - 1) // 2), bias=False, groups=in_planes) self.bn...
class CellA(nn.Module): def __init__(self, in_planes, out_planes, stride=1): super(CellA, self).__init__() self.stride = stride self.sep_conv1 = SepConv(in_planes, out_planes, kernel_size=7, stride=stride) if (stride == 2): self.conv1 = nn.Conv2d(in_planes, out_planes,...
class CellB(nn.Module): def __init__(self, in_planes, out_planes, stride=1): super(CellB, self).__init__() self.stride = stride self.sep_conv1 = SepConv(in_planes, out_planes, kernel_size=7, stride=stride) self.sep_conv2 = SepConv(in_planes, out_planes, kernel_size=3, stride=strid...
class PNASNet(nn.Module): def __init__(self, cell_type, num_cells, num_planes): super(PNASNet, self).__init__() self.in_planes = num_planes self.cell_type = cell_type self.conv1 = nn.Conv2d(3, num_planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchN...
def PNASNetA(): return PNASNet(CellA, num_cells=6, num_planes=44)
def PNASNetB(): return PNASNet(CellB, num_cells=6, num_planes=32)
def test(): net = PNASNetB() x = torch.randn(1, 3, 32, 32) y = net(x) print(y)
class PreActBlock(nn.Module): 'Pre-activation version of the BasicBlock.' expansion = 1 def __init__(self, in_planes, planes, stride=1): super(PreActBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride,...
class PreActBottleneck(nn.Module): 'Pre-activation version of the original Bottleneck module.' expansion = 4 def __init__(self, in_planes, planes, stride=1): super(PreActBottleneck, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, planes, ker...
class PreActResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(PreActResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.layer1 = self._make_layer(block, 64, num_blocks[0], str...
def PreActResNet18(): return PreActResNet(PreActBlock, [2, 2, 2, 2])
def PreActResNet34(): return PreActResNet(PreActBlock, [3, 4, 6, 3])
def PreActResNet50(): return PreActResNet(PreActBottleneck, [3, 4, 6, 3])
def PreActResNet101(): return PreActResNet(PreActBottleneck, [3, 4, 23, 3])
def PreActResNet152(): return PreActResNet(PreActBottleneck, [3, 8, 36, 3])
def test(): net = PreActResNet18() y = net(torch.randn(1, 3, 32, 32)) print(y.size())
class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_s...
class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(blo...
def ResNet18(): return ResNet(BasicBlock, [2, 2, 2, 2])
def ResNet34(): return ResNet(BasicBlock, [3, 4, 6, 3])