code
stringlengths
17
6.64M
def drn_d_40(BatchNorm, pretrained=True): model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 2, 2], arch='D', BatchNorm=BatchNorm) if pretrained: pretrained = model_zoo.load_url(model_urls['drn-d-40']) del pretrained['fc.weight'] del pretrained['fc.bias'] model.load_state_dict(pretrain...
def drn_d_54(BatchNorm, pretrained=True): model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch='D', BatchNorm=BatchNorm) if pretrained: pretrained = model_zoo.load_url(model_urls['drn-d-54']) del pretrained['fc.weight'] del pretrained['fc.bias'] model.load_state_dict(pretrain...
def drn_d_105(BatchNorm, pretrained=True): model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 1, 1], arch='D', BatchNorm=BatchNorm) if pretrained: pretrained = model_zoo.load_url(model_urls['drn-d-105']) del pretrained['fc.weight'] del pretrained['fc.bias'] model.load_state_dict(pretr...
def conv_bn(inp, oup, stride, BatchNorm): return nn.Sequential(nn.Conv2d(inp, oup, 3, stride, 1, bias=False), BatchNorm(oup), nn.ReLU6(inplace=True))
def fixed_padding(inputs, kernel_size, dilation): kernel_size_effective = (kernel_size + ((kernel_size - 1) * (dilation - 1))) pad_total = (kernel_size_effective - 1) pad_beg = (pad_total // 2) pad_end = (pad_total - pad_beg) padded_inputs = F.pad(inputs, (pad_beg, pad_end, pad_beg, pad_end)) ...
class InvertedResidual(nn.Module): def __init__(self, inp, oup, stride, dilation, expand_ratio, BatchNorm): super(InvertedResidual, self).__init__() self.stride = stride assert (stride in [1, 2]) hidden_dim = round((inp * expand_ratio)) self.use_res_connect = ((self.stride...
class MobileNetV2(nn.Module): def __init__(self, output_stride=8, BatchNorm=None, width_mult=1.0, pretrained=True): super(MobileNetV2, self).__init__() block = InvertedResidual input_channel = 32 current_stride = 1 rate = 1 interverted_residual_setting = [[1, 16, 1...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = BatchNorm(planes) self.conv...
class ResNet(nn.Module): def __init__(self, block, layers, output_stride, BatchNorm, pretrained=True): self.inplanes = 64 super(ResNet, self).__init__() blocks = [1, 2, 4] if (output_stride == 16): strides = [1, 2, 2, 1] dilations = [1, 1, 1, 2] eli...
def ResNet101(output_stride, BatchNorm, pretrained=True): 'Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 23, 3], output_stride, BatchNorm, pretrained=pretrained) return model
def fixed_padding(inputs, kernel_size, dilation): kernel_size_effective = (kernel_size + ((kernel_size - 1) * (dilation - 1))) pad_total = (kernel_size_effective - 1) pad_beg = (pad_total // 2) pad_end = (pad_total - pad_beg) padded_inputs = F.pad(inputs, (pad_beg, pad_end, pad_beg, pad_end)) ...
class SeparableConv2d(nn.Module): def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False, BatchNorm=None): super(SeparableConv2d, self).__init__() self.conv1 = nn.Conv2d(inplanes, inplanes, kernel_size, stride, 0, dilation, groups=inplanes, bias=bias) self.bn...
class Block(nn.Module): def __init__(self, inplanes, planes, reps, stride=1, dilation=1, BatchNorm=None, start_with_relu=True, grow_first=True, is_last=False, skip=None): super(Block, self).__init__() if ((planes != inplanes) or (stride != 1)): self.skip = nn.Conv2d(inplanes, planes, ...
class AlignedXception(nn.Module): '\n Modified Alighed Xception\n ' def __init__(self, output_stride, BatchNorm, pretrained=False, mode='xception_71'): super(AlignedXception, self).__init__() if (output_stride == 16): entry_block3_stride = 2 middle_block_dilation...
def SeparateConv(C_in, C_out, kernel_size, stride=1, padding=0, dilation=1, bias=False, BatchNorm=ABN): return nn.Sequential(nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, groups=C_in, bias=False), BatchNorm(C_in), nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias...
class Decoder(nn.Module): def __init__(self, num_classes, backbone, BatchNorm, args, separate): super(Decoder, self).__init__() if ((backbone == 'resnet') or (backbone == 'drn')): low_level_inplanes = 256 elif (backbone == 'xception'): low_level_inplanes = 256 ...
def build_decoder(num_classes, backbone, BatchNorm, args, separate): return Decoder(num_classes, backbone, BatchNorm, args, separate)
class DeepLab(nn.Module): def __init__(self, backbone='resnet', output_stride=16, num_classes=19, use_ABN=True, freeze_bn=False, args=None, separate=False): super(DeepLab, self).__init__() if (backbone == 'drn'): output_stride = 8 if use_ABN: BatchNorm = ABN ...
class ABN(nn.Module): 'Activated Batch Normalization\n\n This gathers a `BatchNorm2d` and an activation function in a single module\n ' def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True, activation='leaky_relu', slope=0.01): 'Creates an Activated Batch Normalization module\n...
class InPlaceABN(ABN): 'InPlace Activated Batch Normalization' def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True, activation='leaky_relu', slope=0.01): 'Creates an InPlace Activated Batch Normalization module\n\n Parameters\n ----------\n num_features : int\n ...
class InPlaceABNSync(ABN): 'InPlace Activated Batch Normalization with cross-GPU synchronization\n This assumes that it will be replicated across GPUs using the same mechanism as in `nn.DistributedDataParallel`.\n ' def forward(self, x): return inplace_abn_sync(x, self.weight, self.bias, self.r...
def _check(fn, *args, **kwargs): success = fn(*args, **kwargs) if (not success): raise RuntimeError('CUDA Error encountered in {}'.format(fn))
def _broadcast_shape(x): out_size = [] for (i, s) in enumerate(x.size()): if (i != 1): out_size.append(1) else: out_size.append(s) return out_size
def _reduce(x): if (len(x.size()) == 2): return x.sum(dim=0) else: (n, c) = x.size()[0:2] return x.contiguous().view((n, c, (- 1))).sum(2).sum(0)
def _count_samples(x): count = 1 for (i, s) in enumerate(x.size()): if (i != 1): count *= s return count
def _act_forward(ctx, x): if (ctx.activation == ACT_LEAKY_RELU): _backend.leaky_relu_forward(x, ctx.slope) elif (ctx.activation == ACT_ELU): _backend.elu_forward(x) elif (ctx.activation == ACT_NONE): pass
def _act_backward(ctx, x, dx): if (ctx.activation == ACT_LEAKY_RELU): _backend.leaky_relu_backward(x, dx, ctx.slope) elif (ctx.activation == ACT_ELU): _backend.elu_backward(x, dx) elif (ctx.activation == ACT_NONE): pass
class InPlaceABN(autograd.Function): @staticmethod def forward(ctx, x, weight, bias, running_mean, running_var, training=True, momentum=0.1, eps=1e-05, activation=ACT_LEAKY_RELU, slope=0.01): ctx.training = training ctx.momentum = momentum ctx.eps = eps ctx.activation = activa...
class InPlaceABNSync(autograd.Function): @classmethod def forward(cls, ctx, x, weight, bias, running_mean, running_var, training=True, momentum=0.1, eps=1e-05, activation=ACT_LEAKY_RELU, slope=0.01, equal_batches=True): ctx.training = training ctx.momentum = momentum ctx.eps = eps ...
class GlobalAvgPool2d(nn.Module): def __init__(self): "Global average pooling over the input's spatial dimensions" super(GlobalAvgPool2d, self).__init__() def forward(self, inputs): in_size = inputs.size() return inputs.view((in_size[0], in_size[1], (- 1))).mean(dim=2)
class SingleGPU(nn.Module): def __init__(self, module): super(SingleGPU, self).__init__() self.module = module def forward(self, input): return self.module(input.cuda(non_blocking=True))
def _sum_ft(tensor): 'sum over the first and last dimention' return tensor.sum(dim=0).sum(dim=(- 1))
def _unsqueeze_ft(tensor): 'add new dementions at the front and the tail' return tensor.unsqueeze(0).unsqueeze((- 1))
class _SynchronizedBatchNorm(_BatchNorm): def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True): super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine) self._sync_master = SyncMaster(self._data_parallel_master) self._is_paral...
class SynchronizedBatchNorm1d(_SynchronizedBatchNorm): "Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a\n mini-batch.\n .. math::\n y = \\frac{x - mean[x]}{ \\sqrt{Var[x] + \\epsilon}} * gamma + beta\n This module differs from the built-in PyTorch BatchNorm1d as th...
class SynchronizedBatchNorm2d(_SynchronizedBatchNorm): "Applies Batch Normalization over a 4d input that is seen as a mini-batch\n of 3d inputs\n .. math::\n y = \\frac{x - mean[x]}{ \\sqrt{Var[x] + \\epsilon}} * gamma + beta\n This module differs from the built-in PyTorch BatchNorm2d as the mean ...
class SynchronizedBatchNorm3d(_SynchronizedBatchNorm): "Applies Batch Normalization over a 5d input that is seen as a mini-batch\n of 4d inputs\n .. math::\n y = \\frac{x - mean[x]}{ \\sqrt{Var[x] + \\epsilon}} * gamma + beta\n This module differs from the built-in PyTorch BatchNorm3d as the mean ...
class FutureResult(object): 'A thread-safe future implementation. Used only as one-to-one pipe.' def __init__(self): self._result = None self._lock = threading.Lock() self._cond = threading.Condition(self._lock) def put(self, result): with self._lock: assert (...
class SlavePipe(_SlavePipeBase): 'Pipe for master-slave communication.' def run_slave(self, msg): self.queue.put((self.identifier, msg)) ret = self.result.get() self.queue.put(True) return ret
class SyncMaster(object): 'An abstract `SyncMaster` object.\n - During the replication, as the data parallel will trigger an callback of each module, all slave devices should\n call `register(id)` and obtain an `SlavePipe` to communicate with the master.\n - During the forward pass, master device invokes...
class CallbackContext(object): pass
def execute_replication_callbacks(modules): '\n Execute an replication callback `__data_parallel_replicate__` on each module created by original replication.\n The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`\n Note that, as all modules are isomorphism, we assign ea...
class DataParallelWithCallback(DataParallel): '\n Data Parallel with a replication callback.\n An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by\n original `replicate` function.\n The callback will be invoked with arguments `__data_parallel_rep...
def patch_replication_callback(data_parallel): '\n Monkey-patch an existing `DataParallel` object. Add the replication callback.\n Useful when you have customized `DataParallel` implementation.\n Examples:\n > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)\n > sync_bn = DataP...
def as_numpy(v): if isinstance(v, Variable): v = v.data return v.cpu().numpy()
class TorchTestCase(unittest.TestCase): def assertTensorClose(self, a, b, atol=0.001, rtol=0.001): (npa, npb) = (as_numpy(a), as_numpy(b)) self.assertTrue(np.allclose(npa, npb, atol=atol), 'Tensor close check failed\n{}\n{}\nadiff={}, rdiff={}'.format(a, b, np.abs((npa - npb)).max(), np.abs(((npa...
class Path(object): @staticmethod def db_root_dir(dataset): if (dataset == 'pascal'): return '/path/to/datasets/VOCdevkit/VOC2012/' elif (dataset == 'sbd'): return '/path/to/datasets/benchmark_RELEASE/' elif (dataset == 'cityscapes'): return '/path/...
class ASPP(nn.Module): def __init__(self, C, depth, num_classes, conv=nn.Conv2d, norm=NaiveBN, momentum=0.0003, mult=1): super(ASPP, self).__init__() self._C = C self._depth = depth self._num_classes = num_classes self.global_pooling = nn.AdaptiveAvgPool2d(1) self....
class Retrain_Autodeeplab(nn.Module): def __init__(self, args, input_channels=3): super(Retrain_Autodeeplab, self).__init__() filter_param_dict = {0: 1, 1: 2, 2: 4, 3: 8} BatchNorm2d = (ABN if args.use_ABN else NaiveBN) if (((not args.dist) and args.use_ABN) or (args.dist and args...
class Decoder(nn.Module): def __init__(self, num_classes, filter_multiplier, BatchNorm=NaiveBN, args=None, last_level=0): super(Decoder, self).__init__() low_level_inplanes = filter_multiplier C_low = 48 self.conv1 = nn.Conv2d(low_level_inplanes, C_low, 1, bias=False) self...
class TensorboardSummary(object): def __init__(self, directory): self.directory = directory def create_summary(self): writer = SummaryWriter(log_dir=os.path.join(self.directory)) return writer def visualize_image(self, writer, dataset, image, target, output, global_step): ...
def calculate_weigths_labels(dataset, dataloader, num_classes): z = np.zeros((num_classes,)) tqdm_batch = tqdm(dataloader) print('Calculating classes weights') for sample in tqdm_batch: y = sample['label'] y = y.detach().cpu().numpy() mask = ((y >= 0) & (y < num_classes)) ...
def copy_state_dict(cur_state_dict, pre_state_dict, prefix=''): def _get_params(key): key = (prefix + key) if (key in pre_state_dict): return pre_state_dict[key] return None for k in cur_state_dict.keys(): v = _get_params(k) try: if (v is None):...
def setup_logger(logpth): logfile = 'Deeplab_v3plus-{}.log'.format(time.strftime('%Y-%m-%d-%H-%M-%S')) logfile = osp.join(logpth, logfile) FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s' log_level = logging.INFO if (dist.is_initialized() and (dist.get_rank() != 0)): log_leve...
class Logger(object): def __init__(self, args, logger_str): self._logger_name = args.save_path self._logger_str = logger_str self._save_path = os.path.join(self._logger_name, (self._logger_str + '.txt')) self._file = open(self._save_path, 'w') def log(self, string, save=True)...
class SegmentationLosses(object): def __init__(self, weight=None, size_average=True, batch_average=True, ignore_index=255, cuda=False): self.ignore_index = ignore_index self.weight = weight self.size_average = size_average self.cuda = cuda def build_loss(self, mode='ce'): ...
class OhemCELoss(nn.Module): def __init__(self, thresh, n_min, ignore_index=255, cuda=False, *args, **kwargs): super(OhemCELoss, self).__init__() self.thresh = thresh self.n_min = n_min self.ignore_lb = ignore_index self.criteria = nn.CrossEntropyLoss(ignore_index=ignore_i...
def build_criterion(args): print('=> Trying bulid {:}loss'.format(args.criterion)) if (args.criterion == 'Ohem'): return OhemCELoss(thresh=args.thresh, n_min=args.n_min, cuda=True) elif (args.criterion == 'crossentropy'): return SegmentationLosses(weight=args.weight, cuda=True).build_loss(...
class LR_Scheduler(object): 'Learning Rate Scheduler\n\n Step mode: ``lr = baselr * 0.1 ^ {floor(epoch-1 / lr_step)}``\n\n Cosine mode: ``lr = baselr * 0.5 * (1 + cos(iter/maxiter))``\n\n Poly mode: ``lr = baselr * (1 - iter/maxiter) ^ 0.9``\n\n Args:\n args:\n :attr:`args.lr_scheduler...
class Evaluator(object): def __init__(self, num_class): self.num_class = num_class self.confusion_matrix = np.zeros(((self.num_class,) * 2)) def Pixel_Accuracy(self): Acc = (np.diag(self.confusion_matrix).sum() / self.confusion_matrix.sum()) return Acc def Pixel_Accuracy...
class Optimizer(object): def __init__(self, model, lr0, momentum, wd, warmup_steps, warmup_start_lr, max_iter, power): self.warmup_steps = warmup_steps self.warmup_start_lr = warmup_start_lr self.lr0 = lr0 self.lr = self.lr0 self.max_iter = float(max_iter) self.pow...
class Saver(object): def __init__(self, args, use_dist=False): self.args = args self.use_dist = use_dist self.directory = os.path.join('run', args.dataset, args.checkname) self.runs = sorted(glob.glob(os.path.join(self.directory, 'experiment_*'))) run_id = ((max([int(x.spl...
class Iter_LR_Scheduler(object): 'Learning Rate Scheduler\n\n Step mode: ``lr = baselr * 0.1 ^ {floor(epoch-1 / lr_step)}``\n\n Cosine mode: ``lr = baselr * 0.5 * (1 + cos(iter/maxiter))``\n\n Poly mode: ``lr = baselr * (1 - iter/maxiter) ^ 0.9``\n\n Args:\n args:\n :attr:`args.lr_sche...
class TensorboardSummary(object): def __init__(self, directory, use_dist=False): self.directory = directory self.use_dist = use_dist def create_summary(self): writer = SummaryWriter(logdir=os.path.join(self.directory)) return writer def visualize_image(self, writer, data...
class AverageMeter(object): def __init__(self): self.val = None self.sum = None self.cnt = None self.avg = None self.ema = None self.initialized = False def update(self, val, n=1): if (not self.initialized): self.initialize(val, n) ...
def inter_and_union(pred, mask, num_class): pred = np.asarray(pred, dtype=np.uint8).copy() mask = np.asarray(mask, dtype=np.uint8).copy() pred += 1 mask += 1 pred = (pred * (mask > 0)) inter = (pred * (pred == mask)) (area_inter, _) = np.histogram(inter, bins=num_class, range=(1, num_class...
def time_for_file(): ISOTIMEFORMAT = '%d-%h-at-%H-%M-%S' return '{}'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time())))
def prepare_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) random.seed(seed) np.random.seed(seed)
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 BasicBlock(nn.Module): '\n first applies batch norm and relu before applying convolution\n we can change the order of operations if needed\n ' def __init__(self, in_planes, out_planes, stride, dropRate=0.0): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes...
class NetworkBlock(nn.Module): def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0): super(NetworkBlock, self).__init__() self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate) def _make_layer(self, block, in_planes, out_planes, ...
class Backbone_Pt(nn.Module): '\n wide resnet\n ' def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0, in_channels=3): super(Backbone_Pt, self).__init__() nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)] assert (((depth - 4) % 6) ==...
class Backbone_Audio(nn.Module): '\n wide resnet for audio\n ' def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0, in_channels=3): super(Backbone_Audio, self).__init__() nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)] assert (((de...
def download_from_s3(s3_bucket, task, download_dir): s3 = boto3.client('s3') if (task == 'smnist'): data_files = ['s2_mnist.gz'] s3_folder = 'spherical' if (task == 'scifar100'): data_files = ['s2_cifar100.gz'] s3_folder = 'spherical' elif (task == 'sEMG'): data...
def download_protein_folder(bucket_name, local_dir=None): s3 = boto3.resource('s3') bucket = s3.Bucket(bucket_name) for obj in bucket.objects.filter(Prefix='protein'): target = (obj.key if (local_dir is None) else os.path.join(local_dir, os.path.relpath(obj.key, 'protein'))) if (not os.pat...
def accuracy_rate(predictions: torch.Tensor, labels: torch.Tensor) -> float: 'Return the accuracy rate based on dense predictions and sparse labels.' assert (len(predictions) == len(labels)), 'Predictions and labels must have the same length.' assert (len(labels.shape) == 1), 'Labels must be a column vect...
class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self
class BackboneTrial(PyTorchTrial): def __init__(self, trial_context: PyTorchTrialContext) -> None: self.context = trial_context self.hparams = AttrDict(trial_context.get_hparams()) self.last_epoch = 0 self.download_directory = self.download_data_from_s3() dataset_hypers = ...
def accuracy_rate(predictions: torch.Tensor, labels: torch.Tensor) -> float: 'Return the accuracy rate based on dense predictions and sparse labels.' assert (len(predictions) == len(labels)), 'Predictions and labels must have the same length.' assert (len(labels.shape) == 1), 'Labels must be a column vect...
class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self
class BackboneTrial(PyTorchTrial): def __init__(self, trial_context: PyTorchTrialContext) -> None: self.context = trial_context self.hparams = AttrDict(trial_context.get_hparams()) self.last_epoch = 0 self.download_directory = self.download_data_from_s3() self.criterion = ...
class Conv1dSamePadding(nn.Conv1d): 'Represents the "Same" padding functionality from Tensorflow.\n See: https://github.com/pytorch/pytorch/issues/3867\n Note that the padding argument in the initializer doesn\'t do anything now\n ' def forward(self, input): return conv1d_same_padding(input,...
def conv1d_same_padding(input, weight, bias, stride, dilation, groups): (kernel, dilation, stride) = (weight.size(2), dilation[0], stride[0]) l_out = l_in = input.size(2) padding = (((((l_out - 1) * stride) - l_in) + (dilation * (kernel - 1))) + 1) if ((padding % 2) != 0): input = F.pad(input,...
class ConvBlock(nn.Module): def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int) -> None: super().__init__() self.layers = nn.Sequential(Conv1dSamePadding(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride), nn.BatchNorm1d(...
class ResNet1D(nn.Module): 'A PyTorch implementation of the ResNet Baseline\n From https://arxiv.org/abs/1909.04939\n Attributes\n ----------\n sequence_length:\n The size of the input sequence\n mid_channels:\n The 3 residual blocks will have as output channels:\n [mid_channel...
class ResNetBlock(nn.Module): def __init__(self, in_channels: int, out_channels: int) -> None: super().__init__() channels = [in_channels, out_channels, out_channels, out_channels] kernel_sizes = [8, 5, 3] self.layers = nn.Sequential(*[ConvBlock(in_channels=channels[i], out_channe...
def download_from_s3(s3_bucket, task, download_dir): s3 = boto3.client('s3') if (task == 'ECG'): data_files = ['challenge2017.pkl'] s3_folder = 'ECG' elif (task == 'satellite'): data_files = ['satellite_train.npy', 'satellite_test.npy'] s3_folder = 'satellite' elif (tas...
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 load_data(task, path, train=False): if (task == 'ECG'): return load_ECG_data(path, train) elif (task == 'satellite'): return load_satellite_data(path, train) elif (task == 'deepsea'): return load_deepsea_data(path, train) else: raise NotImplementedError
def load_ECG_data(path, train): return (read_data_physionet_4_with_val(path) if train else read_data_physionet_4(path))
def load_satellite_data(path, train): train_file = os.path.join(path, 'satellite_train.npy') test_file = os.path.join(path, 'satellite_test.npy') (all_train_data, all_train_labels) = (np.load(train_file, allow_pickle=True)[()]['data'], np.load(train_file, allow_pickle=True)[()]['label']) (test_data, t...
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 read_data_physionet_4_with_val(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 =...
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): ...
def load_deepsea_data(path, train): data = np.load(os.path.join(path, 'deepsea_filtered.npz')) (train_data, train_labels) = (torch.from_numpy(data['x_train']).type(torch.FloatTensor), torch.from_numpy(data['y_train']).type(torch.LongTensor)) train_data = train_data.permute(0, 2, 1) trainset = data_uti...
class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self
class BackboneTrial(PyTorchTrial): def __init__(self, trial_context: PyTorchTrialContext) -> None: self.context = trial_context self.hparams = AttrDict(trial_context.get_hparams()) self.last_epoch = 0 self.download_directory = self.download_data_from_s3() dataset_hypers = ...
class BilevelDataset(Dataset): def __init__(self, dataset): '\n We will split the data into a train split and a validation split\n and return one image from each split as a single observation.\n\n Args:\n dataset: PyTorch Dataset object\n ' inds = np.arange(...
class BilevelCosmicDataset(Dataset): def __init__(self, dataset): '\n We will split the data into a train split and a validation split\n and return one image from each split as a single observation.\n\n Args:\n dataset: PyTorch Dataset object\n ' inds = np.a...