code stringlengths 17 6.64M |
|---|
class TestReproducibility(unittest.TestCase):
def _test_reproducibility(self, name, extra_flags=None, delta=0.0001, resume_checkpoint='checkpoint1.pt', max_epoch=3):
if (extra_flags is None):
extra_flags = []
with tempfile.TemporaryDirectory(name) as data_dir:
with self.as... |
class TestResamplingDataset(unittest.TestCase):
def setUp(self):
self.strings = ['ab', 'c', 'def', 'ghij']
self.weights = [4.0, 2.0, 7.0, 1.5]
self.size_ratio = 2
self.dataset = ListDataset(self.strings, np.array([len(s) for s in self.strings]))
def _test_common(self, resampl... |
class TestSequenceGeneratorBase(unittest.TestCase):
def assertHypoTokens(self, hypo, tokens):
self.assertTensorEqual(hypo['tokens'], torch.LongTensor(tokens))
def assertHypoScore(self, hypo, pos_probs, normalized=True, lenpen=1.0):
pos_scores = torch.FloatTensor(pos_probs).log()
self... |
class TestSequenceGenerator(TestSequenceGeneratorBase):
def setUp(self):
(self.tgt_dict, self.w1, self.w2, src_tokens, src_lengths, self.model) = test_utils.sequence_generator_setup()
self.sample = {'net_input': {'src_tokens': src_tokens, 'src_lengths': src_lengths}}
def test_with_normalizat... |
class TestDiverseBeamSearch(TestSequenceGeneratorBase):
def setUp(self):
d = test_utils.dummy_dictionary(vocab_size=2)
self.assertEqual(d.pad(), 1)
self.assertEqual(d.eos(), 2)
self.assertEqual(d.unk(), 3)
self.eos = d.eos()
self.w1 = 4
self.w2 = 5
... |
class TestDiverseSiblingsSearch(TestDiverseBeamSearch):
def assertHypoScore(self, hypo, pos_probs, sibling_rank, diversity_rate, normalized=True, lenpen=1.0):
pos_scores = torch.FloatTensor(pos_probs).log()
pos_scores.sub_((torch.Tensor(sibling_rank) * diversity_rate))
self.assertAlmostEq... |
class TestTopPSamplingSearch(TestSequenceGeneratorBase):
def setUp(self):
d = test_utils.dummy_dictionary(vocab_size=2)
self.assertEqual(d.pad(), 1)
self.assertEqual(d.eos(), 2)
self.assertEqual(d.unk(), 3)
self.eos = d.eos()
self.w1 = 4
self.w2 = 5
... |
class TestSequenceScorer(unittest.TestCase):
def test_sequence_scorer(self):
d = test_utils.dummy_dictionary(vocab_size=2)
self.assertEqual(d.pad(), 1)
self.assertEqual(d.eos(), 2)
self.assertEqual(d.unk(), 3)
eos = d.eos()
w1 = 4
w2 = 5
data = [{'s... |
class TestSparseMultiheadAttention(unittest.TestCase):
def test_sparse_multihead_attention(self):
attn_weights = torch.randn(1, 8, 8)
bidirectional_sparse_mask = torch.tensor([[0, 0, 0, 0, 0, float('-inf'), float('-inf'), 0], [0, 0, 0, 0, 0, float('-inf'), float('-inf'), 0], [0, 0, 0, 0, 0, float... |
class TestTokenBlockDataset(unittest.TestCase):
def _build_dataset(self, data, **kwargs):
sizes = [len(x) for x in data]
underlying_ds = test_utils.TestDataset(data)
return TokenBlockDataset(underlying_ds, sizes, **kwargs)
def test_eos_break_mode(self):
data = [torch.tensor([... |
def mock_trainer(epoch, num_updates, iterations_in_epoch):
trainer = MagicMock()
trainer.load_checkpoint.return_value = {'train_iterator': {'epoch': epoch, 'iterations_in_epoch': iterations_in_epoch, 'shuffle': False}}
trainer.get_num_updates.return_value = num_updates
return trainer
|
def mock_dict():
d = MagicMock()
d.pad.return_value = 1
d.eos.return_value = 2
d.unk.return_value = 3
return d
|
def get_trainer_and_epoch_itr(epoch, epoch_size, num_updates, iterations_in_epoch):
tokens = torch.LongTensor(list(range(epoch_size))).view(1, (- 1))
tokens_ds = data.TokenBlockDataset(tokens, sizes=[tokens.size((- 1))], block_size=1, pad=0, eos=1, include_targets=False)
trainer = mock_trainer(epoch, num_... |
class TestLoadCheckpoint(unittest.TestCase):
def setUp(self):
self.args_mock = MagicMock()
self.args_mock.optimizer_overrides = '{}'
self.args_mock.reset_dataloader = False
self.args_mock.reset_meters = False
self.args_mock.reset_optimizer = False
self.patches = {'... |
class TestUtils(unittest.TestCase):
def test_convert_padding_direction(self):
pad = 1
left_pad = torch.LongTensor([[2, 3, 4, 5, 6], [1, 7, 8, 9, 10], [1, 1, 1, 11, 12]])
right_pad = torch.LongTensor([[2, 3, 4, 5, 6], [7, 8, 9, 10, 1], [11, 12, 1, 1, 1]])
self.assertAlmostEqual(rig... |
class CrfRnnNet(Fcn8s):
'\n The full CRF-RNN network with the FCN-8s backbone as described in the paper:\n\n Conditional Random Fields as Recurrent Neural Networks,\n S. Zheng, S. Jayasumana, B. Romera-Paredes, V. Vineet, Z. Su, D. Du, C. Huang and P. Torr,\n ICCV 2015 (https://arxiv.org/abs/1502.0324... |
class CrfRnn(nn.Module):
'\n PyTorch implementation of the CRF-RNN module described in the paper:\n\n Conditional Random Fields as Recurrent Neural Networks,\n S. Zheng, S. Jayasumana, B. Romera-Paredes, V. Vineet, Z. Su, D. Du, C. Huang and P. Torr,\n ICCV 2015 (https://arxiv.org/abs/1502.03240).\n ... |
class PermutoFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, q_in, features):
q_out = permuto_cpp.forward(q_in, features)[0]
ctx.save_for_backward(features)
return q_out
@staticmethod
def backward(ctx, grad_q_out):
feature_saved = ctx.saved_tensors[0... |
def _spatial_features(image, sigma):
'\n Return the spatial features as a Tensor\n\n Args:\n image: Image as a Tensor of shape (channels, height, wight)\n sigma: Bandwidth parameter\n\n Returns:\n Tensor of shape [h, w, 2] with spatial features\n '
sigma = float(sigma)
(... |
class AbstractFilter(ABC):
'\n Super-class for permutohedral-based Gaussian filters\n '
def __init__(self, image):
self.features = self._calc_features(image)
self.norm = self._calc_norm(image)
def apply(self, input_):
output = PermutoFunction.apply(input_, self.features)
... |
class SpatialFilter(AbstractFilter):
'\n Gaussian filter in the spatial ([x, y]) domain\n '
def __init__(self, image, gamma):
'\n Create new instance\n\n Args:\n image: Image tensor of shape (3, height, width)\n gamma: Standard deviation\n '
... |
class BilateralFilter(AbstractFilter):
'\n Gaussian filter in the bilateral ([r, g, b, x, y]) domain\n '
def __init__(self, image, alpha, beta):
'\n Create new instance\n\n Args:\n image: Image tensor of shape (3, height, width)\n alpha: Smoothness (spatial... |
class DenseCRFParams(object):
'\n Parameters for the DenseCRF model\n '
def __init__(self, alpha=160.0, beta=3.0, gamma=3.0, spatial_ker_weight=3.0, bilateral_ker_weight=5.0):
'\n Default values were taken from https://github.com/sadeepj/crfasrnn_keras. More details about these parameter... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--weights', help='Path to the .pth file (download from https://tinyurl.com/crfasrnn-weights-pth)', required=True)
parser.add_argument('--image', help='Path to the input image', required=True)
parser.add_argument('--output', help='Path... |
def main():
input_file = 'image.jpg'
output_file = 'labels.png'
(img_data, img_h, img_w, size) = util.get_preprocessed_image(input_file)
saved_weights_path = 'crfasrnn_weights.pth'
model = CrfRnnNet()
model.load_state_dict(torch.load(saved_weights_path))
model.eval()
out = model.forwar... |
class CrossEntropyLoss2d(nn.Module):
def __init__(self, weight=None):
super().__init__()
self.loss = nn.NLLLoss2d(weight)
def forward(self, outputs, targets):
return self.loss(F.log_softmax(outputs), targets)
|
class MyDataset(torch.utils.data.Dataset):
def __init__(self, imList, labelList, transform=None):
self.imList = imList
self.labelList = labelList
self.transform = transform
def __len__(self):
return len(self.imList)
def __getitem__(self, idx):
image_name = self.i... |
class iouEval():
def __init__(self, nClasses):
self.nClasses = nClasses
self.reset()
def reset(self):
self.overall_acc = 0
self.per_class_acc = np.zeros(self.nClasses, dtype=np.float32)
self.per_class_iu = np.zeros(self.nClasses, dtype=np.float32)
self.mIOU = ... |
class CBR(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm2d(nOut, momentum=0.95, eps=0.001)
self.act =... |
class CB(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm2d(nOut, momentum=0.95, eps=0.001)
def forward(se... |
class C(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
def forward(self, input):
output = self.conv(input)
return outpu... |
class BasicResidualBlock(nn.Module):
def __init__(self, nIn, nOut, prob=0.03):
super().__init__()
self.c1 = CBR(nIn, nOut, 3, 1)
self.c2 = CB(nOut, nOut, 3, 1)
self.act = nn.ReLU(True)
def forward(self, input):
output = self.c1(input)
output = self.c2(output)
... |
class DownSamplerA(nn.Module):
def __init__(self, nIn, nOut):
super().__init__()
self.conv = CBR(nIn, nOut, 3, 2)
def forward(self, input):
output = self.conv(input)
return output
|
class BR(nn.Module):
def __init__(self, nOut):
super().__init__()
self.bn = nn.BatchNorm2d(nOut, momentum=0.95, eps=0.001)
self.act = nn.ReLU(True)
def forward(self, input):
output = self.bn(input)
output = self.act(output)
return output
|
class CDilated(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1, d=1):
super().__init__()
padding = (int(((kSize - 1) / 2)) * d)
self.conv = nn.Conv2d(nIn, nOut, (kSize, kSize), stride=stride, padding=(padding, padding), bias=False, dilation=d)
def forward(self, input):
... |
class DilatedParllelResidualBlockB1(nn.Module):
'\n ESP Block from ESPNet. See details here: ESPNet: Efficient Spatial Pyramid of Dilated Convolutions for Semantic Segmentation\n Link: https://arxiv.org/abs/1803.06815\n '
def __init__(self, nIn, nOut, prob=0.03):
super().__init__()
k... |
class PSPDec(nn.Module):
'\n Inspired or Adapted from Pyramid Scene Network paper\n Link: https://arxiv.org/abs/1612.01105\n '
def __init__(self, nIn, nOut, downSize, upSize=48):
super().__init__()
self.features = nn.Sequential(nn.AdaptiveAvgPool2d(downSize), nn.Conv2d(nIn, nOut, 1, ... |
class ResNetC1(nn.Module):
'\n This model uses ESP blocks for encoding and PSP blocks for decoding\n '
def __init__(self, classes):
super().__init__()
self.level1 = CBR(3, 16, 7, 2)
self.p01 = PSPDec((16 + classes), classes, 160, 192)
self.p02 = PSPDec((16 + classes), cl... |
class ResNetD1(nn.Module):
'\n This model uses ResNet blocks for encoding and PSP blocks for decoding\n '
def __init__(self, classes):
super().__init__()
self.level1 = CBR(3, 16, 7, 2)
self.p01 = PSPDec((16 + classes), classes, 160, 192)
self.p02 = PSPDec((16 + c... |
def make_dot(var, params=None):
' Produces Graphviz representation of PyTorch autograd graph\n Blue nodes are the Variables that require grad, orange are Tensors\n saved for backward in torch.autograd.Function\n Args:\n var: output Variable\n params: dict of (name, Variable) to add names to... |
def val(args, val_loader, model, criterion):
model.eval()
iouEvalVal = iouEval(args.classes)
epoch_loss = []
total_batches = len(val_loader)
for (i, (input, target)) in enumerate(val_loader):
start_time = time.time()
if (args.onGPU == True):
input = input.cuda()
... |
def train(args, train_loader, model, criterion, optimizer, epoch):
model.train()
iouEvalTrain = iouEval(args.classes)
epoch_loss = []
total_batches = len(train_loader)
for (i, (input, target)) in enumerate(train_loader):
start_time = time.time()
if (args.onGPU == True):
... |
def save_checkpoint(state, filenameCheckpoint='checkpoint.pth.tar'):
torch.save(state, filenameCheckpoint)
|
def trainValidateSegmentation(args):
if (not os.path.isfile(args.cached_data_file)):
dataLoader = ld.LoadData(args.data_dir, args.classes, args.cached_data_file)
if (dataLoader is None):
print('Error while processing the data. Please check')
exit((- 1))
data = dataL... |
class CrossEntropyLoss2d(nn.Module):
def __init__(self, weight=None):
super().__init__()
self.loss = nn.NLLLoss2d(weight)
def forward(self, outputs, targets):
return self.loss(F.log_softmax(outputs), targets)
|
class MyDataset(torch.utils.data.Dataset):
def __init__(self, imList, labelList, diagList, transform=None):
self.imList = imList
self.labelList = labelList
self.diagList = diagList
self.transform = transform
def __len__(self):
return len(self.imList)
def __getite... |
class iouEval():
def __init__(self, nClasses):
self.nClasses = nClasses
self.reset()
def reset(self):
self.overall_acc = 0
self.per_class_acc = np.zeros(self.nClasses, dtype=np.float32)
self.per_class_iu = np.zeros(self.nClasses, dtype=np.float32)
self.mIOU = ... |
class CBR(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm2d(nOut, momentum=0.95, eps=0.001)
self.act =... |
class CB(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm2d(nOut, momentum=0.95, eps=0.001)
def forward(se... |
class C(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
def forward(self, input):
output = self.conv(input)
return outpu... |
class DownSampler(nn.Module):
def __init__(self, nIn, nOut):
super().__init__()
self.conv = nn.Conv2d(nIn, (nOut - nIn), 3, stride=2, padding=1, bias=False)
self.pool = nn.AvgPool2d(3, stride=2, padding=1)
self.bn = nn.BatchNorm2d(nOut, momentum=0.95, eps=0.001)
self.act =... |
class BasicResidualBlock(nn.Module):
def __init__(self, nIn, nOut, prob=0.03):
super().__init__()
self.c1 = CBR(nIn, nOut, 3, 1)
self.c2 = CB(nOut, nOut, 3, 1)
self.act = nn.ReLU(True)
def forward(self, input):
output = self.c1(input)
output = self.c2(output)
... |
class DownSamplerA(nn.Module):
def __init__(self, nIn, nOut):
super().__init__()
self.conv = CBR(nIn, nOut, 3, 2)
def forward(self, input):
output = self.conv(input)
return output
|
class BR(nn.Module):
def __init__(self, nOut):
super().__init__()
self.bn = nn.BatchNorm2d(nOut, momentum=0.95, eps=0.001)
self.act = nn.ReLU(True)
def forward(self, input):
output = self.bn(input)
output = self.act(output)
return output
|
class CDilated(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1, d=1):
super().__init__()
padding = (int(((kSize - 1) / 2)) * d)
self.conv = nn.Conv2d(nIn, nOut, (kSize, kSize), stride=stride, padding=(padding, padding), bias=False, dilation=d)
def forward(self, input):
... |
class CDilated1(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1, d=1):
super().__init__()
padding = (int(((kSize - 1) / 2)) * d)
self.conv = nn.Conv2d(nIn, nOut, (kSize, kSize), stride=stride, padding=(padding, padding), bias=False, dilation=d)
self.br = BR(nOut)
de... |
class DilatedParllelResidualBlockB(nn.Module):
def __init__(self, nIn, nOut, prob=0.03):
super().__init__()
n = int((nOut / 5))
n1 = (nOut - (4 * n))
self.c1 = C(nIn, n, 1, 1)
self.d1 = CDilated(n, n1, 3, 1, 1)
self.d2 = CDilated(n, n, 3, 1, 2)
self.d4 = CD... |
class DilatedParllelResidualBlockB1(nn.Module):
def __init__(self, nIn, nOut, prob=0.03):
super().__init__()
n = int((nOut / 4))
n1 = (nOut - (3 * n))
self.c1 = C(nIn, n, 3, 1)
self.d1 = CDilated(n, n1, 3, 1, 1)
self.d2 = CDilated(n, n, 3, 1, 2)
self.d4 = C... |
class PSPDec(nn.Module):
def __init__(self, nIn, nOut, downSize, upSize=48):
super().__init__()
self.features = nn.Sequential(nn.AdaptiveAvgPool2d(downSize), nn.Conv2d(nIn, nOut, 1, bias=False), nn.BatchNorm2d(nOut, momentum=0.95, eps=0.001), nn.ReLU(True), nn.Upsample(size=upSize, mode='bilinear... |
class ResNetC1(nn.Module):
'\n Segmentation model with ESP as the encoding block.\n This is the same as in stage 1\n '
def __init__(self, classes):
super().__init__()
self.level1 = CBR(3, 16, 7, 2)
self.p01 = PSPDec((16 + classes), classes, 160, 192)
self.p02 ... |
class ResNetC1_YNet(nn.Module):
'\n Jointly learning the segmentation and classification with ESP as encoding blocks\n '
def __init__(self, classes, diagClasses, segNetFile=None):
super().__init__()
self.level4_0 = DownSamplerA(512, 128)
self.level4_1 = DilatedParllelResidualBlo... |
class ResNetD1(nn.Module):
'\n Segmentation model with RCB as encoding blocks.\n This is the same as in Stage 1\n '
def __init__(self, classes):
super().__init__()
self.level1 = CBR(3, 16, 7, 2)
self.p01 = PSPDec((16 + classes), classes, 160, 192)
self.p02 = P... |
class ResNetD1_YNet(nn.Module):
'\n Jointly learning the segmentation and classification with RCB as encoding blocks\n '
def __init__(self, classes, diagClasses, segNetFile=None):
super().__init__()
self.level4_0 = DownSamplerA(512, 128)
self.level4_1 = BasicResidualBloc... |
def make_dot(var, params=None):
' Produces Graphviz representation of PyTorch autograd graph\n Blue nodes are the Variables that require grad, orange are Tensors\n saved for backward in torch.autograd.Function\n Args:\n var: output Variable\n params: dict of (name, Variable) to add names to... |
def val(args, val_loader, model, criterion, criterion1):
model.eval()
iouEvalVal = iouEval(args.classes)
iouDiagEvalVal = iouEval(args.diagClasses)
epoch_loss = []
class_loss = []
total_batches = len(val_loader)
for (i, (input, target, target2)) in enumerate(val_loader):
start_time... |
def train(args, train_loader, model, criterion, criterion1, optimizer, epoch):
model.train()
iouEvalTrain = iouEval(args.classes)
iouDiagEvalTrain = iouEval(args.diagClasses)
epoch_loss = []
class_loss = []
total_batches = len(train_loader)
for (i, (input, target, target2)) in enumerate(tr... |
def save_checkpoint(state, filenameCheckpoint='checkpoint.pth.tar'):
torch.save(state, filenameCheckpoint)
|
def trainValidateSegmentation(args):
if (not os.path.isfile(args.cached_data_file)):
dataLoader = ld.LoadData(args.data_dir, args.classes, args.diagClasses, args.cached_data_file)
if (dataLoader == None):
print('Error while caching the data. Please check')
exit((- 1))
... |
class Data():
def __init__(self, args):
kwargs = {}
if (not args.cpu):
kwargs['collate_fn'] = default_collate
kwargs['pin_memory'] = True
else:
kwargs['collate_fn'] = default_collate
kwargs['pin_memory'] = False
self.loader_train = N... |
class Benchmark(srdata.SRData):
def __init__(self, args, train=True):
super(Benchmark, self).__init__(args, train, benchmark=True)
def _scan(self):
list_hr = []
list_lr = [[] for _ in self.scale]
for entry in os.scandir(self.dir_hr):
filename = os.path.splitext(en... |
class Demo(data.Dataset):
def __init__(self, args, train=False):
self.args = args
self.name = 'Demo'
self.scale = args.scale
self.idx_scale = 0
self.train = False
self.benchmark = False
self.filelist = []
for f in os.listdir(args.dir_demo):
... |
class DIV2K(srdata.SRData):
def __init__(self, args, train=True):
super(DIV2K, self).__init__(args, train)
self.repeat = (args.test_every // (args.n_train // args.batch_size))
def _scan(self):
list_hr = []
list_lr = [[] for _ in self.scale]
if self.train:
... |
class MyImage(data.Dataset):
def __init__(self, args, train=False):
self.args = args
self.train = False
self.name = 'MyImage'
self.scale = args.scale
self.idx_scale = 0
apath = ((((args.testpath + '/') + args.testset) + '/x') + str(args.scale[0]))
self.file... |
def _ms_loop(dataset, index_queue, data_queue, done_event, collate_fn, scale, seed, init_fn, worker_id):
try:
collate._use_shared_memory = True
signal_handling._set_worker_signal_handlers()
torch.set_num_threads(1)
random.seed(seed)
torch.manual_seed(seed)
data_queu... |
class _MSDataLoaderIter(_DataLoaderIter):
def __init__(self, loader):
self.dataset = loader.dataset
self.scale = loader.scale
self.collate_fn = loader.collate_fn
self.batch_sampler = loader.batch_sampler
self.num_workers = loader.num_workers
self.pin_memory = (load... |
class MSDataLoader(DataLoader):
def __init__(self, cfg, *args, **kwargs):
super(MSDataLoader, self).__init__(*args, **kwargs, num_workers=cfg.n_threads)
self.scale = cfg.scale
def __iter__(self):
return _MSDataLoaderIter(self)
|
class Adversarial(nn.Module):
def __init__(self, args, gan_type):
super(Adversarial, self).__init__()
self.gan_type = gan_type
self.gan_k = args.gan_k
self.discriminator = discriminator.Discriminator(args, gan_type)
if (gan_type != 'WGAN_GP'):
self.optimizer = ... |
class Discriminator(nn.Module):
def __init__(self, args, gan_type='GAN'):
super(Discriminator, self).__init__()
in_channels = 3
out_channels = 64
depth = 7
bn = True
act = nn.LeakyReLU(negative_slope=0.2, inplace=True)
m_features = [common.BasicBlock(args.n... |
class VGG(nn.Module):
def __init__(self, conv_index, rgb_range=1):
super(VGG, self).__init__()
vgg_features = models.vgg19(pretrained=True).features
modules = [m for m in vgg_features]
if (conv_index == '22'):
self.vgg = nn.Sequential(*modules[:8])
elif (conv_i... |
def default_conv(in_channels, out_channels, kernel_size, bias=True):
return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias)
|
class MeanShift(nn.Conv2d):
def __init__(self, rgb_range, rgb_mean, rgb_std, sign=(- 1)):
super(MeanShift, self).__init__(3, 3, kernel_size=1)
std = torch.Tensor(rgb_std)
self.weight.data = torch.eye(3).view(3, 3, 1, 1)
self.weight.data.div_(std.view(3, 1, 1, 1))
self.bias... |
class BasicBlock(nn.Sequential):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)):
m = [nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), stride=stride, bias=bias)]
if bn:
m.append(nn.BatchNorm2d(o... |
class ResBlock(nn.Module):
def __init__(self, conv, n_feat, kernel_size, bias=True, bn=False, act=nn.ReLU(True), res_scale=1):
super(ResBlock, self).__init__()
m = []
for i in range(2):
m.append(conv(n_feat, n_feat, kernel_size, bias=bias))
if bn:
m... |
class Upsampler(nn.Sequential):
def __init__(self, conv, scale, n_feat, bn=False, act=False, bias=True):
m = []
if ((scale & (scale - 1)) == 0):
for _ in range(int(math.log(scale, 2))):
m.append(conv(n_feat, (4 * n_feat), 3, bias))
m.append(nn.PixelShuf... |
def make_model(args, parent=False):
return DRLN(args)
|
class CALayer(nn.Module):
def __init__(self, channel, reduction=16):
super(CALayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.c1 = ops.BasicBlock(channel, (channel // reduction), 3, 1, 3, 3)
self.c2 = ops.BasicBlock(channel, (channel // reduction), 3, 1, 5, 5)
... |
class Block(nn.Module):
def __init__(self, in_channels, out_channels, group=1):
super(Block, self).__init__()
self.r1 = ops.ResidualBlock(in_channels, out_channels)
self.r2 = ops.ResidualBlock((in_channels * 2), (out_channels * 2))
self.r3 = ops.ResidualBlock((in_channels * 4), (o... |
class DRLN(nn.Module):
def __init__(self, args):
super(DRLN, self).__init__()
self.scale = args.scale[0]
chs = 64
self.sub_mean = ops.MeanShift((0.4488, 0.4371, 0.404), sub=True)
self.add_mean = ops.MeanShift((0.4488, 0.4371, 0.404), sub=False)
self.head = nn.Conv2... |
def init_weights(modules):
pass
|
class MeanShift(nn.Module):
def __init__(self, mean_rgb, sub):
super(MeanShift, self).__init__()
sign = ((- 1) if sub else 1)
r = (mean_rgb[0] * sign)
g = (mean_rgb[1] * sign)
b = (mean_rgb[2] * sign)
self.shifter = nn.Conv2d(3, 3, 1, 1, 0)
self.shifter.wei... |
class BasicBlock(nn.Module):
def __init__(self, in_channels, out_channels, ksize=3, stride=1, pad=1, dilation=1):
super(BasicBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channels, out_channels, ksize, stride, pad, dilation), nn.ReLU(inplace=True))
init_weights(self.modul... |
class GBasicBlock(nn.Module):
def __init__(self, in_channels, out_channels, ksize=3, stride=1, pad=1, dilation=1):
super(GBasicBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channels, out_channels, ksize, stride, pad, dilation, groups=4), nn.ReLU(inplace=True))
init_weight... |
class BasicBlockSig(nn.Module):
def __init__(self, in_channels, out_channels, ksize=3, stride=1, pad=1):
super(BasicBlockSig, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channels, out_channels, ksize, stride, pad), nn.Sigmoid())
init_weights(self.modules)
def forward(self... |
class GBasicBlockSig(nn.Module):
def __init__(self, in_channels, out_channels, ksize=3, stride=1, pad=1):
super(GBasicBlockSig, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channels, out_channels, ksize, stride, pad, groups=4), nn.Sigmoid())
init_weights(self.modules)
def ... |
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(ResidualBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channels, out_channels, 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, 3, 1, 1))
init_weights(self.modules)
... |
class GResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(GResidualBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channels, out_channels, 3, 1, 1, groups=4), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, 1, 1, 0))
init_weights(sel... |
class EResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, group=1):
super(EResidualBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channels, out_channels, 3, 1, 1, groups=group), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, 3, 1, 1, groups=group... |
class ConvertBlock(nn.Module):
def __init__(self, in_channels, out_channels, blocks):
super(ConvertBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d((in_channels * blocks), ((out_channels * blocks) // 2), 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(((out_channels * blocks) // 2), ((out_c... |
class UpsampleBlock(nn.Module):
def __init__(self, n_channels, scale, multi_scale, group=1):
super(UpsampleBlock, self).__init__()
if multi_scale:
self.up2 = _UpsampleBlock(n_channels, scale=2, group=group)
self.up3 = _UpsampleBlock(n_channels, scale=3, group=group)
... |
class _UpsampleBlock(nn.Module):
def __init__(self, n_channels, scale, group=1):
super(_UpsampleBlock, self).__init__()
modules = []
if ((scale == 2) or (scale == 4) or (scale == 8)):
for _ in range(int(math.log(scale, 2))):
modules += [nn.Conv2d(n_channels, (4... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.