code
stringlengths
17
6.64M
def run_model(method: str, classes: List[str], backbone: str): results = {} for cls in classes: if (method == 'spade'): model = SPADE(k=50, backbone_name=backbone) elif (method == 'padim'): model = PaDiM(d_reduced=350, backbone_name=backbone) elif (method == 'pa...
@click.command() @click.argument('method') @click.option('--dataset', default='all', help='Dataset name, defaults to all datasets.') @click.option('--backbone', default='wide_resnet50_2', help='The TIMM compatible backbone.') def cli_interface(method: str, dataset: str, backbone: str): if (dataset == 'all'): ...
def get_tqdm_params(): return TQDM_PARAMS
class GaussianBlur(): def __init__(self, radius: int=4): self.radius = radius self.unload = transforms.ToPILImage() self.load = transforms.ToTensor() self.blur_kernel = ImageFilter.GaussianBlur(radius=4) def __call__(self, img): map_max = img.max() final_map =...
def get_coreset_idx_randomp(z_lib: tensor, n: int=1000, eps: float=0.9, float16: bool=True, force_cpu: bool=False) -> tensor: 'Returns n coreset idx for given z_lib.\n \n Performance on AMD3700, 32GB RAM, RTX3080 (10GB):\n CPU: 40-60 it/s, GPU: 500+ it/s (float32), 1500+ it/s (float16)\n\n Args:\n ...
def print_and_export_results(results: dict, method: str): 'Writes results to .yaml and serialized results to .txt.' print('\n โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ') print(' โ”‚ Results summary โ”‚') print(' โ”ขโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ช') print(f" โ”ƒ average image rocauc: {results['averag...
def serialize_results(results: dict) -> str: 'Serialize a results dict into something usable in markdown.' n_first_col = 20 ans = [] for (k, v) in results.items(): s = (k + (' ' * (n_first_col - len(k)))) s = (s + f'| {(v[0] * 100):.1f} | {(v[1] * 100):.1f} |') ans.append(s) ...
def tensor_to_img(x, normalize=False): if normalize: x *= IMAGENET_STD.unsqueeze((- 1)).unsqueeze((- 1)) x += IMAGENET_MEAN.unsqueeze((- 1)).unsqueeze((- 1)) x = x.clip(0.0, 1.0).permute(1, 2, 0).detach().numpy() return x
def pred_to_img(x, range): (range_min, range_max) = range x -= range_min if ((range_max - range_min) > 0): x /= (range_max - range_min) return tensor_to_img(x)
def show_pred(sample, score, fmap, range): sample_img = tensor_to_img(sample, normalize=True) fmap_img = pred_to_img(fmap, range) plt.imshow(sample_img) plt.imshow(fmap_img, cmap='jet', alpha=0.5) plt.axis('off') buf = io.BytesIO() plt.savefig(buf, format='png', bbox_inches='tight', pad_in...
def get_sample_images(dataset, n): n_data = len(dataset) ans = [] if (n < n_data): indexes = np.random.choice(n_data, n, replace=False) else: indexes = list(range(n_data)) for index in indexes: (sample, _) = dataset[index] ans.append(tensor_to_img(sample, normalize=...
def main(): with open('./docs/streamlit_instructions.md', 'r') as file: md_file = file.read() st.markdown(md_file) st.sidebar.title('Config') app_custom_dataset = st.sidebar.checkbox('Custom dataset', False) if app_custom_dataset: app_custom_train_images = st.sidebar.file_uploader(...
@contextmanager def st_redirect(src, dst, msg): 'https://discuss.streamlit.io/t/cannot-print-the-terminal-output-in-streamlit/6602' placeholder = st.info(msg) sleep(3) output_func = getattr(placeholder, dst) with StringIO() as buffer: old_write = src.write def new_write(b): ...
@contextmanager def st_stdout(dst, msg): 'https://discuss.streamlit.io/t/cannot-print-the-terminal-output-in-streamlit/6602' with st_redirect(sys.stdout, dst, msg): (yield)
@contextmanager def st_stderr(dst): 'https://discuss.streamlit.io/t/cannot-print-the-terminal-output-in-streamlit/6602' with st_redirect(sys.stderr, dst): (yield)
def main(): with tf.Session() as sess: (model_cfg, model_outputs) = posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride'] num_images = args.num_images filenames = [f.path for f in os.scandir(args.image_dir) if (f.is_file() and f.path.endswith(('.png', '.jp...
def main(): if (not os.path.exists(args.image_dir)): os.makedirs(args.image_dir) for f in TEST_IMAGES: url = os.path.join(GOOGLE_CLOUD_IMAGE_BUCKET, f) print(('Downloading %s' % f)) urllib.request.urlretrieve(url, os.path.join(args.image_dir, f))
def load_config(config_name='config.yaml'): cfg_f = open(os.path.join(BASE_DIR, config_name), 'r+') cfg = yaml.load(cfg_f) return cfg
def download_file(checkpoint, filename, base_dir): output_path = os.path.join(base_dir, checkpoint, filename) url = posixpath.join(GOOGLE_CLOUD_STORAGE_DIR, checkpoint, filename) req = urllib.request.Request(url) response = urllib.request.urlopen(req) if (response.info().get('Content-Encoding') ==...
def download(checkpoint, base_dir='./weights/'): save_dir = os.path.join(base_dir, checkpoint) if (not os.path.exists(save_dir)): os.makedirs(save_dir) download_file(checkpoint, 'manifest.json', base_dir) with open(os.path.join(save_dir, 'manifest.json'), 'r') as f: json_dict = json.lo...
def main(): checkpoint = CHECKPOINTS[CHK] download(checkpoint)
def traverse_to_targ_keypoint(edge_id, source_keypoint, target_keypoint_id, scores, offsets, output_stride, displacements): height = scores.shape[0] width = scores.shape[1] source_keypoint_indices = np.clip(np.round((source_keypoint / output_stride)), a_min=0, a_max=[(height - 1), (width - 1)]).astype(np....
def decode_pose(root_score, root_id, root_image_coord, scores, offsets, output_stride, displacements_fwd, displacements_bwd): num_parts = scores.shape[2] num_edges = len(PARENT_CHILD_TUPLES) instance_keypoint_scores = np.zeros(num_parts) instance_keypoint_coords = np.zeros((num_parts, 2)) instance...
def model_id_to_ord(model_id): if (0 <= model_id < 4): return model_id elif (model_id == 50): return 0 elif (model_id == 75): return 1 elif (model_id == 100): return 2 else: return 3
def load_config(model_ord): converter_cfg = posenet.converter.config.load_config() checkpoints = converter_cfg['checkpoints'] output_stride = converter_cfg['outputStride'] checkpoint_name = checkpoints[model_ord] model_cfg = {'output_stride': output_stride, 'checkpoint_name': checkpoint_name} ...
def load_model(model_id, sess, model_dir=MODEL_DIR): model_ord = model_id_to_ord(model_id) model_cfg = load_config(model_ord) model_path = os.path.join(model_dir, ('model-%s.pb' % model_cfg['checkpoint_name'])) if (not os.path.exists(model_path)): print(('Cannot find model file %s, converting ...
def main(): with tf.Session() as sess: (model_cfg, model_outputs) = posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride'] if (args.file is not None): cap = cv2.VideoCapture(args.file) else: cap = cv2.VideoCapture(args.cam_id) ...
def pooling_factor(pool_type='avg'): return (2 if (pool_type == 'avgmaxc') else 1)
def adaptive_avgmax_pool2d(x, pool_type='avg', padding=0, count_include_pad=False): 'Selectable global pooling function with dynamic input kernel size\n ' if (pool_type == 'avgmaxc'): x = torch.cat([F.avg_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include...
class AdaptiveAvgMaxPool2d(torch.nn.Module): 'Selectable global pooling layer with dynamic input kernel size\n ' def __init__(self, output_size=1, pool_type='avg'): super(AdaptiveAvgMaxPool2d, self).__init__() self.output_size = output_size self.pool_type = pool_type if ((p...
def _convert_bn(k): aux = False if (k == 'bias'): add = 'beta' elif (k == 'weight'): add = 'gamma' elif (k == 'running_mean'): aux = True add = 'moving_mean' elif (k == 'running_var'): aux = True add = 'moving_var' else: assert False, ('U...
def convert_from_mxnet(model, checkpoint_prefix, debug=False): (_, mxnet_weights, mxnet_aux) = mxnet.model.load_checkpoint(checkpoint_prefix, 0) remapped_state = {} for state_key in model.state_dict().keys(): k = state_key.split('.') aux = False mxnet_key = '' if (k[(- 1)] ...
def main(): args = parser.parse_args() if ('dpn' not in args.model): print('Error: Can only convert DPN models.') exit(1) if (not has_mxnet): print('Error: Cannot import MXNet module. Please install.') exit(1) model = model_factory.create_model(args.model, num_classes=1...
def natural_key(string_): 'See http://www.codinghorror.com/blog/archives/001018.html' return [(int(s) if s.isdigit() else s) for s in re.split('(\\d+)', string_.lower())]
def find_images_and_targets(folder, types=IMG_EXTENSIONS, class_to_idx=None, leaf_name_only=True, sort=True): if (class_to_idx is None): class_to_idx = dict() build_class_idx = True else: build_class_idx = False labels = [] filenames = [] for (root, subdirs, files) in os.wa...
class Dataset(data.Dataset): def __init__(self, root, transform=None): (imgs, _, _) = find_images_and_targets(root) if (len(imgs) == 0): raise RuntimeError(((('Found 0 images in subfolders of: ' + root) + '\nSupported image extensions are: ') + ','.join(IMG_EXTENSIONS))) self....
def main(): args = parser.parse_args() num_classes = 1000 model = model_factory.create_model(args.model, num_classes=num_classes, pretrained=args.pretrained, test_time_pool=args.test_time_pool) if (args.restore_checkpoint and os.path.isfile(args.restore_checkpoint)): print("=> loading checkpoi...
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val...
def create_model(model_name, num_classes=1000, pretrained=False, **kwargs): if ('test_time_pool' in kwargs): test_time_pool = kwargs.pop('test_time_pool') else: test_time_pool = True if (model_name == 'dpn68'): model = dpn68(pretrained=pretrained, test_time_pool=test_time_pool, num...
class LeNormalize(object): 'Normalize to -1..1 in Google Inception style\n ' def __call__(self, tensor): for t in tensor: t.sub_(0.5).mul_(2.0) return tensor
def get_transforms_eval(model_name, img_size=224, crop_pct=None): crop_pct = (crop_pct or DEFAULT_CROP_PCT) if ('dpn' in model_name): if (crop_pct is None): if (img_size == 224): scale_size = int(math.floor((img_size / DEFAULT_CROP_PCT))) else: s...
def main(): args = parser.parse_args() test_time_pool = False if (('dpn' in args.model) and (args.img_size > 224) and (not args.no_test_pool)): test_time_pool = True if ((not args.checkpoint) and (not args.pretrained)): args.pretrained = True num_classes = 1000 model = model_fa...
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val...
def accuracy(output, target, topk=(1,)): 'Computes the precision@k for the specified values of k' 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)).expand_as(pred)) res = [] for k in topk: ...
def main(): args = parser.parse_args() args.gpu_id = 0 if args.c2_prefix: args.c2_init = (args.c2_prefix + '.init.pb') args.c2_predict = (args.c2_prefix + '.predict.pb') model = model_helper.ModelHelper(name='le_net', init_params=False) init_net_proto = caffe2_pb2.NetDef() with...
def natural_key(string_): 'See http://www.codinghorror.com/blog/archives/001018.html' return [(int(s) if s.isdigit() else s) for s in re.split('(\\d+)', string_.lower())]
def find_images_and_targets(folder, types=IMG_EXTENSIONS, class_to_idx=None, leaf_name_only=True, sort=True): if (class_to_idx is None): class_to_idx = dict() build_class_idx = True else: build_class_idx = False labels = [] filenames = [] for (root, subdirs, files) in os.wa...
class Dataset(data.Dataset): def __init__(self, root, transform=None, load_bytes=False): (imgs, _, _) = find_images_and_targets(root) if (len(imgs) == 0): raise RuntimeError(((('Found 0 images in subfolders of: ' + root) + '\nSupported image extensions are: ') + ','.join(IMG_EXTENSION...
def fast_collate(batch): targets = torch.tensor([b[1] for b in batch], dtype=torch.int64) batch_size = len(targets) tensor = torch.zeros((batch_size, *batch[0][0].shape), dtype=torch.uint8) for i in range(batch_size): tensor[i] += torch.from_numpy(batch[i][0]) return (tensor, targets)
class PrefetchLoader(): def __init__(self, loader, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD): self.loader = loader self.mean = torch.tensor([(x * 255) for x in mean]).cuda().view(1, 3, 1, 1) self.std = torch.tensor([(x * 255) for x in std]).cuda().view(1, 3, 1, 1) def __i...
def create_loader(dataset, input_size, batch_size, is_training=False, use_prefetcher=True, interpolation='bilinear', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_workers=1, crop_pct=None, tensorflow_preprocessing=False): if isinstance(input_size, tuple): img_size = input_size[(- 2):] else...
def distorted_bounding_box_crop(image_bytes, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None): 'Generates cropped_image using one of the bboxes randomly distorted.\n\n See `tf.image.sample_distorted_bounding_box` for more documentation.\n\n ...
def _at_least_x_are_equal(a, b, x): 'At least `x` of `a` and `b` `Tensors` are equal.' match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x)
def _decode_and_random_crop(image_bytes, image_size, resize_method): 'Make a random crop of image_size.' bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) image = distorted_bounding_box_crop(image_bytes, bbox, min_object_covered=0.1, aspect_ratio_range=((3.0 / 4), (4.0 / 3.0)), a...
def _decode_and_center_crop(image_bytes, image_size, resize_method): 'Crops to center of image with padding then scales image_size.' shape = tf.image.extract_jpeg_shape(image_bytes) image_height = shape[0] image_width = shape[1] padded_center_crop_size = tf.cast(((image_size / (image_size + CROP_P...
def _flip(image): 'Random horizontal image flip.' image = tf.image.random_flip_left_right(image) return image
def preprocess_for_train(image_bytes, use_bfloat16, image_size=IMAGE_SIZE, interpolation='bicubic'): 'Preprocesses the given image for evaluation.\n\n Args:\n image_bytes: `Tensor` representing an image binary of arbitrary size.\n use_bfloat16: `bool` for whether to use bfloat16.\n image_size: i...
def preprocess_for_eval(image_bytes, use_bfloat16, image_size=IMAGE_SIZE, interpolation='bicubic'): 'Preprocesses the given image for evaluation.\n\n Args:\n image_bytes: `Tensor` representing an image binary of arbitrary size.\n use_bfloat16: `bool` for whether to use bfloat16.\n image_size: im...
def preprocess_image(image_bytes, is_training=False, use_bfloat16=False, image_size=IMAGE_SIZE, interpolation='bicubic'): 'Preprocesses the given image.\n\n Args:\n image_bytes: `Tensor` representing an image binary of arbitrary size.\n is_training: `bool` for whether the preprocessing is for trainin...
class TfPreprocessTransform(): def __init__(self, is_training=False, size=224, interpolation='bicubic'): self.is_training = is_training self.size = (size[0] if isinstance(size, tuple) else size) self.interpolation = interpolation self._image_bytes = None self.process_image...
def resolve_data_config(model, args, default_cfg={}, verbose=True): new_config = {} default_cfg = default_cfg if ((not default_cfg) and (model is not None) and hasattr(model, 'default_cfg')): default_cfg = model.default_cfg in_chans = 3 input_size = (in_chans, 224, 224) if (args.img_si...
class ToNumpy(): def __call__(self, pil_img): np_img = np.array(pil_img, dtype=np.uint8) if (np_img.ndim < 3): np_img = np.expand_dims(np_img, axis=(- 1)) np_img = np.rollaxis(np_img, 2) return np_img
class ToTensor(): def __init__(self, dtype=torch.float32): self.dtype = dtype def __call__(self, pil_img): np_img = np.array(pil_img, dtype=np.uint8) if (np_img.ndim < 3): np_img = np.expand_dims(np_img, axis=(- 1)) np_img = np.rollaxis(np_img, 2) return t...
def _pil_interp(method): if (method == 'bicubic'): return Image.BICUBIC elif (method == 'lanczos'): return Image.LANCZOS elif (method == 'hamming'): return Image.HAMMING else: return Image.BILINEAR
def transforms_imagenet_eval(img_size=224, crop_pct=None, interpolation='bilinear', use_prefetcher=False, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD): crop_pct = (crop_pct or DEFAULT_CROP_PCT) if isinstance(img_size, tuple): assert (len(img_size) == 2) if (img_size[(- 1)] == img_size...
def add_override_act_fn(name, fn): global _OVERRIDE_FN _OVERRIDE_FN[name] = fn
def update_override_act_fn(overrides): assert isinstance(overrides, dict) global _OVERRIDE_FN _OVERRIDE_FN.update(overrides)
def clear_override_act_fn(): global _OVERRIDE_FN _OVERRIDE_FN = dict()
def add_override_act_layer(name, fn): _OVERRIDE_LAYER[name] = fn
def update_override_act_layer(overrides): assert isinstance(overrides, dict) global _OVERRIDE_LAYER _OVERRIDE_LAYER.update(overrides)
def clear_override_act_layer(): global _OVERRIDE_LAYER _OVERRIDE_LAYER = dict()
def get_act_fn(name='relu'): ' Activation Function Factory\n Fetching activation fns by name with this function allows export or torch script friendly\n functions to be returned dynamically based on current config.\n ' if (name in _OVERRIDE_FN): return _OVERRIDE_FN[name] use_me = (not (co...
def get_act_layer(name='relu'): ' Activation Layer Factory\n Fetching activation layers by name with this function allows export or torch script friendly\n functions to be returned dynamically based on current config.\n ' if (name in _OVERRIDE_LAYER): return _OVERRIDE_LAYER[name] use_me =...
def swish(x, inplace: bool=False): 'Swish - Described originally as SiLU (https://arxiv.org/abs/1702.03118v3)\n and also as Swish (https://arxiv.org/abs/1710.05941).\n\n TODO Rename to SiLU with addition to PyTorch\n ' return (x.mul_(x.sigmoid()) if inplace else x.mul(x.sigmoid()))
class Swish(nn.Module): def __init__(self, inplace: bool=False): super(Swish, self).__init__() self.inplace = inplace def forward(self, x): return swish(x, self.inplace)
def mish(x, inplace: bool=False): 'Mish: A Self Regularized Non-Monotonic Neural Activation Function - https://arxiv.org/abs/1908.08681\n ' return x.mul(F.softplus(x).tanh())
class Mish(nn.Module): def __init__(self, inplace: bool=False): super(Mish, self).__init__() self.inplace = inplace def forward(self, x): return mish(x, self.inplace)
def sigmoid(x, inplace: bool=False): return (x.sigmoid_() if inplace else x.sigmoid())
class Sigmoid(nn.Module): def __init__(self, inplace: bool=False): super(Sigmoid, self).__init__() self.inplace = inplace def forward(self, x): return (x.sigmoid_() if self.inplace else x.sigmoid())
def tanh(x, inplace: bool=False): return (x.tanh_() if inplace else x.tanh())
class Tanh(nn.Module): def __init__(self, inplace: bool=False): super(Tanh, self).__init__() self.inplace = inplace def forward(self, x): return (x.tanh_() if self.inplace else x.tanh())
def hard_swish(x, inplace: bool=False): inner = F.relu6((x + 3.0)).div_(6.0) return (x.mul_(inner) if inplace else x.mul(inner))
class HardSwish(nn.Module): def __init__(self, inplace: bool=False): super(HardSwish, self).__init__() self.inplace = inplace def forward(self, x): return hard_swish(x, self.inplace)
def hard_sigmoid(x, inplace: bool=False): if inplace: return x.add_(3.0).clamp_(0.0, 6.0).div_(6.0) else: return (F.relu6((x + 3.0)) / 6.0)
class HardSigmoid(nn.Module): def __init__(self, inplace: bool=False): super(HardSigmoid, self).__init__() self.inplace = inplace def forward(self, x): return hard_sigmoid(x, self.inplace)
@torch.jit.script def swish_jit(x, inplace: bool=False): 'Swish - Described originally as SiLU (https://arxiv.org/abs/1702.03118v3)\n and also as Swish (https://arxiv.org/abs/1710.05941).\n\n TODO Rename to SiLU with addition to PyTorch\n ' return x.mul(x.sigmoid())
@torch.jit.script def mish_jit(x, _inplace: bool=False): 'Mish: A Self Regularized Non-Monotonic Neural Activation Function - https://arxiv.org/abs/1908.08681\n ' return x.mul(F.softplus(x).tanh())
class SwishJit(nn.Module): def __init__(self, inplace: bool=False): super(SwishJit, self).__init__() def forward(self, x): return swish_jit(x)
class MishJit(nn.Module): def __init__(self, inplace: bool=False): super(MishJit, self).__init__() def forward(self, x): return mish_jit(x)
@torch.jit.script def hard_sigmoid_jit(x, inplace: bool=False): return (x + 3).clamp(min=0, max=6).div(6.0)
class HardSigmoidJit(nn.Module): def __init__(self, inplace: bool=False): super(HardSigmoidJit, self).__init__() def forward(self, x): return hard_sigmoid_jit(x)
@torch.jit.script def hard_swish_jit(x, inplace: bool=False): return (x * (x + 3).clamp(min=0, max=6).div(6.0))
class HardSwishJit(nn.Module): def __init__(self, inplace: bool=False): super(HardSwishJit, self).__init__() def forward(self, x): return hard_swish_jit(x)
@torch.jit.script def swish_jit_fwd(x): return x.mul(torch.sigmoid(x))
@torch.jit.script def swish_jit_bwd(x, grad_output): x_sigmoid = torch.sigmoid(x) return (grad_output * (x_sigmoid * (1 + (x * (1 - x_sigmoid)))))
class SwishJitAutoFn(torch.autograd.Function): ' torch.jit.script optimised Swish w/ memory-efficient checkpoint\n Inspired by conversation btw Jeremy Howard & Adam Pazske\n https://twitter.com/jeremyphoward/status/1188251041835315200\n\n Swish - Described originally as SiLU (https://arxiv.org/abs/1702.0...
def swish_me(x, inplace=False): return SwishJitAutoFn.apply(x)
class SwishMe(nn.Module): def __init__(self, inplace: bool=False): super(SwishMe, self).__init__() def forward(self, x): return SwishJitAutoFn.apply(x)
@torch.jit.script def mish_jit_fwd(x): return x.mul(torch.tanh(F.softplus(x)))
@torch.jit.script def mish_jit_bwd(x, grad_output): x_sigmoid = torch.sigmoid(x) x_tanh_sp = F.softplus(x).tanh() return grad_output.mul((x_tanh_sp + ((x * x_sigmoid) * (1 - (x_tanh_sp * x_tanh_sp)))))