repo_name
stringlengths 8
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence |
---|---|---|---|---|
adcrn/knest | [
"a274dc9ddb642cc30f837e225f000bf33430eb43"
] | [
"utils/compare.py"
] | [
"# UCF Senior Design 2017-18\n# Group 38\n\nfrom PIL import Image\nimport cv2\nimport imagehash\nimport math\nimport numpy as np\n\nDIFF_THRES = 20\nLIMIT = 2\nRESIZE = 1000\n\n\ndef calc_hash(img):\n \"\"\"\n Calculate the wavelet hash of the image\n img: (ndarray) image file\n \"\"\"\n # resize image if height > 1000\n img = resize(img)\n return imagehash.whash(Image.fromarray(img))\n\n\ndef compare(hash1, hash2):\n \"\"\"\n Calculate the difference between two images\n hash1: (array) first wavelet hash\n hash2: (array) second wavelet hash\n \"\"\"\n return hash1 - hash2\n\n\ndef limit(img, std_hash, count):\n \"\"\"\n Determine whether image should be removed from image dictionary in main.py\n img: (ndarray) image file\n std_hash: (array) wavelet hash of comparison standard\n count: (int) global count of images similar to comparison standard\n \"\"\"\n # calculate hash for given image\n cmp_hash = calc_hash(img)\n\n # compare to standard\n diff = compare(std_hash, cmp_hash)\n\n # image is similar to standard\n if diff <= DIFF_THRES:\n # if there are 3 similar images already, remove image\n if count >= LIMIT:\n return 'remove'\n\n # non-similar image found\n else:\n # update comparison standard\n return 'update_std'\n\n # else continue reading images with same standard\n return 'continue'\n\n\ndef resize(img):\n \"\"\"\n Resize an image\n img: (ndarray) RGB color image\n \"\"\"\n # get dimensions of image\n width = np.shape(img)[1]\n height = np.shape(img)[0]\n\n # if height of image is greater than 1000, resize it to 1000\n if width > RESIZE:\n # keep resize proportional\n scale = RESIZE / width\n resized_img = cv2.resize(\n img, (RESIZE, math.floor(height / scale)), cv2.INTER_AREA)\n # return resized image\n return resized_img\n\n # if height of image is less than 1000, return image unresized\n return img\n\n\ndef set_standard(images, filename):\n \"\"\"\n Set new comparison standard and update information\n images: (dictionary) dictionary containing all the image data\n filename: (String) name of the image file\n \"\"\"\n return filename, calc_hash(images[filename]), 0\n"
] | [
[
"numpy.shape"
]
] |
dongmengshi/easylearn | [
"df528aaa69c3cf61f5459a04671642eb49421dfb",
"df528aaa69c3cf61f5459a04671642eb49421dfb"
] | [
"eslearn/utils/lc_featureSelection_variance.py",
"eslearn/machine_learning/test/GCNNCourseCodes/metrics.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 24 14:38:20 2018\ndimension reduction with VarianceThreshold using sklearn.\nFeature selector that removes all low-variance features.\n@author: lenovo\n\"\"\"\nfrom sklearn.feature_selection import VarianceThreshold\nimport numpy as np\n#\nnp.random.seed(1)\nX = np.random.randn(100, 10)\nX = np.hstack([X, np.zeros([100, 5])])\n#\n\n\ndef featureSelection_variance(X, thrd):\n sel = VarianceThreshold(threshold=thrd)\n X_selected = sel.fit_transform(X)\n mask = sel.get_support()\n return X_selected, mask\n\n\nX = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]\nselector = VarianceThreshold()\nselector.fit_transform(X)\nselector.variances_\n",
"import tensorflow as tf\n\n\ndef masked_softmax_cross_entropy(preds, labels, mask):\n \"\"\"Softmax cross-entropy loss with masking.\"\"\"\n loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels) \n mask = tf.cast(mask, dtype=tf.float32)\n mask /= tf.reduce_mean(mask)\n loss *= mask\n return tf.reduce_mean(loss)\n\ndef sigmoid_cross_entropy(preds, labels):\n \"\"\"Softmax cross-entropy loss with masking.\"\"\"\n loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=preds, labels=labels) \n return tf.reduce_mean(loss)\n\ndef softmax_cross_entropy(preds, labels):\n \"\"\"Softmax cross-entropy loss with masking.\"\"\"\n loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels) \n return tf.reduce_mean(loss)\n\ndef masked_accuracy(preds, labels, mask):\n \"\"\"Accuracy with masking.\"\"\"\n correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1))\n accuracy_all = tf.cast(correct_prediction, tf.float32)\n mask = tf.cast(mask, dtype=tf.float32)\n mask /= tf.reduce_mean(mask)\n accuracy_all *= mask\n return tf.reduce_mean(accuracy_all)\n\ndef inductive_multiaccuracy(preds, labels):\n \"\"\"Accuracy with masking.\"\"\"\n\n correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1)) \n return tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n\ndef inductive_accuracy(preds, labels):\n \"\"\"Accuracy with masking.\"\"\"\n\n predicted = tf.nn.sigmoid(preds)\n correct_pred = tf.equal(tf.round(predicted), labels)\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) \n return accuracy\n"
] | [
[
"numpy.random.randn",
"numpy.random.seed",
"numpy.zeros",
"sklearn.feature_selection.VarianceThreshold"
],
[
"tensorflow.nn.sigmoid_cross_entropy_with_logits",
"tensorflow.nn.sigmoid",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.round",
"tensorflow.reduce_mean",
"tensorflow.cast",
"tensorflow.argmax"
]
] |
silent567/examples | [
"e9de12549125ecd93a4924f6b8e2bbf66d7635d9"
] | [
"mnist/my_multi_tune3.py"
] | [
"#!/usr/bin/env python\n# coding=utf-8\n\nfrom my_multi_main3 import main\nimport numpy as np\nimport argparse\nimport time\n\nparser = argparse.ArgumentParser(description='PyTorch MNIST Example')\nparser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\nparser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\nparser.add_argument('--momentum', type=float, default=0.5, metavar='M',\n help='SGD momentum (default: 0.5)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--save-model', action='store_true', default=False,\n help='For Saving the current Model')\nparser.add_argument('--norm-flag', type=bool, default=False,\n help='Triggering the Layer Normalization flag for attention scores')\nparser.add_argument('--gamma', type=float, default=None,\n help='Controlling the sparisty of gfusedmax/sparsemax, the smaller, the more sparse')\nparser.add_argument('--lam', type=float, default=1.0,\n help='Lambda: Controlling the smoothness of gfusedmax, the larger, the smoother')\nparser.add_argument('--max-type', type=str, default='softmax',choices=['softmax','sparsemax','gfusedmax'],\n help='mapping function in attention')\nparser.add_argument('--optim-type', type=str, default='SGD',choices=['SGD','Adam'],\n help='mapping function in attention')\nparser.add_argument('--head-cnt', type=int, default=2, metavar='S', choices=[1,2,4,5,10],\n help='Number of heads for attention (default: 1)')\n\nargs = parser.parse_args()\n\nhyperparameter_choices = {\n 'lr':list(10**np.arange(-4,-1,0.5)),\n 'norm_flag': [True,False],\n 'gamma':list(10**np.arange(-1,3,0.5))+[None,],\n 'lam':list(10**np.arange(-2,2,0.5)),\n 'max_type':['softmax','sparsemax','gfusedmax'],\n # 'max_type':['sparsemax'],\n 'optim_type':['SGD','Adam'],\n 'head_cnt':[1,2,4,5,10,20]\n}\n\nparam_num = 25\nrecord = np.zeros([param_num,len(hyperparameter_choices)+1])\nrecord_name = 'record3_multi_%s.csv'%time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())\nfor n in range(param_num):\n for param_index,(k,v) in enumerate(hyperparameter_choices.items()):\n print(param_index,k)\n value_index = np.random.choice(len(v))\n if isinstance(v[value_index],str) or isinstance(v[value_index],bool) or v[value_index] is None:\n record[n,param_index] = value_index\n else:\n record[n,param_index] = v[value_index]\n setattr(args,k,v[value_index])\n record[n,-1] = main(args)\n np.savetxt(record_name, record, delimiter=',')\n\n\n\n"
] | [
[
"numpy.arange",
"numpy.savetxt"
]
] |
neonbjb/DL-Art-School | [
"a6f0f854b987ac724e258af8b042ea4459a571bc"
] | [
"codes/data/image_corruptor.py"
] | [
"import functools\nimport random\nfrom math import cos, pi\n\nimport cv2\nimport kornia\nimport numpy as np\nimport torch\nfrom kornia.augmentation import ColorJitter\n\nfrom data.util import read_img\nfrom PIL import Image\nfrom io import BytesIO\n\n\n# Get a rough visualization of the above distribution. (Y-axis is meaningless, just spreads data)\nfrom utils.util import opt_get\n\n'''\nif __name__ == '__main__':\n import numpy as np\n import matplotlib.pyplot as plt\n data = np.asarray([get_rand() for _ in range(5000)])\n plt.plot(data, np.random.uniform(size=(5000,)), 'x')\n plt.show()\n'''\n\n\ndef kornia_color_jitter_numpy(img, setting):\n if setting * 255 > 1:\n # I'm using Kornia's ColorJitter, which requires pytorch arrays in b,c,h,w format.\n img = torch.from_numpy(img).permute(2,0,1).unsqueeze(0)\n img = ColorJitter(setting, setting, setting, setting)(img)\n img = img.squeeze(0).permute(1,2,0).numpy()\n return img\n\n\n# Performs image corruption on a list of images from a configurable set of corruption\n# options.\nclass ImageCorruptor:\n def __init__(self, opt):\n self.opt = opt\n self.reset_random()\n self.blur_scale = opt['corruption_blur_scale'] if 'corruption_blur_scale' in opt.keys() else 1\n self.fixed_corruptions = opt['fixed_corruptions'] if 'fixed_corruptions' in opt.keys() else []\n self.num_corrupts = opt['num_corrupts_per_image'] if 'num_corrupts_per_image' in opt.keys() else 0\n self.cosine_bias = opt_get(opt, ['cosine_bias'], True)\n if self.num_corrupts == 0:\n return\n else:\n self.random_corruptions = opt['random_corruptions'] if 'random_corruptions' in opt.keys() else []\n\n def reset_random(self):\n if 'random_seed' in self.opt.keys():\n self.rand = random.Random(self.opt['random_seed'])\n else:\n self.rand = random.Random()\n\n # Feeds a random uniform through a cosine distribution to slightly bias corruptions towards \"uncorrupted\".\n # Return is on [0,1] with a bias towards 0.\n def get_rand(self):\n r = self.rand.random()\n if self.cosine_bias:\n return 1 - cos(r * pi / 2)\n else:\n return r\n\n def corrupt_images(self, imgs, return_entropy=False):\n if self.num_corrupts == 0 and not self.fixed_corruptions:\n if return_entropy:\n return imgs, []\n else:\n return imgs\n\n if self.num_corrupts == 0:\n augmentations = []\n else:\n augmentations = random.choices(self.random_corruptions, k=self.num_corrupts)\n\n # Sources of entropy\n corrupted_imgs = []\n entropy = []\n undo_fns = []\n applied_augs = augmentations + self.fixed_corruptions\n for img in imgs:\n for aug in augmentations:\n r = self.get_rand()\n img, undo_fn = self.apply_corruption(img, aug, r, applied_augs)\n if undo_fn is not None:\n undo_fns.append(undo_fn)\n for aug in self.fixed_corruptions:\n r = self.get_rand()\n img, undo_fn = self.apply_corruption(img, aug, r, applied_augs)\n entropy.append(r)\n if undo_fn is not None:\n undo_fns.append(undo_fn)\n # Apply undo_fns after all corruptions are finished, in same order.\n for ufn in undo_fns:\n img = ufn(img)\n corrupted_imgs.append(img)\n\n\n if return_entropy:\n return corrupted_imgs, entropy\n else:\n return corrupted_imgs\n\n def apply_corruption(self, img, aug, rand_val, applied_augmentations):\n undo_fn = None\n if 'color_quantization' in aug:\n # Color quantization\n quant_div = 2 ** (int(rand_val * 10 / 3) + 2)\n img = img * 255\n img = (img // quant_div) * quant_div\n img = img / 255\n elif 'color_jitter' in aug:\n lo_end = 0\n hi_end = .2\n setting = rand_val * (hi_end - lo_end) + lo_end\n img = kornia_color_jitter_numpy(img, setting)\n elif 'gaussian_blur' in aug:\n img = cv2.GaussianBlur(img, (0,0), self.blur_scale*rand_val*1.5)\n elif 'motion_blur' in aug:\n # Motion blur\n intensity = self.blur_scale*rand_val * 3 + 1\n angle = random.randint(0,360)\n k = np.zeros((intensity, intensity), dtype=np.float32)\n k[(intensity - 1) // 2, :] = np.ones(intensity, dtype=np.float32)\n k = cv2.warpAffine(k, cv2.getRotationMatrix2D((intensity / 2 - 0.5, intensity / 2 - 0.5), angle, 1.0),\n (intensity, intensity))\n k = k * (1.0 / np.sum(k))\n img = cv2.filter2D(img, -1, k)\n elif 'block_noise' in aug:\n # Large distortion blocks in part of an img, such as is used to mask out a face.\n pass\n elif 'lq_resampling' in aug:\n # Random mode interpolation HR->LR->HR\n if 'lq_resampling4x' == aug:\n scale = 4\n else:\n if rand_val < .3:\n scale = 1\n elif rand_val < .7:\n scale = 2\n else:\n scale = 4\n if scale > 1:\n interpolation_modes = [cv2.INTER_NEAREST, cv2.INTER_CUBIC, cv2.INTER_LINEAR, cv2.INTER_LANCZOS4]\n mode = random.randint(0,4) % len(interpolation_modes)\n # Downsample first, then upsample using the random mode.\n img = cv2.resize(img, dsize=(img.shape[1]//scale, img.shape[0]//scale), interpolation=mode)\n def lq_resampling_undo_fn(scale, img):\n return cv2.resize(img, dsize=(img.shape[1]*scale, img.shape[0]*scale), interpolation=cv2.INTER_LINEAR)\n undo_fn = functools.partial(lq_resampling_undo_fn, scale)\n elif 'color_shift' in aug:\n # Color shift\n pass\n elif 'interlacing' in aug:\n # Interlacing distortion\n pass\n elif 'chromatic_aberration' in aug:\n # Chromatic aberration\n pass\n elif 'noise' in aug:\n # Random noise\n if 'noise-5' == aug:\n noise_intensity = 5 / 255.0\n else:\n noise_intensity = (rand_val*6) / 255.0\n img += np.random.rand(*img.shape) * noise_intensity\n elif 'jpeg' in aug:\n if 'noise' not in applied_augmentations and 'noise-5' not in applied_augmentations:\n if aug == 'jpeg':\n lo=10\n range=20\n elif aug == 'jpeg-low':\n lo=15\n range=10\n elif aug == 'jpeg-medium':\n lo=23\n range=25\n elif aug == 'jpeg-broad':\n lo=15\n range=60\n elif aug == 'jpeg-normal':\n lo=47\n range=35\n else:\n raise NotImplementedError(\"specified jpeg corruption doesn't exist\")\n # JPEG compression\n qf = (int((1-rand_val)*range) + lo)\n # Use PIL to perform a mock compression to a data buffer, then swap back to cv2.\n img = (img * 255).astype(np.uint8)\n img = Image.fromarray(img)\n buffer = BytesIO()\n img.save(buffer, \"JPEG\", quality=qf, optimize=True)\n buffer.seek(0)\n jpeg_img_bytes = np.asarray(bytearray(buffer.read()), dtype=\"uint8\")\n img = read_img(\"buffer\", jpeg_img_bytes, rgb=True)\n elif 'saturation' in aug:\n # Lightening / saturation\n saturation = rand_val * .3\n img = np.clip(img + saturation, a_max=1, a_min=0)\n elif 'greyscale' in aug:\n img = np.tile(np.mean(img, axis=2, keepdims=True), [1,1,3])\n elif 'none' not in aug:\n raise NotImplementedError(\"Augmentation doesn't exist\")\n\n return img, undo_fn\n"
] | [
[
"numpy.ones",
"numpy.sum",
"numpy.zeros",
"torch.from_numpy",
"numpy.clip",
"numpy.random.rand",
"numpy.mean"
]
] |
pclucas14/continuum | [
"09034db1371e9646ca660fd4d4df73e61bf77067"
] | [
"tests/test_background_swap.py"
] | [
"import os\n\nfrom torch.utils.data import DataLoader\nfrom continuum.datasets import CIFAR10, InMemoryDataset\nfrom continuum.datasets import MNIST\nimport torchvision\nfrom continuum.scenarios import TransformationIncremental\nimport pytest\nimport numpy as np\n\nfrom continuum.transforms.bg_swap import BackgroundSwap\n\nDATA_PATH = os.environ.get(\"CONTINUUM_DATA_PATH\")\n\n# Uncomment for debugging via image output\n# import matplotlib.pyplot as plt\n\n\ndef test_bg_swap_fast():\n \"\"\"\n Fast test for background swap.\n \"\"\"\n bg_x = np.ones(shape=[2, 5, 5, 3]) * -1\n bg_y = np.random.rand(2)\n\n fg = np.random.normal(loc=.5, scale=.1, size=[5, 5])\n bg = InMemoryDataset(bg_x, bg_y)\n\n bg_swap = BackgroundSwap(bg, input_dim=(5, 5), normalize_bg=None)\n\n spliced_1_channel = bg_swap(fg)[:, :, 0]\n\n assert np.array_equal((spliced_1_channel <= -1), (fg <= .5))\n\n\n@pytest.mark.slow\ndef test_background_swap_numpy():\n \"\"\"\n Test background swap on a single ndarray input.\n \"\"\"\n mnist = MNIST(DATA_PATH, download=True, train=True)\n cifar = CIFAR10(DATA_PATH, download=True, train=True)\n\n bg_swap = BackgroundSwap(cifar, input_dim=(28, 28))\n\n im = mnist.get_data()[0][0]\n im = bg_swap(im)\n\n # Uncomment for debugging\n # plt.imshow(im, interpolation='nearest')\n # plt.show()\n\n\n@pytest.mark.slow\ndef test_background_swap_torch():\n \"\"\"\n Test background swap on a single tensor input.\n \"\"\"\n cifar = CIFAR10(DATA_PATH, download=True, train=True)\n\n mnist = torchvision.datasets.MNIST(DATA_PATH, train=True, download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor()\n ]))\n\n bg_swap = BackgroundSwap(cifar, input_dim=(28, 28))\n im = mnist[0][0]\n\n im = bg_swap(im)\n\n # Uncomment for debugging\n # plt.imshow(im.permute(1, 2, 0), interpolation='nearest')\n # plt.show()\n\n\n@pytest.mark.slow\ndef test_background_tranformation():\n \"\"\"\n Example code using TransformationIncremental to create a setting with 3 tasks.\n \"\"\"\n cifar = CIFAR10(DATA_PATH, train=True)\n mnist = MNIST(DATA_PATH, download=False, train=True)\n nb_task = 3\n list_trsf = []\n for i in range(nb_task):\n list_trsf.append([torchvision.transforms.ToTensor(), BackgroundSwap(cifar, bg_label=i, input_dim=(28, 28)),\n torchvision.transforms.ToPILImage()])\n scenario = TransformationIncremental(mnist, base_transformations=[torchvision.transforms.ToTensor()],\n incremental_transformations=list_trsf)\n folder = \"tests/samples/background_trsf/\"\n if not os.path.exists(folder):\n os.makedirs(folder)\n for task_id, task_data in enumerate(scenario):\n task_data.plot(path=folder, title=f\"background_{task_id}.jpg\", nb_samples=100, shape=[28, 28, 3])\n loader = DataLoader(task_data)\n _, _, _ = next(iter(loader))\n"
] | [
[
"numpy.ones",
"torch.utils.data.DataLoader",
"numpy.random.rand",
"numpy.array_equal",
"numpy.random.normal"
]
] |
g-nightingale/tox_examples | [
"d7714375c764580b4b8af9db61332ced4e851def"
] | [
"packaging/squarer/ml_squarer.py"
] | [
"import numpy as np\n\n\ndef train_ml_squarer() -> None:\n print(\"Training!\")\n\n\ndef square() -> int:\n \"\"\"Square a number...maybe\"\"\"\n return np.random.randint(1, 100)\n\n\nif __name__ == '__main__':\n train_ml_squarer()"
] | [
[
"numpy.random.randint"
]
] |
GOOGLE-M/SGC | [
"78ad8d02b80808302e38559e2d0f430f66a809bd"
] | [
"venv/lib/python3.7/site-packages/torch/utils/benchmark/utils/timer.py"
] | [
"\"\"\"Timer class based on the timeit.Timer class, but torch aware.\"\"\"\nimport enum\nimport timeit\nimport textwrap\nfrom typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union\n\nimport numpy as np\nimport torch\nfrom torch.utils.benchmark.utils import common, cpp_jit\nfrom torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType\nfrom torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface\n\n\n__all__ = [\"Timer\", \"timer\", \"Language\"]\n\n\nif torch.has_cuda and torch.cuda.is_available():\n def timer() -> float:\n torch.cuda.synchronize()\n return timeit.default_timer()\nelse:\n timer = timeit.default_timer\n\n\nclass Language(enum.Enum):\n PYTHON = 0\n CPP = 1\n\n\nclass CPPTimer:\n def __init__(\n self,\n stmt: str,\n setup: str,\n timer: Callable[[], float],\n globals: Dict[str, Any],\n ) -> None:\n if timer is not timeit.default_timer:\n raise NotImplementedError(\n \"PyTorch was built with CUDA and a GPU is present; however \"\n \"Timer does not yet support GPU measurements. If your \"\n \"code is CPU only, pass `timer=timeit.default_timer` to the \"\n \"Timer's constructor to indicate this. (Note that this will \"\n \"produce incorrect results if the GPU is in fact used, as \"\n \"Timer will not synchronize CUDA.)\"\n )\n\n if globals:\n raise ValueError(\"C++ timing does not support globals.\")\n\n self._stmt: str = textwrap.dedent(stmt)\n self._setup: str = textwrap.dedent(setup)\n self._timeit_module: Optional[TimeitModuleType] = None\n\n def timeit(self, number: int) -> float:\n if self._timeit_module is None:\n self._timeit_module = cpp_jit.compile_timeit_template(\n self._stmt,\n self._setup,\n )\n\n return self._timeit_module.timeit(number)\n\n\nclass Timer(object):\n \"\"\"Helper class for measuring execution time of PyTorch statements.\n\n For a full tutorial on how to use this class, see:\n https://pytorch.org/tutorials/recipes/recipes/benchmark.html\n\n The PyTorch Timer is based on `timeit.Timer` (and in fact uses\n `timeit.Timer` internally), but with several key differences:\n\n 1) Runtime aware:\n Timer will perform warmups (important as some elements of PyTorch are\n lazily initialized), set threadpool size so that comparisons are\n apples-to-apples, and synchronize asynchronous CUDA functions when\n necessary.\n\n 2) Focus on replicates:\n When measuring code, and particularly complex kernels / models,\n run-to-run variation is a significant confounding factor. It is\n expected that all measurements should include replicates to quantify\n noise and allow median computation, which is more robust than mean.\n To that effect, this class deviates from the `timeit` API by\n conceptually merging `timeit.Timer.repeat` and `timeit.Timer.autorange`.\n (Exact algorithms are discussed in method docstrings.) The `timeit`\n method is replicated for cases where an adaptive strategy is not\n desired.\n\n 3) Optional metadata:\n When defining a Timer, one can optionally specify `label`, `sub_label`,\n `description`, and `env`. (Defined later) These fields are included in\n the representation of result object and by the `Compare` class to group\n and display results for comparison.\n\n 4) Instruction counts\n In addition to wall times, Timer can run a statement under Callgrind\n and report instructions executed.\n\n Directly analogous to `timeit.Timer` constructor arguments:\n\n `stmt`, `setup`, `timer`, `globals`\n\n PyTorch Timer specific constructor arguments:\n\n `label`, `sub_label`, `description`, `env`, `num_threads`\n\n Args:\n stmt: Code snippet to be run in a loop and timed.\n\n setup: Optional setup code. Used to define variables used in `stmt`\n\n timer:\n Callable which returns the current time. If PyTorch was built\n without CUDA or there is no GPU present, this defaults to\n `timeit.default_timer`; otherwise it will synchronize CUDA before\n measuring the time.\n\n globals:\n A dict which defines the global variables when `stmt` is being\n executed. This is the other method for providing variables which\n `stmt` needs.\n\n label:\n String which summarizes `stmt`. For instance, if `stmt` is\n \"torch.nn.functional.relu(torch.add(x, 1, out=out))\"\n one might set label to \"ReLU(x + 1)\" to improve readability.\n\n sub_label:\n Provide supplemental information to disambiguate measurements\n with identical stmt or label. For instance, in our example\n above sub_label might be \"float\" or \"int\", so that it is easy\n to differentiate:\n \"ReLU(x + 1): (float)\"\n\n \"ReLU(x + 1): (int)\"\n when printing Measurements or summarizing using `Compare`.\n\n description:\n String to distinguish measurements with identical label and\n sub_label. The principal use of `description` is to signal to\n `Compare` the columns of data. For instance one might set it\n based on the input size to create a table of the form: ::\n\n | n=1 | n=4 | ...\n ------------- ...\n ReLU(x + 1): (float) | ... | ... | ...\n ReLU(x + 1): (int) | ... | ... | ...\n\n\n using `Compare`. It is also included when printing a Measurement.\n\n env:\n This tag indicates that otherwise identical tasks were run in\n different environments, and are therefore not equivilent, for\n instance when A/B testing a change to a kernel. `Compare` will\n treat Measurements with different `env` specification as distinct\n when merging replicate runs.\n\n num_threads:\n The size of the PyTorch threadpool when executing `stmt`. Single\n threaded performace is important as both a key inference workload\n and a good indicator of intrinsic algorithmic efficiency, so the\n default is set to one. This is in contrast to the default PyTorch\n threadpool size which tries to utilize all cores.\n \"\"\"\n\n _timer_cls: Type[TimerClass] = timeit.Timer\n\n def __init__(\n self,\n stmt: str = \"pass\",\n setup: str = \"pass\",\n timer: Callable[[], float] = timer,\n globals: Optional[Dict[str, Any]] = None,\n label: Optional[str] = None,\n sub_label: Optional[str] = None,\n description: Optional[str] = None,\n env: Optional[str] = None,\n num_threads: int = 1,\n language: Union[Language, str] = Language.PYTHON,\n ):\n if not isinstance(stmt, str):\n raise ValueError(\"Currently only a `str` stmt is supported.\")\n\n # We copy `globals` to prevent mutations from leaking.\n # (For instance, `eval` adds the `__builtins__` key)\n self._globals = dict(globals or {})\n if language in (Language.PYTHON, \"py\", \"python\"):\n # Include `torch` if not specified as a convenience feature.\n self._globals.setdefault(\"torch\", torch)\n self._language: Language = Language.PYTHON\n\n elif language in (Language.CPP, \"cpp\", \"c++\"):\n assert self._timer_cls is timeit.Timer, \"_timer_cls has already been swapped.\"\n self._timer_cls = CPPTimer\n setup = (\"\" if setup == \"pass\" else setup)\n self._language = Language.CPP\n\n else:\n raise ValueError(f\"Invalid language `{language}`.\")\n\n # Convenience adjustment so that multi-line code snippets defined in\n # functions do not IndentationError (Python) or look odd (C++). The\n # leading newline removal is for the initial newline that appears when\n # defining block strings. For instance:\n # textwrap.dedent(\"\"\"\n # print(\"This is a stmt\")\n # \"\"\")\n # produces '\\nprint(\"This is a stmt\")\\n'.\n #\n # Stripping this down to 'print(\"This is a stmt\")' doesn't change\n # what gets executed, but it makes __repr__'s nicer.\n stmt = textwrap.dedent(stmt)\n stmt = (stmt[1:] if stmt and stmt[0] == \"\\n\" else stmt).rstrip()\n setup = textwrap.dedent(setup)\n setup = (setup[1:] if setup and setup[0] == \"\\n\" else setup).rstrip()\n\n self._timer = self._timer_cls(\n stmt=stmt,\n setup=setup,\n timer=timer,\n globals=valgrind_timer_interface.CopyIfCallgrind.unwrap_all(self._globals),\n )\n self._task_spec = common.TaskSpec(\n stmt=stmt,\n setup=setup,\n label=label,\n sub_label=sub_label,\n description=description,\n env=env,\n num_threads=num_threads,\n )\n\n def timeit(self, number: int = 1000000) -> common.Measurement:\n \"\"\"Mirrors the semantics of timeit.Timer.timeit().\n\n Execute the main statement (`stmt`) `number` times.\n https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit\n \"\"\"\n with common.set_torch_threads(self._task_spec.num_threads):\n # Warmup\n self._timer.timeit(number=max(int(number // 100), 1))\n\n return common.Measurement(\n number_per_run=number,\n raw_times=[self._timer.timeit(number=number)],\n task_spec=self._task_spec\n )\n\n def repeat(self, repeat: int = -1, number: int = -1) -> None:\n raise NotImplementedError(\"See `Timer.blocked_autorange.`\")\n\n def autorange(self, callback: Optional[Callable[[int, float], NoReturn]] = None) -> None:\n raise NotImplementedError(\"See `Timer.blocked_autorange.`\")\n\n def _threaded_measurement_loop(\n self,\n number: int,\n time_hook: Callable[[], float],\n stop_hook: Callable[[List[float]], bool],\n min_run_time: float,\n max_run_time: Optional[float] = None,\n callback: Optional[Callable[[int, float], NoReturn]] = None\n ) -> List[float]:\n total_time = 0.0\n can_stop = False\n times: List[float] = []\n with common.set_torch_threads(self._task_spec.num_threads):\n while (total_time < min_run_time) or (not can_stop):\n time_spent = time_hook()\n times.append(time_spent)\n total_time += time_spent\n if callback:\n callback(number, time_spent)\n can_stop = stop_hook(times)\n if max_run_time and total_time > max_run_time:\n break\n return times\n\n def _estimate_block_size(self, min_run_time: float) -> int:\n with common.set_torch_threads(self._task_spec.num_threads):\n # Estimate the block size needed for measurement to be negligible\n # compared to the inner loop. This also serves as a warmup.\n overhead = np.median([self._timer.timeit(0) for _ in range(5)])\n number = 1\n while True:\n time_taken = self._timer.timeit(number)\n relative_overhead = overhead / time_taken\n if relative_overhead <= 1e-4 and time_taken >= min_run_time / 1000:\n break\n if time_taken > min_run_time:\n break\n number *= 10\n return number\n\n def adaptive_autorange(\n self,\n threshold: float = 0.1,\n *,\n min_run_time: float = 0.01,\n max_run_time: float = 10.0,\n callback: Optional[Callable[[int, float], NoReturn]] = None,\n ) -> common.Measurement:\n number = self._estimate_block_size(min_run_time=0.05)\n\n def time_hook() -> float:\n return self._timer.timeit(number)\n\n def stop_hook(times: List[float]) -> bool:\n if len(times) > 3:\n return common.Measurement(\n number_per_run=number,\n raw_times=times,\n task_spec=self._task_spec\n ).meets_confidence(threshold=threshold)\n return False\n times = self._threaded_measurement_loop(\n number, time_hook, stop_hook, min_run_time, max_run_time, callback=callback)\n\n return common.Measurement(\n number_per_run=number,\n raw_times=times,\n task_spec=self._task_spec\n )\n\n def blocked_autorange(\n self,\n callback: Optional[Callable[[int, float], NoReturn]] = None,\n min_run_time: float = 0.2,\n ) -> common.Measurement:\n \"\"\"Measure many replicates while keeping timer overhead to a minimum.\n\n At a high level, blocked_autorange executes the following pseudo-code::\n\n `setup`\n\n total_time = 0\n while total_time < min_run_time\n start = timer()\n for _ in range(block_size):\n `stmt`\n total_time += (timer() - start)\n\n Note the variable `block_size` in the inner loop. The choice of block\n size is important to measurement quality, and must balance two\n competing objectives:\n\n 1) A small block size results in more replicates and generally\n better statistics.\n\n 2) A large block size better amortizes the cost of `timer`\n invocation, and results in a less biased measurement. This is\n important because CUDA syncronization time is non-trivial\n (order single to low double digit microseconds) and would\n otherwise bias the measurement.\n\n blocked_autorange sets block_size by running a warmup period,\n increasing block size until timer overhead is less than 0.1% of\n the overall computation. This value is then used for the main\n measurement loop.\n\n Returns:\n A `Measurement` object that contains measured runtimes and\n repetition counts, and can be used to compute statistics.\n (mean, median, etc.)\n \"\"\"\n number = self._estimate_block_size(min_run_time)\n\n def time_hook() -> float:\n return self._timer.timeit(number)\n\n def stop_hook(times: List[float]) -> bool:\n return True\n\n times = self._threaded_measurement_loop(\n number, time_hook, stop_hook,\n min_run_time=min_run_time,\n callback=callback)\n\n return common.Measurement(\n number_per_run=number,\n raw_times=times,\n task_spec=self._task_spec\n )\n\n def collect_callgrind(\n self,\n number: int = 100,\n collect_baseline: bool = True\n ) -> valgrind_timer_interface.CallgrindStats:\n \"\"\"Collect instruction counts using Callgrind.\n\n Unlike wall times, instruction counts are deterministic\n (modulo non-determinism in the program itself and small amounts of\n jitter from the Python interpreter.) This makes them ideal for detailed\n performance analysis. This method runs `stmt` in a separate process\n so that Valgrind can instrument the program. Performance is severely\n degraded due to the instrumentation, howevever this is ameliorated by\n the fact that a small number of iterations is generally sufficient to\n obtain good measurements.\n\n In order to to use this method `valgrind`, `callgrind_control`, and\n `callgrind_annotate` must be installed.\n\n Because there is a process boundary between the caller (this process)\n and the `stmt` execution, `globals` cannot contain arbitrary in-memory\n data structures. (Unlike timing methods) Instead, globals are\n restricted to builtins, `nn.Modules`'s, and TorchScripted functions/modules\n to reduce the surprise factor from serialization and subsequent\n deserialization. The `GlobalsBridge` class provides more detail on this\n subject. Take particular care with nn.Modules: they rely on pickle and\n you may need to add an import to `setup` for them to transfer properly.\n\n By default, a profile for an empty statement will be collected and\n cached to indicate how many instructions are from the Python loop which\n drives `stmt`.\n\n Returns:\n A `CallgrindStats` object which provides instruction counts and\n some basic facilities for analyzing and manipulating results.\n \"\"\"\n if not isinstance(self._task_spec.stmt, str):\n raise ValueError(\"`collect_callgrind` currently only supports string `stmt`\")\n\n # Check that the statement is valid. It doesn't guarantee success, but it's much\n # simpler and quicker to raise an exception for a faulty `stmt` or `setup` in\n # the parent process rather than the valgrind subprocess.\n self._timer.timeit(1)\n is_python = (self._language == Language.PYTHON)\n assert is_python or not self._globals\n return valgrind_timer_interface.wrapper_singleton().collect_callgrind(\n task_spec=self._task_spec,\n globals=self._globals,\n number=number,\n collect_baseline=collect_baseline and is_python,\n is_python=is_python)\n"
] | [
[
"torch.utils.benchmark.utils.common.TaskSpec",
"torch.utils.benchmark.utils.valgrind_wrapper.timer_interface.wrapper_singleton",
"torch.utils.benchmark.utils.common.Measurement",
"torch.utils.benchmark.utils.valgrind_wrapper.timer_interface.CopyIfCallgrind.unwrap_all",
"torch.cuda.synchronize",
"torch.utils.benchmark.utils.common.set_torch_threads",
"torch.utils.benchmark.utils.cpp_jit.compile_timeit_template",
"torch.cuda.is_available"
]
] |
mohammedshariqnawaz/Pedestron | [
"9785feb94f00e07ae24a662525b4678f12d0fdc8"
] | [
"mmdet/models/detectors/csp.py"
] | [
"\nfrom .single_stage import SingleStageDetector\nfrom ..registry import DETECTORS\nfrom mmdet.core import bbox2result\nimport torch.nn as nn\nimport torch\nfrom .. import builder\nimport numpy as np\nimport cv2\nfrom mmdet.core import bbox2roi, bbox2result, build_assigner, build_sampler\n\n@DETECTORS.register_module\nclass CSP(SingleStageDetector):\n\n def __init__(self,\n backbone,\n neck,\n bbox_head,\n refine_roi_extractor=None,\n refine_head=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None,\n detached=True,\n return_feature_maps=False):\n super(CSP, self).__init__(backbone, neck, bbox_head, train_cfg,\n test_cfg, pretrained)\n if refine_head is not None:\n self.refine_roi_extractor = builder.build_roi_extractor(\n refine_roi_extractor)\n self.refine_head = builder.build_head(refine_head)\n self.return_feature_maps = return_feature_maps\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n self.detached = detached\n\n def show_input_debug(self, img, classification_maps, scale_maps, offset_maps):\n img_numpy = img.cpu().numpy().copy()[0]\n # img_numpy = np.transpose(img_numpy, [1, 2, 0]) * [58.395, 57.12, 57.375] + [123.675, 116.28, 103.53]\n img_numpy = np.transpose(img_numpy, [1, 2, 0]) + [102.9801, 115.9465, 122.7717]\n img_numpy = img_numpy[:, :, ::-1]\n img_numpy = img_numpy.astype(np.uint8)\n strides = [8, 16, 32, 64, 128]\n img_nows = []\n for i, stride in enumerate(strides):\n img_now = img_numpy.copy()\n # cls_numpy = classification_maps[0][i].cpu().numpy().copy()[0][2]\n cls_numpy = classification_maps[0][i].cpu().numpy().copy()[0][:80]\n scale_numpy = scale_maps[0][i].cpu().numpy().copy()[0][0] * stride\n offset_numpy = offset_maps[0][i].cpu().numpy().copy()[0][:2]\n cs, ys, xs = cls_numpy.nonzero()\n print(len(ys))\n for c, x, y in zip(cs, xs, ys):\n cv2.imshow(str(c), classification_maps[0][i].cpu().numpy().copy()[0][80+c])\n realx = x\n realy = y\n height = scale_numpy[y, x]\n realy = realy + 0.5 + offset_numpy[0][y, x]\n realx = realx + 0.5 + offset_numpy[1][y, x]\n realy = realy * stride\n realx = realx * stride\n top_y = int(realy - height/2)\n top_x = int(realx)\n down_y = int(realy + height/2)\n down_x = int(realx)\n top_left = (int(top_x - height * 0.1), int(top_y))\n down_right = (int(down_x + height * 0.1), down_y)\n cv2.rectangle(img_now, top_left, down_right, (255, 255, 5*int(c)), 2)\n img_nows.append(img_now)\n cv2.imshow(str(i) +'img', img_now)\n cv2.waitKey(0)\n\n def show_input_debug_caltech(self, img, classification_maps, scale_maps, offset_maps):\n for j in range(img.shape[0]):\n img_numpy = img.cpu().numpy().copy()[j]\n img_numpy = np.transpose(img_numpy, [1, 2, 0]) * [58.395, 57.12, 57.375] + [123.675, 116.28, 103.53]\n img_numpy = img_numpy[:, :, ::-1]\n img_numpy = img_numpy.astype(np.uint8)\n strides = [4]\n img_nows = []\n for i, stride in enumerate(strides):\n img_now = img_numpy.copy()\n cls_numpy = classification_maps[j][i].cpu().numpy().copy()[0][2]\n ignore_numpy = classification_maps[j][i].cpu().numpy().copy()[0][1]\n cv2.imshow('ignore', ignore_numpy)\n scale_numpy = scale_maps[j][i].cpu().numpy().copy()[0][0] * stride\n offset_numpy = offset_maps[j][i].cpu().numpy().copy()[0][:2]\n ys, xs = cls_numpy.nonzero()\n print(len(ys))\n for x, y in zip(xs, ys):\n # cv2.imshow(str(c), classification_maps[j][i].cpu().numpy().copy()[0][c])\n realx = x\n realy = y\n height = scale_numpy[y, x]\n realy = realy + 0.5 + offset_numpy[0][y, x]\n realx = realx + 0.5 + offset_numpy[1][y, x]\n realy = realy * stride\n realx = realx * stride\n top_y = int(realy - height/2)\n top_x = int(realx)\n down_y = int(realy + height/2)\n down_x = int(realx)\n top_left = (int(top_x - height * 0.1), int(top_y))\n down_right = (int(down_x + height * 0.1), down_y)\n cv2.rectangle(img_now, top_left, down_right, (255, 255, 125), 2)\n img_nows.append(img_now)\n cv2.imshow(str(i) +'img', img_now)\n cv2.waitKey(0)\n\n def show_input_debug_head(self, img, classification_maps, scale_maps, offset_maps):\n for j in range(img.shape[0]):\n img_numpy = img.cpu().numpy().copy()[j]\n img_numpy = np.transpose(img_numpy, [1, 2, 0]) * [58.395, 57.12, 57.375] + [123.675, 116.28, 103.53]\n img_numpy = img_numpy[:, :, ::-1]\n img_numpy = img_numpy.astype(np.uint8)\n strides = [4]\n img_nows = []\n for i, stride in enumerate(strides):\n img_now = img_numpy.copy()\n cls_numpy = classification_maps[j][i].cpu().numpy().copy()[0][2]\n ignore_numpy = classification_maps[j][i].cpu().numpy().copy()[0][1]\n cv2.imshow('ignore', ignore_numpy)\n scale_numpy = scale_maps[j][i].exp().cpu().numpy().copy()[0][0] * stride\n offset_numpy = offset_maps[j][i].cpu().numpy().copy()[0][:2]\n ys, xs = cls_numpy.nonzero()\n for x, y in zip(xs, ys):\n # cv2.imshow(str(c), classification_maps[j][i].cpu().numpy().copy()[0][c])\n realx = x\n realy = y\n height = scale_numpy[y, x]\n realy = realy + 0.5 + offset_numpy[0][y, x]\n realx = realx + 0.5 + offset_numpy[1][y, x]\n realy = realy * stride\n realx = realx * stride\n top_y = int(realy)\n top_x = int(realx)\n down_y = int(realy + height)\n down_x = int(realx)\n top_left = (int(top_x - height * 0.41/2), int(top_y))\n down_right = (int(down_x + height * 0.41/2), down_y)\n cv2.rectangle(img_now, top_left, down_right, (255, 255, 125), 2)\n img_nows.append(img_now)\n cv2.imshow(str(i) +'img', img_now)\n cv2.waitKey(0)\n\n def show_mot_input_debug(self, img, classification_maps, scale_maps, offset_maps):\n for j in range(img.shape[0]):\n img_numpy = img.cpu().numpy().copy()[j]\n img_numpy = np.transpose(img_numpy, [1, 2, 0]) * [58.395, 57.12, 57.375] + [123.675, 116.28, 103.53]\n # img_numpy = np.transpose(img_numpy, [1, 2, 0]) + [102.9801, 115.9465, 122.7717]\n img_numpy = img_numpy[:, :, ::-1]\n img_numpy = img_numpy.astype(np.uint8)\n strides = [4]\n img_nows = []\n for i, stride in enumerate(strides):\n img_now = img_numpy.copy()\n # cls_numpy = classification_maps[0][i].cpu().numpy().copy()[0][2]\n cls_numpy = classification_maps[j][i].cpu().numpy().copy()[0][2]\n instance_numpy = classification_maps[j][i].cpu().numpy().copy()[0][3]\n scale_numpy = scale_maps[j][i].cpu().numpy().copy()[0][0] * stride\n offset_numpy = offset_maps[j][i].cpu().numpy().copy()[0][:2]\n ys, xs = cls_numpy.nonzero()\n for x, y in zip(xs, ys):\n c=0\n cv2.imshow(str(c), classification_maps[j][i].cpu().numpy().copy()[0][2])\n realx = x\n realy = y\n height = scale_numpy[y, x]\n realy = realy + 0.5 + offset_numpy[0][y, x]\n realx = realx + 0.5 + offset_numpy[1][y, x]\n realy = realy * stride\n realx = realx * stride\n top_y = int(realy - height/2)\n top_x = int(realx)\n down_y = int(realy + height/2)\n down_x = int(realx)\n top_left = (int(top_x - height * 0.1), int(top_y))\n down_right = (int(down_x + height * 0.1), down_y)\n cv2.rectangle(img_now, top_left, down_right, (255, 255, 5*int(c)), 2)\n instance = instance_numpy[y, x]\n cv2.putText(img_now, str(instance), top_left, cv2.FONT_HERSHEY_COMPLEX, 1, 255)\n img_nows.append(img_now)\n cv2.imshow(str(i) +'img', img_now)\n cv2.waitKey(0)\n\n @property\n def refine(self):\n return hasattr(self, 'refine_head') and self.refine_head is not None\n\n def forward_train(self,\n img,\n img_metas,\n gt_bboxes,\n gt_labels,\n gt_bboxes_ignore=None,\n classification_maps=None,\n scale_maps=None,\n offset_maps=None):\n # for tracking data which batch is produced by dataset instead of data loader\n if type(img) == list:\n img=img[0]\n img_metas=img_metas[0]\n gt_bboxes=gt_bboxes[0]\n gt_labels=gt_labels[0]\n gt_bboxes_ignore = gt_bboxes_ignore[0]\n classification_maps = classification_maps[0]\n scale_maps = scale_maps[0]\n offset_maps = offset_maps[0]\n\n losses = dict()\n x = self.extract_feat(img)\n # self.show_input_debug(img, classification_maps, scale_maps, offset_maps)\n # self.show_input_debug_caltech(img, classification_maps, scale_maps, offset_maps)\n # self.show_mot_input_debug(img, classification_maps, scale_maps, offset_maps)\n # self.show_input_debug_head(img, classification_maps, scale_maps, offset_maps)\n\n outs = self.bbox_head(x)\n loss_inputs = outs + (gt_bboxes, gt_labels, classification_maps, scale_maps, offset_maps, img_metas, self.train_cfg.csp_head if self.refine else self.train_cfg)\n losses_bbox = self.bbox_head.loss(\n *loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)\n losses.update(losses_bbox)\n \n if self.refine:\n if self.detached:\n x = tuple([i.detach() for i in x])\n bbox_inputs = outs + (img_metas, self.train_cfg.csp_head, False)\n bbox_list = self.bbox_head.get_bboxes(*bbox_inputs, no_strides=False) # no_strides to not upscale yet\n \n bbox_list = [\n bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes)[0]\n for det_bboxes, det_labels in bbox_list\n ]\n\n bbox_assigner = build_assigner(self.train_cfg.rcnn.assigner)\n bbox_sampler = build_sampler(\n self.train_cfg.rcnn.sampler, context=self)\n num_imgs = img.size(0)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [None for _ in range(num_imgs)]\n sampling_results = []\n \n for i in range(num_imgs):\n if bbox_list[i].shape[0] == 0 or gt_bboxes[i].shape[0] == 0:\n continue\n bbox = torch.tensor(bbox_list[i]).float().cuda()\n assign_result = bbox_assigner.assign(\n bbox, gt_bboxes[i], gt_bboxes_ignore[i],\n gt_labels[i])\n sampling_result = bbox_sampler.sample(\n assign_result,\n bbox,\n gt_bboxes[i],\n gt_labels[i])\n sampling_results.append(sampling_result)\n\n samp_list = [res.bboxes for res in sampling_results]\n if len(samp_list) == 0:\n losses.update(dict(loss_refine_cls=torch.tensor(0).float().cuda(), acc=torch.tensor(0).float().cuda()))\n return losses\n rois = bbox2roi(samp_list).float()\n if self.refine_head.loss_opinion is not None:\n pred_scores = torch.cat([torch.tensor(bbox[:, 4]).float().cuda() for bbox in bbox_list], dim=0)\n pred_rois = bbox2roi([torch.tensor(bbox).float().cuda() for bbox in bbox_list])\n pred_feats = self.refine_roi_extractor(\n x, pred_rois)\n pred_scores_refine = self.refine_head(pred_feats)\n loss_opinion = self.refine_head.compute_opinion_loss(pred_scores, pred_scores_refine)\n losses.update(loss_opinion)\n bbox_feats = self.refine_roi_extractor(\n x, rois)\n cls_score = self.refine_head(bbox_feats)\n bbox_targets = self.refine_head.get_target(\n sampling_results, gt_bboxes, gt_labels, self.train_cfg.rcnn)\n loss_refine = self.refine_head.loss(cls_score,\n *bbox_targets[:2])\n losses.update(dict(loss_refine_cls=loss_refine[\"loss_cls\"], distL1=loss_refine[\"dist\"]))\n\n return losses\n\n def simple_test_accuracy(self, img, img_meta):\n gts = img_meta[0][\"gts\"]\n x = self.extract_feat(img)\n if self.detached:\n x = (x[0].detach(),)\n\n rois = bbox2roi(gts)\n if rois.shape[0] == 0:\n return 0, 0\n\n roi_feats = self.refine_roi_extractor(\n x, rois)\n cls_score = self.refine_head.get_scores(roi_feats)\n\n return (cls_score > 0.5).float().sum(), rois.size(0)\n\n def simple_test(self, img, img_meta, rescale=False, return_id=False):\n x = self.extract_feat(img)\n outs = self.bbox_head(x)\n bbox_inputs = outs + (img_meta, self.test_cfg.csp_head if self.refine else self.test_cfg, False) # TODO://Handle rescalling\n if self.return_feature_maps:\n return self.bbox_head.get_bboxes_features(*bbox_inputs)\n bbox_list = self.bbox_head.get_bboxes(*bbox_inputs, no_strides=False)\n im_scale = img_meta[0][\"scale_factor\"]\n if \"id\" in img_meta[0]:\n img_id = img_meta[0][\"id\"]\n else:\n img_id = 0\n if self.refine:\n if self.detached:\n x = (x[0].detach(),)\n bbox_list = [\n bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes)[0]\n for det_bboxes, det_labels in bbox_list\n ]\n refine_cfg = self.test_cfg.get('rcnn', None)\n bbox_list = [torch.tensor(bbox).float().cuda() for bbox in bbox_list]\n rois = bbox2roi(bbox_list)\n bbox_list = [bbox/im_scale for bbox in bbox_list]\n if rois.shape[0] == 0:\n cls_score = None\n else:\n roi_feats = self.refine_roi_extractor(\n x, rois)\n cls_score = self.refine_head.get_scores(roi_feats)\n\n res_buffer = []\n if cls_score is not None:\n if refine_cfg is not None:\n res_buffer = self.refine_head.suppress_boxes(rois, cls_score, img_meta, cfg=refine_cfg)\n else:\n res_buffer = self.refine_head.combine_scores(bbox_list, cls_score)\n if return_id:\n return res_buffer, img_id\n return res_buffer\n\n bbox_results = [\n bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes)\n for det_bboxes, det_labels in bbox_list\n ]\n if return_id:\n return bbox_results[0], img_id\n return bbox_results[0]\n\n def foward_features(self, features):\n bbox_list = self.bbox_head.get_bboxes(*features)\n bbox_results = [\n bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes)\n for det_bboxes, det_labels in bbox_list\n ]\n return bbox_results[0]\n"
] | [
[
"torch.tensor",
"numpy.transpose"
]
] |
MichaelAllen1966/stroke_outcome_algorithm | [
"99050bf4e0b19c38c8973fe10234fee4f230a172"
] | [
"clinical_outcome.py"
] | [
"\"\"\"\nClass to hold clinical outcome model.\nPredicts probability of good outcome of patient(s) or group(s) of patients.\n\nCall `calculate_outcome_for_all(args)` from outside of the object\n\nInputs\n======\n\nAll inputs take np arrays (for multiple groups of patients).\n\nmimic: proportion of patients with stroke mimic\n\nich: proportion of patients with intracerebral haemorrhage (ICH). \nOr probability of a patient having an ICH, when using for a single patient.\n\nnlvo: proportion of patients with non-large vessel occlusions (nLVO). \nOr probability of a patient having an NLVO, when using for a single patient.\n\nlvo: proportion of patients with large vessel occlusions (LVO). \nOr probability of a patient having a LVO, when using for a single patient.\n\nonset_to_needle: minutes from onset to thrombolysis\n\nonset_to_ouncture: minutes from onset to thrombectomy\n\nnlvo_eligible_for_treatment: proportion of patients with NLVO suitable for \ntreatment with thrombolysis. Or probability of a patient with NVLO being \neligible for treatment.\n\nlvo_eligible_for_treatment: proportion of patients with LVO suitable for \ntreatment with thrombolysis and/or thrombectomy. Or probability of a patient \nwith LVO being eligible for treatment.\n\nReturns\n=======\n\nProbability of good outcome: The probability of having a good outcome (modified\nRankin Scale 0-1) for the patient or group of patients (np array).\n\n\nReferences for decay of effect of thrombolysis and thrombectomy\n===============================================================\n\nDecay of effect of thrombolysis without image selection of patients taken from:\nEmberson, Jonathan, Kennedy R. Lees, Patrick Lyden, Lisa Blackwell, \nGregory Albers, Erich Bluhmki, Thomas Brott, et al (2014). “Effect of Treatment \nDelay, Age, and Stroke Severity on the Effects of Intravenous Thrombolysis with\nAlteplase for Acute Ischaemic Stroke: A Meta-Analysis of Individual Patient\nData from Randomised Trials.” The Lancet 384: 1929–1935.\nhttps://doi.org/10.1016/S0140-6736(14)60584-5.\n\n* Time to no effect = 6.3hrs\n\nDecay of effect of thrombectomy without image selection of patients taken from:\nFransen, Puck S. S., Olvert A. Berkhemer, Hester F. Lingsma, Debbie Beumer, \nLucie A. van den Berg, Albert J. Yoo, Wouter J. Schonewille, et al. (2016)\n“Time to Reperfusion and Treatment Effect for Acute Ischemic Stroke: A \nRandomized Clinical Trial.” JAMA Neurology 73: 190–96. \nhttps://doi.org/10.1001/jamaneurol.2015.3886.\n\n* Time to no effect = 8hrs\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n\nclass Clinical_outcome:\n def __init__(self):\n \"\"\"Constructor for clinical outcome model\n \"\"\"\n self.name = \"Clinical outcome model\"\n self.thrombectomy_time_no_effect = 8 * 60\n self.thrombolysis_time_no_effect = 6.3 * 60\n self.maximum_permitted_time_to_thrombectomy = 360\n self.maximum_permitted_time_to_thrombolysis = 270\n\n def calculate_outcome_for_all(self,\n mimic,\n ich,\n nlvo,\n lvo,\n onset_to_needle,\n onset_to_puncture,\n nlvo_eligible_for_treatment,\n lvo_eligible_for_treatment,\n prop_thrombolysed_lvo_receiving_thrombectomy):\n \"\"\"\n Calculates the probability of good outcome for all patients admitted\n with acute stroke. \n\n Based on:\n Holodinsky JK, Williamson TS, Demchuk AM, et al. Modeling Stroke Patient\n Transport for All Patients With Suspected Large-Vessel Occlusion. JAMA \n Neurol. 2018;75(12):1477-1486. doi:10.1001/jamaneurol.2018.2424\n \n Sums outcomes for:\n\n 1) mimics\n 2) ICH\n 3) non-LVO\n 4) LVO treated with thrombolysis\n 5) LVO treated with thrombectomy (if thrombolysis not successful in a\n drip and ship configuration)\n\n arguments\n ---------\n\n np arrays (each row is a given geographic area with different \n characteristics)\n\n mimic: proportion of patients with stroke mimic\n ich: proportion of patients with ICH\n nlvo: proportion of patients with non-lvo\n lvo: proportion of patients with lvo\n onset_to_needle: minutes from onset to thrombolysis\n onset_to_ounctureL minutes from onset to thrombectomy\n nlvo_eligible_for_treatment: proportion of nlvo suitable for treatment\n lvo_eligible_for_treatment: proportion of lvo suitable for treatment\n\n returns\n -------\n\n probability of good outcome for all (np array)\n \"\"\"\n \n # Get outcomes\n # ------------\n \n outcomes = pd.DataFrame()\n\n # Calculate good outcomes for mimics\n outcomes['mimic'] = self._calculate_outcome_for_stroke_mimics(\n mimic.shape)\n\n # Calculate good outcomes for ich \n outcomes['ich'] = self._calculate_outcome_for_ICH(mimic.shape)\n\n # Calculate good outcomes for nlvo without treatment\n outcomes['nlvo_base'] = \\\n np.full(nlvo.shape, 0.4622)\n \n # Calculate good outcomes for nlvo with thrombolysis\n outcomes['nlvo_add_ivt'] = \\\n self._calculate_thrombolysis_outcome_for_nlvo(onset_to_needle)\n\n # Calculate good outcomes for lvo without treatment\n outcomes['lvo_base'] = \\\n np.full(nlvo.shape, 0.1328)\n \n # Calculate good outcomes for lvo with thrombolysis\n outcomes['lvo_add_ivt'] = \\\n self._calculate_thrombolysis_outcome_for_lvo(onset_to_needle)\n\n # Calculate good outcomes for lvo with thrombolysis\n outcomes['lvo_add_et'] = \\\n self._calculate_thrombectomy_outcome_for_lvo(onset_to_puncture)\n\n \n # Weight outcome results by proportion of patients\n # ------------------------------------------------\n \n # 'Results' are good outcomes\n results = pd.DataFrame()\n \n # Results for mimic\n results['mimic'] = outcomes['mimic'] * mimic\n \n # Results for ich\n results['ich'] = outcomes['ich'] * ich\n \n # Results for nlvo\n results['nlvo_base'] = nlvo * outcomes['nlvo_base']\n \n results['nlvo_ivt'] = \\\n nlvo * outcomes['nlvo_add_ivt'] * nlvo_eligible_for_treatment\n \n # Results for lvo\n results['lvo_base'] = lvo * outcomes['lvo_base']\n \n results['lvo_ivt'] = \\\n lvo * outcomes['lvo_add_ivt'] * lvo_eligible_for_treatment\n \n # Adjust thrombectomy/thrombolysis ratio for LVO \n # Reduce thrombectomy treatment by LVO responding to IVT\n lvo_receiving_et = ((lvo * lvo_eligible_for_treatment * \n prop_thrombolysed_lvo_receiving_thrombectomy) - \n results['lvo_ivt'])\n\n results['lvo_et'] = lvo_receiving_et * outcomes['lvo_add_et']\n\n p_good = results.sum(axis=1).values\n\n return p_good\n\n @staticmethod\n def _calculate_outcome_for_ICH(array_shape):\n \"\"\"\n Calculates the probability of good outcome for patients with intra-\n cranial haemorrhage (ICH).\n\n Sets all values to 0.24 \n\n Based on Holodinsky et al. (2018) Drip-and-Ship vs. Mothership: \n Modelling Stroke Patient Transport for All Suspected Large Vessel\n Occlusion Patients. JAMA Neuro (in press)\n\n arguments\n ---------\n\n array size\n\n returns\n -------\n\n probability of good outcome for ICH (np array)\n \"\"\"\n\n # Create an array of required length and set all values to 0.24\n p_good = np.zeros(array_shape)\n p_good[:] = 0.24\n\n return p_good \n\n @staticmethod\n def _calculate_outcome_for_stroke_mimics(array_shape):\n \"\"\"\n Calculates the probability of good outcome for patients with stroke\n mimic\n\n Sets all values to 1\n\n Based on Holodinsky et al. (2018) Drip-and-Ship vs. Mothership: \n Modelling Stroke Patient Transport for All Suspected Large Vessel\n Occlusion Patients. JAMA Neuro (in press)\n\n arguments\n ---------\n\n array size\n\n returns\n -------\n\n probability of good outcome for stroke mimiccs (np array)\n \"\"\"\n\n # Create an array of required length and set all values to 0.9\n p_good = np.zeros(array_shape)\n p_good[:] = 1\n\n return p_good\n \n def _calculate_thrombectomy_outcome_for_lvo(self, onset_to_puncture):\n \"\"\"\n Calculates the probability of additional good outcome for LVO patients\n receiving thrombectomy.\n\n arguments\n ---------\n\n onset_to_puncture : np array in minutes\n\n returns\n -------\n\n probability of additional good outcome if given thrombectomy (np array)\n \"\"\"\n\n p_good_max = 0.5208\n p_good_min = 0.1328\n \n # Convert probability to odds\n odds_good_max = p_good_max / (1 - p_good_max)\n odds_good_min = p_good_min / (1 - p_good_min)\n \n # Calculate fraction of effective time used\n fraction_max_effect_time_used = \\\n onset_to_puncture / self.thrombectomy_time_no_effect\n \n # Calculate odds of good outcome with treatment\n odds_good = np.exp(np.log(odds_good_max) - \n ((np.log(odds_good_max) - np.log(odds_good_min)) \n * fraction_max_effect_time_used))\n \n # Convert odds to probability\n prob_good = odds_good / (1 + odds_good)\n prob_good[prob_good < p_good_min] = p_good_min\n \n # Calculate probability of additional good outcome\n p_good_add = prob_good - p_good_min\n \n # Set additional good outcomes to zero if past permitted treatment time\n mask = onset_to_puncture > self.maximum_permitted_time_to_thrombectomy\n p_good_add[mask] = 0 \n \n # Ensure no negative outcomes\n mask = p_good_add < 0\n p_good_add[mask] = 0 \n\n return p_good_add \n\n def _calculate_thrombolysis_outcome_for_lvo(self, onset_to_needle):\n \"\"\"\n Calculates the probability of additional good outcome for LVO patients\n receiving thrombolysis. Does not include baseline untreated good\n comes.\n\n arguments\n ---------\n \n onset_to_needle : np array in minutes\n\n\n returns\n -------\n\n probability of additional good outcome if given thrombolysis \n (np array)\n \"\"\"\n \n p_good_max = 0.2441\n p_good_min = 0.1328\n \n # Convert probability to odds\n odds_good_max = p_good_max / (1 - p_good_max)\n odds_good_min = p_good_min / (1 - p_good_min)\n \n # Calculate fraction of effective time used \n fraction_max_effect_time_used = \\\n onset_to_needle / self.thrombolysis_time_no_effect\n\n # Calculate odds of good outcome with treatment\n odds_good = np.exp(np.log(odds_good_max) - \n ((np.log(odds_good_max) - np.log(odds_good_min)) \n * fraction_max_effect_time_used))\n\n # Convert odds to probability\n prob_good = odds_good / (1 + odds_good)\n prob_good[prob_good < p_good_min] = p_good_min\n \n # Calculate probability of additional good outcome\n p_good_add = prob_good - p_good_min\n \n # Set additional good outcomes to zero if past permitted treatment time\n mask = onset_to_needle> self.maximum_permitted_time_to_thrombolysis\n p_good_add[mask] = 0 \n \n # Ensure no negative outcomes\n mask = p_good_add < 0\n p_good_add[mask] = 0 \n\n # return outcome and proportion of treated who respond\n return p_good_add\n\n def _calculate_thrombolysis_outcome_for_nlvo(self, onset_to_needle):\n \"\"\"\n Calculates the probability of good outcome for non-LVO patients\n receiving thrombolysis.\n\n arguments\n ---------\n\n onset_to_needle : np array in minutes\n\n returns\n -------\n\n probability of good outcome if given thrombolysis (np array)\n \"\"\"\n\n p_good_max = 0.6444\n p_good_min = 0.4622\n \n # Convert probability to odds\n odds_good_max = p_good_max / (1 - p_good_max)\n odds_good_min = p_good_min / (1 - p_good_min)\n \n # Calculate fraction of effective time used \n fraction_max_effect_time_used = (onset_to_needle / \n self.thrombolysis_time_no_effect)\n \n # Calculate odds of good outcome with treatment\n odds_good = np.exp(np.log(odds_good_max) - \n ((np.log(odds_good_max) - np.log(odds_good_min)) \n * fraction_max_effect_time_used))\n \n # Convert odds to probability\n prob_good = odds_good / (1 + odds_good)\n prob_good[prob_good < p_good_min] = p_good_min\n \n # Calculate probability of additional good outcome\n p_good_add = prob_good - p_good_min\n \n mask = onset_to_needle> self.maximum_permitted_time_to_thrombolysis\n p_good_add[mask] = 0 \n \n # Ensure no negative outcomes\n mask = p_good_add < 0\n p_good_add[mask] = 0 \n\n # return outcome and proportion of treated who respond\n return p_good_add\n"
] | [
[
"numpy.log",
"pandas.DataFrame",
"numpy.zeros",
"numpy.full"
]
] |
brettelliot/event-study | [
"cffc6a80dbc4b33e68e863488428996af51cc991"
] | [
"examples/earnings_surprises/earnings-converter.py"
] | ["import pandas as pd\nfrom pandas.compat import StringIO\nimport numpy\nnumpy.set_printoptions(thre(...TRUNCATED) | [
[
"numpy.set_printoptions",
"pandas.compat.StringIO"
]
] |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 27