code
stringlengths
17
6.64M
def contrast(img, factor, **__): return ImageEnhance.Contrast(img).enhance(factor)
def color(img, factor, **__): return ImageEnhance.Color(img).enhance(factor)
def brightness(img, factor, **__): return ImageEnhance.Brightness(img).enhance(factor)
def sharpness(img, factor, **__): return ImageEnhance.Sharpness(img).enhance(factor)
def _randomly_negate(v): 'With 50% prob, negate the value' return ((- v) if (random.random() > 0.5) else v)
def _rotate_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 30.0) level = _randomly_negate(level) return (level,)
def _enhance_level_to_arg(level, _hparams): return ((((level / _MAX_LEVEL) * 1.8) + 0.1),)
def _enhance_increasing_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 0.9) level = (1.0 + _randomly_negate(level)) return (level,)
def _shear_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 0.3) level = _randomly_negate(level) return (level,)
def _translate_abs_level_to_arg(level, hparams): translate_const = hparams['translate_const'] level = ((level / _MAX_LEVEL) * float(translate_const)) level = _randomly_negate(level) return (level,)
def _translate_rel_level_to_arg(level, hparams): translate_pct = hparams.get('translate_pct', 0.45) level = ((level / _MAX_LEVEL) * translate_pct) level = _randomly_negate(level) return (level,)
def _posterize_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 4)),)
def _posterize_increasing_level_to_arg(level, hparams): return ((4 - _posterize_level_to_arg(level, hparams)[0]),)
def _posterize_original_level_to_arg(level, _hparams): return ((int(((level / _MAX_LEVEL) * 4)) + 4),)
def _solarize_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 256)),)
def _solarize_increasing_level_to_arg(level, _hparams): return ((256 - _solarize_level_to_arg(level, _hparams)[0]),)
def _solarize_add_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 110)),)
class AugmentOp(): '\n Apply for video.\n ' def __init__(self, name, prob=0.5, magnitude=10, hparams=None): hparams = (hparams or _HPARAMS_DEFAULT) self.aug_fn = NAME_TO_OP[name] self.level_fn = LEVEL_TO_ARG[name] self.prob = prob self.magnitude = magnitude ...
def _select_rand_weights(weight_idx=0, transforms=None): transforms = (transforms or _RAND_TRANSFORMS) assert (weight_idx == 0) rand_weights = _RAND_CHOICE_WEIGHTS_0 probs = [rand_weights[k] for k in transforms] probs /= np.sum(probs) return probs
def rand_augment_ops(magnitude=10, hparams=None, transforms=None): hparams = (hparams or _HPARAMS_DEFAULT) transforms = (transforms or _RAND_TRANSFORMS) return [AugmentOp(name, prob=0.5, magnitude=magnitude, hparams=hparams) for name in transforms]
class RandAugment(): def __init__(self, ops, num_layers=2, choice_weights=None): self.ops = ops self.num_layers = num_layers self.choice_weights = choice_weights def __call__(self, img): ops = np.random.choice(self.ops, self.num_layers, replace=(self.choice_weights is None), ...
def rand_augment_transform(config_str, hparams): "\n RandAugment: Practical automated data augmentation... - https://arxiv.org/abs/1909.13719\n\n Create a RandAugment transform\n :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by\n dashe...
def get_args(): parser = argparse.ArgumentParser('MVD pre-training script', add_help=False) parser.add_argument('--batch_size', default=64, type=int) parser.add_argument('--epochs', default=800, type=int) parser.add_argument('--save_ckpt_freq', default=50, type=int) parser.add_argument('--update_f...
def get_image_teacher_model(args): print(f'Creating teacher model: {args.image_teacher_model}') model = create_model(args.image_teacher_model, pretrained=False, img_size=args.teacher_input_size) return model
def get_video_teacher_model(args): print(f'Creating teacher model: {args.video_teacher_model}') model = create_model(args.video_teacher_model, pretrained=False, img_size=args.video_teacher_input_size, drop_path_rate=args.video_teacher_drop_path) return model
def get_model(args): print(f'Creating model: {args.model}') model = create_model(args.model, pretrained=False, drop_path_rate=args.drop_path, drop_block_rate=None, decoder_depth=args.decoder_depth, use_cls_token=args.use_cls_token, num_frames=args.num_frames, target_feature_dim=args.distillation_target_dim, t...
def main(args): utils.init_distributed_mode(args) print(args) device = torch.device(args.device) seed = (args.seed + utils.get_rank()) torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True model = get_model(args) model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(m...
class SmoothedValue(object): 'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n ' def __init__(self, window_size=20, fmt=None): if (fmt is None): fmt = '{median:.4f} ({global_avg:.4f})' self.deque = deque(maxlen=wi...
class MetricLogger(object): def __init__(self, delimiter='\t'): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for (k, v) in kwargs.items(): if (v is None): continue if isinstance(v, torch.Tensor...
class TensorboardLogger(object): def __init__(self, log_dir): self.writer = SummaryWriter(logdir=log_dir) self.step = 0 def set_step(self, step=None): if (step is not None): self.step = step else: self.step += 1 def update(self, head='scalar', ste...
def seed_worker(worker_id): worker_seed = (torch.initial_seed() % (2 ** 32)) np.random.seed(worker_seed) random.seed(worker_seed)
def _load_checkpoint_for_ema(model_ema, checkpoint): '\n Workaround for ModelEma._load_checkpoint to accept an already-loaded object\n ' mem_file = io.BytesIO() temp = {} temp['state_dict_ema'] = checkpoint torch.save(temp, mem_file) mem_file.seek(0) model_ema._load_checkpoint(mem_fi...
def setup_for_distributed(is_master): '\n This function disables printing when not in master process\n ' import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if (is_master or force): builtin_p...
def is_dist_avail_and_initialized(): if (not dist.is_available()): return False if (not dist.is_initialized()): return False return True
def get_world_size(): if (not is_dist_avail_and_initialized()): return 1 return dist.get_world_size()
def get_rank(): if (not is_dist_avail_and_initialized()): return 0 return dist.get_rank()
def is_main_process(): return (get_rank() == 0)
def save_on_master(*args, **kwargs): if is_main_process(): torch.save(*args, **kwargs)
def init_distributed_mode(args): if args.dist_on_itp: args.rank = int(os.environ['OMPI_COMM_WORLD_RANK']) args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE']) args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK']) args.dist_url = ('tcp://%s:%s' % (os.environ['MASTER_ADDR'], ...
def load_state_dict(model, state_dict, prefix='', ignore_missing='relative_position_index'): missing_keys = [] unexpected_keys = [] error_msgs = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if (metadata is not None): state_dict._metadata = metadat...
class NativeScalerWithGradNormCount(): state_dict_key = 'amp_scaler' def __init__(self): self._scaler = torch.cuda.amp.GradScaler() def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): self._scaler.scale(loss).backward(create_graph=c...
def get_grad_norm_(parameters, norm_type: float=2.0) -> torch.Tensor: if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = [p for p in parameters if (p.grad is not None)] norm_type = float(norm_type) if (len(parameters) == 0): return torch.tensor(0.0) dev...
def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, start_warmup_value=0, warmup_steps=(- 1)): warmup_schedule = np.array([]) warmup_iters = (warmup_epochs * niter_per_ep) if (warmup_steps > 0): warmup_iters = warmup_steps print(('Set warmup steps = %d' % warmu...
def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, model_ema=None): output_dir = Path(args.output_dir) epoch_name = str(epoch) if (loss_scaler is not None): checkpoint_paths = [(output_dir / ('checkpoint-%s.pth' % epoch_name))] for checkpoint_path in checkpoint_p...
def remove_key_in_checkpoint(checkpoint, remove_key_list=None): if isinstance(remove_key_list, list): original_key_list = list(checkpoint.keys()) for k in original_key_list: for remove_key in remove_key_list: if (remove_key in k): del checkpoint[k] ...
def auto_find_start_epoch(args): output_dir = Path(args.output_dir) if (args.auto_resume and (len(args.resume) == 0)): import glob all_checkpoints = glob.glob(os.path.join(output_dir, 'checkpoint-*.pth')) latest_ckpt = (- 1) for ckpt in all_checkpoints: t = ckpt.spl...
def auto_load_model(args, model, model_without_ddp, optimizer, loss_scaler, model_ema=None): output_dir = Path(args.output_dir) if (loss_scaler is not None): if (args.auto_resume and (len(args.resume) == 0)): import glob all_checkpoints = glob.glob(os.path.join(output_dir, 'che...
def create_ds_config(args): args.deepspeed_config = os.path.join(args.output_dir, 'deepspeed_config.json') with open(args.deepspeed_config, mode='w') as writer: ds_config = {'train_batch_size': ((args.batch_size * args.update_freq) * get_world_size()), 'train_micro_batch_size_per_gpu': args.batch_size...
def multiple_samples_collate(batch, fold=False): '\n Collate function for repeated augmentation. Each instance in the batch has\n more than one sample.\n Args:\n batch (tuple or list): data batch to collate.\n Returns:\n (tuple): collated data batch.\n ' (inputs, labels, video_idx...
def multiple_pretrain_samples_collate(batch, fold=False): '\n Collate function for repeated augmentation. Each instance in the batch has\n more than one sample.\n Args:\n batch (tuple or list): data batch to collate.\n Returns:\n (tuple): collated data batch.\n ' (inputs_0, inputs...
class Config(object): 'Base configuration class. For custom configurations, create a\n sub-class that inherits from this one and override properties\n that need to be changed.\n ' NAME = None GPU_COUNT = 1 IMAGES_PER_GPU = 2 STEPS_PER_EPOCH = 1000 VALIDATION_STEPS = 200 IMAGE_MIN_...
class ParallelModel(KM.Model): 'Subclasses the standard Keras Model and adds multi-GPU support.\n It works by creating a copy of the model on each GPU. Then it slices\n the inputs and sends a slice to each copy of the model, and then\n merges the outputs together and applies the loss on the combined\n ...
class CocoConfig(Config): 'Configuration for training on MS COCO.\n Derives from the base Config class and overrides values specific\n to the COCO dataset.\n ' NAME = 'coco' IMAGES_PER_GPU = 32 GPU_COUNT = 2
class CocoDataset(utils.Dataset): def load_coco(self, dataset_dir, subset, year=DEFAULT_DATASET_YEAR, class_ids=None, class_map=None, return_coco=False, auto_download=False): 'Load a subset of the COCO dataset.\n dataset_dir: The root directory of the COCO dataset.\n subset: What to load (t...
class Dataset(object): 'The base class for dataset classes.\n To use it, create a new class that adds functions specific to the dataset\n you want to use. For example:\n\n class CatsAndDogsDataset(Dataset):\n def load_cats_and_dogs(self):\n ...\n def load_mask(self, image_id):\n ...
def resize_image(image, min_dim=None, max_dim=None, padding=False): "\n Resizes an image keeping the aspect ratio.\n\n min_dim: if provided, resizes the image such that it's smaller\n dimension == min_dim\n max_dim: if provided, ensures that the image longest side doesn't\n exceed this valu...
def parse_args(args=None): parser = argparse.ArgumentParser(description='Training and Testing Knowledge Graph Embedding Models', usage='train.py [<args>] [-h | --help]') parser.add_argument('--cuda', action='store_true', help='use GPU') parser.add_argument('--seed', default=10, type=int) parser.add_ar...
def override_config(args): '\n Override model and data configuration\n ' with open(os.path.join(args.init_checkpoint, 'config.json'), 'r') as fjson: argparse_dict = json.load(fjson) args.countries = argparse_dict['countries'] if (args.data_path is None): args.data_path = argparse...
def save_model(model, optimizer, save_variable_list, args, best_valid=False): '\n Save the parameters of the model and the optimizer,\n as well as some other variables such as step and learning_rate\n ' argparse_dict = vars(args) if best_valid: save_path = (args.save_path + '/best_model')...
def read_triple(file_path, entity2id, relation2id): '\n Read triples and map them into ids.\n ' triples = [] with open(file_path) as fin: for line in fin: (h, r, t) = line.strip().split('\t') triples.append((entity2id[h], relation2id[r], entity2id[t])) return trip...
def set_logger(args): '\n Write logs to checkpoint and console\n ' if args.do_train: log_file = os.path.join((args.save_path or args.init_checkpoint), 'train.log') else: log_file = os.path.join((args.save_path or args.init_checkpoint), 'test.log') logging.basicConfig(format='%(as...
def log_metrics(mode, step, metrics): '\n Print the evaluation logs\n ' for metric in metrics: logging.info(('%s %s at step %d: %f' % (mode, metric, step, metrics[metric])))
def objective(): if (args.seed != 0): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) if ((args.house_dim % 2) == 0): args.house_num = args.house_dim else: args.house_n...
def t_start(j, Js=[(1, 2), (3, 4), (5, 6)], Trange=(1, 10)): '\n Helper for `E_gt_func`\n \n :param j: index from 0 to len(Js) (included) on which to get the start\n :param Js: ground truth events, as a list of couples\n :param Trange: range of the series where Js is included\n :return: generali...
def t_stop(j, Js=[(1, 2), (3, 4), (5, 6)], Trange=(1, 10)): '\n Helper for `E_gt_func`\n \n :param j: index from 0 to len(Js) (included) on which to get the stop\n :param Js: ground truth events, as a list of couples\n :param Trange: range of the series where Js is included\n :return: generalize...
def E_gt_func(j, Js, Trange): '\n Get the affiliation zone of element j of the ground truth\n \n :param j: index from 0 to len(Js) (excluded) on which to get the zone\n :param Js: ground truth events, as a list of couples\n :param Trange: range of the series where Js is included, can \n be (-mat...
def get_all_E_gt_func(Js, Trange): '\n Get the affiliation partition from the ground truth point of view\n \n :param Js: ground truth events, as a list of couples\n :param Trange: range of the series where Js is included, can \n be (-math.inf, math.inf) for distance measures\n :return: affiliati...
def affiliation_partition(Is=[(1, 1.5), (2, 5), (5, 6), (8, 9)], E_gt=[(1, 2.5), (2.5, 4.5), (4.5, 10)]): '\n Cut the events into the affiliation zones\n The presentation given here is from the ground truth point of view,\n but it is also used in the reversed direction in the main function.\n \n :p...
def interval_length(J=(1, 2)): '\n Length of an interval\n \n :param J: couple representating the start and stop of an interval, or None\n :return: length of the interval, and 0 for a None interval\n ' if (J is None): return 0 return (J[1] - J[0])
def sum_interval_lengths(Is=[(1, 2), (3, 4), (5, 6)]): '\n Sum of length of the intervals\n \n :param Is: list of intervals represented by starts and stops\n :return: sum of the interval length\n ' return sum([interval_length(I) for I in Is])
def interval_intersection(I=(1, 3), J=(2, 4)): '\n Intersection between two intervals I and J\n I and J should be either empty or represent a positive interval (no point)\n \n :param I: an interval represented by start and stop\n :param J: a second interval of the same form\n :return: an interva...
def interval_subset(I=(1, 3), J=(0, 6)): '\n Checks whether I is a subset of J\n \n :param I: an non empty interval represented by start and stop\n :param J: a second non empty interval of the same form\n :return: True if I is a subset of J\n ' if ((I[0] >= J[0]) and (I[1] <= J[1])): ...
def cut_into_three_func(I, J): '\n Cut an interval I into a partition of 3 subsets:\n the elements before J,\n the elements belonging to J,\n and the elements after J\n \n :param I: an interval represented by start and stop, or None for an empty one\n :param J: a non empty interva...
def get_pivot_j(I, J): "\n Get the single point of J that is the closest to I, called 'pivot' here,\n with the requirement that I should be outside J\n \n :param I: a non empty interval (start, stop)\n :param J: another non empty interval, with empty intersection with I\n :return: the element j ...
def integral_mini_interval(I, J): "\n In the specific case where interval I is located outside J,\n integral of distance from x to J over the interval x \\in I.\n This is the *integral* i.e. the sum.\n It's not the mean (not divided by the length of I yet)\n \n :param I: a interval (start, stop)...
def integral_interval_distance(I, J): "\n For any non empty intervals I, J, compute the\n integral of distance from x to J over the interval x \\in I.\n This is the *integral* i.e. the sum. \n It's not the mean (not divided by the length of I yet)\n The interval I can intersect J or not\n \n ...
def integral_mini_interval_P_CDFmethod__min_piece(I, J, E): '\n Helper of `integral_mini_interval_Pprecision_CDFmethod`\n In the specific case where interval I is located outside J,\n compute the integral $\\int_{d_min}^{d_max} \\min(m, x) dx$, with:\n - m the smallest distance from J to E,\n - d_m...
def integral_mini_interval_Pprecision_CDFmethod(I, J, E): '\n Integral of the probability of distances over the interval I.\n In the specific case where interval I is located outside J,\n compute the integral $\\int_{x \\in I} Fbar(dist(x,J)) dx$.\n This is the *integral* i.e. the sum (not the mean)\n...
def integral_interval_probaCDF_precision(I, J, E): '\n Integral of the probability of distances over the interval I.\n Compute the integral $\\int_{x \\in I} Fbar(dist(x,J)) dx$.\n This is the *integral* i.e. the sum (not the mean)\n \n :param I: a single (non empty) predicted interval in the zone ...
def cut_J_based_on_mean_func(J, e_mean): '\n Helper function for the recall.\n Partition J into two intervals: before and after e_mean\n (e_mean represents the center element of E the zone of affiliation)\n \n :param J: ground truth interval\n :param e_mean: a float number (center value of E)\n ...
def integral_mini_interval_Precall_CDFmethod(I, J, E): '\n Integral of the probability of distances over the interval J.\n In the specific case where interval J is located outside I,\n compute the integral $\\int_{y \\in J} Fbar_y(dist(y,I)) dy$.\n This is the *integral* i.e. the sum (not the mean)\n ...
def integral_interval_probaCDF_recall(I, J, E): '\n Integral of the probability of distances over the interval J.\n Compute the integral $\\int_{y \\in J} Fbar_y(dist(y,I)) dy$.\n This is the *integral* i.e. the sum (not the mean)\n\n :param I: a single (non empty) predicted interval\n :param J: gr...
def affiliation_precision_distance(Is=[(1, 2), (3, 4), (5, 6)], J=(2, 5.5)): '\n Compute the individual average distance from Is to a single ground truth J\n \n :param Is: list of predicted events within the affiliation zone of J\n :param J: couple representating the start and stop of a ground truth i...
def affiliation_precision_proba(Is=[(1, 2), (3, 4), (5, 6)], J=(2, 5.5), E=(0, 8)): '\n Compute the individual precision probability from Is to a single ground truth J\n \n :param Is: list of predicted events within the affiliation zone of J\n :param J: couple representating the start and stop of a gr...
def affiliation_recall_distance(Is=[(1, 2), (3, 4), (5, 6)], J=(2, 5.5)): '\n Compute the individual average distance from a single J to the predictions Is\n \n :param Is: list of predicted events within the affiliation zone of J\n :param J: couple representating the start and stop of a ground truth i...
def affiliation_recall_proba(Is=[(1, 2), (3, 4), (5, 6)], J=(2, 5.5), E=(0, 8)): '\n Compute the individual recall probability from a single ground truth J to Is\n \n :param Is: list of predicted events within the affiliation zone of J\n :param J: couple representating the start and stop of a ground t...
def convert_vector_to_events(vector=[0, 1, 1, 0, 0, 1, 0]): '\n Convert a binary vector (indicating 1 for the anomalous instances)\n to a list of events. The events are considered as durations,\n i.e. setting 1 at index i corresponds to an anomalous interval [i, i+1).\n \n :param vector: a list of ...
def infer_Trange(events_pred, events_gt): '\n Given the list of events events_pred and events_gt, get the\n smallest possible Trange corresponding to the start and stop indexes \n of the whole series.\n Trange will not influence the measure of distances, but will impact the\n measures of probabilit...
def has_point_anomalies(events): '\n Checking whether events contain point anomalies, i.e.\n events starting and stopping at the same time.\n \n :param events: a list of couples corresponding to predicted events\n :return: True is the events have any point anomalies, False otherwise\n ' if (...
def _sum_wo_nan(vec): '\n Sum of elements, ignoring math.isnan ones\n \n :param vec: vector of floating numbers\n :return: sum of the elements, ignoring math.isnan ones\n ' vec_wo_nan = [e for e in vec if (not math.isnan(e))] return sum(vec_wo_nan)
def _len_wo_nan(vec): '\n Count of elements, ignoring math.isnan ones\n \n :param vec: vector of floating numbers\n :return: count of the elements, ignoring math.isnan ones\n ' vec_wo_nan = [e for e in vec if (not math.isnan(e))] return len(vec_wo_nan)
def read_gz_data(filename='data/machinetemp_groundtruth.gz'): '\n Load a file compressed with gz, such that each line of the\n file is either 0 (representing a normal instance) or 1 (representing)\n an anomalous instance.\n :param filename: file path to the gz compressed file\n :return: list of int...
def read_all_as_events(): '\n Load the files contained in the folder `data/` and convert\n to events. The length of the series is kept.\n The convention for the file name is: `dataset_algorithm.gz`\n :return: two dictionaries:\n - the first containing the list of events for each dataset and alg...
def f1_func(p, r): '\n Compute the f1 function\n :param p: precision numeric value\n :param r: recall numeric value\n :return: f1 numeric value\n ' return (((2 * p) * r) / (p + r))
def test_events(events): '\n Verify the validity of the input events\n :param events: list of events, each represented by a couple (start, stop)\n :return: None. Raise an error for incorrect formed or non ordered events\n ' if (type(events) is not list): raise TypeError('Input `events` sho...
def pr_from_events(events_pred, events_gt, Trange): '\n Compute the affiliation metrics including the precision/recall in [0,1],\n along with the individual precision/recall distances and probabilities\n \n :param events_pred: list of predicted events, each represented by a couple\n indicating the ...
def produce_all_results(): '\n Produce the affiliation precision/recall for all files\n contained in the `data` repository\n :return: a dictionary indexed by data names, each containing a dictionary\n indexed by algorithm names, each containing the results of the affiliation\n metrics (precision, r...
class Config(object): def __init__(self): self.dataset = 'IOpsCompetition' self.input_channels = 1 self.kernel_size = 4 self.stride = 1 self.final_out_channels = 32 self.hidden_size = 64 self.num_layers = 3 self.project_channels = 20 self.dr...
class augmentations(object): def __init__(self): self.scale_ratio = 1.1 self.jitter_ratio = 0.1
class Config(object): def __init__(self): self.dataset = 'UCR' self.input_channels = 1 self.kernel_size = 8 self.stride = 1 self.final_out_channels = 64 self.hidden_size = 128 self.num_layers = 3 self.project_channels = 32 self.dropout = 0.4...