code
stringlengths
17
6.64M
def _raise_key_rename_error(full_key): new_key = _RENAMED_KEYS[full_key] if isinstance(new_key, tuple): msg = (' Note: ' + new_key[1]) new_key = new_key[0] else: msg = '' raise KeyError('Key {} was renamed to {}; please update your config.{}'.format(full_key, new_key, msg))
def _decode_cfg_value(v): 'Decodes a raw config value (e.g., from a yaml config files or command\n line argument) into a Python object.\n ' if isinstance(v, dict): return AttrDict(v) try: v = literal_eval(v) except ValueError: pass except SyntaxError: pass ...
def _check_and_coerce_cfg_value_type(value_a, value_b, key, full_key): 'Checks that `value_a`, which is intended to replace `value_b` is of the\n right type. The type is correct if it matches exactly or is one of a few\n cases in which the type can be easily coerced.\n ' type_b = type(value_b) ty...
def save_object(obj, file_name): 'Save a Python object by pickling it.' file_name = os.path.abspath(file_name) with open(file_name, 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def cache_url(url_or_file, cache_dir): 'Download the file specified by the URL to the cache_dir and return the\n path to the cached file. If the argument is not a URL, simply return it as\n is.\n ' is_url = (re.match('^(?:http)s?://', url_or_file, re.IGNORECASE) is not None) if (not is_url): ...
def assert_cache_file_is_ok(url, file_path): 'Check that cache file has the correct hash.' cache_file_md5sum = _get_file_md5sum(file_path) ref_md5sum = _get_reference_md5sum(url) assert (cache_file_md5sum == ref_md5sum), 'Target URL {} appears to be downloaded to the local cache file {}, but the md5 h...
def _progress_bar(count, total): 'Report download progress.\n Credit:\n https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console/27871113\n ' bar_len = 60 filled_len = int(round(((bar_len * count) / float(total)))) percents = round(((100.0 * count) / float(total)), 1) ...
def download_url(url, dst_file_path, chunk_size=8192, progress_hook=_progress_bar): 'Download url and write it to dst_file_path.\n Credit:\n https://stackoverflow.com/questions/2028517/python-urllib2-progress-hook\n ' response = urllib.request.urlopen(url) total_size = response.info().getheader('...
def _get_file_md5sum(file_name): 'Compute the md5 hash of a file.' hash_obj = hashlib.md5() with open(file_name, 'r') as f: hash_obj.update(f.read()) return hash_obj.hexdigest()
def _get_reference_md5sum(url): "By convention the md5 hash for url is stored in url + '.md5sum'." url_md5sum = (url + '.md5sum') md5sum = urllib.request.urlopen(url_md5sum).read().strip() return md5sum
class CosineRestartAnnealingLR(object): def __init__(self, optimizer, T_max, lr_period, lr_step, eta_min=0, last_step=(- 1), use_warmup=False, warmup_mode='linear', warmup_steps=0, warmup_startlr=0, warmup_targetlr=0, use_restart=False): self.use_warmup = use_warmup self.warmup_mode = warmup_mode...
def get_lr_scheduler(config, optimizer, num_examples=None, batch_size=None): if (num_examples is None): num_examples = config.data.num_examples epoch_steps = ((num_examples // batch_size) + 1) if config.optim.use_multi_stage: max_steps = (epoch_steps * config.optim.multi_stage.stage_epochs...
def comp_multadds(model, input_size=(3, 224, 224)): input_size = ((1,) + tuple(input_size)) model = model.cuda() input_data = torch.randn(input_size).cuda() model = add_flops_counting_methods(model) model.start_flops_count() with torch.no_grad(): _ = model(input_data) mult_adds = (...
def comp_multadds_fw(model, input_data, use_gpu=True): model = add_flops_counting_methods(model) if use_gpu: model = model.cuda() model.start_flops_count() with torch.no_grad(): output_data = model(input_data) mult_adds = (model.compute_average_flops_cost() / 1000000.0) return ...
def add_flops_counting_methods(net_main_module): 'Adds flops counting functions to an existing model. After that\n the flops count should be activated and the model should be run on an input\n image.\n Example:\n fcn = add_flops_counting_methods(fcn)\n fcn = fcn.cuda().train()\n fcn.start_flops_...
def compute_average_flops_cost(self): '\n A method that will be available after add_flops_counting_methods() is called\n on a desired net object.\n Returns current mean flops consumption per image.\n ' batches_count = self.__batch_counter__ flops_sum = 0 for module in self.modules(): ...
def start_flops_count(self): '\n A method that will be available after add_flops_counting_methods() is called\n on a desired net object.\n Activates the computation of mean flops consumption per image.\n Call it before you run the network.\n ' add_batch_counter_hook_function(self) self.appl...
def stop_flops_count(self): '\n A method that will be available after add_flops_counting_methods() is called\n on a desired net object.\n Stops computing the mean flops consumption per image.\n Call whenever you want to pause the computation.\n ' remove_batch_counter_hook_function(self) sel...
def reset_flops_count(self): '\n A method that will be available after add_flops_counting_methods() is called\n on a desired net object.\n Resets statistics computed so far.\n ' add_batch_counter_variables_or_reset(self) self.apply(add_flops_counter_variable_or_reset)
def add_flops_mask(module, mask): def add_flops_mask_func(module): if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)): module.__mask__ = mask module.apply(add_flops_mask_func)
def remove_flops_mask(module): module.apply(add_flops_mask_variable_or_reset)
def conv_flops_counter_hook(conv_module, input, output): input = input[0] batch_size = input.shape[0] (output_height, output_width) = output.shape[2:] (kernel_height, kernel_width) = conv_module.kernel_size in_channels = conv_module.in_channels out_channels = conv_module.out_channels conv_...
def linear_flops_counter_hook(linear_module, input, output): input = input[0] batch_size = input.shape[0] overall_flops = ((linear_module.in_features * linear_module.out_features) * batch_size) linear_module.__flops__ += overall_flops
def batch_counter_hook(module, input, output): input = input[0] batch_size = input.shape[0] module.__batch_counter__ += batch_size
def add_batch_counter_variables_or_reset(module): module.__batch_counter__ = 0
def add_batch_counter_hook_function(module): if hasattr(module, '__batch_counter_handle__'): return handle = module.register_forward_hook(batch_counter_hook) module.__batch_counter_handle__ = handle
def remove_batch_counter_hook_function(module): if hasattr(module, '__batch_counter_handle__'): module.__batch_counter_handle__.remove() del module.__batch_counter_handle__
def add_flops_counter_variable_or_reset(module): if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)): module.__flops__ = 0
def add_flops_counter_hook_function(module): if isinstance(module, torch.nn.Conv2d): if hasattr(module, '__flops_handle__'): return handle = module.register_forward_hook(conv_flops_counter_hook) module.__flops_handle__ = handle elif isinstance(module, torch.nn.Linear): ...
def remove_flops_counter_hook_function(module): if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)): if hasattr(module, '__flops_handle__'): module.__flops_handle__.remove() del module.__flops_handle__
def add_flops_mask_variable_or_reset(module): if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)): module.__mask__ = None
class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes, dropRate=0.0): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.relu = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=Fa...
class BottleneckBlock(nn.Module): def __init__(self, in_planes, out_planes, dropRate=0.0): super(BottleneckBlock, self).__init__() inter_planes = (out_planes * 4) self.bn1 = nn.BatchNorm2d(in_planes) self.relu = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(in_planes, inter...
class TransitionBlock(nn.Module): def __init__(self, in_planes, out_planes, dropRate=0.0): super(TransitionBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.relu = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, padding=...
class DenseBlock(nn.Module): def __init__(self, nb_layers, in_planes, growth_rate, block, dropRate=0.0): super(DenseBlock, self).__init__() self.layer = self._make_layer(block, in_planes, growth_rate, nb_layers, dropRate) def _make_layer(self, block, in_planes, growth_rate, nb_layers, dropRa...
class DenseNet3(nn.Module): def __init__(self, depth, num_classes, growth_rate=12, reduction=0.5, bottleneck=True, dropRate=0.0): super(DenseNet3, self).__init__() in_planes = (2 * growth_rate) n = ((depth - 4) / 3) if (bottleneck == True): n = (n / 2) bloc...
class NeuralNet(nn.Module): def __init__(self, input_size, hidden_size_1, hidden_size_2, num_classes): super(NeuralNet, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size_1) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_size_1, hidden_size_2) self.fc3 = nn.L...
class UNet2Sigmoid(nn.Module): def __init__(self, n_channels, n_classes, hidden=32): super(type(self), self).__init__() self.inc = inconv(n_channels, hidden) self.down1 = down(hidden, (hidden * 2)) self.up8 = up((hidden * 2), hidden) self.outc = outconv(hidden, n_classes) ...
def get_dirs(base_dir, data_base): train_dirs = [] test_dirs = [] test_base = os.path.join(data_base, 'npy_test') train_base = os.path.join(data_base, 'npy_train') print('------------------------------------------------------------') print('Fetching directories for the test set') print('--...
def adam(params: List[Tensor], grads: List[Tensor], exp_avgs: List[Tensor], exp_avg_sqs: List[Tensor], max_exp_avg_sqs: List[Tensor], state_steps: List[int], *, amsgrad: bool, beta1: float, beta2: float, lr: float, weight_decay: float, eps: float): 'Functional API that performs Adam algorithm computation.\n Se...
class Adam(Optimizer): 'Implements Adam algorithm.\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n The implementation of the L2 penalty follows changes proposed in\n `Decoupled Weight Decay Regularization`_.\n Args:\n params (iterable): iterable of parameters to optim...
class GaussianRF(object): def __init__(self, dim, size, alpha=2, tau=3, sigma=None, boundary='periodic', device=None): self.dim = dim self.device = device if (sigma is None): sigma = (tau ** (0.5 * ((2 * alpha) - self.dim))) k_max = (size // 2) if (dim == 1): ...
def parse_function(example_proto): dics = {'x': tf.io.FixedLenFeature([1000, 4], tf.int64), 'y': tf.io.FixedLenFeature([36], tf.int64)} parsed_example = tf.io.parse_single_example(example_proto, dics) x = tf.reshape(parsed_example['x'], [1000, 4]) y = tf.reshape(parsed_example['y'], [36]) x = tf.c...
def get_train_data(batch_size): filenames = ['./data/traindata-00.tfrecord'] dataset = tf.data.TFRecordDataset(filenames, buffer_size=100000, num_parallel_reads=4) dataset = dataset.shuffle(buffer_size=10000) dataset = dataset.map(map_func=parse_function, num_parallel_calls=tf.data.experimental.AUTOTU...
def get_valid_data(): data = np.load('../deepsea_filtered.npz') x = data['x_val'] y = data['y_val'] return (x, y)
def get_test_data(): filename = '../deepsea_filtered.npz' data = np.load(filename) x = data['x_test'].astype(float) y = data['y_test'] return (x, y)
class DeepSEA(keras.Model): def __init__(self): super(DeepSEA, self).__init__() self.conv_1 = keras.layers.Conv1D(filters=320, kernel_size=8, strides=1, use_bias=False, padding='SAME', activation='relu', kernel_regularizer=tf.keras.regularizers.l2(5e-07), kernel_constraint=tf.keras.constraints.Ma...
def serialize_example(x, y): example = {'x': tf.train.Feature(int64_list=tf.train.Int64List(value=x.flatten())), 'y': tf.train.Feature(int64_list=tf.train.Int64List(value=y.flatten()))} example = tf.train.Features(feature=example) example = tf.train.Example(features=example) serialized_example = examp...
def traindata_to_tfrecord(): filename = '../deepsea_filtered.npz' with np.load(filename) as file: x = file['x_train'] y = file['y_train'] for file_num in range(1): with tf.io.TFRecordWriter(('./data/traindata-%.2d.tfrecord' % file_num)) as writer: for i in tqdm(range((f...
def testdata_to_tfrecord(): filename = '../deepsea_filtered.npz' data = np.load(filename) x = data['x_test'] y = data['y_test'] with tf.io.TFRecordWriter('./data/testdata.tfrecord') as writer: for i in tqdm(range(len(y)), desc='Processing Test Data', ascii=True): example_proto ...
class ECGDataset(Dataset): def __init__(self, data, label, pid=None): self.data = data self.label = label self.pid = pid def __getitem__(self, index): return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long)) def __len_...
def read_data_physionet_4(path, window_size=1000, stride=500): with open(os.path.join(path, 'challenge2017.pkl'), 'rb') as fin: res = pickle.load(fin) all_data = res['data'] for i in range(len(all_data)): tmp_data = all_data[i] tmp_std = np.std(tmp_data) tmp_mean = np.mean(...
def slide_and_cut(X, Y, window_size, stride, output_pid=False, datatype=4): out_X = [] out_Y = [] out_pid = [] n_sample = X.shape[0] mode = 0 for i in range(n_sample): tmp_ts = X[i] tmp_Y = Y[i] if (tmp_Y == 0): i_stride = stride elif (tmp_Y == 1): ...
class NeuralNet(nn.Module): def __init__(self, input_size, hidden_size_1, hidden_size_2, num_classes): super(NeuralNet, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size_1) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_size_1, hidden_size_2) self.fc3 = nn.L...
class MyDataset(Dataset): def __init__(self, data, label): self.data = data self.label = label def __getitem__(self, index): return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long)) def __len__(self): return len(self.d...
class ACNN(nn.Module): '\n \n Input:\n X: (n_samples, n_channel, n_length)\n Y: (n_samples)\n \n Output:\n out: (n_samples)\n \n Pararmetes:\n n_classes: number of classes\n \n ' def __init__(self, in_channels, out_channels, att_channels, n_len_...
class MyDataset(Dataset): def __init__(self, data, label): self.data = data self.label = label def __getitem__(self, index): return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long)) def __len__(self): return len(self.d...
class CNN(nn.Module): '\n \n Input:\n X: (n_samples, n_channel, n_length)\n Y: (n_samples)\n \n Output:\n out: (n_samples)\n \n Pararmetes:\n n_classes: number of classes\n \n ' def __init__(self, in_channels, out_channels, n_len_seg, n_classes,...
class MyDataset(Dataset): def __init__(self, data, label): self.data = data self.label = label def __getitem__(self, index): return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long)) def __len__(self): return len(self.d...
class CRNN(nn.Module): '\n \n Input:\n X: (n_samples, n_channel, n_length)\n Y: (n_samples)\n \n Output:\n out: (n_samples)\n \n Pararmetes:\n n_classes: number of classes\n \n ' def __init__(self, in_channels, out_channels, n_len_seg, n_classes...
class MyDataset(Dataset): def __init__(self, data, label): self.data = data self.label = label def __getitem__(self, index): return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long)) def __len__(self): return len(self.d...
class MyConv1dPadSame(nn.Module): '\n extend nn.Conv1d to support SAME padding\n\n input: (n_sample, in_channels, n_length)\n output: (n_sample, out_channels, (n_length+stride-1)//stride)\n ' def __init__(self, in_channels, out_channels, kernel_size, stride, groups=1): super(MyConv1dPadSa...
class MyMaxPool1dPadSame(nn.Module): '\n extend nn.MaxPool1d to support SAME padding\n\n params:\n kernel_size: kernel size\n stride: the stride of the window. Default value is kernel_size\n \n input: (n_sample, n_channel, n_length)\n ' def __init__(self, kernel_size): su...
class Swish(nn.Module): def forward(self, x): return (x * F.sigmoid(x))
class BasicBlock(nn.Module): '\n Basic Block: \n conv1 -> convk -> conv1\n\n params:\n in_channels: number of input channels\n out_channels: number of output channels\n ratio: ratio of channels to out_channels\n kernel_size: kernel window length\n stride: kernel ste...
class BasicStage(nn.Module): '\n Basic Stage:\n block_1 -> block_2 -> ... -> block_M\n ' def __init__(self, in_channels, out_channels, ratio, kernel_size, stride, groups, i_stage, m_blocks, use_bn=True, use_do=True, verbose=False): super(BasicStage, self).__init__() self.in_chann...
class Net1D(nn.Module): '\n \n Input:\n X: (n_samples, n_channel, n_length)\n Y: (n_samples)\n \n Output:\n out: (n_samples)\n \n params:\n in_channels\n base_filters\n filter_list: list, filters for each stage\n m_blocks_list: list, numbe...
class MyDataset(Dataset): def __init__(self, data, label): self.data = data self.label = label def __getitem__(self, index): return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long)) def __len__(self): return len(self.d...
class MyConv1dPadSame(nn.Module): '\n extend nn.Conv1d to support SAME padding\n ' def __init__(self, in_channels, out_channels, kernel_size, stride, groups=1): super(MyConv1dPadSame, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.k...
class MyMaxPool1dPadSame(nn.Module): '\n extend nn.MaxPool1d to support SAME padding\n ' def __init__(self, kernel_size): super(MyMaxPool1dPadSame, self).__init__() self.kernel_size = kernel_size self.stride = 1 self.max_pool = torch.nn.MaxPool1d(kernel_size=self.kernel_...
class BasicBlock(nn.Module): '\n ResNet Basic Block\n ' def __init__(self, in_channels, out_channels, kernel_size, stride, groups, downsample, use_bn, use_do, is_first_block=False): super(BasicBlock, self).__init__() self.in_channels = in_channels self.kernel_size = kernel_size ...
class ResNet1D(nn.Module): '\n \n Input:\n X: (n_samples, n_channel, n_length)\n Y: (n_samples)\n \n Output:\n out: (n_samples)\n \n Pararmetes:\n in_channels: dim of input, the same as n_channel\n base_filters: number of filters in the first several Co...
def run_exp(base_filters, filter_list, m_blocks_list): dataset = MyDataset(X_train, Y_train) dataset_val = MyDataset(X_test, Y_test) dataset_test = MyDataset(X_test, Y_test) dataloader = DataLoader(dataset, batch_size=batch_size) dataloader_val = DataLoader(dataset_val, batch_size=batch_size, drop...
def train(model, device, train_loader, optimizer): loss_func = torch.nn.CrossEntropyLoss() all_loss = [] prog_iter = tqdm(train_loader, desc='Training', leave=False) for (batch_idx, batch) in enumerate(prog_iter): (input_x, input_y) = tuple((t.to(device) for t in batch)) pred = model(i...
def test(model, device, test_loader, label_test): prog_iter_test = tqdm(test_loader, desc='Testing', leave=False) all_pred_prob = [] for (batch_idx, batch) in enumerate(prog_iter_test): (input_x, input_y) = tuple((t.to(device) for t in batch)) pred = model(input_x) all_pred_prob.ap...
class Network(object): def __init__(self, n_length, base_filters, kernel_size, n_block, n_channel): '\n key parameters to control the model:\n n_length: dimention of input (resolution) [16, 64, 256, 1024, 4096]\n base_filters: number of convolutional filters (width) [8, 16, 3...
def replicate_if_needed(x, min_clip_duration): if (len(x) < min_clip_duration): tile_size = ((min_clip_duration // x.shape[0]) + 1) x = np.tile(x, tile_size)[:min_clip_duration] return x
def process_idx(idx): f = files[idx] fname = f.split('/')[(- 1)].split('.')[0] (x, sr) = sf.read(f) min_clip_duration = int((sr * 1)) parts = [] if (len(x) < min_clip_duration): x = replicate_if_needed(x, min_clip_duration) parts.append(x) else: overlap = int((sr * ...
def process_idx(idx): f = files[idx] fname = f.split('/')[(- 1)] tgt_path = os.path.join(tgt_dir, fname) command = "ffmpeg -loglevel 0 -nostats -i '{}' -ac 1 -ar {} '{}'".format(f, SAMPLE_RATE, tgt_path) sp.call(command, shell=True) if ((idx % 500) == 0): print('Done: {:05d}/{}'.format...
class BidirectionalLSTM(nn.Module): def __init__(self, nIn, nHidden, nOut): super(BidirectionalLSTM, self).__init__() self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True) self.embedding = nn.Linear((nHidden * 2), nOut) def forward(self, input): (recurrent, _) = self.rnn(input...
class ConvReLUBN(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=5, stride=1, padding_size=2): super(ConvReLUBN, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding_size) self.relu = nn.ReLU(inplace=True) self.bn = n...
class CRNN(nn.Module): '\n CRNN model, as described in FSD50k paper Sec 5.B.2\n ' def __init__(self, imgH=96, num_classes=200, nh=64): super(CRNN, self).__init__() assert ((imgH % 16) == 0), 'imgH has to be a multiple of 16' self.kernel_sizes = [5, 5, 5] self.padding_siz...
class _DenseLayer(nn.Module): def __init__(self, num_input_features: int, growth_rate: int, bn_size: int, drop_rate: float, memory_efficient: bool=False) -> None: super(_DenseLayer, self).__init__() self.norm1: nn.BatchNorm2d self.add_module('norm1', nn.BatchNorm2d(num_input_features)) ...
class _DenseBlock(nn.ModuleDict): _version = 2 def __init__(self, num_layers: int, num_input_features: int, bn_size: int, growth_rate: int, drop_rate: float, memory_efficient: bool=False) -> None: super(_DenseBlock, self).__init__() for i in range(num_layers): layer = _DenseLayer(...
class _Transition(nn.Sequential): def __init__(self, num_input_features: int, num_output_features: int) -> None: super(_Transition, self).__init__() self.add_module('norm', nn.BatchNorm2d(num_input_features)) self.add_module('relu', nn.ReLU(inplace=True)) self.add_module('conv', n...
class DenseNet(nn.Module): 'Densenet-BC model class, based on\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n growth_rate (int) - how many filters to add each layer (`k` in paper)\n block_config (list of 4 ints) - how many layers in each pool...
def _load_state_dict(model: nn.Module, model_url: str, progress: bool) -> None: pattern = re.compile('^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$') state_dict = load_state_dict_from_url(model_url, progress=progress) for key in list(state_dict.keys()): ...
def _densenet(arch: str, growth_rate: int, block_config: Tuple[(int, int, int, int)], num_init_features: int, pretrained: bool, progress: bool, **kwargs: Any) -> DenseNet: model = DenseNet(growth_rate, block_config, num_init_features, **kwargs) if pretrained: _load_state_dict(model, model_urls[arch], ...
def densenet121(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> DenseNet: 'Densenet-121 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (...
def densenet161(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> DenseNet: 'Densenet-161 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (...
def densenet169(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> DenseNet: 'Densenet-169 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (...
def densenet201(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> DenseNet: 'Densenet-201 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (...
def model_helper(opt): pretrained = opt.get('pretrained', '') pretrained_fc = opt.get('pretrained_fc', None) if (os.path.isfile(pretrained) and (pretrained_fc > 2) and (type(pretrained_fc) == int)): pretrained_flag = True num_classes = pretrained_fc ckpt = torch.load(pretrained) ...
class FSD50k_Lightning(pl.LightningModule): def __init__(self, hparams): super(FSD50k_Lightning, self).__init__() self.hparams = hparams self.net = model_helper(self.hparams.cfg['model']) if (self.hparams.cfg['model']['type'] == 'multiclass'): if (self.hparams.cw is no...
class NetVLAD(nn.Module): 'NetVLAD layer implementation' def __init__(self, num_clusters=16, dim=512, alpha=100.0, normalize_input=True): '\n Args:\n num_clusters : int\n The number of clusters\n dim : int\n Dimension of descriptors\n ...
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(BasicBlock, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d if ((groups != 1) or (b...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, pool='avgpool', zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() self.pool = pool if (norm_layer is None): no...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * ...