code stringlengths 17 6.64M |
|---|
def run(config_dict):
data_module = config_dict['data-module']
model_module = config_dict['model-module']
training_module = config_dict['training-module']
evaluation_module = config_dict.get('evaluation-module', None)
mode = config_dict['mode']
DataClass = importlib.import_module(data_module).... |
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.noise_g]
for entry in os.scandir(self.dir_hr):
filename = os.path.splitext(... |
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.noise_g]
if self.train:
... |
class MyImage(data.Dataset):
def __init__(self, args, train=False):
self.args = args
self.train = False
self.name = 'MyImage'
self.noise_g = args.noise_g
self.idx_scale = 0
apath = ((((args.testpath + '/') + args.testset) + '/X') + str(args.noise_g[0]))
sel... |
def _ms_loop(dataset, index_queue, data_queue, collate_fn, scale, seed, init_fn, worker_id):
global _use_shared_memory
_use_shared_memory = True
_set_worker_signal_handlers()
torch.set_num_threads(1)
torch.manual_seed(seed)
while True:
r = index_queue.get()
if (r is None):
... |
class _MSDataLoaderIter(_DataLoaderIter):
def __init__(self, loader):
self.dataset = loader.dataset
self.noise_g = loader.noise_g
self.collate_fn = loader.collate_fn
self.batch_sampler = loader.batch_sampler
self.num_workers = loader.num_workers
self.pin_memory = (... |
class MSDataLoader(DataLoader):
def __init__(self, args, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, collate_fn=default_collate, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None):
super(MSDataLoader, self).__init__(dataset, batch_size=batch_size, shuffle=shuff... |
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 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 Merge_Run(nn.Module):
def __init__(self, in_channels, out_channels, ksize=3, stride=1, pad=1, dilation=1):
super(Merge_Run, self).__init__()
self.body1 = nn.Sequential(nn.Conv2d(in_channels, out_channels, ksize, stride, pad), nn.ReLU(inplace=True))
self.body2 = nn.Sequential(nn.Conv... |
class Merge_Run_dual(nn.Module):
def __init__(self, in_channels, out_channels, ksize=3, stride=1, pad=1, dilation=1):
super(Merge_Run_dual, self).__init__()
self.body1 = nn.Sequential(nn.Conv2d(in_channels, out_channels, ksize, stride, pad), nn.ReLU(inplace=True), nn.Conv2d(in_channels, out_chann... |
class BasicBlock(nn.Module):
def __init__(self, in_channels, out_channels, ksize=3, stride=1, pad=1):
super(BasicBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channels, out_channels, ksize, stride, pad), nn.ReLU(inplace=True))
init_weights(self.modules)
def forward(s... |
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 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 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 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... |
def make_model(args, parent=False):
return RIDNET(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), 1, 1, 0)
self.c2 = ops.BasicBlockSig((channel // reduction), channel, 1, 1, 0)
... |
class Block(nn.Module):
def __init__(self, in_channels, out_channels, group=1):
super(Block, self).__init__()
self.r1 = ops.Merge_Run_dual(in_channels, out_channels)
self.r2 = ops.ResidualBlock(in_channels, out_channels)
self.r3 = ops.EResidualBlock(in_channels, out_channels)
... |
class RIDNET(nn.Module):
def __init__(self, args):
super(RIDNET, self).__init__()
n_feats = args.n_feats
kernel_size = 3
reduction = args.reduction
rgb_mean = (0.4488, 0.4371, 0.404)
rgb_std = (1.0, 1.0, 1.0)
self.sub_mean = common.MeanShift(args.rgb_range,... |
def set_template(args):
if (args.template.find('jpeg') >= 0):
args.data_train = 'DIV2K_jpeg'
args.data_test = 'DIV2K_jpeg'
args.epochs = 200
args.lr_decay = 100
if (args.template.find('EDSR_paper') >= 0):
args.model = 'EDSR'
args.n_resblocks = 32
args.n_... |
class Trainer():
def __init__(self, args, loader, my_model, my_loss, ckp):
self.args = args
self.noise_g = args.noise_g
self.ckp = ckp
self.loader_train = loader.loader_train
self.loader_test = loader.loader_test
self.model = my_model
self.loss = my_loss
... |
def main(_):
pp.pprint(flags.FLAGS.__flags)
if (not os.path.exists(FLAGS.checkpoint_dir)):
os.makedirs(FLAGS.checkpoint_dir)
if (not os.path.exists(FLAGS.sample_dir)):
os.makedirs(FLAGS.sample_dir)
filenames = os.listdir('test_real')
data_dir = os.path.join(os.getcwd(), 'test_real'... |
class batch_norm(object):
def __init__(self, epsilon=1e-05, momentum=0.9, name='batch_norm'):
with tf.variable_scope(name):
self.epsilon = epsilon
self.momentum = momentum
self.name = name
def __call__(self, x, train=True):
return tf.contrib.layers.batch_n... |
def conv_cond_concat(x, y):
'Concatenate conditioning vector on feature map axis.'
x_shapes = x.get_shape()
y_shapes = y.get_shape()
return concat([x, (y * tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]]))], 3)
|
def conv2d(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, padding='SAME', name='conv2d'):
with tf.variable_scope(name):
w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[(- 1)], output_dim], initializer=tf.truncated_normal_initializer(stddev=stddev))
conv = tf.nn.conv2d(input_, ... |
def conv2d_xavier(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, padding='SAME', name='conv2d'):
with tf.variable_scope(name):
w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[(- 1)], output_dim], initializer=tf.contrib.layers.xavier_initializer_conv2d())
conv = tf.nn.conv2d(in... |
def deconv2d(input_, output_shape, k_h=3, k_w=3, d_h=1, d_w=1, stddev=0.02, name='deconv2d', with_w=False):
with tf.variable_scope(name):
w = tf.get_variable('w', [k_h, k_w, output_shape[(- 1)], input_.get_shape()[(- 1)]], initializer=tf.random_normal_initializer(stddev=stddev))
try:
d... |
def lrelu(x, leak=0.2, name='lrelu'):
return tf.maximum(x, (leak * x))
|
def linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, with_w=False):
shape = input_.get_shape().as_list()
with tf.variable_scope((scope or 'Linear')):
matrix = tf.get_variable('Matrix', [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev))
bias = ... |
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
|
def conv(inputs, kernel_size, output_num, stride_size=1, init_bias=0.0, conv_padding='SAME', stddev=0.01, activation_func=tf.nn.relu):
input_size = inputs.get_shape().as_list()[(- 1)]
conv_weights = tf.Variable(tf.random_normal([kernel_size, kernel_size, input_size, output_num], dtype=tf.float32, stddev=stdde... |
def fc(inputs, output_size, init_bias=0.0, activation_func=tf.nn.relu, stddev=0.01):
input_shape = inputs.get_shape().as_list()
if (len(input_shape) == 4):
fc_weights = tf.Variable(tf.random_normal([((input_shape[1] * input_shape[2]) * input_shape[3]), output_size], dtype=tf.float32, stddev=stddev), n... |
def lrn(inputs, depth_radius=2, alpha=0.0001, beta=0.75, bias=1.0):
return tf.nn.local_response_normalization(inputs, depth_radius=depth_radius, alpha=alpha, beta=beta, bias=bias)
|
def transform(images):
return ((np.array(images) / 127.5) - 1.0)
|
def inverse_transform(images):
return ((images + 1.0) / 2)
|
def prepare_data(sess, dataset):
"\n Args:\n dataset: choose train dataset or test dataset\n \n For train dataset, output data would be ['.../t1.bmp', '.../t2.bmp', ..., '.../t99.bmp']\n \n "
filenames = os.listdir(dataset)
data_dir = os.path.join(os.getcwd(), dataset)
data = glob.glob(os.... |
def imread(path, is_grayscale=False):
'\n Read image using its path.\n Default value is gray-scale, and image is read by YCbCr format as the paper said.\n '
if is_grayscale:
return scipy.misc.imread(path, flatten=True).astype(np.float)
else:
return scipy.misc.imread(path).astype(np.floa... |
def imsave(image, path):
imsaved = inverse_transform(image).astype(np.float)
return scipy.misc.imsave(path, imsaved)
|
def get_image(image_path, is_grayscale=False):
image = imread(image_path, is_grayscale)
return transform(image)
|
def get_lable(image_path, is_grayscale=False):
image = imread(image_path, is_grayscale)
return (image / 255.0)
|
def imsave_lable(image, path):
return scipy.misc.imsave(path, (image * 255))
|
def _extract_target_file_name(img_src, img_dst, method=None):
'\n '
spl_src = img_src.split('/')
spl_dst = img_dst.split('/')
if ((len(spl_src) > 1) and (len(spl_dst) > 1)):
tmp = ((((((spl_src[(- 2)] + '_') + spl_src[(- 1)][:(- 4)]) + '__') + spl_dst[(- 2)]) + '_') + spl_dst[(- 1)][:(- 4)]... |
def average_checkpoints(model_checkpoints):
params_dict = collections.OrderedDict()
params_keys = None
new_model_params = None
num_models = len(model_checkpoints)
for ckpt in model_checkpoints:
model_params = torch.load(ckpt, map_location='cpu')
if (new_model_params is None):
... |
def main():
parser = argparse.ArgumentParser(description='Average checkpoints')
parser.add_argument('--checkpoint-dir', required=True, type=str, default='results', help='Checkpoint directory location.')
parser.add_argument('--best-n', required=True, type=int, default=5, help='Num of epochs to average')
... |
def general_opts(parser):
group = parser.add_argument_group('General Options')
group.add_argument('--log-interval', type=int, default=5, help='After how many iterations, we should print logs')
group.add_argument('--epochs', type=int, default=100, help='Number of training epochs')
group.add_argument('-... |
def visualization_opts(parser):
group = parser.add_argument_group('Visualization options')
group.add_argument('--im-or-file', type=str, required=True, help='Name of the image or list of images in file to be visualized')
group.add_argument('--is-type-file', action='store_true', default=False, help='Is it a... |
def get_opts(parser):
'General options'
parser = general_opts(parser)
'Optimzier options'
parser = get_optimizer_opts(parser)
'Loss function options'
parser = get_criteria_opts(parser)
'Medical Image model options'
parser = get_model_opts(parser)
'Dataset related options'
parse... |
def get_config(is_visualization=False):
parser = argparse.ArgumentParser(description='Medical Imaging')
parser = get_opts(parser)
if is_visualization:
parser = visualization_opts(parser)
args = parser.parse_args()
random.seed(args.seed)
torch.manual_seed(args.seed)
torch.set_num_th... |
class CrossEntropyWithLabelSmoothing(nn.Module):
def __init__(self, ls_eps=0.1, ignore_idx=None, reduce=True, reduction='mean', *args, **kwargs):
super(CrossEntropyWithLabelSmoothing, self).__init__()
self.ls_eps = ls_eps
self.ignore_idx = ignore_idx
self.reduce = reduce
s... |
class BBWSIDataset(torch.utils.data.Dataset):
'\n This class defines the data loader for Breast biopsy WSIs\n '
def __init__(self, img_dir, split_file, img_extn='tiff', delimeter=','):
'\n :param img_dir: Location of the directory that contains WSIs\n :param split_file: Which file... |
def get_bag_word_pairs(bag_word_size: tuple, scale_factor: int, scale_multipliers: list):
'\n This function returns a list of bag-word size pairs\n :param bag_word_size: Default bag-word size\n :param scale_factor: Factor by which we will increase/decrease the word size\n :param scale_multipliers: Lis... |
def gen_collate_fn(batch, bag_word_size: Optional[tuple]=(1024, 256), is_training: Optional[bool]=False, scale_factor: Optional[int]=32, scale_multipliers: Optional[list]=[(- 2), (- 1), 0, 1, 2]):
'\n :param batch: Batch of image names and labels\n :param bag_word_size: Size of the bag and word\n :param ... |
def _load_image_lessthan_2_29(buf, size):
'buf must be a mutable buffer.'
_convert.argb2rgba(buf)
return PIL.Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
|
def _load_image_morethan_2_29(buffer, size):
'buf must be a buffer.'
MAX_PIXELS_PER_LOAD = ((1 << 29) - 1)
PIXELS_PER_LOAD = (1 << 26)
def do_load(buf, size):
'buf can be a string, but should be a ctypes buffer to avoid an\n extra copy in the caller.'
rawmode = (((sys.byteorder... |
class WSIDataset(torch.utils.data.Dataset):
'\n This class defines the data loader for Breast biopsy WSIs\n '
def __init__(self, img_dir, split_file, img_extn='tiff', delimeter=','):
'\n :param img_dir: Location of the directory that contains WSIs\n :param split_file: Which file t... |
def compute_micro_stats(values_a, values_b, eps=1e-08):
sum_a = np.sum(values_a)
sum_b = np.sum(values_b)
micro_sc = (sum_a / ((sum_a + sum_b) + eps))
return micro_sc
|
def compute_macro_stats(values):
return np.mean(values)
|
class CMMetrics(object):
'\n Metrics defined here: https://www.sciencedirect.com/science/article/pii/S2210832718301546\n '
def __init__(self):
super(CMMetrics, self).__init__()
self.eps = 1e-08
def compute_precision(self, tp, fp):
'\n Precision = TP/(TP + FP)\n ... |
def accuracy(output, target, topk=(1,)):
'Computes the precision@k for the specified values of k'
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expa... |
def compute_f1(y_pred: torch.Tensor, y_true: torch.Tensor, n_classes=4, epsilon=1e-07, is_one_hot=False):
if is_one_hot:
assert (y_pred.dim() == y_true.dim())
else:
assert (len(y_pred.size()) == 2)
assert (len(y_true.size()) == 1)
with torch.no_grad():
y_true = (y_true.to(t... |
class Statistics(object):
'\n This class is used to store the training and validation statistics\n '
def __init__(self):
super(Statistics, self).__init__()
self.loss = 0
self.acc = 0
self.eps = 1e-09
self.counter = 1
def update(self, loss, acc):
'\n ... |
class BaseFeatureExtractor(torch.nn.Module):
'\n This class calls different base feature extractors\n '
def __init__(self, opts):
'\n :param opts: Argument list\n '
super(BaseFeatureExtractor, self).__init__()
if (opts.base_extractor == 'espnetv2'):
fro... |
def get_base_extractor_opts(parser):
'Base feature extractor CNN Model details'
group = parser.add_argument_group('CNN Model Details')
group.add_argument('--base-extractor', default='espnetv2', choices=supported_base_models, help='Which CNN model? Default is espnetv2')
group.add_argument('--s', type=f... |
class EESPNet(nn.Module):
'\n This class defines the ESPNetv2 architecture for the ImageNet classification\n '
def __init__(self, args):
'\n :param classes: number of classes in the dataset. Default is 1000 for the ImageNet dataset\n :param s: factor that scales the number of outp... |
class _InvertedResidual(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size, stride, expansion_factor, bn_momentum=0.1):
super(_InvertedResidual, self).__init__()
assert (stride in [1, 2])
assert (kernel_size in [3, 5])
mid_ch = (in_ch * expansion_factor)
self.apply_... |
def _stack(in_ch, out_ch, kernel_size, stride, exp_factor, repeats, bn_momentum):
' Creates a stack of inverted residuals. '
assert (repeats >= 1)
first = _InvertedResidual(in_ch, out_ch, kernel_size, stride, exp_factor, bn_momentum=bn_momentum)
remaining = []
for _ in range(1, repeats):
r... |
def _round_to_multiple_of(val, divisor, round_up_bias=0.9):
' Asymmetric rounding to make `val` divisible by `divisor`. With default\n bias, will round up, unless the number is no more than 10% greater than the\n smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88. '
assert (0.0 < round_up_bi... |
def _get_depths(alpha):
' Scales tensor depths as in reference MobileNet code, prefers rouding up\n rather than down. '
depths = [32, 16, 24, 40, 80, 96, 192, 320]
return [_round_to_multiple_of((depth * alpha), 8) for depth in depths]
|
class MNASNet(torch.nn.Module):
' MNASNet, as described in https://arxiv.org/pdf/1807.11626.pdf. This\n implements the B1 variant of the model.\n >>> model = MNASNet(1000, 1.0)\n >>> x = torch.rand(1, 3, 224, 224)\n >>> y = model(x)\n >>> y.dim()\n 1\n >>> y.nelement()\n 1000\n '
_v... |
def _make_divisible(v, divisor, min_value=None):
'\n This function is taken from the original tf repo.\n It ensures that all layers have a channel number that is divisible by 8\n It can be seen here:\n https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n :par... |
class ConvBNReLU(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):
padding = ((kernel_size - 1) // 2)
super(ConvBNReLU, self).__init__(nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False), nn.BatchNorm2d(out_planes),... |
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, expand_ratio):
super(InvertedResidual, self).__init__()
self.stride = stride
assert (stride in [1, 2])
hidden_dim = int(round((inp * expand_ratio)))
self.use_res_connect = ((self.stride == 1) and (inp ... |
class MobileNetV2(nn.Module):
def __init__(self, num_classes=1000, width_mult=1.0, inverted_residual_setting=None, round_nearest=8, block=None):
'\n MobileNet V2 main class\n\n Args:\n num_classes (int): Number of classes\n width_mult (float): Width multiplier - adjust... |
class MIModel(torch.nn.Module):
'\n Hollistic Attention Network\n '
def __init__(self, n_classes, cnn_feature_sz, out_features, num_bags_words, num_heads=2, dropout=0.4, attn_type='l2', attn_dropout=0.2, attn_fn='tanh', *args, **kwargs):
super(MIModel, self).__init__()
self.project_... |
class SelfAttention(nn.Module):
'\n This class implements the transformer block with multi-head attention and Feed forward network\n '
def __init__(self, in_dim, num_heads=8, p=0.1, *args, **kwargs):
super(SelfAttention, self).__init__()
self.self_attn = MultiHeadAttn(input_dim=in_dim, ... |
class ContextualAttention(torch.nn.Module):
'\n This class implements the contextual attention.\n For example, we used this class to compute bag-to-bag attention where\n one set of bag is directly from CNN, while the other set of bag is obtained after self-attention\n '
def __init__(s... |
class EESP(nn.Module):
'\n This class defines the EESP block, which is based on the following principle\n REDUCE ---> SPLIT ---> TRANSFORM --> MERGE\n '
def __init__(self, nIn, nOut, stride=1, k=4, r_lim=7, down_method='esp'):
'\n :param nIn: number of input channels\n :par... |
class DownSampler(nn.Module):
'\n Down-sampling fucntion that has three parallel branches: (1) avg pooling,\n (2) EESP block with stride of 2 and (3) efficient long-range connection with the input.\n The output feature maps of branches from (1) and (2) are concatenated and then additively fused with (3) ... |
class CBR(nn.Module):
'\n This class defines the convolution layer with batch normalization and PReLU activation\n '
def __init__(self, nIn, nOut, kSize, stride=1, groups=1):
'\n\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize:... |
class BR(nn.Module):
'\n This class groups the batch normalization and PReLU activation\n '
def __init__(self, nOut):
'\n :param nOut: output feature maps\n '
super().__init__()
self.bn = nn.BatchNorm2d(nOut)
self.act = nn.PReLU(nOut)
def forward(s... |
class CB(nn.Module):
'\n This class groups the convolution and batch normalization\n '
def __init__(self, nIn, nOut, kSize, stride=1, groups=1):
'\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param ... |
class C(nn.Module):
'\n This class is for a convolutional layer.\n '
def __init__(self, nIn, nOut, kSize, stride=1, groups=1):
'\n\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: optional st... |
class CDilated(nn.Module):
'\n This class defines the dilated convolution.\n '
def __init__(self, nIn, nOut, kSize, stride=1, d=1, groups=1):
'\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride... |
class CDilatedB(nn.Module):
'\n This class defines the dilated convolution with batch normalization.\n '
def __init__(self, nIn, nOut, kSize, stride=1, d=1, groups=1):
'\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel s... |
class FFN(nn.Module):
def __init__(self, input_dim, scale, output_dim=None, p=0.1, expansion=False):
super(FFN, self).__init__()
output_dim = (input_dim if (output_dim is None) else output_dim)
proj_features = ((input_dim * scale) if expansion else (input_dim // scale))
self.w_1 =... |
class MultiHeadAttn(torch.nn.Module):
def __init__(self, input_dim, out_dim, num_heads=8, dropout=0.1, *args, **kwargs):
super(MultiHeadAttn, self).__init__()
assert ((input_dim % num_heads) == 0)
self.num_heads = num_heads
self.dim_per_head = (input_dim // num_heads)
self... |
def features_from_cnn(input_words, cnn_model, max_bsz_cnn_gpu0, num_gpus, device):
(batch_size, num_bags, num_words, word_channels, word_height, word_height) = input_words.size()
input_words = input_words.contiguous().view((- 1), word_channels, word_height, word_height)
with torch.no_grad():
b_sz ... |
def prediction(words, cnn_model, mi_model, max_bsz_cnn_gpu0, num_gpus, device, *args, **kwargs):
word_features = features_from_cnn(input_words=words, cnn_model=cnn_model, max_bsz_cnn_gpu0=max_bsz_cnn_gpu0, num_gpus=num_gpus, device=device)
word_features = word_features.to(device=device)
output = mi_model(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.