repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
robes/chisel-benchmark
|
[
"dca6c0e3a779115d10f0589a866402616cf00d00"
] |
[
"chiselbenchmark/plotter.py"
] |
[
"\"\"\"Utility for plotting test results.\"\"\"\n\nimport argparse\nfrom collections import defaultdict\nimport csv\nimport numpy as np\nimport os.path\nimport sys\nimport matplotlib.pyplot as plt\n\n_TESTCASE, _DATASET, _PARAM, _CONDITION, _ROUND, _TIME = 'test', 'dataset', 'param', 'condition', 'round', 'time'\n\n\ndef _stats(iterable):\n \"\"\"Returns mean, std for the iterable, excluding the min and max values.\"\"\"\n l = sorted(iterable)[1:-1] # drop min and max values\n return [np.mean(l), np.std(l)]\n\n\ndef main():\n \"\"\"Main routine.\"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('file', help='Test results spreadsheet to be plotted')\n parser.add_argument('--save', default=False, action='store_true', help='Save plots to files named \"test_case.format\" in working directory')\n parser.add_argument('--show', default=False, action='store_true', help='Show each plot as it is generated')\n parser.add_argument('--format', default='png', help='Format to use when saving plot')\n parser.add_argument('--dpi', type=int, default=300, help='DPI when saving plot')\n parser.add_argument('--yunits', choices=['s', 'ms'], default='s', help='Units for time y-axis')\n args = parser.parse_args()\n\n # factor for y-units\n yunits_factor = {'s': 1, 'ms': 1000}\n\n # line format per condition\n fmt = {'control': '--', 'optimized': ''}\n\n # color palette (colors 3 and 4 never appear together in the current plots)\n colors = defaultdict(lambda: 'xkcd:teal blue', {1: 'xkcd:medium purple', 2: 'xkcd:orange'})\n\n # read results from spreadsheet\n results = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n with open(os.path.expanduser(args.file)) as csvfile:\n csvreader = csv.DictReader(csvfile)\n for row in csvreader:\n results[row[_TESTCASE]][(row[_CONDITION], int(row[_PARAM]))][int(row[_DATASET])].append(yunits_factor[args.yunits]*float(row[_TIME]))\n\n # compute mean, std\n for result in results.values():\n for condition in result.values():\n for key in condition:\n condition[key] = _stats(condition[key])\n\n # plot figures\n for test_case in results:\n fig, ax = plt.subplots()\n for condition_param in results[test_case]:\n datasets, stats = zip(*results[test_case][condition_param].items())\n means, errs = zip(*stats)\n condition, param = condition_param\n ax.errorbar(datasets, means, yerr=errs, label=f'{condition}, n={param}', fmt=fmt[condition],\n color=colors[param], ecolor='xkcd:red', lw=1.5, capsize=3, capthick=1.5)\n ax.set_xticks(datasets)\n ax.set_xscale('log')\n\n ax.set(xlabel='# rows in dataset', ylabel=f'time ({args.yunits})', title=f'{test_case.replace(\"_\", \" \").title()}')\n ax.legend()\n\n if args.save:\n plt.savefig(f'{test_case}.{args.format}', dpi=args.dpi, format=args.format)\n\n if args.show:\n plt.show()\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n"
] |
[
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"numpy.mean",
"numpy.std",
"matplotlib.pyplot.show"
]
] |
titusz/datasketch
|
[
"a483b39fe4e444c372792e5c91c86d9d8d27a4a5"
] |
[
"examples/lsh_examples.py"
] |
[
"'''\nSome examples for LSH\n'''\n\nfrom hashlib import sha1\nimport numpy as np\nfrom datasketch.minhash import MinHash\nfrom datasketch.weighted_minhash import WeightedMinHashGenerator\nfrom datasketch.lsh import WeightedMinHashLSH, MinHashLSH\n\ndata1 = ['minhash', 'is', 'a', 'probabilistic', 'data', 'structure', 'for',\n 'estimating', 'the', 'similarity', 'between', 'datasets']\ndata2 = ['minhash', 'is', 'a', 'probability', 'data', 'structure', 'for',\n 'estimating', 'the', 'similarity', 'between', 'documents']\ndata3 = ['minhash', 'is', 'probability', 'data', 'structure', 'for',\n 'estimating', 'the', 'similarity', 'between', 'documents']\n\nv1 = np.random.uniform(1, 10, 10)\nv2 = np.random.uniform(1, 10, 10)\nv3 = np.random.uniform(1, 10, 10)\n\ndef eg1():\n m1 = MinHash()\n m2 = MinHash()\n m3 = MinHash()\n for d in data1:\n m1.update(d.encode('utf8'))\n for d in data2:\n m2.update(d.encode('utf8'))\n for d in data3:\n m3.update(d.encode('utf8'))\n\n # Create LSH index\n lsh = MinHashLSH(threshold=0.5)\n lsh.insert(\"m2\", m2)\n lsh.insert(\"m3\", m3)\n result = lsh.query(m1)\n print(\"Approximate neighbours with Jaccard similarity > 0.5\", result)\n\ndef eg2():\n mg = WeightedMinHashGenerator(10, 5)\n m1 = mg.minhash(v1)\n m2 = mg.minhash(v2)\n m3 = mg.minhash(v3)\n print(\"Estimated Jaccard m1, m2\", m1.jaccard(m2))\n print(\"Estimated Jaccard m1, m3\", m1.jaccard(m3))\n # Create LSH index\n lsh = WeightedMinHashLSH(threshold=0.1, sample_size=5)\n lsh.insert(\"m2\", m2)\n lsh.insert(\"m3\", m3)\n result = lsh.query(m1)\n print(\"Approximate neighbours with weighted Jaccard similarity > 0.1\", result)\n\nif __name__ == \"__main__\":\n eg1()\n eg2()\n"
] |
[
[
"numpy.random.uniform"
]
] |
biolee3/SAMDNet
|
[
"9a0d70f976e22d512046b4aa5727dd26422d0aff"
] |
[
"modules/sample_generator.py"
] |
[
"import numpy as np\nfrom PIL import Image\n\nfrom .utils import overlap_ratio\n\n\nclass SampleGenerator():\n def __init__(self, type_, img_size, trans=1, scale=1, aspect=None, valid=False):\n self.type = type_\n self.img_size = np.array(img_size) # (w, h)\n self.trans = trans\n self.scale = scale\n self.aspect = aspect\n self.valid = valid\n\n def _gen_samples(self, bb, n):\n #\n # bb: target bbox (min_x,min_y,w,h)\n bb = np.array(bb, dtype='float32')\n\n # (center_x, center_y, w, h)\n sample = np.array([bb[0] + bb[2] / 2, bb[1] + bb[3] / 2, bb[2], bb[3]], dtype='float32')\n samples = np.tile(sample[None, :], (n ,1))\n\n # vary aspect ratio\n if self.aspect is not None:\n ratio = np.random.rand(n, 2) * 2 - 1\n samples[:, 2:] *= self.aspect ** ratio\n\n # sample generation\n if self.type == 'gaussian':\n samples[:, :2] += self.trans * np.mean(bb[2:]) * np.clip(0.5 * np.random.randn(n, 2), -1, 1)\n samples[:, 2:] *= self.scale ** np.clip(0.5 * np.random.randn(n, 1), -1, 1)\n\n elif self.type == 'uniform':\n samples[:, :2] += self.trans * np.mean(bb[2:]) * (np.random.rand(n, 2) * 2 - 1)\n samples[:, 2:] *= self.scale ** (np.random.rand(n, 1) * 2 - 1)\n\n elif self.type == 'whole':\n m = int(2 * np.sqrt(n))\n xy = np.dstack(np.meshgrid(np.linspace(0, 1, m), np.linspace(0, 1, m))).reshape(-1, 2)\n xy = np.random.permutation(xy)[:n]\n samples[:, :2] = bb[2:] / 2 + xy * (self.img_size - bb[2:] / 2 - 1)\n samples[:, 2:] *= self.scale ** (np.random.rand(n, 1) * 2 - 1)\n\n # adjust bbox range\n samples[:, 2:] = np.clip(samples[:, 2:], 10, self.img_size - 10)\n if self.valid:\n samples[:, :2] = np.clip(samples[:, :2], samples[:, 2:] / 2, self.img_size - samples[:, 2:] / 2 - 1)\n else:\n samples[:, :2] = np.clip(samples[:, :2], 0, self.img_size)\n\n # (min_x, min_y, w, h)\n samples[:, :2] -= samples[:, 2:] / 2\n\n return samples\n\n def __call__(self, bbox, n, overlap_range=None, scale_range=None,train_state=False):\n\n if overlap_range is None and scale_range is None:\n return self._gen_samples(bbox, n)\n elif(train_state == True):\n samples = np.tile(bbox[None, :], (n, 1))\n return samples\n else:\n samples = None\n remain = n\n factor = 2\n while remain > 0 and factor < 16:\n samples_ = self._gen_samples(bbox, remain * factor)\n\n idx = np.ones(len(samples_), dtype=bool)\n if overlap_range is not None:\n r = overlap_ratio(samples_, bbox)\n idx *= (r >= overlap_range[0]) * (r <= overlap_range[1])\n if scale_range is not None:\n s = np.prod(samples_[:, 2:], axis=1) / np.prod(bbox[2:])\n idx *= (s >= scale_range[0]) * (s <= scale_range[1])\n\n samples_ = samples_[idx, :]\n samples_ = samples_[:min(remain, len(samples_))]\n if samples is None:\n samples = samples_\n else:\n samples = np.concatenate([samples, samples_])\n remain = n - len(samples)\n factor = factor * 2\n\n return samples\n\n def set_type(self, type_):\n self.type = type_\n\n def set_trans(self, trans):\n self.trans = trans\n\n def expand_trans(self, trans_limit):\n self.trans = min(self.trans * 1.1, trans_limit)\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.random.rand",
"numpy.random.permutation",
"numpy.tile",
"numpy.random.randn",
"numpy.mean",
"numpy.prod",
"numpy.sqrt",
"numpy.clip",
"numpy.linspace"
]
] |
arjunmajum/habitat-api
|
[
"1d374383e6e0d9fa2a7cca016d5b72986a94caf8"
] |
[
"test/test_habitat_task.py"
] |
[
"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\n\nimport numpy as np\nimport pytest\n\nimport habitat\nfrom habitat.utils.test_utils import sample_non_stop_action\n\nCFG_TEST = \"configs/test/habitat_all_sensors_test.yaml\"\nTELEPORT_POSITION = [-3.2890449, 0.15067159, 11.124366]\nTELEPORT_ROTATION = [0.92035, 0, -0.39109465, 0]\n\n\ndef test_task_actions():\n config = habitat.get_config(config_paths=CFG_TEST)\n config.defrost()\n config.TASK.POSSIBLE_ACTIONS = config.TASK.POSSIBLE_ACTIONS + [\"TELEPORT\"]\n config.freeze()\n\n env = habitat.Env(config=config)\n env.reset()\n env.step(\n action={\n \"action\": \"TELEPORT\",\n \"action_args\": {\n \"position\": TELEPORT_POSITION,\n \"rotation\": TELEPORT_ROTATION,\n },\n }\n )\n agent_state = env.sim.get_agent_state()\n assert np.allclose(\n np.array(TELEPORT_POSITION, dtype=np.float32), agent_state.position\n ), \"mismatch in position after teleport\"\n assert np.allclose(\n np.array(TELEPORT_ROTATION, dtype=np.float32),\n np.array([*agent_state.rotation.imag, agent_state.rotation.real]),\n ), \"mismatch in rotation after teleport\"\n env.step(\"TURN_RIGHT\")\n env.close()\n\n\ndef test_task_actions_sampling_for_teleport():\n config = habitat.get_config(config_paths=CFG_TEST)\n config.defrost()\n config.TASK.POSSIBLE_ACTIONS = config.TASK.POSSIBLE_ACTIONS + [\"TELEPORT\"]\n config.freeze()\n\n env = habitat.Env(config=config)\n env.reset()\n while not env.episode_over:\n action = sample_non_stop_action(env.action_space)\n habitat.logger.info(\n f\"Action : \"\n f\"{action['action']}, \"\n f\"args: {action['action_args']}.\"\n )\n env.step(action)\n agent_state = env.sim.get_agent_state()\n habitat.logger.info(agent_state)\n env.close()\n\n\n@pytest.mark.parametrize(\n \"config_file\",\n [\n CFG_TEST,\n \"configs/tasks/pointnav.yaml\",\n \"configs/test/habitat_mp3d_eqa_test.yaml\",\n ],\n)\ndef test_task_actions_sampling(config_file):\n config = habitat.get_config(config_paths=config_file)\n if not os.path.exists(\n config.DATASET.DATA_PATH.format(split=config.DATASET.SPLIT)\n ):\n pytest.skip(\n f\"Please download dataset to data folder \"\n f\"{config.DATASET.DATA_PATH}.\"\n )\n\n env = habitat.Env(config=config)\n env.reset()\n while not env.episode_over:\n action = sample_non_stop_action(env.action_space)\n habitat.logger.info(\n f\"Action : \"\n f\"{action['action']}, \"\n f\"args: {action['action_args']}.\"\n )\n env.step(action)\n agent_state = env.sim.get_agent_state()\n habitat.logger.info(agent_state)\n env.close()\n"
] |
[
[
"numpy.array"
]
] |
ACPudding/FGO-py
|
[
"543043527f35ff9b4c1c7b6f366717610ad56048"
] |
[
"FGO-py/fgoAndroid.py"
] |
[
"import re\nimport threading\nimport time\n\nimport cv2\nimport numpy\nfrom airtest.core.android.adb import ADB\nfrom airtest.core.android.android import Android as Airtest\nfrom airtest.core.android.constant import CAP_METHOD\n\nfrom fgoConst import KEYMAP\nfrom fgoSchedule import schedule\nfrom fgoLogging import getLogger\n\nlogger=getLogger('Android')\nclass Android(Airtest):\n def __init__(self,serial=None,**kwargs):\n self.lock=threading.Lock()\n if serial is None:\n self.name=None\n return\n try:\n super().__init__(serial,**{'cap_method':CAP_METHOD.JAVACAP}|kwargs)\n self.rotation_watcher.reg_callback(lambda _:self.adjustOffset())\n except Exception as e:\n logger.exception(e)\n self.name=None\n else:self.name=self.serialno\n @property\n def avaliable(self):\n if not self.name:return False\n if self.touch_proxy.server_proc.poll()is None:return True # Only compatible with minitouch & maxtouch\n self.name=None\n return False\n @staticmethod\n def enumDevices():return[i for i,_ in ADB().devices('device')]\n def adjustOffset(self):\n self.render=[round(i)for i in self.get_render_resolution(True)]\n self.scale,self.border=(1080/self.render[3],(round(self.render[2]-self.render[3]*16/9)>>1,0))if self.render[2]*9>self.render[3]*16 else(1920/self.render[2],(0,round(self.render[3]-self.render[2]*9/16)>>1))\n self.key={c:[round(p[i]/self.scale+self.border[i]+self.render[i])for i in range(2)]for c,p in KEYMAP.items()}\n def touch(self,pos):\n with self.lock:super().touch([round(pos[i]/self.scale+self.border[i]+self.render[i])for i in range(2)])\n # def swipe(self,rect):\n # with self.lock:super().swipe(*[[rect[i<<1|j]/self.scale+self.border[j]+self.render[j]for j in range(2)]for i in range(2)])\n def swipe(self,rect): # If this doesn't work, use the above one instead\n p1,p2=[numpy.array(self._touch_point_by_orientation([rect[i<<1|j]/self.scale+self.border[j]+self.render[j]for j in range(2)]))for i in range(2)]\n vd=p2-p1\n lvd=numpy.linalg.norm(vd)\n vd/=.2*self.scale*lvd\n vx=numpy.array([0.,0.])\n def send(method,pos):self.touch_proxy.handle(' '.join((method,'0',*[str(i)for i in self.touch_proxy.transform_xy(*pos)],'50\\nc\\n')))\n with self.lock:\n send('d',p1)\n time.sleep(.01)\n for _ in range(2):\n send('m',p1+vx)\n vx+=vd\n time.sleep(.02)\n vd*=5\n while numpy.linalg.norm(vx)<lvd:\n send('m',p1+vx)\n vx+=vd\n time.sleep(.008)\n send('m',p2)\n time.sleep(.35)\n self.touch_proxy.handle('u 0\\nc\\n')\n time.sleep(.02)\n def press(self,key):\n with self.lock:super().touch(self.key[key])\n def perform(self,pos,wait):[(self.press(i),schedule.sleep(j*.001))for i,j in zip(pos,wait)]\n def screenshot(self):return cv2.resize(super().snapshot()[self.render[1]+self.border[1]:self.render[1]+self.render[3]-self.border[1],self.render[0]+self.border[0]:self.render[0]+self.render[2]-self.border[0]],(1920,1080),interpolation=cv2.INTER_CUBIC)\n def invoke169(self):\n x,y=(lambda r:(int(r.group(1)),int(r.group(2))))(re.search(r'(\\d+)x(\\d+)',self.adb.raw_shell('wm size')))\n if x<y:\n if x*16<y*9:self.adb.raw_shell('wm size %dx%d'%(x,x*16//9))\n else:\n if y*16<x*9:self.adb.raw_shell('wm size %dx%d'%(y*16//9,y))\n self.adjustOffset()\n def revoke169(self):self.adb.raw_shell('wm size %dx%d'%(lambda r:(int(r.group(1)),int(r.group(2))))(re.search(r'(\\d+)x(\\d+)',self.adb.raw_shell('wm size'))))\n"
] |
[
[
"numpy.array",
"numpy.linalg.norm"
]
] |
alexus37/MasterThesisCode
|
[
"a7eada603686de75968acc8586fd307a91b0491b"
] |
[
"deepexplain/tf/v2_x/methods.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport numpy as np\nfrom skimage.util import view_as_windows\nimport warnings\nimport logging\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nfrom tensorflow.python.ops import nn_grad, math_grad\n\nfrom deepexplain.tf.v2_x.utils import make_batches, slice_arrays, to_list, unpack_singleton, placeholder_from_data, original_grad, activation\nfrom deepexplain.tf.v2_x.baseClasses import GradientBasedMethod, PerturbationBasedMethod\nfrom deepexplain.tf.v2_x import constants\n\n\n# -----------------------------------------------------------------------------\n# ATTRIBUTION METHODS\n# -----------------------------------------------------------------------------\n\"\"\"\nReturns zero attributions. For testing only.\n\"\"\"\n\n\nclass DummyZero(GradientBasedMethod):\n def get_symbolic_attribution(self,):\n return tf.gradients(ys=self.T, xs=self.X)\n\n @classmethod\n def nonlinearity_grad_override(cls, op, grad):\n input = op.inputs[0]\n return tf.zeros_like(input)\n\n\n\"\"\"\nSaliency maps\nhttps://arxiv.org/abs/1312.6034\n\"\"\"\n\n\nclass Saliency(GradientBasedMethod):\n def get_symbolic_attribution(self):\n return [tf.abs(g) for g in tf.gradients(ys=self.T, xs=self.X)]\n\n\n\"\"\"\nGradient * Input\nhttps://arxiv.org/pdf/1704.02685.pdf - https://arxiv.org/abs/1611.07270\n\"\"\"\n\n\nclass GradientXInput(GradientBasedMethod):\n def get_symbolic_attribution(self):\n return [g * x for g, x in zip(\n tf.gradients(ys=self.T, xs=self.X),\n self.X if self.has_multiple_inputs else [self.X])]\n\n\"\"\"\nLayer-wise Relevance Propagation with epsilon rule\nhttp://journals.plos.org/plosone/article?id=10.1371/journal.pone.0130140\n\"\"\"\n\n\nclass EpsilonLRP(GradientBasedMethod):\n eps = None\n\n def __init__(self, T, X, session, keras_learning_phase, epsilon=1e-4, Y_shape=None):\n assert epsilon > 0.0, 'LRP epsilon must be greater than zero'\n global eps\n eps = epsilon\n super(EpsilonLRP, self).__init__(T, X, session, keras_learning_phase, Y_shape)\n\n def get_symbolic_attribution(self):\n return [g * x for g, x in zip(\n tf.gradients(ys=self.T, xs=self.X),\n self.X if self.has_multiple_inputs else [self.X])]\n\n @classmethod\n def nonlinearity_grad_override(cls, op, grad):\n output = op.outputs[0]\n input = op.inputs[0]\n return grad * output / (input + eps *\n tf.compat.v1.where(input >= 0, tf.ones_like(input), -1 * tf.ones_like(input)))\n\n\n\"\"\"\nIntegrated Gradients\nhttps://arxiv.org/pdf/1703.01365.pdf\n\"\"\"\nclass IntegratedGradients(GradientBasedMethod):\n def __init__(self, T, X, session, keras_learning_phase, steps=100, baseline=None, Y_shape=None):\n self.steps = steps\n self.baseline = baseline\n super(IntegratedGradients, self).__init__(T, X, session, keras_learning_phase, Y_shape)\n\n def run(self, xs, ys=None, batch_size=None):\n self._check_input_compatibility(xs, ys, batch_size)\n\n gradient = None\n for alpha in tqdm(list(np.linspace(1. / self.steps, 1.0, self.steps))):\n xs_mod = [b + (x - b) * alpha for x, b in zip(xs, self.baseline)] if self.has_multiple_inputs \\\n else self.baseline + (xs - self.baseline) * alpha\n _attr = self._session_run(self.explain_symbolic(), xs_mod, ys, batch_size)\n if gradient is None: gradient = _attr\n else: gradient = [g + a for g, a in zip(gradient, _attr)]\n\n results = [g * (x - b) / self.steps for g, x, b in zip(\n gradient,\n xs if self.has_multiple_inputs else [xs],\n self.baseline if self.has_multiple_inputs else [self.baseline])]\n\n return results[0] if not self.has_multiple_inputs else results\n\n\n\n\"\"\"\nDeepLIFT\nThis reformulation only considers the \"Rescale\" rule\nhttps://arxiv.org/abs/1704.02685\n\"\"\"\nclass DeepLIFTRescale(GradientBasedMethod):\n\n _deeplift_ref = {}\n\n def __init__(self, T, X, session, keras_learning_phase, baseline=None, Y_shape=None):\n self.baseline = baseline\n super(DeepLIFTRescale, self).__init__(T, X, session, keras_learning_phase, Y_shape)\n\n def get_symbolic_attribution(self):\n return [g * (x - b) for g, x, b in zip(\n tf.gradients(ys=self.T, xs=self.X),\n self.X if self.has_multiple_inputs else [self.X],\n self.baseline if self.has_multiple_inputs else [self.baseline])]\n\n @classmethod\n def nonlinearity_grad_override(cls, op, grad):\n output = op.outputs[0]\n input = op.inputs[0]\n ref_input = cls._deeplift_ref[op.name]\n ref_output = activation(op.type)(ref_input)\n delta_out = output - ref_output\n delta_in = input - ref_input\n instant_grad = activation(op.type)(0.5 * (ref_input + input))\n return tf.compat.v1.where(tf.abs(delta_in) > 1e-5, grad * delta_out / delta_in,\n original_grad(instant_grad.op, grad))\n\n def _init_references(self):\n # print ('DeepLIFT: computing references...')\n sys.stdout.flush()\n self._deeplift_ref.clear()\n ops = []\n g = tf.compat.v1.get_default_graph()\n for op in g.get_operations():\n if len(op.inputs) > 0 and not op.name.startswith('gradients'):\n if op.type in constants.SUPPORTED_ACTIVATIONS:\n ops.append(op)\n YR = self._session_run([o.inputs[0] for o in ops], self.baseline)\n for (r, op) in zip(YR, ops):\n self._deeplift_ref[op.name] = r\n # print('DeepLIFT: references ready')\n sys.stdout.flush()\n\n\n\"\"\"\nOcclusion method\nGeneralization of the grey-box method presented in https://arxiv.org/pdf/1311.2901.pdf\nThis method performs a systematic perturbation of contiguous hyperpatches in the input,\nreplacing each patch with a user-defined value (by default 0).\n\nwindow_shape : integer or tuple of length xs_ndim\nDefines the shape of the elementary n-dimensional orthotope the rolling window view.\nIf an integer is given, the shape will be a hypercube of sidelength given by its value.\n\nstep : integer or tuple of length xs_ndim\nIndicates step size at which extraction shall be performed.\nIf integer is given, then the step is uniform in all dimensions.\n\"\"\"\nclass Occlusion(PerturbationBasedMethod):\n\n def __init__(self, T, X, session, keras_learning_phase, window_shape=None, step=None):\n super(Occlusion, self).__init__(T, X, session, keras_learning_phase)\n if self.has_multiple_inputs:\n raise RuntimeError('Multiple inputs not yet supported for perturbation methods')\n\n input_shape = X[0].get_shape().as_list()\n if window_shape is not None:\n assert len(window_shape) == len(input_shape), \\\n 'window_shape must have length of input (%d)' % len(input_shape)\n self.window_shape = tuple(window_shape)\n else:\n self.window_shape = (1,) * len(input_shape)\n\n if step is not None:\n assert isinstance(step, int) or len(step) == len(input_shape), \\\n 'step must be integer or tuple with the length of input (%d)' % len(input_shape)\n self.step = step\n else:\n self.step = 1\n self.replace_value = 0.0\n logging.info('Input shape: %s; window_shape %s; step %s' % (input_shape, self.window_shape, self.step))\n\n def run(self, xs, ys=None, batch_size=None):\n self._check_input_compatibility(xs, ys, batch_size)\n input_shape = xs.shape[1:]\n batch_size = xs.shape[0]\n total_dim = np.prod(input_shape).item()\n\n # Create mask\n index_matrix = np.arange(total_dim).reshape(input_shape)\n idx_patches = view_as_windows(index_matrix, self.window_shape, self.step).reshape((-1,) + self.window_shape)\n heatmap = np.zeros_like(xs, dtype=np.float32).reshape((-1), total_dim)\n w = np.zeros_like(heatmap)\n\n # Compute original output\n eval0 = self._session_run(self.T, xs, ys, batch_size)\n\n # Start perturbation loop\n for i, p in enumerate(tqdm(idx_patches)):\n mask = np.ones(input_shape).flatten()\n mask[p.flatten()] = self.replace_value\n masked_xs = mask.reshape((1,) + input_shape) * xs\n delta = eval0 - self._session_run(self.T, masked_xs, ys, batch_size)\n delta_aggregated = np.sum(delta.reshape((batch_size, -1)), -1, keepdims=True)\n heatmap[:, p.flatten()] += delta_aggregated\n w[:, p.flatten()] += p.size\n\n attribution = np.reshape(heatmap / w, xs.shape)\n if np.isnan(attribution).any():\n warnings.warn('Attributions generated by Occlusion method contain nans, '\n 'probably because window_shape and step do not allow to cover the all input.')\n return attribution\n\n\n\"\"\"\nShapley Value sampling\nComputes approximate Shapley Values using \"Polynomial calculation of the Shapley value based on sampling\",\nCastro et al, 2009 (https://www.sciencedirect.com/science/article/pii/S0305054808000804)\n\nsamples : integer (default 5)\nDefined the number of samples for each input feature.\nNotice that evaluating a model samples * n_input_feature times might take a while.\n\nsampling_dims : list of dimension indexes to run sampling on (feature dimensions).\nBy default, all dimensions except the batch dimension will be sampled.\nFor example, with a 4-D tensor that contains color images, single color channels are sampled.\nTo sample pixels, instead, use sampling_dims=[1,2]\n\"\"\"\nclass ShapleySampling(PerturbationBasedMethod):\n\n def __init__(self, T, X, session, keras_learning_phase, samples=5, sampling_dims=None, Y_shape=None):\n super(ShapleySampling, self).__init__(T, X, session, keras_learning_phase, Y_shape)\n if self.has_multiple_inputs:\n raise RuntimeError('Multiple inputs not yet supported for perturbation methods')\n dims = len(X.shape)\n if sampling_dims is not None:\n if not 0 < len(sampling_dims) <= (dims - 1):\n raise RuntimeError('sampling_dims must be a list containing 1 to %d elements' % (dims-1))\n if 0 in sampling_dims:\n raise RuntimeError('Cannot sample batch dimension: remove 0 from sampling_dims')\n if any([x < 1 or x > dims-1 for x in sampling_dims]):\n raise RuntimeError('Invalid value in sampling_dims')\n else:\n sampling_dims = list(range(1, dims))\n\n self.samples = samples\n self.sampling_dims = sampling_dims\n\n def run(self, xs, ys=None, batch_size=None):\n xs_shape = list(xs.shape)\n batch_size = xs.shape[0]\n n_features = int(np.prod([xs.shape[i] for i in self.sampling_dims]).item())\n result = np.zeros((xs_shape[0], n_features))\n\n run_shape = list(xs_shape) # a copy\n run_shape = np.delete(run_shape, self.sampling_dims).tolist()\n run_shape.insert(1, -1)\n\n reconstruction_shape = [xs_shape[0]]\n for j in self.sampling_dims:\n reconstruction_shape.append(xs_shape[j])\n with tqdm(total=self.samples * n_features) as pbar:\n for _ in range(self.samples):\n p = np.random.permutation(n_features)\n x = xs.copy().reshape(run_shape)\n y = None\n for i in p:\n if y is None:\n y = self._session_run(self.T, x.reshape(xs_shape), ys, batch_size)\n x[:, i] = 0\n y0 = self._session_run(self.T, x.reshape(xs_shape), ys, batch_size)\n delta = y - y0\n delta_aggregated = np.sum(delta.reshape((batch_size, -1)), -1, keepdims=False)\n result[:, i] += delta_aggregated\n y = y0\n pbar.update(1)\n\n shapley = result / self.samples\n return shapley.reshape(reconstruction_shape)\n"
] |
[
[
"tensorflow.abs",
"numpy.zeros_like",
"numpy.isnan",
"numpy.delete",
"numpy.reshape",
"numpy.zeros",
"tensorflow.compat.v1.get_default_graph",
"numpy.random.permutation",
"numpy.ones",
"tensorflow.ones_like",
"tensorflow.gradients",
"tensorflow.zeros_like",
"numpy.prod",
"numpy.arange",
"numpy.linspace"
]
] |
amboulouma/3aransia.api
|
[
"3efb495ac6b46ec2064969a29a39e2332201e67a"
] |
[
"api/algorithms.py"
] |
[
"import sys\n\nimport pandas as pd\nimport numpy as np\nimport nltk\n\nfrom api.constants import *\n\n# Translate a Moroccan letter to an Arabian letter\ndef morrocan_letter_to_arabian(letter, position, word_length): \n alphabet = pd.read_csv(BASE_DIR + DATA_DIR + MOROCCAN_ALPHABET)\n try:\n if position == 0:\n values = alphabet.loc[alphabet['MoroccanAlphabet'] == letter]['BeginningofWord']\n return values.values[0]\n elif position == word_length:\n values = alphabet.loc[alphabet['MoroccanAlphabet'] == letter]['EndofWord']\n return values.values[0]\n elif position == -1:\n values = alphabet.loc[alphabet['MoroccanAlphabet'] == letter]['ArabianAlphabet']\n return values.values[0]\n elif position > 0:\n values = alphabet.loc[alphabet['MoroccanAlphabet'] == letter]['MiddleofWord']\n return values.values[0]\n except IndexError as e:\n print(e)\n except TypeError as e:\n print(e)\n\n# Translate Moroccan double letter to Arabian letter\ndef moroccan_double_letter_to_arabian(double_letter, position, word):\n alphabet = pd.read_csv(BASE_DIR + DATA_DIR + MOROCCAN_ALPHABET)\n for i in range(len(word)):\n if double_letter == 'la':\n return morrocan_letter_to_arabian('la', i , len(word))\n elif double_letter == 'ch':\n return morrocan_letter_to_arabian('ch', i , len(word))\n elif double_letter == 'kh':\n return morrocan_letter_to_arabian('kh', i, len(word))\n elif double_letter == 'sh':\n return morrocan_letter_to_arabian('sh', i, len(word))\n elif double_letter == 'gh':\n return morrocan_letter_to_arabian('gh', i, len(word))\n elif double_letter == 'ou':\n return morrocan_letter_to_arabian('ou', i, len(word))\n\n# Translate duplicate Moroccan letter to Arabian letter\ndef moroccan_duplicate_letter_to_arabian(duplicate_letter, position, word):\n alphabet = pd.read_csv(BASE_DIR + DATA_DIR + MOROCCAN_ALPHABET)\n for i in range(len(word)):\n if duplicate_letter in DUPLICATE_MOROCCAN_LETTERS:\n return morrocan_letter_to_arabian(duplicate_letter, i , len(word))\n\n# Translate Moroccan to Arabic\ndef moroccan_to_arabic(_str):\n alphabet = pd.read_csv(BASE_DIR + DATA_DIR + MOROCCAN_ALPHABET)\n arabian_translation = list()\n for word in _str.split():\n moroccan_translation_object = dict()\n arabian_word = []\n word = word.lower()\n word_iterator = iter(range(len(word)))\n for i in word_iterator:\n if i == 0:\n if word[:2] in DOUBLE_MOROCCAN_LETTERS:\n arabian_word.append(moroccan_double_letter_to_arabian(word[0:2], 0, word))\n next(word_iterator)\n elif word[:2] in DUPLICATE_MOROCCAN_LETTERS:\n arabian_word.append(moroccan_duplicate_letter_to_arabian(word[0:2], 0, word))\n next(word_iterator)\n else:\n arabian_word.append(morrocan_letter_to_arabian(word[i], 0, len(word)))\n \n elif i == len(word)-1:\n arabian_word.append(morrocan_letter_to_arabian(word[i], -1, len(word)))\n \n elif i > 0 and (word[i-1] in MOROCCAN_ENDING_LETTERS):\n if (i+2 <= len(word)-1 and word[i+2] == 'e') or i == len(word)-2:\n if i+1 < len(word)-1 and (word[i:i+2] in DOUBLE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_double_letter_to_arabian(word[i:i+2], -1, word))\n next(word_iterator)\n elif i+1 < len(word)-1 and (word[i:i+2] in DUPLICATE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_duplicate_letter_to_arabian(word[i:i+2], -1, word))\n next(word_iterator)\n else:\n arabian_word.append(morrocan_letter_to_arabian(word[i], -1, len(word)))\n elif (i+1 <= len(word)-1 and word[i+1] == 'e') or i == len(word)-1:\n arabian_word.append(morrocan_letter_to_arabian(word[i], -1, len(word)))\n else:\n if i+1 < len(word)-1 and (word[i:i+2] in DOUBLE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_double_letter_to_arabian(word[i:i+2], 0, word))\n next(word_iterator)\n elif i+1 < len(word)-1 and (word[i:i+2] in DUPLICATE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_duplicate_letter_to_arabian(word[i:i+2], 0, word))\n next(word_iterator)\n else:\n arabian_word.append(morrocan_letter_to_arabian(word[i], 0, len(word)))\n \n elif i < len(word)-2 and i+2 == len(word)-1 and word[i+2] == 'e':\n if i+1 < len(word)-1 and (word[i:i+2] in DOUBLE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_double_letter_to_arabian(word[i:i+2], i, word))\n next(word_iterator)\n elif i+1 < len(word)-1 and (word[i:i+2] in DUPLICATE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_duplicate_letter_to_arabian(word[i:i+2], i, word))\n next(word_iterator)\n else:\n arabian_word.append(morrocan_letter_to_arabian(word[i], i, len(word)))\n \n elif i < len(word)-1 and i+1 == len(word)-1 and word[i+1] == 'e':\n arabian_word.append(morrocan_letter_to_arabian(word[i], len(word), len(word)))\n \n elif i > 1 and (word[i-2] in MOROCCAN_ENDING_LETTERS) and word[i-1] == 'e':\n if i+1 < len(word)-1 and (word[i:i+2] in DOUBLE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_double_letter_to_arabian(word[i:i+2], -1, word))\n next(word_iterator)\n elif i+1 < len(word)-1 and (word[i:i+2] in DUPLICATE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_duplicate_letter_to_arabian(word[i:i+2], -1, word))\n next(word_iterator)\n else:\n arabian_word.append(morrocan_letter_to_arabian(word[i], -1, len(word)))\n \n else:\n if i+1 < len(word)-1 and (word[i:i+2] in DOUBLE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_double_letter_to_arabian(word[i:i+2], i, word))\n next(word_iterator)\n elif i+1 < len(word)-1 and (word[i:i+2] in DUPLICATE_MOROCCAN_LETTERS):\n arabian_word.append(moroccan_duplicate_letter_to_arabian(word[i:i+2], i, word))\n next(word_iterator)\n else:\n arabian_word.append(morrocan_letter_to_arabian(word[i], i, len(word)))\n try:\n moroccan_translation_object = {'moroccan_word' : word, 'arabian_word' : (u''.join(arabian_word).replace(u'\\u200e', ''))}\n arabian_translation.append(moroccan_translation_object)\n except TypeError as e:\n print(e, word)\n return arabian_translation\n\n# Translate Arabic to Moroccan\n# TODO\n\n# Function to compute the distance between two words\ndef word_distance(word_1, word_2):\n return nltk.edit_distance(word_1, word_2)\n \n# Converte a letter to its substitute\ndef letter_to_substitute(l):\n if l == '7': \n return 'h'\n if l == '9': \n return 'q'\n else : \n return l\n\n# Word counter\ndef word_count(_str):\n return {word: _str.count(word) for word in _str.split()}\n\n# Get duplicated\ndef generate_duplicates(_str):\n return dict(filter(lambda x:x[1] > 1, word_count(_str).items()))\n\n# Generate lexically close words\ndef generate_close_words(threshold, _str):\n words = set()\n for w in _str.split():\n for y in _str.split():\n if w != y and word_distance(w,y) < threshold: \n words.add((w,y, word_distance(w,y)))\n return sorted(words, key=lambda x:len(x[0]))\n\n# Converte a word to its substitute\ndef word_to_substitute(word):\n return ''.join(list(map(lambda x:letter_to_substitute(x), word)))\n\n# Validate Latin/Digit Moroccan to Arabic dictionary\ndef validate_dictionary(dictionary):\n data = pd.read_csv(dictionary)\n return data\n #TODO\n\n# Temporary function to test\ndef run_tests():\n pass\n \n# Runnin the tests\nrun_tests()"
] |
[
[
"pandas.read_csv"
]
] |
billy-horn/lightning-flash
|
[
"61c741d37182d137f39b771879254db8fd20308f"
] |
[
"flash/vision/classification/model.py"
] |
[
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Any, Callable, Mapping, Sequence, Type, Union\n\nimport torch\nimport torchvision\nfrom pytorch_lightning.metrics import Accuracy\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom flash.core.classification import ClassificationTask\nfrom flash.vision.classification.backbones import torchvision_backbone_and_num_features\nfrom flash.vision.classification.data import ImageClassificationData, ImageClassificationDataPipeline\n\n\nclass ImageClassifier(ClassificationTask):\n \"\"\"Task that classifies images.\n\n Args:\n num_classes: Number of classes to classify.\n backbone: A model to use to compute image features.\n pretrained: Use a pretrained backbone.\n loss_fn: Loss function for training, defaults to cross entropy.\n optimizer: Optimizer to use for training, defaults to `torch.optim.SGD`.\n metrics: Metrics to compute for training and evaluation.\n learning_rate: Learning rate to use for training, defaults to `1e-3`\n \"\"\"\n\n def __init__(\n self,\n num_classes,\n backbone=\"resnet18\",\n num_features: int = None,\n pretrained=True,\n loss_fn: Callable = F.cross_entropy,\n optimizer: Type[torch.optim.Optimizer] = torch.optim.SGD,\n metrics: Union[Callable, Mapping, Sequence, None] = (Accuracy()),\n learning_rate: float = 1e-3,\n ):\n super().__init__(\n model=None,\n loss_fn=loss_fn,\n optimizer=optimizer,\n metrics=metrics,\n learning_rate=learning_rate,\n )\n\n self.save_hyperparameters()\n\n self.backbone, num_features = torchvision_backbone_and_num_features(backbone, pretrained)\n\n self.head = nn.Sequential(\n nn.AdaptiveAvgPool2d((1, 1)),\n nn.Flatten(),\n nn.Linear(num_features, num_classes),\n )\n\n def forward(self, x) -> Any:\n x = self.backbone(x)\n return self.head(x)\n\n @staticmethod\n def default_pipeline() -> ImageClassificationDataPipeline:\n return ImageClassificationData.default_pipeline()\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.Flatten"
]
] |
Marcel-Velez/CLMR
|
[
"730bd9078756650a53b4c6438b29e5aeb2c15134",
"730bd9078756650a53b4c6438b29e5aeb2c15134"
] |
[
"clmr/models/TailedU2Expa.py",
"clmr/models/preliminary_models/NoPadConnectNet5ENDDOWN.py"
] |
[
"import torch\nimport torch.nn as nn\n\nfrom .SingleDeconv import SingleDeconv\n\n\nclass TailedU2Expa(nn.Module):\n def __init__(self, in_channels=35, n_classes=1):\n super(TailedU2Expa, self).__init__()\n\n padding = 0\n stride = 3\n self.pool = nn.MaxPool1d(3, stride=3)\n \n self.conv1 = SingleDeconv(1 , int(in_channels), kernel=3, stride=1, padding=1)\n self.conv2 = SingleDeconv(int(in_channels), in_channels*2, kernel=3, stride=1, padding=1)\n self.conv3 = SingleDeconv(in_channels*2, in_channels*4, kernel=3, stride=1, padding=1)\n self.conv4 = SingleDeconv(in_channels*4, in_channels*8, kernel=3, stride=1, padding=1)\n self.conv5 = SingleDeconv(in_channels*8, in_channels*16, kernel=3, stride=1, padding=1)\n \n \n self.transposedConv6 = nn.ConvTranspose1d(in_channels*16, in_channels*8, kernel_size=3, stride=stride, padding=padding)\n self.transposedConv7 = nn.ConvTranspose1d(in_channels*8, in_channels*4, kernel_size=3, stride=stride, padding=padding)\n # self.transposedConv8 = nn.ConvTranspose1d(in_channels*4, in_channels*2, kernel_size=3, stride=stride, padding=padding)\n # self.transposedConv9 = nn.ConvTranspose1d(in_channels*2, in_channels*1, kernel_size=3, stride=stride, padding=padding)\n\n self.conv6 = SingleDeconv(in_channels*16, in_channels*8, kernel=3, stride=1, padding=1)\n self.conv7 = SingleDeconv(in_channels*8, in_channels*4, kernel=3, stride=1, padding=1)\n # self.conv8 = SingleDeconv(in_channels*4, in_channels*2, kernel=3, stride=1, padding=1)\n # self.conv9 = SingleDeconv(int(in_channels*2), in_channels*1, kernel=3, stride=1, padding=1)\n\n\n # tail part\n # self.convDown1 = SingleDeconv(int(in_channels*1), in_channels*2, kernel=3, stride=1, padding=1)\n # self.convDown2 = SingleDeconv(in_channels*2, in_channels*4, kernel=3, stride=1, padding=1)\n self.convDown3 = SingleDeconv(in_channels*4, in_channels*8, kernel=3, stride=1, padding=1)\n self.convDown4 = SingleDeconv(in_channels*8, 512, kernel=3, stride=1, padding=1)\n\n\n self.output_avg = nn.AvgPool1d(729)\n\n self.fc = nn.Linear(512, n_classes)\n nn.init.xavier_uniform_(self.fc.weight)\n\n def forward(self, x):\n\n c1 = self.conv1(x)\n p1 = self.pool(c1)\n\n c2 = self.conv2(p1)\n p2 = self.pool(c2)\n\n c3 = self.conv3(p2)\n p3 = self.pool(c3)\n\n c4 = self.conv4(p3)\n p4 = self.pool(c4)\n\n c5 = self.conv5(p4)\n\n # expansive\n u6 = self.transposedConv6(c5)\n u6 = torch.cat((u6, c4), axis=1)\n c6 = self.conv6(u6)\n\n u7 = self.transposedConv7(c6)\n u7 = torch.cat((u7, c3), axis=1)\n c7 = self.conv7(u7)\n\n # u8 = self.transposedConv8(c7)\n # u8 = torch.cat((u8, c2), axis=1)\n # c8 = self.conv8(u8)\n\n # u9 = self.transposedConv9(c8)\n # u9 = torch.cat((u9, c1), axis=1)\n # c9 = self.conv9(u9)\n\n # p9 = self.pool(c9)\n \n # tail\n # c10 = self.convDown1(p9)\n # p10 = self.pool(c8)\n \n # c11 = self.convDown2(p10)\n p11 = self.pool(c7)\n\n c12 = self.convDown3(p11)\n p12 = self.pool(c12)\n\n c13 = self.convDown4(p12)\n\n output = self.output_avg(c13)\n output = self.fc(output.permute(0,2,1))\n\n return output.view(output.shape[0],-1)\n\n\n\n\n\n",
"import numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport sys\nfrom torch.autograd import Variable\nimport math\n\nimport torch.nn.functional as F\n\n\nfrom torchsummary import summary\n\nPOOLSIZE = 2\nDROPOUT_RATE = .25\ndef init_weights(m):\n if isinstance(m, nn.Linear):\n torch.nn.init.xavier_uniform(m.weight)\n m.bias.data.fill_(0.01)\n\nclass Deconv(nn.Module):\n def __init__(self, in_chan, out_chan, kernel, stride, padding):\n super(Deconv, self).__init__()\n\n self.layers = []\n self.layers.append(nn.Conv1d(in_chan, out_chan, kernel_size=kernel, stride=stride, padding=padding))\n self.layers.append(nn.BatchNorm1d(out_chan))\n self.layers.append(nn.ReLU())\n\n self.layers.append(nn.Conv1d(out_chan, out_chan, kernel_size=kernel, stride=stride, padding=padding))\n self.layers.append(nn.BatchNorm1d(out_chan))\n self.layers.append(nn.ReLU())\n\n self.layers = nn.Sequential(*self.layers)\n\n self.layers.apply(init_weights)\n\n def forward(self, x):\n\n out = self.layers(x)\n\n return out\n\n\n\nclass NoPadConnectNet5ENDDOWN(nn.Module):\n def __init__(self, in_channels=16, n_classes=1):\n super(NoPadConnectNet5ENDDOWN, self).__init__()\n\n padding = 0\n self.pool = nn.MaxPool1d(2, stride=2)\n dropout = nn.Dropout(DROPOUT_RATE)\n \n self.conv1 = Deconv(1 , int(in_channels), kernel=3, stride=1, padding=padding)\n self.conv2 = Deconv(int(in_channels), in_channels*2, kernel=3, stride=1, padding=padding)\n self.conv3 = Deconv(in_channels*2, in_channels*4, kernel=3, stride=1, padding=padding)\n self.conv4 = Deconv(in_channels*4, in_channels*8, kernel=3, stride=1, padding=padding)\n self.conv5 = Deconv(in_channels*8, in_channels*16, kernel=3, stride=1, padding=padding)\n \n\n\n self.transposedConv6 = nn.ConvTranspose1d(in_channels*16, in_channels*8, kernel_size=2, stride=2, padding=padding)\n self.transposedConv7 = nn.ConvTranspose1d(in_channels*8, in_channels*4, kernel_size=2, stride=2, padding=padding)#, padding='same')\n self.transposedConv8 = nn.ConvTranspose1d(in_channels*4, in_channels*2, kernel_size=2, stride=2, padding=padding)#, padding='same')\n self.transposedConv9 = nn.ConvTranspose1d(in_channels*2, in_channels*1, kernel_size=2, stride=2, padding=padding)#, padding='same')\n\n self.conv6 = Deconv(in_channels*16, in_channels*8, kernel=3, stride=1, padding=padding)\n self.conv7 = Deconv(in_channels*8, in_channels*4, kernel=3, stride=1, padding=padding) # 8 from trans conv and 4 from same res\n self.conv8 = Deconv(in_channels*4, in_channels*2, kernel=3, stride=1, padding=padding) # x from trans conv and 2 from same res\n self.conv9 = Deconv(int(in_channels*2), in_channels*1, kernel=3, stride=1, padding=padding) # x from trans conv and 1 from same res\n\n # self.conv_to_n_classes = nn.Conv1d(in_channels=in_channels, out_channels=512, kernel_size=1, stride=1, padding=0)\n\n # go down again\n self.convDown1 = Deconv(int(in_channels*3), in_channels*2, kernel=3, stride=1, padding=padding)\n self.convDown2 = Deconv(in_channels*6, in_channels*4, kernel=3, stride=1, padding=padding)\n self.convDown3 = Deconv(in_channels*12, in_channels*8, kernel=3, stride=1, padding=padding)\n self.convDown4 = Deconv(in_channels*24, in_channels*16, kernel=3, stride=1, padding=padding)\n self.convDown5 = Deconv(in_channels*16, in_channels*32, kernel=3, stride=1, padding=padding)\n self.convDown6 = Deconv(in_channels*32, in_channels*32, kernel=3, stride=1, padding=padding)\n self.convDown7 = Deconv(in_channels*32, in_channels*32, kernel=3, stride=1, padding=padding)\n self.convDown8 = Deconv(in_channels*32, in_channels*32, kernel=3, stride=1, padding=padding)\n self.convDown9 = Deconv(in_channels*32, in_channels*32, kernel=3, stride=1, padding=padding)\n self.convDown10 = Deconv(in_channels*32, in_channels*32, kernel=3, stride=1, padding=padding)\n\n\n self.output_avg = nn.AvgPool1d(49)\n\n self.fc = nn.Linear(512, n_classes)\n torch.nn.init.xavier_uniform(self.fc.weight)\n\n def forward(self, x):\n\n c1 = self.conv1(x)\n p1 = self.pool(c1)\n\n c2 = self.conv2(p1)\n p2 = self.pool(c2)\n\n c3 = self.conv3(p2)\n p3 = self.pool(c3)\n\n c4 = self.conv4(p3)\n p4 = self.pool(c4)\n\n c5 = self.conv5(p4)\n # p5 = self.pool(c5)\n\n # c_extra_down = self.extra_down(p5)\n\n # c_extra_up = self.extra_up(c_extra_down)\n # c_concat_extra = torch.cat((c_extra_up, c5[:,:,4:-4]),axis=1)\n # c_extra_conv = self.extra_conv(c_concat_extra)\n\n # expansive\n u6 = self.transposedConv6(c5)\n u6 = torch.cat((u6, c4[:,:,5:-4]), axis=1) # sum to 10\n c6 = self.conv6(u6)\n\n\n u7 = self.transposedConv7(c6)\n u7 = torch.cat((u7, c3[:,:,18:-17]), axis=1) # sum to 10\n c7 = self.conv7(u7)\n\n u8 = self.transposedConv8(c7)\n u8 = torch.cat((u8, c2[:,:,43:-43]), axis=1) # sum to 10\n c8 = self.conv8(u8)\n\n # going up 1 less\n u9 = self.transposedConv9(c8)\n u9 = torch.cat((u9, c1[:,:,95:-94]), axis=1) # sum to 10\n c9 = self.conv9(u9)\n\n p9 = self.pool(c9)\n # and way down we go \n \n newthrough1 = torch.cat((p9, c8[:,:,1:-1]), axis=1) # sum to 10\n c10 = self.convDown1(newthrough1)\n p10 = self.pool(c10)\n \n newthrough2 = torch.cat((p10, c7[:,:,3:-2]), axis=1) # sum to 10\n c11 = self.convDown2(newthrough2)\n p11 = self.pool(c11)\n\n # p11 = F.pad(p11, (2,2))\n newthrough3 = torch.cat((p11, c6[:,:,4:-3]), axis=1) # sum to 10\n c12 = self.convDown3(newthrough3)\n p12 = self.pool(c12)\n\n newthrough4 = torch.cat((p12, c5[:,:,4:-4]), axis=1) # sum to 10\n c13 = self.convDown4(newthrough4)\n p13 = self.pool(c13)\n \n\n # standalone three layer deeper than rest of network\n c14 = self.convDown5(p13)\n p14 = self.pool(c14)\n\n c15 = self.convDown6(p14)\n p15 = self.pool(c15)\n\n c16 = self.convDown7(p15)\n p16 = self.pool(c16)\n\n c17 = self.convDown8(p16)\n p17 = self.pool(c17)\n\n c18 = self.convDown9(p17)\n p18 = self.pool(c18)\n\n c19 = self.convDown10(p18)\n\n output = self.output_avg(c19)\n # print(output)\n # output = self.fc2(output)\n output = self.fc(output.permute(0,2,1))\n\n # print('out', output)\n\n # print(self.weight)\n # exit()\n return output.view(output.shape[0],-1)\n\n\n\n\n\n"
] |
[
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.AvgPool1d",
"torch.nn.ConvTranspose1d",
"torch.nn.init.xavier_uniform_",
"torch.nn.MaxPool1d"
],
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.cat",
"torch.nn.ConvTranspose1d",
"torch.nn.AvgPool1d",
"torch.nn.Conv1d",
"torch.nn.init.xavier_uniform",
"torch.nn.Sequential",
"torch.nn.ReLU",
"torch.nn.BatchNorm1d",
"torch.nn.MaxPool1d"
]
] |
kabilar/workflow-calcium-imaging
|
[
"0647d65af6a92caecdd5cc251b74153c68068ca8"
] |
[
"tests/__init__.py"
] |
[
"# run tests: pytest -sv --cov-report term-missing --cov=workflow-calcium-imaging -p no:warnings\n\nimport os\nimport pytest\nimport pandas as pd\nimport pathlib\nimport datajoint as dj\nimport numpy as np\n\nfrom workflow_calcium_imaging.paths import get_imaging_root_data_dir\n\n# ------------------- SOME CONSTANTS -------------------\n\ntest_user_data_dir = pathlib.Path('./tests/user_data')\ntest_user_data_dir.mkdir(exist_ok=True)\n\nsessions_dirs = ['subject0/session1',\n 'subject1/20200609_170519',\n 'subject1/20200609_171646',\n 'subject2/20200420_1843959',\n 'subject3/210107_run00_orientation_8dir']\n\nis_multi_scan_processing = False\n\n# ------------------- FIXTURES -------------------\n\n\n@pytest.fixture(autouse=True)\ndef dj_config():\n if pathlib.Path('./dj_local_conf.json').exists():\n dj.config.load('./dj_local_conf.json')\n dj.config['safemode'] = False\n dj.config['custom'] = {\n 'database.prefix': (os.environ.get('DATABASE_PREFIX')\n or dj.config['custom']['database.prefix']),\n 'imaging_root_data_dir': (os.environ.get('IMAGING_ROOT_DATA_DIR')\n or dj.config['custom']['imaging_root_data_dir'])\n }\n return\n\n\n@pytest.fixture(autouse=True)\ndef test_data(dj_config):\n test_data_dir = pathlib.Path(dj.config['custom']['imaging_root_data_dir'])\n\n test_data_exists = np.all([(test_data_dir / p).exists() for p in sessions_dirs])\n\n if not test_data_exists:\n try:\n dj.config['custom'].update({\n 'djarchive.client.endpoint': os.environ['DJARCHIVE_CLIENT_ENDPOINT'],\n 'djarchive.client.bucket': os.environ['DJARCHIVE_CLIENT_BUCKET'],\n 'djarchive.client.access_key': os.environ['DJARCHIVE_CLIENT_ACCESSKEY'],\n 'djarchive.client.secret_key': os.environ['DJARCHIVE_CLIENT_SECRETKEY']\n })\n except KeyError as e:\n raise FileNotFoundError(\n f'Test data not available at {test_data_dir}.'\n f'\\nAttempting to download from DJArchive,'\n f' but no credentials found in environment variables.'\n f'\\nError: {str(e)}')\n\n import djarchive_client\n from workflow_calcium_imaging import version\n\n client = djarchive_client.client()\n workflow_version = version.__version__\n\n client.download('workflow-calcium-ephys-test-set',\n workflow_version.replace('.', '_'),\n str(test_data_dir), create_target=False)\n return\n\n\n@pytest.fixture\ndef pipeline():\n from workflow_calcium_imaging import pipeline\n\n global is_multi_scan_processing\n is_multi_scan_processing = 'processing_task_id' in pipeline.imaging.ProcessingTask.heading.names\n\n yield {'subject': pipeline.subject,\n 'lab': pipeline.lab,\n 'imaging': pipeline.imaging,\n 'scan': pipeline.scan,\n 'session': pipeline.session,\n 'Equipment': pipeline.Equipment,\n 'get_imaging_root_data_dir': pipeline.get_imaging_root_data_dir}\n\n pipeline.subject.Subject.delete()\n\n\n@pytest.fixture\ndef subjects_csv():\n \"\"\" Create a 'subjects.csv' file\"\"\"\n input_subjects = pd.DataFrame(columns=['subject', 'sex',\n 'subject_birth_date',\n 'subject_description'])\n input_subjects.subject = ['subject0', 'subject1', 'subject2', 'subject3']\n input_subjects.sex = ['M', 'F', 'M', 'F']\n input_subjects.subject_birth_date = [\n '2020-01-01 00:00:01', '2020-01-01 00:00:01',\n '2020-01-01 00:00:01', '2020-01-01 00:00:01']\n input_subjects.subject_description = ['mika_animal', '91760', '90853', 'sbx-JC015']\n input_subjects = input_subjects.set_index('subject')\n\n subjects_csv_path = pathlib.Path('./tests/user_data/subjects.csv')\n input_subjects.to_csv(subjects_csv_path) # write csv file\n\n yield input_subjects, subjects_csv_path\n\n subjects_csv_path.unlink() # delete csv file after use\n\n\n@pytest.fixture\ndef ingest_subjects(pipeline, subjects_csv):\n from workflow_calcium_imaging.ingest import ingest_subjects\n _, subjects_csv_path = subjects_csv\n ingest_subjects(subjects_csv_path)\n return\n\n\n@pytest.fixture\ndef sessions_csv(test_data):\n \"\"\" Create a 'sessions.csv' file\"\"\"\n root_dir = pathlib.Path(get_imaging_root_data_dir())\n\n input_sessions = pd.DataFrame(columns=['subject', 'session_dir'])\n input_sessions.subject = ['subject0',\n 'subject1',\n 'subject1',\n 'subject2',\n 'subject3']\n input_sessions.session_dir = [(root_dir / sess_dir).as_posix()\n for sess_dir in sessions_dirs]\n input_sessions = input_sessions.set_index('subject')\n\n sessions_csv_path = pathlib.Path('./tests/user_data/sessions.csv')\n input_sessions.to_csv(sessions_csv_path) # write csv file\n\n yield input_sessions, sessions_csv_path\n\n sessions_csv_path.unlink() # delete csv file after use\n\n\n@pytest.fixture\ndef ingest_sessions(ingest_subjects, sessions_csv):\n from workflow_calcium_imaging.ingest import ingest_sessions\n _, sessions_csv_path = sessions_csv\n ingest_sessions(sessions_csv_path)\n return\n\n\n@pytest.fixture\ndef testdata_paths():\n return {\n 'scanimage_2d': 'subject1/20200609_171646',\n 'scanimage_3d': 'subject2/20200420_1843959',\n 'scanimage_multiroi': 'subject0/session1',\n 'scanbox_3d': 'subject3/210107_run00_orientation_8dir',\n 'suite2p_2d': 'subject1/20200609_171646/suite2p',\n 'suite2p_3d_a': 'subject2/20200420_1843959/suite2p',\n 'suite2p_3d_b': 'subject3/210107_run00_orientation_8dir/suite2p',\n 'caiman_2d': 'subject1/20200609_170519/caiman'\n }\n\n\n@pytest.fixture\ndef suite2p_paramset(pipeline):\n imaging = pipeline['imaging']\n\n params_suite2p = {'look_one_level_down': 0.0,\n 'fast_disk': [],\n 'delete_bin': False,\n 'mesoscan': False,\n 'h5py': [],\n 'h5py_key': 'data',\n 'save_path0': [],\n 'subfolders': [],\n 'nplanes': 1,\n 'nchannels': 1,\n 'functional_chan': 1,\n 'tau': 1.0,\n 'fs': 10.0,\n 'force_sktiff': False,\n 'preclassify': 0.0,\n 'save_mat': False,\n 'combined': True,\n 'aspect': 1.0,\n 'do_bidiphase': False,\n 'bidiphase': 0.0,\n 'do_registration': True,\n 'keep_movie_raw': False,\n 'nimg_init': 300,\n 'batch_size': 500,\n 'maxregshift': 0.1,\n 'align_by_chan': 1,\n 'reg_tif': False,\n 'reg_tif_chan2': False,\n 'subpixel': 10,\n 'smooth_sigma': 1.15,\n 'th_badframes': 1.0,\n 'pad_fft': False,\n 'nonrigid': True,\n 'block_size': [128, 128],\n 'snr_thresh': 1.2,\n 'maxregshiftNR': 5.0,\n '1Preg': False,\n 'spatial_hp': 50.0,\n 'pre_smooth': 2.0,\n 'spatial_taper': 50.0,\n 'roidetect': True,\n 'sparse_mode': False,\n 'diameter': 12,\n 'spatial_scale': 0,\n 'connected': True,\n 'nbinned': 5000,\n 'max_iterations': 20,\n 'threshold_scaling': 1.0,\n 'max_overlap': 0.75,\n 'high_pass': 100.0,\n 'inner_neuropil_radius': 2,\n 'min_neuropil_pixels': 350,\n 'allow_overlap': False,\n 'chan2_thres': 0.65,\n 'baseline': 'maximin',\n 'win_baseline': 60.0,\n 'sig_baseline': 10.0,\n 'prctile_baseline': 8.0,\n 'neucoeff': 0.7,\n 'xrange': np.array([0, 0]),\n 'yrange': np.array([0, 0])}\n\n # doing the insert here as well, since most of the test will require this paramset inserted\n imaging.ProcessingParamSet.insert_new_params(\n 'suite2p', 0, 'Calcium imaging analysis with'\n ' Suite2p using default Suite2p parameters', params_suite2p)\n\n yield params_suite2p\n\n (imaging.ProcessingParamSet & 'paramset_idx = 0').delete()\n\n\n@pytest.fixture\ndef caiman2D_paramset(pipeline):\n imaging = pipeline['imaging']\n\n params_caiman_2d = {'fnames': None,\n 'dims': None,\n 'decay_time': 0.4,\n 'dxy': (1, 1),\n 'var_name_hdf5': 'mov',\n 'last_commit': 'GITW-a99c03c9cb221e802ec71aacfb988257810c8c4a',\n 'mmap_F': None,\n 'mmap_C': None,\n 'block_size_spat': 5000,\n 'dist': 3,\n 'expandCore': np.array([[0, 0, 1, 0, 0],\n [0, 1, 1, 1, 0],\n [1, 1, 1, 1, 1],\n [0, 1, 1, 1, 0],\n [0, 0, 1, 0, 0]], dtype='int32'),\n 'extract_cc': True,\n 'maxthr': 0.1,\n 'medw': None,\n 'method_exp': 'dilate',\n 'method_ls': 'lasso_lars',\n 'n_pixels_per_process': None,\n 'nb': 1,\n 'normalize_yyt_one': True,\n 'nrgthr': 0.9999,\n 'num_blocks_per_run_spat': 20,\n 'se': np.array([[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]], dtype = 'uint8'),\n 'ss': np.array([[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]], dtype = 'uint8'),\n 'thr_method': 'nrg',\n 'update_background_components': True,\n 'ITER': 2,\n 'bas_nonneg': False,\n 'block_size_temp': 5000,\n 'fudge_factor': 0.96,\n 'lags': 5,\n 'optimize_g': False,\n 'memory_efficient': False,\n 'method_deconvolution': 'oasis',\n 'noise_method': 'mean',\n 'noise_range': [0.25, 0.5],\n 'num_blocks_per_run_temp': 20,\n 'p': 2,\n 's_min': None,\n 'solvers': ['ECOS', 'SCS'],\n 'verbosity': False,\n 'K': 30,\n 'SC_kernel': 'heat',\n 'SC_sigma': 1,\n 'SC_thr': 0,\n 'SC_normalize': True,\n 'SC_use_NN': False,\n 'SC_nnn': 20,\n 'alpha_snmf': 100,\n 'center_psf': False,\n 'gSig': [5, 5],\n 'gSiz': (11, 11),\n 'init_iter': 2,\n 'kernel': None,\n 'lambda_gnmf': 1,\n 'maxIter': 5,\n 'max_iter_snmf': 500,\n 'method_init': 'greedy_roi',\n 'min_corr': 0.85,\n 'min_pnr': 20,\n 'nIter': 5,\n 'normalize_init': True,\n 'options_local_NMF': None,\n 'perc_baseline_snmf': 20,\n 'ring_size_factor': 1.5,\n 'rolling_length': 100,\n 'rolling_sum': True,\n 'seed_method': 'auto',\n 'sigma_smooth_snmf': (0.5, 0.5, 0.5),\n 'ssub': 2,\n 'ssub_B': 2,\n 'tsub': 2,\n 'check_nan': True,\n 'compute_g': False,\n 'include_noise': False,\n 'max_num_samples_fft': 3072,\n 'pixels': None,\n 'sn': None,\n 'border_pix': 0,\n 'del_duplicates': False,\n 'in_memory': True,\n 'low_rank_background': True,\n 'memory_fact': 1,\n 'n_processes': 1,\n 'nb_patch': 1,\n 'only_init': True,\n 'p_patch': 0,\n 'remove_very_bad_comps': False,\n 'rf': None,\n 'skip_refinement': False,\n 'p_ssub': 2,\n 'stride': None,\n 'p_tsub': 2,\n 'N_samples_exceptionality': 12,\n 'batch_update_suff_stat': False,\n 'dist_shape_update': False,\n 'ds_factor': 1,\n 'epochs': 1,\n 'expected_comps': 500,\n 'full_XXt': False,\n 'init_batch': 200,\n 'init_method': 'bare',\n 'iters_shape': 5,\n 'max_comp_update_shape': np.inf,\n 'max_num_added': 5,\n 'max_shifts_online': 10,\n 'min_SNR': 2.5,\n 'min_num_trial': 5,\n 'minibatch_shape': 100,\n 'minibatch_suff_stat': 5,\n 'motion_correct': True,\n 'movie_name_online': 'online_movie.mp4',\n 'normalize': False,\n 'n_refit': 0,\n 'num_times_comp_updated': np.inf,\n 'opencv_codec': 'H264',\n 'path_to_model': None,\n 'ring_CNN': False,\n 'rval_thr': 0.8,\n 'save_online_movie': False,\n 'show_movie': False,\n 'simultaneously': False,\n 'sniper_mode': False,\n 'stop_detection': False,\n 'test_both': False,\n 'thresh_CNN_noisy': 0.5,\n 'thresh_fitness_delta': -50,\n 'thresh_fitness_raw': -60.97977932734429,\n 'thresh_overlap': 0.5,\n 'update_freq': 200,\n 'update_num_comps': True,\n 'use_corr_img': False,\n 'use_dense': True,\n 'use_peak_max': True,\n 'W_update_factor': 1,\n 'SNR_lowest': 0.5,\n 'cnn_lowest': 0.1,\n 'gSig_range': None,\n 'min_cnn_thr': 0.9,\n 'rval_lowest': -1,\n 'use_cnn': True,\n 'use_ecc': False,\n 'max_ecc': 3,\n 'do_merge': True,\n 'merge_thr': 0.8,\n 'merge_parallel': False,\n 'max_merge_area': None,\n 'border_nan': 'copy',\n 'gSig_filt': None,\n 'is3D': False,\n 'max_deviation_rigid': 3,\n 'max_shifts': (6, 6),\n 'min_mov': None,\n 'niter_rig': 1,\n 'nonneg_movie': True,\n 'num_frames_split': 80,\n 'num_splits_to_process_els': None,\n 'num_splits_to_process_rig': None,\n 'overlaps': (32, 32),\n 'pw_rigid': False,\n 'shifts_opencv': True,\n 'splits_els': 14,\n 'splits_rig': 14,\n 'strides': (96, 96),\n 'upsample_factor_grid': 4,\n 'use_cuda': False,\n 'n_channels': 2,\n 'use_bias': False,\n 'use_add': False,\n 'pct': 0.01,\n 'patience': 3,\n 'max_epochs': 100,\n 'width': 5,\n 'loss_fn': 'pct',\n 'lr': 0.001,\n 'lr_scheduler': None,\n 'remove_activity': False,\n 'reuse_model': False}\n\n imaging.ProcessingParamSet.insert_new_params(\n 'caiman', 1, 'Calcium imaging analysis with'\n ' CaImAn using default CaImAn parameters for 2d planar images',\n params_caiman_2d)\n\n yield params_caiman_2d\n\n (imaging.ProcessingParamSet & 'paramset_idx = 1').delete()\n\n\n@pytest.fixture\ndef caiman3D_paramset(pipeline):\n imaging = pipeline['imaging']\n\n params_caiman_3d = {'fnames': None,\n 'dims': None,\n 'decay_time': 0.4,\n 'dxy': (1, 1),\n 'var_name_hdf5': 'mov',\n 'last_commit': 'GITW-a99c03c9cb221e802ec71aacfb988257810c8c4a',\n 'mmap_F': None,\n 'mmap_C': None,\n 'block_size_spat': 5000,\n 'dist': 3,\n 'expandCore': np.array([[0, 0, 1, 0, 0],\n [0, 1, 1, 1, 0],\n [1, 1, 1, 1, 1],\n [0, 1, 1, 1, 0],\n [0, 0, 1, 0, 0]], dtype = 'int32'),\n 'extract_cc': True,\n 'maxthr': 0.1,\n 'medw': None,\n 'method_exp': 'dilate',\n 'method_ls': 'lasso_lars',\n 'n_pixels_per_process': None,\n 'nb': 1,\n 'normalize_yyt_one': True,\n 'nrgthr': 0.9999,\n 'num_blocks_per_run_spat': 20,\n 'se': np.array([[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]], dtype = 'uint8'),\n 'ss': np.array([[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]], dtype = 'uint8'),\n 'thr_method': 'nrg',\n 'update_background_components': True,\n 'ITER': 2,\n 'bas_nonneg': False,\n 'block_size_temp': 5000,\n 'fudge_factor': 0.96,\n 'lags': 5,\n 'optimize_g': False,\n 'memory_efficient': False,\n 'method_deconvolution': 'oasis',\n 'noise_method': 'mean',\n 'noise_range': [0.25, 0.5],\n 'num_blocks_per_run_temp': 20,\n 'p': 2,\n 's_min': None,\n 'solvers': ['ECOS', 'SCS'],\n 'verbosity': False,\n 'K': 30,\n 'SC_kernel': 'heat',\n 'SC_sigma': 1,\n 'SC_thr': 0,\n 'SC_normalize': True,\n 'SC_use_NN': False,\n 'SC_nnn': 20,\n 'alpha_snmf': 100,\n 'center_psf': False,\n 'gSig': (5, 5, 1),\n 'gSiz': (11, 11),\n 'init_iter': 2,\n 'kernel': None,\n 'lambda_gnmf': 1,\n 'maxIter': 5,\n 'max_iter_snmf': 500,\n 'method_init': 'greedy_roi',\n 'min_corr': 0.85,\n 'min_pnr': 20,\n 'nIter': 5,\n 'normalize_init': True,\n 'options_local_NMF': None,\n 'perc_baseline_snmf': 20,\n 'ring_size_factor': 1.5,\n 'rolling_length': 100,\n 'rolling_sum': True,\n 'seed_method': 'auto',\n 'sigma_smooth_snmf': (0.5, 0.5, 0.5),\n 'ssub': 2,\n 'ssub_B': 2,\n 'tsub': 2,\n 'check_nan': True,\n 'compute_g': False,\n 'include_noise': False,\n 'max_num_samples_fft': 3072,\n 'pixels': None,\n 'sn': None,\n 'border_pix': 0,\n 'del_duplicates': False,\n 'in_memory': True,\n 'low_rank_background': True,\n 'memory_fact': 1,\n 'n_processes': 1,\n 'nb_patch': 1,\n 'only_init': True,\n 'p_patch': 0,\n 'remove_very_bad_comps': False,\n 'rf': None,\n 'skip_refinement': False,\n 'p_ssub': 2,\n 'stride': None,\n 'p_tsub': 2,\n 'N_samples_exceptionality': 12,\n 'batch_update_suff_stat': False,\n 'dist_shape_update': False,\n 'ds_factor': 1,\n 'epochs': 1,\n 'expected_comps': 500,\n 'full_XXt': False,\n 'init_batch': 200,\n 'init_method': 'bare',\n 'iters_shape': 5,\n 'max_comp_update_shape': np.inf,\n 'max_num_added': 5,\n 'max_shifts_online': 10,\n 'min_SNR': 2.5,\n 'min_num_trial': 5,\n 'minibatch_shape': 100,\n 'minibatch_suff_stat': 5,\n 'motion_correct': True,\n 'movie_name_online': 'online_movie.mp4',\n 'normalize': False,\n 'n_refit': 0,\n 'num_times_comp_updated': np.inf,\n 'opencv_codec': 'H264',\n 'path_to_model': None,\n 'ring_CNN': False,\n 'rval_thr': 0.8,\n 'save_online_movie': False,\n 'show_movie': False,\n 'simultaneously': False,\n 'sniper_mode': False,\n 'stop_detection': False,\n 'test_both': False,\n 'thresh_CNN_noisy': 0.5,\n 'thresh_fitness_delta': -50,\n 'thresh_fitness_raw': -60.97977932734429,\n 'thresh_overlap': 0.5,\n 'update_freq': 200,\n 'update_num_comps': True,\n 'use_corr_img': False,\n 'use_dense': True,\n 'use_peak_max': True,\n 'W_update_factor': 1,\n 'SNR_lowest': 0.5,\n 'cnn_lowest': 0.1,\n 'gSig_range': None,\n 'min_cnn_thr': 0.9,\n 'rval_lowest': -1,\n 'use_cnn': False,\n 'use_ecc': False,\n 'max_ecc': 3,\n 'do_merge': True,\n 'merge_thr': 0.8,\n 'merge_parallel': False,\n 'max_merge_area': None,\n 'border_nan': 'copy',\n 'gSig_filt': None,\n 'is3D': False,\n 'max_deviation_rigid': 3,\n 'max_shifts': (6, 6, 1),\n 'min_mov': None,\n 'niter_rig': 1,\n 'nonneg_movie': True,\n 'num_frames_split': 80,\n 'num_splits_to_process_els': None,\n 'num_splits_to_process_rig': None,\n 'overlaps': (32, 32, 1),\n 'pw_rigid': False,\n 'shifts_opencv': True,\n 'splits_els': 14,\n 'splits_rig': 14,\n 'strides': (96, 96, 1),\n 'upsample_factor_grid': 4,\n 'use_cuda': False,\n 'n_channels': 2,\n 'use_bias': False,\n 'use_add': False,\n 'pct': 0.01,\n 'patience': 3,\n 'max_epochs': 100,\n 'width': 5,\n 'loss_fn': 'pct',\n 'lr': 0.001,\n 'lr_scheduler': None,\n 'remove_activity': False,\n 'reuse_model': False}\n\n imaging.ProcessingParamSet.insert_new_params(\n 'caiman', 2, 'Calcium imaging analysis with'\n ' CaImAn using default CaImAn parameters for 3d volumetric images',\n params_caiman_3d)\n\n yield params_caiman_3d\n\n (imaging.ProcessingParamSet & 'paramset_idx = 2').delete()\n\n\n@pytest.fixture\ndef scan_info(pipeline, ingest_sessions):\n scan = pipeline['scan']\n\n scan.ScanInfo.populate()\n\n yield\n\n scan.ScanInfo.delete()\n\n\n@pytest.fixture\ndef processing_tasks(pipeline, suite2p_paramset, caiman2D_paramset, caiman3D_paramset, scan_info):\n global is_multi_scan_processing\n\n imaging = pipeline['imaging']\n scan = pipeline['scan']\n session = pipeline['session']\n get_imaging_root_data_dir = pipeline['get_imaging_root_data_dir']\n root_dir = pathlib.Path(get_imaging_root_data_dir())\n\n if is_multi_scan_processing:\n for session_key in (session.Session & scan.ScanInfo - imaging.ProcessingTask).fetch(\n 'KEY'):\n scan_file = root_dir / (scan.ScanInfo.ScanFile & session_key).fetch('file_path')[0]\n recording_dir = scan_file.parent\n # suite2p\n suite2p_dir = recording_dir / 'suite2p'\n if suite2p_dir.exists():\n processing_key = {**session_key,\n 'paramset_idx': 0,\n 'processing_task_id': 0}\n imaging.ProcessingTask.insert1({**processing_key,\n 'processing_output_dir': suite2p_dir.as_posix()})\n imaging.ProcessingTask.Scan.insert(\n {**processing_key, **scan_key}\n for scan_key in (scan.Scan & session_key).fetch('KEY'))\n # caiman\n caiman_dir = recording_dir / 'caiman'\n if caiman_dir.exists():\n is_3D = (scan.ScanInfo & session_key).fetch('ndepths')[0] > 1\n processing_key = {**session_key,\n 'paramset_idx': 1 if not is_3D else 2,\n 'processing_task_id': 0}\n imaging.ProcessingTask.insert1({**processing_key,\n 'processing_output_dir': caiman_dir.as_posix()})\n imaging.ProcessingTask.Scan.insert(\n {**processing_key, **scan_key}\n for scan_key in (scan.Scan & session_key).fetch('KEY'))\n else:\n for scan_key in (scan.Scan & scan.ScanInfo - imaging.ProcessingTask).fetch('KEY'):\n scan_file = root_dir / (scan.ScanInfo.ScanFile & scan_key).fetch('file_path')[0]\n recording_dir = scan_file.parent\n # suite2p\n suite2p_dir = recording_dir / 'suite2p'\n if suite2p_dir.exists():\n imaging.ProcessingTask.insert1({**scan_key,\n 'paramset_idx': 0,\n 'processing_output_dir': suite2p_dir.as_posix()})\n # caiman\n caiman_dir = recording_dir / 'caiman'\n if caiman_dir.exists():\n is_3D = (scan.ScanInfo & scan_key).fetch1('ndepths') > 1\n imaging.ProcessingTask.insert1({**scan_key,\n 'paramset_idx': 1 if not is_3D else 2,\n 'processing_output_dir': caiman_dir.as_posix()})\n\n yield\n\n imaging.ProcessingTask.delete()\n\n\n@pytest.fixture\ndef processing(processing_tasks, pipeline):\n imaging = pipeline['imaging']\n\n imaging.Processing.populate()\n\n yield\n\n imaging.Processing.delete()\n\n\n@pytest.fixture\ndef curations(processing, pipeline):\n imaging = pipeline['imaging']\n\n for key in (imaging.ProcessingTask - imaging.Curation).fetch('KEY'):\n imaging.Curation().create1_from_processing_task(key)\n\n yield\n\n imaging.Curation.delete()\n"
] |
[
[
"pandas.DataFrame",
"numpy.array"
]
] |
eco32i/biodata
|
[
"61d5fdd946bf10043fe2374e8c18a38cdc271b30"
] |
[
"utils/utils.py"
] |
[
"import pandas as pd\nimport numpy as np\nfrom ggplot import *\n\ndef compute_prob_vector(ps_file, prob_paired=True):\n '''\n Given a text file derived from the RNAfold output of the form\n \n i j sqrt(prob) ubox\n \n computes a vector (dict) of probabilities for every nucleotide\n to be in paired (or unpaired) state.\n '''\n prob_vector = {}\n with open(ps_file) as fi:\n for line in fi.readlines():\n line = line.strip()\n posi, posj, sqrt_prob, box = line.split()\n curr_i = prob_vector.get(int(posi), 0)\n curr_j = prob_vector.get(int(posj), 0)\n prob_vector.update({\n int(posi)-1: curr_i + float(sqrt_prob)**2,\n int(posj)-1: curr_j + float(sqrt_prob)**2,\n })\n if prob_paired:\n return prob_vector\n else:\n return dict([(pos, 1-p) for pos,p in prob_vector.items()])\n \ndef compute_prob_vector_max(ps_file, prob_paired=True):\n '''\n Given a text file derived from the RNAfold output of the form\n \n i j sqrt(prob) ubox\n \n computes a vector (dict) of probabilities for every nucleotide\n to be in paired (or unpaired) state.\n '''\n prob_vector = {}\n with open(ps_file) as fi:\n for line in fi.readlines():\n line = line.strip()\n posi, posj, sqrt_prob, box = line.split()\n curr_i = prob_vector.get(int(posi), 0)\n curr_j = prob_vector.get(int(posj), 0)\n curr_prob = float(sqrt_prob)**2\n indi = int(posi)\n indj = int(posj)\n if indi in prob_vector:\n if curr_prob > prob_vector[indi]:\n prob_vector[indi] = curr_prob\n else:\n prob_vector[indi] = curr_prob\n if indj in prob_vector:\n if curr_prob > prob_vector[indj]:\n prob_vector[indj] = curr_prob\n else:\n prob_vector[indj] = curr_prob\n \n if prob_paired:\n return prob_vector\n else:\n return dict([(pos, 1-p) for pos,p in prob_vector.items()])\n \n\ndef trange_df(base_name, prob_func=compute_prob_vector, \n trange=range(35,43), abs_value=True):\n '''\n Same as `compute_diff_df` but builds dataframe in a long format\n suitable for ggplot faceting.\n '''\n T0 = trange[0]\n prob0 = prob_func('%s_%d.txt' % (base_name, T0))\n chunks = []\n for temp in trange[1:]:\n df = pd.DataFrame()\n prob_vector = prob_func('%s_%d.txt' % (base_name,temp))\n npos = max(set(prob0.keys()) | set(prob_vector.keys())) + 1\n d0 = np.zeros(npos)\n dt = np.zeros(npos)\n d0[list(prob0.keys())] = list(prob0.values())\n dt[list(prob_vector.keys())] = list(prob_vector.values())\n df['pos'] = range(npos)\n if abs_value:\n df['Diff'] = abs(d0 - dt)\n else:\n df['Diff'] = dt - d0\n df['Temp'] = temp\n chunks.append(df)\n return pd.concat(chunks)\n\ndef sig_positions(df, num_sigma=6):\n mean = df['Diff'].mean()\n sigma = df['Diff'].std()\n threshold = num_sigma * sigma\n return abs(df['Diff'] - mean) > threshold\n\n\ndef compute_diff_df(base_name, trange=range(35,43), abs_value=True):\n '''\n Given the base_name for tab-delimited files containing base\n pairing probabilities calculated by RNAfold computes a\n dataframe containing probability difference vectors for each\n temperature value in the range relative to the lowest T in the\n range.\n '''\n T0 = trange[0]\n prob = compute_prob_vector('%s_%d.txt' % (base_name, T0))\n df = pd.DataFrame(prob.items(), columns=['Position', 'Prob_%d' % T0])\n for temp in trange[1:]:\n prob = compute_prob_vector('%s_%d.txt' % (base_name, temp))\n prob_key = 'Prob_%d' % temp\n df[prob_key] = pd.Series(prob.values())\n if abs_value:\n df['Diff_%d' % temp] = abs(df[prob_key] - df['Prob_%d' % T0])\n else:\n df['Diff_%d' % temp] = df[prob_key] - df['Prob_%d' % T0]\n return df\n\ndef get_sig_positions(df, trange=range(37,43), num_sigma=6):\n '''\n Given the dataframe of probability differences for a T range\n and the level of significannce in sigmas returns positions in the\n dataframe where the probability difference at the highest T\n exceeds the sigma threshold.\n '''\n colnames = ['Diff_%d' % temp for temp in trange[1:]]\n diff_cols = [df[colname] for colname in colnames]\n all_diff = pd.concat(diff_cols)\n mean = all_diff.mean()\n sigma = all_diff.std()\n threshold = num_sigma * sigma\n print('Mean:\\t%f\\nSigma:\\t%f\\nThreshold:\\t%f\\n' % (mean, sigma, threshold))\n return df[abs(df['Diff_%d' % trange[-1]] - mean) > threshold].sort(['Position'])\n\ndef plot_RSMD(df, trange=range(37,43)):\n df_sum = pd.DataFrame()\n df_sum['Temp'] = trange[1:]\n df_sum['RMSD'] = [np.sqrt(((df[df['Temp'] == T]['Diff'])**2).sum()) for T in trange[1:]]\n p = ggplot(df_sum, aes(x='Temp', y='RMSD')) + geom_line()\n return p"
] |
[
[
"pandas.DataFrame",
"numpy.zeros",
"pandas.concat"
]
] |
erdc/pynirom
|
[
"7385333cb4804300a7a048d32e009c9c659f019d"
] |
[
"pynirom/node/main.py"
] |
[
"#! usr/bin/env python\n\n\"\"\"\nBase module for PODNODE NIROM\n\"\"\"\n\nimport numpy as np\nimport pickle\nimport time\n\nimport pynirom\nfrom pynirom.node import node as node\n\nimport tensorflow as tf\nif tf.__version__ == '1.15.0':\n tf.compat.v1.enable_eager_execution()\nelif tf.__version__.split('.')[0] == 2: # in ['2.2.0','2.3.0']:\n tf.keras.backend.set_floatx('float64')\n\nfrom tfdiffeq import odeint,odeint_adjoint\nfrom tfdiffeq.adjoint import odeint as adjoint_odeint\n\n\nclass NODEBase(object):\n \"\"\"\n Base class for Non-intrusive Reduced Order Modeling (NIROM)\n with Neural ODE (NODE) for the approximation of the dynamics\n in a suitable reduced space defined by linear or nonlinear\n dimension reduction methods.\n\n \"\"\"\n @staticmethod\n def save_to_disk(filename, ROM, **options):\n \"\"\"\n Save the instance in ROM to disk using options\n Start with absolutely simplest approach using pickle\n \"\"\"\n outfile = open(filename, 'wb')\n protocol = options.get('protocol', pickle.HIGHEST_PROTOCOL)\n try:\n pickle.dump(ROM, outfile, protocol=protocol)\n finally:\n outfile.close()\n return ROM\n\n @staticmethod\n def read_from_disk(filename, **options):\n \"\"\"\n Read the instance in ROM to disk using options\n Start with absolutely simplest approach using pickle\n \"\"\"\n infile = open(filename, 'rb')\n encoding = options.get('encoding', 'latin1')\n ROM = None\n try:\n ROM = pickle.load(infile, encoding=encoding)\n except TypeError:\n ROM = pickle.load(infile)\n finally:\n infile.close()\n return ROM\n\n def __init__(self, device, **options):\n self._device = device\n\n\n @property\n def n_latent(self):\n \"\"\"\n User specified size of the latent\n space vector used to model dynamics\n with NODE. For multicomponent systems,\n this is equal to the combined size of\n the latent space representations of all\n system components.\n \"\"\"\n return self._n_latent\n\n @property\n def n_snap(self):\n \"\"\"\n Return number of snapshots used in training\n \"\"\"\n return self._n_snap_train\n\n @property\n def n_reduced(self):\n \"\"\"\n Size of latent space representation of\n each system component.\n Output as a dictionary with\n system components as keys\n \"\"\"\n return self._n_reduced\n\n @property\n def train_state(self):\n \"\"\"\n Latent space snapshots used for training\n array dim. = Latent space size X training time points\n \"\"\"\n return self._train_state\n\n @property\n def init_state(self):\n \"\"\"\n Latent space training snapshot at initial time\n array dim. = (Latent space size,)\n \"\"\"\n return self._init_state\n\n @property\n def train_times(self):\n \"\"\"\n Time points array used for training\n \"\"\"\n return self._train_time\n\n @property\n def pred_state(self):\n \"\"\"\n Latent space predictions using NODE\n array dim. = Latent space size X prediction time points\n \"\"\"\n return self._predicted_state\n\n @property\n def optimizer(self):\n \"\"\"\n Optimizer adopted for NN training\n \"\"\"\n return self._optimizer\n\n @property\n def learn_rate(self):\n \"\"\"\n Learning rate used for NODE Training\n Can either be a fixed value or\n a Learning rate scheduler\n \"\"\"\n return self._learn_rate\n\n @property\n def solver(self):\n \"\"\"\n ODE solver used for latent space evolution\n and backward gradient evolution in the\n adjoint method\n \"\"\"\n return self._solver\n\n @property\n def adjoint(self):\n \"\"\"\n Boolean flag indicating the use of the\n adjoint method in NODE training\n \"\"\"\n return self._adjoint\n\n @property\n def augmented(self):\n \"\"\"\n Boolean flag indicating the use of augmented\n states or the ANODE method for training\n \"\"\"\n return self._augmented\n\n\n def prepare_input_data(self, Z_train, nw, times_train, stack_order,\n times_predict=None, Z_pred_true=None):\n \"\"\"\n Set up latent space data in a format suitable\n for modeling with NODE\n\n Input::\n Z_train: Dict of latent space training snapshots for each component\n nw: Dict of latent space dimensions for each component\n times_train: Numpy array of training time points\n stack_order: String denoting the order in which the components\n are vertically stacked in the combined latent space\n snapshot vector\n times_predict: [Optional] Numpy array of prediction time points\n Z_pred_true: [Optional] Dict of true latent space snapshots at the\n prediction time points for each component. Used for\n computing NODE prediction error\n\n Output::\n train_state_array: Numpy array of vertically stacked latent space\n training snapshots with time on 0th axis\n init_state: Stacked latent space vector at initial training time\n state_len: Total dimension of the latent space combining all components\n dt_train: Time step of training snapshots\n true_pred_state_array: Numpy array of vertically stacked true latent\n space snapshots at prediction time points with time on\n 0th axis [Optional]\n dt_predict: Time step of the time series to be used for computing\n the NODE prediction [Optional]\n \"\"\"\n state_len = np.sum(list(nw.values()))\n train_state_array = np.zeros((times_train.size, state_len));\n if times_predict is not None:\n assert Z_pred_true is not None, \"Prediction time points provided, but true snapshots not provided\"\n true_pred_state_array = np.zeros((times_predict.size, state_len));\n else:\n true_pred_state_array = None\n ctr=0\n stack = stack_order.split(',')\n for key in stack:\n train_state_array[:,ctr:ctr+nw[key]] = Z_train[key].T\n if times_predict is not None:\n true_pred_state_array[:,ctr:ctr+nw[key]] = Z_pred_true[key].T\n ctr+=nw[key]\n\n init_state = train_state_array[0,:]\n dt_train = (times_train[-1]-times_train[0])/(times_train.size-1)\n if times_predict is not None:\n dt_predict = (times_predict[-1]-times_predict[0])/(times_predict.size)\n\n self._train_state = train_state_array\n self._init_state = init_state\n self._train_time = times_train\n self._n_snap_train = times_train.size\n self._n_latent = state_len\n self._n_reduced = nw\n\n if times_predict is not None:\n return train_state_array, true_pred_state_array, init_state, state_len, dt_train, dt_predict\n else:\n return train_state_array, init_state, state_len, dt_train\n\n\n def preprocess_data(self, scale_states=False, scale_time=False, augmented=False,\n lr_decay=True,init_lr = 0.001, opt='RMSprop', minibatch=False,**options):\n \"\"\"\n\n Input::\n scale_states: Boolean. If True, scale training state array\n scale_time: Boolean. If True, scale training time array\n scaling_method: [Optional] string. If scale_states++True, specify\n the scaling function to be used.\n 'centered' - maps each element to [-1,1]\n 'maxabs' - also maps each element to [-1,1]\n 'minmax' - maps each element to [0,1]\n augmented: Boolean. If True, augment states arrays by a fixed size\n aug_dim: [Optional] int32/64. If augmented==True, specify size of\n augmentation\n lr_decay: Boolean. If True, define a learning rate scheduler\n init_lr: float32/64. Initial learning rate used either as a fixed\n learning rate for training or as the starting\n learning rate used by the scheduler\n decay_steps: [Optional] int32/64. If lr_decay==True, set the number of\n epochs to wait before reducing learning rate\n decay_rate: [Optional] float32/64. If lr_decay==True, set the decay rate\n staircase: Boolean. [Optional] If True, decays the learning rate at\n discrete intervals\n opt: string. Specify the Optimization algorithm for hyperparameter tuning\n Currently accepts 'Adam' or 'RMSprop'\n\n Output::\n true_state_tensor: Augmented state array casted to a TF tensor\n time_tensor: Time array casted to a TF tensor\n init_tensor: Initial state vector casted to a TF tensor\n learn_rate: Fixed learning rate or Scheduler\n opimizer: Returns the chosen optimizer\n \"\"\"\n if scale_time:\n times_train, tscale = node.scale_time(self._train_time)\n self._time_scaler = tscale\n else:\n times_train = self._train_time\n self._scale_time = scale_time\n\n if scale_states:\n train_state_array, scaling_param = node.scale_states(self._train_state,\n method=options['scaling_method'])\n self._state_scaler = scaling_param\n else:\n train_state_array = self._train_state\n self._scale_states = scale_states\n\n if augmented:\n aug_dim = options['aug_dim']\n self._n_latent += aug_dim\n else:\n aug_dim = 0\n self._augmented = augmented\n self._aug_dim = aug_dim\n\n true_state_tensor, time_tensor, init_tensor = node.augment_state(train_state_array,\n times_train, aug_dim)\n\n if minibatch:\n decay_steps = options['decay_steps']*np.floor(self._n_snap_train/options['batch_size'])\n else:\n decay_steps = options['decay_steps']\n learn_rate = node.set_learning_rate(decay=lr_decay, init_lr = init_lr,\n decay_steps = decay_steps, decay_rate = options['decay_rate'],\n staircase = options['staircase'])\n\n optimizer = node.set_optimizer(opt=opt, learn_rate=learn_rate)\n\n self._learn_rate = learn_rate\n self._optimizer = optimizer\n\n return true_state_tensor, time_tensor, init_tensor, learn_rate, optimizer\n\n\n def train_model(self, true_state_tensor, times_tensor, init_tensor, epochs, savedir,\n solver='rk4', purpose='train', adjoint=False, minibatch=False, **options):\n \"\"\"\n NODE model training using specified configuration\n Input::\n true_state_tensor: Augmented state array casted as a TF tensor\n time_tensor: Time array casted as a TF tensor\n init_tensor: Initial state vector casted as a TF tensor\n epochs: Number of epochs to train\n savedir: Directory location to save the trained TF model\n solver: ODE solver to use for NODE training (Check `tfdiffeq` documentation for options)\n purpose: Training mode. Available options are\n 'train': Train a model from scratch\n 'retrain': Re-train an existing pretrained model. Also specify 'pre_trained_dir'\n as an optional argument to denote the location of the pretrained model\n 'eval': Generate NODE predictions using an existing model. Also specify\n 'pre_trained_dir' as an optional argument to denote the location of the\n pretrained model\n adjoint: Boolean. If True, the adjoint calculations are used in NODE training\n minibatch: Boolean. If True, minibatches are used in NODE training\n pre_trained_dir: [Optional] String. Specifies the location of the pretrained NODE model\n used during 'retrain' or 'eval' mode\n\n Output::\n train_loss_results: List. Training loss values after each epoch\n train_lr: List. Current learning rate after every epoch that the model state is saved\n saved_ep: List. Current epoch number every time the model state is saved\n \"\"\"\n\n self._solver = solver\n self._adjoint = adjoint\n\n if purpose == 'train':\n train_loss_results, train_lr, saved_ep = node.run_node(true_state_tensor, times_tensor,\n init_tensor, epochs, savedir, optimizer=self._optimizer,\n learn_rate= self._learn_rate, device=self._device, solver=self._solver,\n purpose=purpose, adjoint=self._adjoint, minibatch=minibatch)\n elif purpose == 'retrain':\n train_loss_results, train_lr, saved_ep = node.run_node(true_state_tensor, times_tensor,\n init_tensor, epochs, savedir, optimizer=self._optimizer,\n learn_rate= self._learn_rate, device=self._device, solver=self._solver,\n purpose=purpose, adjoint=self._adjoint, minibatch=minibatch,\n pre_trained_dir=options['pre_trained_dir'])\n\n return train_loss_results, train_lr, saved_ep\n\n\n def predict_time(self, times_predict, init_tensor, pre_trained_dir, **options):\n \"\"\"\n Evaluate reduced order POD-NODE model\n at queried online time points\n\n Input:\n times_predict : array of time points at which NODE predictions are sought\n init_tensor: Initial state tensor (possibly augmented)\n pre_trained_dir: Location of pretrained NODE TF model\n aug_dim: [Optional]\n \"\"\"\n if self._scale_time:\n times_predict, tscale = node.scale_time(times_predict, tscale=self._time_scaler)\n else:\n pass\n\n self._predict_time = times_predict\n\n\n print(\"\\n---- Computing NODE NIROM solution ----\\n\")\n pred_start_time = time.time()\n pred_state_array = node.eval_node(times_predict, self._n_latent, init_tensor,\n pre_trained_dir, adjoint=self._adjoint, augmented=self._augmented,\n solver=self._solver, aug_dim=self._aug_dim)\n pred_end_time = time.time()\n print(\"Time needed to compute NODE predictions = %f minutes\"%((pred_end_time-pred_start_time)/60))\n\n print(\"\\n---- Postprocessing NODE solution ----\\n\")\n pred_state_array, times_predict = self.postprocess_results(pred_state_array)\n self._predicted_state = pred_state_array\n\n return pred_state_array, times_predict\n\n\n def postprocess_results(self, pred_state_array, **options):\n \"\"\"\n Post-process NODE predicted states\n Input::\n pred_state_array: predictions directly generated by NODE\n\n Output::\n predicted_states: Apply any inverse state scaling\n transforms to predicted state array\n times_predict: Apply any inverse time scaling\n transforms to time array used for predictions\n \"\"\"\n if self._augmented:\n pred_state_array = node.deaugment_state(pred_state_array, self._aug_dim)\n\n if self._scale_states:\n pred_state_array = node.scale_states_inverse(pred_state_array, self._state_scaler)\n\n if self._scale_time:\n times_predict = node.scale_time_inverse(self._predict_time, self._time_scaler)\n self._predict_time = times_predict\n\n return pred_state_array, self._predict_time\n\n\n\n def compute_error(self, true, pred, soln_names, metric='rms'):\n \"\"\"\n Utility function to compute different\n error metrics based on the provided true solution\n and the nirom solution projected on to the full\n dimensional space\n\n Input::\n true: Dictionary with 2d arrays of true solutions\n pred: Dictionary with 2d arrays of PODRBF predictions\n soln_names: Dictionary with names of solution\n components\n metric: type of error metric\n 'rms' = Root mean square error\n 'rel' = relative error\n Output::\n err: Dictionary of error values.\n Each key is a 1d array with error\n values for a solution component\n \"\"\"\n\n err = {}\n Nn = true[soln_names[0]].shape[0]\n if metric == 'rms':\n for ivar, key in enumerate(soln_names):\n err[key] = np.linalg.norm(true[key][:,:] - pred[key][:,:], axis = 0)/ \\\n np.sqrt(Nn)\n elif metric == 'rel':\n for ivar, key in enumerate(soln_names):\n err[key] = np.linalg.norm(true[key][:,:] - pred[key][:,:], axis = 0)/ \\\n np.linalg.norm(true[key][:,:], axis = 0)\n\n return err\n\n\n\n\n### ------- Define NN approximation of time derivative-----------------\nclass DNN(tf.keras.Model):\n\n def __init__(self, state_len, N_layers=1, N_neurons=256, act_f='tanh', **kwargs):\n super().__init__(**kwargs)\n\n try:\n aug_dim = kwargs['aug_dim']\n except:\n aug_dim = 0\n if N_layers == 1:\n\n self.eqn = tf.keras.Sequential([tf.keras.layers.Dense(N_neurons, activation=act_f,\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros',\n input_shape=(state_len+aug_dim,)),\n tf.keras.layers.Dense(state_len+aug_dim)])\n\n elif N_layers == 2:\n\n self.eqn = tf.keras.Sequential([tf.keras.layers.Dense(N_neurons, activation=act_f,\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros',\n input_shape=(state_len+aug_dim,)),\n tf.keras.layers.Dense(N_neurons, activation='linear',\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros'),\n tf.keras.layers.Dense(state_len+aug_dim)])\n\n elif N_layers == 3:\n\n self.eqn = tf.keras.Sequential([tf.keras.layers.Dense(N_neurons, activation=act_f,\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros',\n input_shape=(state_len+aug_dim,)),\n tf.keras.layers.Dense(N_neurons, activation=act_f,\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros'),\n tf.keras.layers.Dense(N_neurons, activation='linear',\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros'),\n tf.keras.layers.Dense(state_len+aug_dim)])\n\n elif N_layers == 4:\n self.eqn = tf.keras.Sequential([tf.keras.layers.Dense(N_neurons, activation=act_f,\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros',\n input_shape=(state_len+aug_dim,)),\n tf.keras.layers.Dense(N_neurons, activation=act_f,\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros'),\n tf.keras.layers.Dense(N_neurons, activation=act_f,\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros'),\n tf.keras.layers.Dense(N_neurons, activation='linear',\n kernel_initializer = tf.keras.initializers.glorot_uniform(),\n bias_initializer='zeros'),\n tf.keras.layers.Dense(state_len+aug_dim)])\n\n @tf.function\n def call(self, t, y):\n i0 = self.eqn(y)\n\n return i0\n"
] |
[
[
"tensorflow.keras.backend.set_floatx",
"numpy.linalg.norm",
"numpy.zeros",
"tensorflow.keras.layers.Dense",
"numpy.sqrt",
"tensorflow.compat.v1.enable_eager_execution",
"tensorflow.keras.initializers.glorot_uniform",
"tensorflow.__version__.split",
"numpy.floor"
]
] |
NCBI-Hackathons/Machine_Learning_Immunogenicity
|
[
"6c6e9a3901f77a7e46ca2b00eb3352e4dc5563f1"
] |
[
"src/generate_peptide_tensors.py"
] |
[
"from argparse import ArgumentParser\nimport numpy as np\nimport pandas as pd\nfrom pickle import dump\nfrom tqdm import tqdm\n\nAA = ('A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y')\nAA_ENCODING = dict((a, 2**i) for i,a in enumerate(AA))\n\ndef generate_peptide_tensor(data, aaprops, output, maxlen = 20):\n peptides = pd.read_csv(data, sep=\"\\t\")\n npep = peptides.shape[0]\n aaprops = pd.read_csv(aaprops, sep=\"\\t\", index_col=2)\n aaprops = aaprops.iloc[:, 3:aaprops.shape[1]]\n nprop = aaprops.shape[1]\n shape = (npep, maxlen, nprop+1)\n tensor = np.zeros(shape)\n for i, p in tqdm(enumerate(peptides.iloc[:, 0])):\n if len(p) > maxlen:\n continue\n for j, a in enumerate(p):\n try:\n tensor[i, j, 0] = AA_ENCODING[a]\n tensor[i, j, 1:] = aaprops.loc[a, :]\n except:\n print(\"Invalid AA: {} in {}\".format(a, p))\n print(\"Writing tensor to file\")\n with open(output, 'wb') as o:\n dump(tensor, o)\n \ndef main():\n parser = ArgumentParser()\n parser.add_argument(\"-a\", \"--aaprops\", help=\"Amino Acid property file\")\n parser.add_argument(\"-d\", \"--data\", help=\"IEDB data file\")\n parser.add_argument(\"-o\", \"--output\", help=\"Output pickle file for Numpy array\")\n args = parser.parse_args()\n \n generate_peptide_tensor(args.data, args.aaprops, args.output)\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.read_csv",
"numpy.zeros"
]
] |
uafseismo/pysep
|
[
"e776c2a9e1a9a6d84daa6c60e982fe4f3a31d19f"
] |
[
"record_section.py"
] |
[
"#!/usr/bin/evn python3\n\"\"\"\nRecord Section plotting tool for seismic waveforms (observed and synthetic)\n\nThis is a refactor of Pysep's Python utility `plotw_rs`, a record section\nplotting script. The intent of this script is to plot multiple time series'\nbased on source-receiver characteristics (i.e., src-rcv distance, backazimuth).\n\n.. note:: Code History\n Written by Carl Tape (11/21/2011) and Yun Wang (11/2011) in Matlab\n Translated to Python by Nealy Sims (1/2021)\n Upgraded by Aakash Gupta (9/2021)\n Refactored by Bryant Chow (3/2022)\n\n.. requires::\n obspy >= 1.2 (expected to bring in numpy and matplotlib)\n\n.. rubric:: Examples\n 1) Print the help message to see available options and flags\n $ python record_section.py -h\n\n 2) From the command line: The following example code blocks work with pysep \n to download data for a southern California event.\n\n # cd path/to/pysep\n $ python rungetwaveform.py event_input_mtuq2022 2 # 20200404015318920\n\n a) Plot a record section for the socal event with default values\n\n $ python record_section.py --pysep_path 20200404015318920 \n\n b) Plot high-passed data with 7 km/s move out (focused on direct arrivals),\n show direct arrivals through to surface waves for all traces, thin lines\n to accentuate high frequencies. Overwrite previous figure and split\n figure onto multiple pages\n\n $ python record_section.py --pysep_path 20200404015318920 \\\n --move_out 7 --min_period_s 1 --xlim_s 100 175 \\\n --linewidth .25 --max_traces_per_rs 60 --overwrite\n\n c) Plot bandpassed data with 4 km/s move out (focused on surface waves),\n horizontal components only (radial, transverse),\n thicken up default linewidth and increase spacing between adjacent \n seismograms \n\n $ python record_section.py --pysep_path 20200404015318920 \\\n --components RT --move_out 4 --min_period_s 2 --max_period_s 50 \\\n --xlim_s 50 200 --y_axis_spacing 3 --linewidth 1 \\\n --amplitude_scale_factor 4 --overwrite \n\n d) Plot bandpassed transverse component, sort by azimuth, scale by the \n maximum amplitude of ALL traces shown on the figure. \n Scale amplitudes by factor 2 for better visualization\n and start azimuth plotting at 180* (as opposed to default 0*).\n\n $ python record_section.py --pysep_path 20200404015318920 \\\n --sort_by azimuth --scale_by global_norm --components T \\\n --min_period_s 2 --max_period_s 30 --move_out 4 \\\n --amplitude_scale_factor 2 --azimuth_start_deg 180 \\\n --linewidth 1 --overwrite\n\n e) Plot bandpassed vertical components sorted by absolute distance.\n Reduce amplitudes by 1/4 (0.25). Set y label fontsize smaller than \n default and at the max X value of the figure (far to the right)\n\n $ python record_section.py --pysep_path 20200404015318920 \\\n --sort_by abs_distance_r --components Z --min_period_s 2 \\\n --max_period_s 50 --amplitude_scale_factor 0.25 \\\n --y_label_loc x_max --y_label_fontsize 7 --overwrite \\\n --linewidth 1\n\n 3) From the Python interpreter: this is an example code block that can be\n written into a Python script or run from inside a Python interactive \n environment. Code block assumes we have downloaded event data with Pysep\n\n >>> import os\n >>> from glob import glob\n >>> from obspy import read\n >>> from record_section import plotw_rs\n >>> st = Stream()\n >>> for fid in glob(os.path.join(\"20200404015318920\", \"*.?\")):\n >>> st += read(fid)\n >>> plotw_rs(st=st, sort_by=\"distance_r\")\n\"\"\"\nimport os\nimport sys\nimport argparse\nimport textwrap\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom glob import glob\nfrom datetime import datetime\nfrom matplotlib.ticker import MultipleLocator\nfrom obspy import read, Stream\nfrom obspy.geodetics import (kilometers2degrees, gps2dist_azimuth)\n\n\n# Unicode degree symbol for plot text\nDEG = u\"\\N{DEGREE SIGN}\"\n\n\ndef myround(x, base=5, choice=\"near\"):\n \"\"\"\n Round value x to nearest base, round 'up','down' or to 'near'est base\n\n :type x: float\n :param x: value to be rounded\n :type base: int\n :param base: nearest integer to be rounded to\n :type choice: str\n :param choice: method of rounding, 'up', 'down' or 'near'\n :rtype roundout: int\n :return: rounded value\n \"\"\"\n if choice == \"near\":\n roundout = int(base * round(float(x)/base))\n elif choice == \"down\":\n roundout = int(base * np.floor(float(x)/base))\n elif choice == \"up\":\n roundout = int(base * np.ceil(float(x)/base))\n return roundout\n\n\nclass Dict(dict):\n \"\"\"Simple dictionary overload for nicer get/set attribute characteristics\"\"\"\n def __setattr__(self, key, value):\n self[key] = value\n\n def __getattr__(self, key):\n return self[key]\n\n\nclass RecordSection:\n \"\"\"\n Record section plotting tool which takes ObsPy streams and \n 1) preprocesses and filters waveforms,\n 2) sorts source-receiver pairs based on User input, \n 3) produces record section waveform figures.\n \"\"\"\n def __init__(self, pysep_path=None, st=None, st_syn=None, sort_by=\"default\",\n scale_by=None, time_shift_s=None, move_out=None,\n min_period_s=None, max_period_s=None,\n preprocess=\"st\", max_traces_per_rs=None, integrate=0,\n xlim_s=None, components=\"ZRTNE12\", y_label_loc=\"default\",\n y_axis_spacing=1, amplitude_scale_factor=1, \n azimuth_start_deg=0., distance_units=\"km\", \n geometric_spreading_factor=0.5, geometric_spreading_k_val=None, \n figsize=(9, 11), show=True, save=\"./record_section.png\", \n overwrite=False, **kwargs):\n \"\"\"\n Set the default record section plotting parameters and enforce types.\n Run some internal parameter derivation functions by manipulating input\n data and parameters.\n\n :type pysep_path: str\n :param pysep_path: path to Pysep output, which is expected to contain\n trace-wise SAC waveform files which will be read\n :type st: obspy.core.stream.Stream\n :param st: Stream objects containing observed time series to be plotted\n on the record section. Can contain any number of traces\n :type st_syn: obspy.core.stream.Stream\n :param st_syn: Stream objects containing synthetic time series to be\n plotted on the record section. Must be same length as `st`\n :type sort_by: str\n :param sort_by: How to sort the Y-axis of the record section, available:\n - 'default': Don't sort, just iterate directly through Stream\n - 'alphabetical': sort alphabetically A->Z. Components sorted \n separately with parameter `components`\n - 'azimuth': sort by source-receiver azimuth (deg) with constant\n vertical spacing on the y-axis. Requires `azimuth_start_deg`\n - 'backazimuth': sort by source-receiver backazimuth (deg) with\n constant vertical spacing. Requires `azimuth_start_deg`\n - 'distance': sort by source-receiver distance (km) with constant\n vertical spacing. Requires `distance_units`\n - 'abs_distance': absolute vertical spacing of waveforms defined by\n source-receiver distance. Requires `distance_units`\n - 'abs_azimuth': absolute vertical spacing of waveforms defined\n by source-receiver azimuth (deg).\n - 'abs_backazimuth': absolute vertical spacing of waveforms by\n source-receiver backazimuth (deg).\n - '*_r': Add a '_r' to any of the values about to REVERSE the sort,\n e.g., 'alphabetical_r' sort will go Z->A\n :type scale_by: list\n :param scale_by: scale amplitude of waveforms by available:\n - None: Not set, no amplitude scaling, waveforms shown raw\n - 'normalize': scale each trace by the maximum amplitude,\n i.e., > a /= max(abs(a)) # where 'a' is time series amplitudes\n - 'global_norm': scale by the largest amplitude to be displayed on\n the screen. Will not consider waveforms which have been \n excluded on other basis (e.g., wrong component)\n i.e., > st[i].max /= max([max(abs(tr.data)) for tr in st])\n - 'geometric_spreading': TODO this is not implemented yet.\n scale amplitudes globally by predicting the\n expected geometric spreading amplitude reduction and correcting\n for this factor. Requires `geometric_spreading_factor`, and \n optional `geometric_spreading_k_val`\n :type time_shift_s: float OR list of float\n :param time_shift_s: apply static time shift to waveforms, two options:\n 1. float (e.g., -10.2), will shift ALL waveforms by\n that number (i.e., -10.2 second time shift applied)\n 2. list (e.g., [5., -2., ... 11.2]), will apply individual time\n shifts to EACH trace in the stream. The length of this list MUST\n match the number of traces in your input stream.\n :type amplitude_scale_factor: float OR list of float\n :param amplitude_scale_factor: apply scale factor to all amplitudes.\n Used as a dial to adjust amplitudes manually. Defaults to 1.\n Two options:\n 1. float (e.g., 1.2), will multiply ALL waveforms by that number\n 2. list (e.g., [5., -2., ... 11.2]), will apply individual amplitude\n scale to EACH trace in the stream. The length of this list MUST\n match the number of traces in your input stream.\n :type move_out: float\n :param move_out: Optional. A velocity value that will be used to\n calculate move out, which will time shift seismograms based on\n their source receiver distance. This parameter will be ADDED\n to time_shift_s (both float and list), if it is provided.\n Should be in units of `distance_units`/s\n :type min_period_s: float\n :param min_period_s: minimum filter period in seconds\n :type max_period_s: float\n :param max_period_s: maximum filter period in seconds\n :type preprocess: str\n :param preprocess: choose which data to preprocess, options are:\n - 'st': process waveforms in st (default)\n - 'st_syn': process waveforms in st_syn. st still must be given\n - 'both': process waveforms in both st and st_syn\n - None: do not run preprocessing step (including filter)\n :type max_traces_per_rs: int\n :param max_traces_per_rs: maximum number of traces to show on a single\n record section plot. Defaults to all traces in the Stream\n :type xlim_s: list of float\n :param xlim_s: [start, stop] in units of time, seconds, to set the\n xlimits of the figure\n :type components: str\n :param components: a sequence of strings representing acceptable\n components from the data. Also determines the order these are shown\n EVEN when sorted by other variables. For example, components=='ZR'\n would only display Z and R components, and Z components would be\n should BEFORE R components for the SAME station.\n :type integrate: int\n :param integrate: apply integration `integrate` times on all traces.\n acceptable values [-inf, inf], where positive values are integration\n and negative values are differentiation\n e.g., if integrate == 2, will integrate each trace twice.\n or if integrate == -1, will differentiate once\n or if integrate == 0, do nothing (default)\n :type y_axis_spacing: float\n :param y_axis_spacing: spacing between adjacent seismograms applied to\n Y-axis on relative (not absolute) scales. Defaults to 1.\n :type y_label_loc: str\n :param y_label_loc: Location to place waveform labels on the y-axis\n - 'default': auto choose the best location based on `sort_by`\n - 'y_axis': Replace tick labels on the y-axis (left side of figure),\n This won't work if using absolute sorting and will be over-\n written by 'default'\n - 'y_axis_right': Replace tick labels on the right side of the \n y-axis. This option won't work with absolute sorting\n - 'x_min': Place labels on top of the waveforms at the global min\n x-value on the figure\n - 'x_min': Place labels on top of the waveforms at the global max\n x-value on the figure\n - None: Don't plot any text labels\n :type azimuth_start_deg: float\n :param azimuth_start_deg: If sorting by azimuth, this defines the \n azimuthal angle for the waveform at the top of the figure.\n Set to 0 for default behavior\n :type distance_units: str\n :param distance_units: Y-axis units when sorting by epicentral distance\n 'km': kilometers on the sphere\n 'deg': degrees on the sphere\n 'km_utm': kilometers on flat plane, UTM coordinate system\n :type geometric_spreading_factor: float\n :param geometric_spreading_factor: geometrical spreading factor when\n using the `scale_by` parameter. Defaults to 0.5 for surface waves.\n Use values of 0.5 to 1.0 for regional surface waves\n :type geometric_spreading_k_val: float\n :param geometric_spreading_k_val: K value used to scale the geometric\n spreading factor (TODO figure out what this actually is)\n :type figsize: tuple of float\n :param figsize: size the of the figure, passed into plt.subplots()\n :type show: bool\n :param show: show the figure as a graphical output\n :type save: str\n :param save: path to save output figure, will create the parent\n directory if it doesn't exist. If None, will not save.\n :type overwrite: bool\n :param overwrite: if the path defined by `save` exists, will overwrite\n the existing figure\n :raises AssertionError: if any parameters are set incorrectly\n \"\"\"\n # Read files from path if provided\n if pysep_path is not None and os.path.exists(pysep_path):\n # Expected file format: 20200404015318920.CI.LRL..BH.r\n fids = glob(os.path.join(pysep_path, \"*.*.*.*.*.?\"))\n print(f\"Reading {len(fids)} files from: {pysep_path}\")\n if fids:\n # Overwrite stream, so reading takes precedence\n st = Stream()\n for fid in fids:\n st += read(fid)\n\n assert(st), \\\n \"Stream object not found, please check inputs `st` and `pysep_path\"\n\n # User defined parameters, do some type-setting\n self.st = st.copy()\n try:\n self.st_syn = st_syn.copy()\n except AttributeError:\n self.st_syn = None\n\n # Y-Axis sorting parameters\n self.sort_by = sort_by.lower()\n self.y_axis_spacing = float(y_axis_spacing)\n self.azimuth_start_deg = float(azimuth_start_deg)\n self.components = str(components)\n\n # Amplitude scaling parameters\n self.scale_by = scale_by\n self.amplitude_scale_factor = amplitude_scale_factor\n self.geometric_spreading_factor = float(geometric_spreading_factor)\n self.geometric_spreading_k_val = geometric_spreading_k_val\n\n # Time shift parameters\n self.move_out = move_out\n self.time_shift_s = time_shift_s\n\n # Filtering parameters\n self.min_period_s = min_period_s\n self.max_period_s = max_period_s\n self.preprocess = preprocess\n self.max_traces_per_rs = max_traces_per_rs\n self.integrate = int(integrate)\n\n # Plotting parameters\n self.xlim_s = xlim_s\n self.distance_units = distance_units.lower()\n self.y_label_loc = y_label_loc\n self.figsize = figsize\n self.show = bool(show)\n self.save = save\n self.overwrite = bool(overwrite)\n self.kwargs = Dict(kwargs)\n\n # Run checks to ensure that all the parameters are set properly\n # And get some new, initial parameters that are required for other\n # 'get' functions\n self.check_parameters()\n self.stats = self.get_srcrcv_stats()\n self.distances, self.azimuths, self.backazimuths = \\\n self.get_srcrcv_dist_az_baz()\n\n # Internally used parameters that will be filled out by other functions\n self.f = None\n self.ax = None\n self.idx = []\n self.station_ids = []\n self.max_amplitudes = []\n self.amplitude_scaling = []\n self.y_axis = []\n self.xlim = [] # unit: samples\n self.sorted_idx = []\n\n def check_parameters(self):\n \"\"\"\n Check that parameters are set properly and in line with how they\n are expected by the program\n\n .. note::\n Not using assertions here because we want all incorrect parameters\n to be evaluated together and displayed at once, that way the user\n doesn't have to run this function multiple times to figure out how\n to set their parameters correctly\n\n :raises AssertionError: If any parameters are not set as expected by\n plotw_rs functionality\n \"\"\"\n print(\"checking parameter acceptability\")\n\n # Used to keep track of which parameters failed and in what way\n err = Dict()\n\n # Check to make sure there is data\n if not bool(self.st):\n err.st = f\"stream has {len(self.st)} traces, no data\"\n\n # Check that stream has SAC headers if we want to sort by dist or (b)az.\n # Pysep should have created these\n if self.sort_by != \"default\" and \\\n any(_ in self.sort_by for _ in [\"azimuth\", \"distance\"]):\n _idx = []\n for i, tr in enumerate(self.st):\n if not hasattr(tr.stats, \"sac\"):\n _idx.append(i)\n if _idx:\n err.st = (f\"{len(_idx)} traces have no SAC header, plotw_rs \"\n f\"expects SAC headers for sorting. Trace indexes \"\n f\"are: {_idx}\")\n\n if self.st_syn is not None:\n if len(self.st) != len(self.st_syn):\n err.st_syn = f\"length must match `st` (which is {len(self.st)})\"\n\n # Check the `sort_by` sorting parameter options\n acceptable_sort_by = [\"default\", \"azimuth\", \"backazimuth\",\n \"distance\", \"alphabetical\", \"abs_azimuth\",\n \"abs_distance\"]\n # Allow reverse sorts\n acceptable_sort_by += [f\"{_}_r\" for _ in acceptable_sort_by]\n if self.sort_by not in acceptable_sort_by:\n err.sort_by = f\"must be in {acceptable_sort_by}\"\n\n if \"azimuth\" in self.sort_by:\n if not (0 <= self.azimuth_start_deg <= 360):\n err.azimuth_start_deg = f\"0 < azi < 360\"\n\n acceptable_distance_units = [\"km\", \"km_utm\", \"deg\"]\n if (\"distance\" in self.sort_by) and \\\n (self.distance_units not in acceptable_distance_units):\n err.azimuth_start_deg = \\\n f\"must be in {acceptable_distance_units}\"\n\n if self.scale_by is not None:\n acceptable_scale_by = [\"normalize\", \"global_norm\",\n \"geometric_spreading\"]\n if self.scale_by not in acceptable_scale_by:\n err.scale_by = f\"must be in {acceptable_scale_by}\"\n\n if self.time_shift_s is not None:\n acceptable_time_shift_s = [int, float, list]\n if type(self.time_shift_s) not in acceptable_time_shift_s:\n err.time_shift_s = f\"must be in {acceptable_time_shift_s}\"\n if isinstance(self.time_shift_s, list) and \\\n len(self.time_shift_s) != len(self.st):\n err.time_shift_s = f\"must be list of length {len(self.st)}\"\n\n # Defaults to float value of 1\n acceptable_scale_factor = [int, float, list]\n if type(self.amplitude_scale_factor) not in acceptable_scale_factor:\n err.amplitude_scale_factor = f\"must be in {acceptable_scale_factor}\"\n if isinstance(self.amplitude_scale_factor, list) and \\\n len(self.amplitude_scale_factor) != len(self.st):\n err.amplitude_scale_factor = f\"must be list length {len(self.st)}\"\n\n if self.min_period_s is not None and self.max_period_s is not None:\n if self.min_period_s >= self.max_period_s:\n err.min_period_s = \"must be less than `max_period_s`\"\n\n if self.preprocess is not None:\n acceptable_preprocess = [\"both\", \"st\"]\n if self.preprocess not in acceptable_preprocess:\n err.preprocess = f\"must be in {acceptable_preprocess}\"\n\n # Overwrite the max traces per record section, enforce type int\n if self.max_traces_per_rs is None:\n self.max_traces_per_rs = int(len(self.st))\n else:\n self.max_traces_per_rs = int(self.max_traces_per_rs)\n\n if self.xlim_s is not None:\n if len(self.xlim_s) != 2:\n err.xlim_s = f\"must be of length 2, [start, stop]\"\n elif self.xlim_s[0] > self.xlim_s[1]:\n err.xlim_s = f\"start time must be less than stop time\"\n\n acceptable_y_label_loc = [\"default\", \"y_axis\", \"y_axis_right\", \"x_min\",\n \"x_max\", None]\n if self.y_label_loc not in acceptable_y_label_loc:\n err.y_label_loc = f\"must be in {acceptable_y_label_loc}\"\n if \"abs\" in self.sort_by and \"y_axis\" in self.sort_by:\n err.y_label_loc = (f\"absolute sorting means 'y_axis' label loc is\" \n f\"not available\")\n\n if len(self.figsize) != 2:\n err.figsize = \"must be tuple defining (horizontal, vertical) extent\"\n\n if os.path.exists(self.save) and not self.overwrite:\n err.save = (f\"path {self.save} already exists. Use '--overwrite' \" \n f\"flag to save over existing figures.\")\n\n _dirname = os.path.abspath(os.path.dirname(self.save))\n if not os.path.exists(_dirname):\n print(f\"creating output directory {_dirname}\")\n os.makedirs(_dirname)\n\n if err:\n out = \"ERROR - Parameter errors, please make following changes:\\n\"\n out += \"\\n\".join([f\"\\t{key}: {val}\" for key, val in err.items()])\n print(out)\n sys.exit(-1)\n\n def get_skip_idx(self):\n \"\"\"\n Get a list of any traces that don't adhere to user-defined boundaries\n such as dist, az, baz, id, or component matches. Don't actually remove\n the traces from the stream but rather just collect indices we can use\n to skip when plotting.\n\n TODO add distance, azi and backazi skip criteria\n\n :rtype: np.array\n :return: returns an indexing list which can be used to skip over\n traces that don't adhere to certain criteria\n \"\"\"\n skip_idx = []\n for idx in self.idx:\n tr = self.st[idx]\n # Component-wise removal\n if tr.stats.component not in self.components:\n skip_idx.append(idx)\n # !!! Add more here\n print(f\"criteria check will remove \"\n f\"{len(skip_idx)}/{len(self.st)} traces\")\n\n return np.array(skip_idx)\n\n def get_parameters(self):\n \"\"\"\n Calculate parameters in a specific order and based on the user-defined\n information.\n\n .. note::\n The order of function calls here is important! Some of the 'get' \n functions require the results of other 'get' functions. \n\n Calculated Parameters\n ::\n np.array idx:\n a linear indexing of all the traces in the stream\n np.array station_ids:\n an ordered list of station ids, used to get station names\n that match the index defined in `idx`\n np.array max_amplitudes:\n abs max amplitudes of each trace, used for normalization\n np.array amplitude_scaling:\n An array to scale amplitudes based on user choices\n np.array time_shift_s:\n An array to time shift time series based on user choices\n np.array y_axis:\n Y-Axis values based on sorting algorithm, used for plotting\n np.array distances:\n source-receiver distances in `distance_units` units\n np.array azimuths:\n source-receiver azimuths in degrees\n np.array backazimuths:\n source-receiver backazimuths in degrees\n np.array sorted_idx:\n sorted indexing on all the traces of the stream based on the\n chosen sorting algorithm\n \"\"\"\n # Extract basic information from the Stream\n self.idx = np.arange(0, len(self.st), 1)\n self.station_ids = np.array([tr.get_id() for tr in self.st])\n\n self.time_shift_s = self.get_time_shifts() # !!! OVERWRITES user input\n self.xlim = self.get_xlims()\n\n # Max amplitudes should be RELATIVE to what were showing (e.g., if\n # zoomed in on the P-wave, max amplitude should NOT be the surface wave)\n for tr, xlim in zip(self.st, self.xlim):\n start, stop = xlim\n self.max_amplitudes.append(max(abs(tr.data[start:stop])))\n self.max_amplitudes = np.array(self.max_amplitudes)\n\n # Figure out which indices we'll be plotting\n sorted_idx = self.get_sorted_idx()\n skip_idx = self.get_skip_idx()\n # Remove skip indexes from sorted index to get the final ordered list\n self.sorted_idx = np.array([_ for _ in sorted_idx if _ not in skip_idx])\n\n # Figure out how to manipulate each of the traces in the Stream\n self.y_axis = self.get_y_axis_positions()\n self.amplitude_scaling = self.get_amplitude_scaling()\n\n def get_xlims(self):\n \"\"\"\n The x-limits of each trace depend on the overall time shift (either \n static or applied through move out), as well as the sampling rate of\n each trace (which can vary). Retrieve an index-dependent list of\n x-limits which can be used to truncate the time series during plotting.\n\n .. note::\n Requires that get_time_shifts() has already been run\n\n :rtype: np.array\n :return: an array of tuples defining the start and stop indices for EACH\n trace to be used during plotting. Already includes time shift \n information so xlim can be applied DIRECTLY to the time shifted data\n \"\"\"\n xlim = []\n if self.xlim_s is None:\n # None's will index the entire trace\n xlim = np.array([(None, None) for _ in range(len(self.st))])\n else:\n # Looping to allow for delta varying among traces,\n # AND apply the time shift so that indices can be used directly in\n # the plotting function\n for tr, tshift in zip(self.st, self.time_shift_s):\n start, stop = [int(_/tr.stats.delta) for _ in self.xlim_s]\n sshift = int(tshift / tr.stats.delta) # unit: samples\n xlim.append((start-sshift, stop-sshift))\n\n xlim = np.array(xlim)\n return xlim\n\n def get_srcrcv_stats(self):\n \"\"\"\n Get source receiver information such as min max values, and\n count-related numbers (e.g., num stations) to be used mainly for print\n statements and text information\n\n Stats Arguments\n ::\n np.array event_names:\n unique event names taken from the SAC header\n int nevents:\n number of unique events in the stream\n np.array unique_sta_ids:\n unique station codes taken from trace stats\n int nstation_ids:\n number of unique station codes\n np.array network_codes:\n unique network codes taken from station ids\n int nnetwork:\n number of unique network codes\n np.array station_codes:\n unique station codes taken from station ids\n int nstation:\n number of unique station codes\n np.array location_codes:\n unique location codes taken from station ids\n int nlocation:\n number of unique location codes\n np.array channel_codes:\n unique channel codes taken from station ids\n int nchannel:\n number of unique channel codes\n bool reverse_sort:\n determine if the user wants to reverse their sort, they do this\n by appending '_r' to the end of the `sort_by` argument\n \"\"\"\n print(\"getting source-receiver stats\")\n\n def _unique(list_):\n \"\"\"return a unique numpy array derived from a list\"\"\"\n return np.unique(np.array(list_, dtype=str))\n\n stats = Dict()\n stats.event_names = _unique([tr.stats.sac.kevnm for tr in self.st])\n stats.nevents = len(stats.event_names)\n stats.unique_sta_ids = _unique([tr.get_id() for tr in self.st])\n stats.longest_id = max([len(_) for _ in stats.unique_sta_ids])\n stats.nstation_ids = len(stats.unique_sta_ids)\n\n # Get unique network, station, location and channel codes. Also numbers\n for name in [\"network\", \"station\", \"location\", \"channel\", \"component\"]:\n stats[f\"{name}_codes\"] = _unique(\n [getattr(tr.stats, name) for tr in self.st]\n )\n stats[f\"n{name}\"] = len(stats[f\"{name}_codes\"])\n\n # We use `not` in `reverse_sort` to make the top of the y-axis the\n # starting point, which seems more intuitive for record sections, but\n # is opposite the behavior when you increment from 0\n stats.reverse_sort = not bool(\"_r\" in self.sort_by)\n\n # Initiate empty lists for _plot_trace() to fill with min and max data\n # values which can be used for global plotting parameters like xlims\n stats.xmin, stats.xmax, stats.ymin, stats.ymax = [], [], [], []\n\n return stats\n\n def get_time_shifts(self):\n \"\"\"\n Very simple function which allows float inputs for time shifts and\n ensures that time shifts are always per-trace arrays\n Applies the move out by calculating a time shift using src-rcv distance\n\n :rtype: np.array\n :return: a stream-lengthed array of time shifts that can be applied\n per trace\n \"\"\"\n # No user input means time shifts will be 0, so nothing happens\n time_shift_arr = np.zeros(len(self.st))\n if self.time_shift_s is not None:\n # User inputs a static time shift\n if isinstance(self.time_shift_s, (int, float)):\n time_shift_arr += self.time_shift_s\n # User input an array which should have already been checked for len\n else:\n time_shift_arr = self.time_shift_s\n time_shift_arr = np.array(time_shift_arr)\n\n # Further change the time shift if we have move out input\n if self.move_out:\n print(f\"apply {self.move_out} {self.distance_units}/s move out\")\n move_out_arr = self.distances / self.move_out\n time_shift_arr -= move_out_arr\n\n return time_shift_arr\n\n def get_srcrcv_dist_az_baz(self):\n \"\"\"\n Convenience function to wrap _get_srcrcv_dist_az_baz_trace into a loop \n over the whole stream and return lists of distances, azimuths, and \n backazimuths\n\n :rtype distances: np.array\n :return distances: source-receiver distances in user-defined units in\n the original order of Stream\n :rtype azimuths: np.array\n :return azimuths: source-receiver azimuths (deg) in the original\n order of Stream\n :rtype backazimuths: np.array\n :return backazimuths: source-receiver azimuths (deg) in the original\n order of Stream\n \"\"\"\n print(\"calculating source-receiver distance and (back)azimuths\")\n\n distances, azimuths, backazimuths = [], [], []\n for tr in self.st:\n gcd, az, baz = self._get_srcrcv_dist_az_baz_trace(tr=tr)\n distances.append(gcd)\n azimuths.append(az)\n backazimuths.append(baz)\n\n distances = np.array(distances)\n azimuths = np.array(azimuths)\n backazimuths = np.array(backazimuths)\n\n return distances, azimuths, backazimuths\n\n def _get_srcrcv_dist_az_baz_trace(self, tr=None, idx=0):\n \"\"\"\n Check the source-receiver characteristics such as src-rcv distance,\n azimuth, backazimuth for a given trace.\n\n .. note::\n This function ASSUMES that SAC headers have been written to the\n traces. Otherwise we will need more complicated ways to get\n event lat and lon\n\n :type tr: obspy.core.trace.Trace\n :param tr: trace to get srcrcv information for. If None, will use `idx`\n :type idx: int\n :param idx: if `tr`==None, user can provide index of self.st (Stream)\n defaults to index 0\n :rtype gcdist: float\n :return gcdist: great circle distance in units specified by\n `distance_units`, can be 'km' or 'deg'\n :rtype az: float\n :return az: azimuth (degrees) between source and receiver\n :rtype baz: float\n :return baz: azimuth (degrees) between source and receiver\n \"\"\"\n # Default to the first trace in the Stream\n if tr is None:\n tr = self.st[int(idx)]\n try:\n dist = tr.stats.sac.dist # units: km\n az = tr.stats.sac.az # units: deg\n baz = tr.stats.sac.baz # units: deg\n except AttributeError:\n # If for whatever reason SAC headers dont contain this info already\n # Use ObsPy to get great circle distance, azimuth and backazimuth\n dist, az, baz = gps2dist_azimuth(lat1=tr.stats.sac.evla,\n lon1=tr.stats.sac.evlo,\n lat2=tr.stats.sac.stla,\n lon2=tr.stats.sac.stlo)\n dist *= 1E-3 # units: m -> km\n\n # Ensure that 0 <= (b)az <= 360\n az = az % 360\n baz = baz % 360\n\n # Make sure distance is in the correct units, default units 'km'\n if self.distance_units == \"deg\":\n dist = kilometers2degrees(dist) # units: km -> deg\n elif self.distance_units == \"km_utm\":\n # Overwrite `dist`, could probably skip that calc above but\n # leaving for now as I don't think this option will be used heavily.\n dist_deg = np.sqrt(\n ((tr.stats.sac.stlo - tr.stats.sac.evlo) ** 2) /\n ((tr.stats.sac.stla - tr.stats.sac.evla) ** 2)\n )\n dist = kilometers2degrees(dist_deg) # units: km\n\n return dist, az, baz\n\n def get_amplitude_scaling(self):\n \"\"\"\n Scale the amplitudes of all the waveforms by producing a Stream\n dependent scale factor based on user choice. It is expected that the\n output array will be DIVIDED by the data arrays:\n\n i.e., st[i].data /= self.amplitude_scaling[i]\n\n .. note::\n Needs to be run AFTER preprocessing because filtering etc. will\n affect the final amplitudes of the waveforms\n\n :rtype: np.array\n :return: an array corresponding to the Stream indexes which provides\n a per-trace scaling coefficient\n \"\"\"\n print(f\"determining amplitude scaling with: {self.scale_by}\")\n\n # Don't scale by anything\n if self.scale_by is None:\n amp_scaling = np.ones(len(self.st))\n # Scale by the max amplitude of each trace\n elif self.scale_by == \"normalize\":\n amp_scaling = self.max_amplitudes\n # When using absolute distance scale, scale waveforms to minmax dist\n if \"abs\" in self.sort_by:\n if \"distance\" in self.sort_by:\n print(\"scaling amplitudes for absolute distance\")\n scale = np.mean(self.distances) / 10\n elif \"backazimuth\" in self.sort_by:\n print(\"scaling amplitudes for absolute backazimuth\")\n scale = self.backazimuths.max() - self.backazimuths.min()\n scale /= 100\n elif \"azimuth\" in self.sort_by:\n print(\"scaling amplitudes for absolute azimuth\")\n scale = self.azimuths.max() - self.azimuths.min()\n scale /= 50\n # Divide to make waveforms larger\n amp_scaling /= scale\n # Scale by the largest amplitude shown\n elif self.scale_by == \"global_norm\":\n global_max = self.max_amplitudes[self.sorted_idx].max()\n amp_scaling = np.ones(len(self.st)) * global_max\n # Scale by the theoretical geometrical spreading factor\n elif self.scale_by == \"geometric_spreading\":\n amp_scaling = self._calculate_geometric_spreading()\n\n # Apply manual scale factor if provided, default value is 1 so nothing\n # Divide because the amplitude scale divides the data array, which means\n # `amplitude_scale_factor` will be MULTIPLIED by the data array\n amp_scaling /= self.amplitude_scale_factor\n\n return amp_scaling\n\n def _calculate_geometric_spreading(self):\n \"\"\"\n Stations with larger source-receiver distances will have their amplitude\n scaled by a larger value.\n\n For information on geometric spreading, see Stein and Wysession,\n Section 4.3.4, Eq 20 (for Rayleigh waves, geometrical spreading\n factor = 0.5). For our purposes, this will fold the attenuation factor\n into the same single factor that accounts for geometric spreading.\n\n .. note::\n This does not take into account the variation in amplitude.\n\n TODO Plot geometric spreading with best-fitting curve\n\n :type max_amplitudes: list\n :param max_amplitudes: list of maximum amplitudes for each trace in the\n stream. IF not given, will be calculated on the fly. Optional incase\n this has been calculated already and you want to save time\n :rtype: list\n :return: scale factor per trace in the stream based on theoretical\n geometrical spreading factor. This is meant to be MULTIPLIED by the\n data arrays\n \"\"\"\n raise NotImplementedError(\"This function is currently work in progress\")\n\n print(\"calculating geometrical spreading for amplitude normalization\")\n\n # Create a sinusoidal function based on distances in degrees\n sin_del = np.sin(np.array(self.dist) / (180 / np.pi))\n\n # !!! TODO Stein and Wysession and figure out vector names\n if self.geometric_spreading_k_val is not None:\n k_vector = self.max_amplitudes * \\\n (sin_del ** self.geometric_spreading_factor)\n k_val = np.median(k_vector)\n else:\n k_val = self.geometric_spreading_k_val\n\n w_vector = k_val / (sin_del ** self.geometric_spreading_factor)\n\n return w_vector\n\n def get_sorted_idx(self):\n \"\"\"\n Sort the source-receiver pairs by the chosen parameters. Except for in\n `default` sorting, always maintains component ordering defined by the\n user, i.e., for the same station, components will be ordered by the\n `component` parameter.\n\n :rtype: np.array\n :return: returns an indexing list which is sorted based on the user\n defined `sort_by` argument.\n \"\"\"\n print(f\"determining sort order with parameter: {self.sort_by}\")\n\n # Retain input ordering but run sorting to allow reversing\n if \"default\" in self.sort_by:\n sorted_idx = sorted(self.idx, reverse=self.stats.reverse_sort)\n # Sort alphabetically BUT allow component sorting\n elif \"alphabetical\" in self.sort_by:\n sorted_idx = self._sort_by_alphabetical()\n # Sort by dist, az or baz\n else:\n components = self._get_component_order()\n # Azimuthal sorts are allowed to start at a value other than 0\n # Backazimuth needs to come first because 'azimuth' can return both\n if \"backazimuth\" in self.sort_by:\n sort_list = (self.backazimuths - self.azimuth_start_deg) % 360\n elif \"azimuth\" in self.sort_by:\n sort_list = (self.azimuths - self.azimuth_start_deg) % 360\n elif \"distance\" in self.sort_by:\n sort_list = self.distances\n\n # Sort by the values, AND the components (e.g., Z->R->T or whatever)\n _, _, sorted_idx = \\\n zip(*sorted(zip(sort_list, components, self.idx),\n reverse=self.stats.reverse_sort)\n )\n sorted_idx = np.array(list(sorted_idx))\n\n return sorted_idx\n\n def _sort_by_alphabetical(self):\n \"\"\"\n Sort by full station name in order. That is, network is sorted, then\n within network, station is sorted, and so on. Components are sorted\n last and NOT in alphabetical order. They are ordered based on the\n user-input `components` parameter.\n\n :rtype: np.array\n :return: indexing of networks and stations sorted alphabetically\n \"\"\"\n networks = [_.split(\".\")[0] for _ in self.station_ids]\n stations = [_.split(\".\")[1] for _ in self.station_ids]\n locations = [_.split(\".\")[2] for _ in self.station_ids]\n components = self._get_component_order()\n zipped = zip(networks, stations, locations, components, self.idx)\n arr_out = np.array(\n list(zip(*sorted(zipped, reverse=self.stats.reverse_sort)))\n )\n\n return arr_out[-1].astype(int)\n\n def _get_component_order(self):\n \"\"\"\n When we are sorting, we want components to be sorted by the\n preferred order (i.e, ZRT, Z index is 0, T is 2), which means the\n components have to be reordered to adhere to the sorting algorithm.\n ALSO we need to ensure that we honor component order even if\n everything else is being sorted reverse alphabetically so the\n components entry needs to be the opposite of stats.reverse_sort\n\n :rtype: list\n :return: components converted to integer values which can be used for\n sorting algorithms.\n \"\"\"\n channels = [_.split(\".\")[3] for _ in self.station_ids]\n # ASSUMING component is the last entry in the channel, SEED convention\n components = [_[-1] for _ in channels]\n if self.stats.reverse_sort:\n comp_list = self.components\n else:\n comp_list = self.components[::-1]\n\n # Can't list comp here incase `comp_list` does NOT contain one of the\n # available components, which will throw a ValueError. Use a random\n # number to catch these.\n numbered_components = []\n for comp in components:\n try:\n numbered_components.append(comp_list.index(comp))\n except ValueError:\n numbered_components.append(-999)\n\n return numbered_components\n\n def get_y_axis_positions(self):\n \"\"\"\n Determine how seismograms are vertically separated on the Y-Axis when\n plotting. Allows for constant separation, or absolute separation based\n on distance or (back)azimuth separation.\n\n :rtype: np.array\n :return: an array of actual y-axis positions that can be passed directly\n to plt.plot() (or similar)\n \"\"\"\n print(f\"determining y-axis positioning for sort: {self.sort_by}\")\n\n # Default weights provides constant `y_axis_spacing` between seismos\n if self.sort_by == \"default\" or \"abs_\" not in self.sort_by:\n y_range = np.arange(0, len(self.sorted_idx), 1)\n y_axis = self.y_axis_spacing * y_range\n # Absolute y-axis (i.e., absolute distance or (back)azimuth) will just\n # plot the actual distance or azimuth value\n else:\n if \"backazimuth\" in self.sort_by:\n y_axis = self.backazimuths\n elif \"azimuth\" in self.sort_by:\n y_axis = self.azimuths\n elif \"distance\" in self.sort_by:\n y_axis = self.distances\n\n return y_axis\n\n def process_st(self):\n \"\"\"\n Preprocess the Stream with optional filtering in place.\n\n .. note::\n Data in memory will be irretrievably altered by running preprocess.\n\n TODO Add feature to allow list-like periods to individually filter\n seismograms. At the moment we just apply a blanket filter.\n \"\"\"\n if self.preprocess is None:\n print(\"no preprocessing applied\")\n return\n elif self.preprocess == \"st\":\n print(f\"preprocessing {len(self.st)} `st` waveforms\")\n preprocess_list = [self.st]\n elif self.preprocess == \"st_syn\":\n print(f\"preprocessing {len(self.st_syn)} `st_syn` waveforms\")\n preprocess_list = [self.st_syn]\n elif self.preprocess == \"both\":\n print(f\"preprocessing {len(self.st) + len(self.st_syn)} \"\n f\"`st` and `st_syn` waveforms\")\n preprocess_list = [self.st, self.st_syn]\n\n for st in preprocess_list:\n # Fill any data gaps with mean of the data, do it on a trace by \n # trace basis to get individual mean values\n for tr in st:\n tr.trim(starttime=tr.stats.starttime, endtime=tr.stats.endtime,\n pad=True, fill_value=tr.data.mean())\n st.detrend(\"demean\")\n st.taper(max_percentage=0.05, type=\"cosine\")\n\n # Allow multiple filter options based on user input\n # Min period but no max period == low-pass\n if self.max_period_s is not None and self.min_period_s is None:\n print(f\"apply lowpass filter w/ cutoff {1/self.max_period_s}\")\n st.filter(\"lowpass\", freq=1/self.max_period_s, zerophase=True)\n # Max period but no min period == high-pass\n elif self.min_period_s is not None and self.max_period_s is None:\n print(f\"apply highpass filter w/ cutoff {1/self.min_period_s}\")\n st.filter(\"highpass\", freq=1/self.min_period_s, zerophase=True)\n # Both min and max period == band-pass\n elif self.min_period_s is not None and \\\n self.max_period_s is not None:\n print(f\"applying bandpass filter w/ \"\n f\"[{1/self.max_period_s}, {self.min_period_s}]\")\n st.filter(\"bandpass\", freqmin=1/self.max_period_s,\n freqmax=1/self.min_period_s, zerophase=True)\n else:\n print(\"no filtering applied\")\n\n # Integrate and differentiate N number of times specified by user\n st.detrend(\"simple\")\n if self.integrate != 0:\n if self.integrate < 0:\n func = \"differentiate\"\n elif self.integrate > 0:\n func = \"integrate\"\n for i in range(np.abs(self.integrate)):\n print(\"{func} all waveform data\")\n getattr(st, func)()\n\n def plot(self, subset=None, page_num=None, **kwargs):\n \"\"\"\n Plot record sections based on all the available information\n\n :type subset: list of int\n :param subset: subset of `sorted_idx` if there are too many waveforms to\n plot on one page (set by `max_traces_per_rs`). e.g., to get the\n first 10 entries, subset=[0,10]\n :type page_num: int\n :param page_num: If multiple pages are required due to exceeding \n `max_traces_per_rs`, page_num will make adjustments to the figure\n name and title to differentiate different pages of the same record\n section\n \"\"\"\n if subset is None:\n start, stop = 0, None # None will allow full list traversal\n nwav = len(self.sorted_idx)\n else:\n start, stop = subset\n nwav = stop - start\n\n print(f\"plotting record section for {nwav} waveforms\")\n\n # Do a text output of station information so the user can check\n # that the plot is doing things correctly\n print(\"PLOTTING LINE CHECK STARTING FROM BOTTOM\")\n print(\"\\nIDX\\tY\\t\\tID\\tDIST\\tAZ\\tBAZ\\tTSHIFT\\tYABSMAX\")\n self.f, self.ax = plt.subplots(figsize=self.figsize)\n\n # Allow choosing observed or synthetic data, defaults to observed\n # Allow different waveform looks based on observed vs. synthetic\n for choice in [\"st\", \"st_syn\"]:\n if getattr(self, choice) is None:\n continue\n # Main plotting call. Indexes should already be sorted\n for y_idx, idx in enumerate(self.sorted_idx[start:stop]):\n # Absolute scaling requires plotting actual dist or az values\n # Relative scaling just requires a linear index to stack seismos\n if \"abs_\" in self.sort_by:\n y_index = idx\n else:\n y_index = y_idx + start\n self._plot_trace(idx=idx, y_index=y_index, choice=choice,\n **kwargs)\n\n # Change the aesthetic look of the figure, should be run before other\n # set functions as they may overwrite what is done here\n self._set_plot_aesthetic()\n\n # Partition the figure by user-specified azimuth bins \n if self.sort_by and \"azimuth\" in self.sort_by:\n self._plot_azimuth_bins()\n\n # Finalize the figure accoutrements\n self._plot_title(nwav=nwav, page_num=page_num)\n self._plot_axes(start=start, stop=stop)\n\n if self.save:\n # Allow appending page numbers to figure names,\n # e.g., default.png -> default_01.png\n if page_num:\n fid, ext = os.path.splitext(self.save)\n save_fid = f\"{fid}_{page_num:0>2}{ext}\"\n else:\n save_fid = self.save\n print(f\"\\nsaving figure to {save_fid}\")\n plt.savefig(save_fid)\n if self.show:\n plt.show()\n\n def _plot_trace(self, idx, y_index, choice=\"st\"):\n \"\"\"\n Plot a single trace on the record section, with amplitude scaling,\n time shifts, etc. Observed waveforms are black, synthetics are red.\n\n :type idx: int\n :param idx: index of the trace to plot and all trace-ordered values like\n amplitude scaling and time shifts\n :type y_index: int\n :param y_index: numerical order which this trace was plotted, as each\n trace is plotted on top of the previous one. y_index should be\n iterated linearly in the loop that calls this function.\n :type choice: str\n :param choice: choice of 'st' or 'st_syn' depending on whether you want\n to plot the observed or synthetic waveforms\n \"\"\"\n linewidth = self.kwargs.get(\"linewidth\", .25)\n\n # Used to differentiate the two types of streams for plotting diffs\n choices = [\"st\", \"st_syn\"]\n assert (choice in choices)\n c = choices.index(choice)\n tr = getattr(self, choice)[idx] # i.e., tr = self.st[idx]\n\n # Plot actual data on with amplitude scaling, time shift, and y-offset\n tshift = self.time_shift_s[idx]\n \n # These are still the entire waveform\n x = tr.times() + tshift\n y = tr.data / self.amplitude_scaling[idx] + self.y_axis[y_index]\n\n # Truncate waveforms to get figure scaling correct. \n start, stop = self.xlim[idx]\n x = x[start:stop]\n y = y[start:stop]\n\n self.ax.plot(x, y, c=[\"k\", \"r\"][c], linewidth=linewidth, zorder=10)\n\n # Sanity check print station information to check against plot\n print(f\"{idx}\"\n f\"\\t{int(self.y_axis[y_index])}\"\n f\"\\t{tr.get_id():<6}\"\n f\"\\t{self.distances[idx]:6.2f}\"\n f\"\\t{self.azimuths[idx]:6.2f}\"\n f\"\\t{self.backazimuths[idx]:6.2f}\"\n f\"\\t{self.time_shift_s[idx]:4.2f}\"\n f\"\\t{self.max_amplitudes[idx]:.2E}\")\n\n # Retain some stats for global plot args\n self.stats.xmin.append(x.min())\n self.stats.xmax.append(x.max())\n self.stats.ymin.append(y.min())\n self.stats.ymax.append(y.max())\n\n def _plot_azimuth_bins(self):\n \"\"\"\n If plotting by azimuth, create visual bin separators so the user has\n a visual understanding of radiation patterns etc.\n \"\"\"\n azimuth_binsize = self.kwargs.get(\"azimuth_binsize\", 45)\n\n # Look of the azimuth bin lines\n c = self.kwargs.get(\"azimuth_bin_c\", \"r\")\n lw = self.kwargs.get(\"azimuth_bin_lw\", .75)\n ls = self.kwargs.get(\"azimuth_bin_ls\", \"-\")\n z = self.kwargs.get(\"azimuth_bin_zorder\", 5)\n\n azimuth_bins = np.arange(self.azimuth_start_deg,\n self.azimuth_start_deg + 360,\n azimuth_binsize)\n # Make sure that the bins go from 0 <= azimuth_bins <= 360\n azimuth_bins = azimuth_bins % 360\n\n # In an absolute plot, the y values are simply the azimuth bins\n if \"abs\" in self.sort_by:\n y_vals = azimuth_bins\n s_vals = [f\"{azbin}{DEG}\" for azbin in azimuth_bins]\n # In a relative plot, the y values need to be found between seismograms\n else:\n s_vals, y_vals = [], []\n # Brute force determine where these azimuth bins would fit into the \n # actual plotted azimuths, draw a line between adjacent seismograms\n # i.e., iterating and looking if the bin value fits between\n # two adjacent azimuth values\n for azbin in azimuth_bins:\n # Edge case for 0 deg azimuth bin since azimuth wraps on 0\n # Look for the top minimum azimuth value, place line above that\n if azbin == 0:\n dy = abs(self.y_axis[1] - self.y_axis[0])\n azis = self.azimuths[self.sorted_idx]\n i = max(np.where(azis == azis.min())[0])\n y_vals.append(self.y_axis[i] + dy/2)\n else:\n for i, idx in enumerate(self.sorted_idx[1:]):\n j = i + 1\n idx_minus_one = self.sorted_idx[i]\n azi_low = self.azimuths[idx]\n azi_high = self.azimuths[idx_minus_one]\n # Break if bin is in between azi values for two seismos\n if azi_low <= azbin <= azi_high:\n break\n else:\n continue\n # Mean gives the space in between two adjacent seismograms\n y_vals.append(np.mean([self.y_axis[i], self.y_axis[j]]))\n\n s_vals.append(f\"{azbin}{DEG}\")\n\n for y, (s_val, y_val) in enumerate(zip(s_vals, y_vals)):\n # Dealing with the case where two bins occupy the same space,\n # only plot the first one that occurs\n if y_val == y_vals[y-1]:\n continue\n plt.axhline(y=y_val, c=c, linewidth=lw, linestyle=ls, zorder=z)\n plt.text(x=max(self.stats.xmax), y=y_val, s=s_val, c=c, ha=\"right\")\n\n def _plot_axes(self, start=0, stop=None):\n \"\"\"\n Contains the logic in how to handle the x- and y-axis labels, ticks etc.\n\n Logic options for how to plot the y-axis:\n - Relative: Relative plotting means the yticklabels will get replaced\n by station information. This can either be on the right or left\n side but will be attached to the actual axis\n - Absolute: Absolute plotting means the y-axis actual represents\n something (e.g., distance, azimuth). That means labels can not\n replace the y-ticks and they have to be placed within the figure\n\n .. note::\n Relative plotting can also place labels OFF the y-axis, at which\n point the y-axis is turned off because it contains no usable\n information\n\n :type start: int\n :param start: optional starting index for creating text labels\n :type stop: int\n :param stop: optional stop index for creating text labels\n \"\"\"\n # Sort out how the y-axis will be labeled with station information and\n # dist/azimuth if we're doing absolute sorting\n if \"abs_\" in self.sort_by:\n self._set_y_axis_absolute()\n if self.y_label_loc is not None:\n # By default, place absolute sorted labels at xmin\n if self.y_label_loc == \"default\":\n loc = \"x_min\"\n else:\n loc = self.y_label_loc\n self._set_y_axis_text_labels(start=start, stop=stop, loc=loc)\n elif self.y_label_loc is not None:\n # By default, relative plotting shows labels on the right side\n if self.y_label_loc == \"default\":\n loc = \"y_axis\"\n else:\n loc = self.y_label_loc\n self._set_y_axis_text_labels(start=start, stop=stop, loc=loc)\n print(f\"placing station labels on y-axis at: {loc}\")\n\n # User requests that we turn off y-axis\n if self.y_label_loc is None:\n print(f\"user requests turning off y-axis w/ `y_label_loc`== None\")\n self.ax.get_yaxis().set_visible(False)\n # OR EDGE CASE: Relative plotting but labels are not placed on the\n # y-axis, turn off the y-axis cause it doesn't mean anything anymore\n elif self.y_label_loc not in [\"default\", \"y_axis\", \"y_axis_right\"] and \\\n \"abs\" not in self.sort_by:\n print(\"turning off y-axis as it contains no information\")\n self.ax.get_yaxis().set_visible(False)\n\n # Reverse the y-axis if we are doing absolute y-axis and reversing\n if \"abs_\" in self.sort_by and \"_r\" in self.sort_by:\n print(\"user requests inverting y-axis with absolute reverse sort\")\n self.ax.invert_yaxis()\n\n # X-axis label is different if we time shift\n if self.time_shift_s.sum() == 0:\n plt.xlabel(\"Time [s]\")\n else:\n plt.xlabel(\"Relative Time [s]\")\n\n # Allow user defined x-axis limits\n if self.xlim_s is None:\n self.ax.set_xlim([min(self.stats.xmin), max(self.stats.xmax)])\n else:\n self.ax.set_xlim(self.xlim_s)\n\n plt.tight_layout()\n\n def _set_y_axis_absolute(self):\n \"\"\"\n If 'abs_' in sort_by, then the Y-axis should be shown in absolute scale.\n That means we need to format the text labels, add some labelling etc.\n \"\"\"\n # Reset tick label size to be larger to match absolute x-axis size\n ytick_fontsize = self.kwargs.get(\"ytick_fontsize\", 12)\n self.ax.tick_params(axis=\"y\", labelsize=ytick_fontsize)\n\n if \"distance\" in self.sort_by:\n if \"km\" in self.distance_units:\n ytick_minor = self.kwargs.get(\"ytick_minor\", 25)\n ytick_major = self.kwargs.get(\"ytick_major\", 100)\n elif \"deg\" in self.distance_units:\n ytick_minor = self.kwargs.get(\"ytick_minor\", 0.25)\n ytick_major = self.kwargs.get(\"ytick_major\", 1.0)\n ylabel = f\"Distance [{self.distance_units}]\"\n elif \"azimuth\" in self.sort_by:\n ytick_minor = self.kwargs.get(\"ytick_minor\", 45)\n ytick_major = self.kwargs.get(\"ytick_major\", 90)\n ylabel = f\"Azimuth [{DEG}]\"\n\n # Set ytick label major and minor which is either dist or az\n self.ax.yaxis.set_major_locator(MultipleLocator(ytick_major))\n self.ax.yaxis.set_minor_locator(MultipleLocator(ytick_minor))\n self.ax.set_ylabel(ylabel)\n\n def _set_y_axis_text_labels(self, start=0, stop=-1, loc=\"y_axis\"):\n \"\"\"\n Plot a text label next to each trace describing the station,\n azimuth and source-receiver distance. We need to do this all at once\n because we have to replace all ticks and tick labels at once.\n\n .. note::\n if using the 'subset' option in plot, need to also tell the y-axis\n plotter that we are only plotting a subset of data by using the\n `start` and `stop` parameters\n\n :type start: int\n :param start: starting index for plotting, default to start 0\n :type stop: int\n :param stop: stop index for plotting, default to end -1\n :type loc: str\n :param loc: location to place the y_axis text labels, available:\n - y_axis: Place labels along the y-axis (left side of the figure)\n Will replace the actual y-tick labels so not applicable for\n absolute sorting which requries the y-axis labels\n - y_axis_right: same as `y_axis` but set on the right side of figure\n - x_min: Place labels on the waveforms at the minimum x value\n - x_max: Place labels on the waveforms at the maximum x value\n \"\"\"\n c = self.kwargs.get(\"y_label_c\", \"k\")\n fontsize = self.kwargs.get(\"y_label_fontsize\", 10)\n\n y_tick_labels = []\n for idx in self.sorted_idx[start:stop]:\n str_id = self.station_ids[idx]\n if self.sort_by is not None and \"backazimuth\" in self.sort_by:\n # This is named `str_az` but it's actually backazimuths\n str_az = f\"{self.backazimuths[idx]:6.2f}{DEG}\"\n else:\n str_az = f\"{self.azimuths[idx]:6.2f}{DEG}\"\n\n # Allow degree distance to use the unicode * symbol\n if self.distance_units == \"deg\":\n du = DEG\n else: \n du = self.distance_units\n\n str_dist = f\"{self.distances[idx]:5.2f}{du}\"\n\n # Looks something like: NN.SSS.LL.CC|30*|250.03km\n label = \\\n f\"{str_id:>{self.stats.longest_id}}|{str_az:>8}|{str_dist:>8}\"\n # Add time shift if we have shifted at all\n if self.time_shift_s[idx] != 0:\n label += f\"|{self.time_shift_s[idx]:.2f}s\"\n y_tick_labels.append(label)\n\n if \"y_axis\" in loc:\n # For relative plotting (not abs_), replace y_tick labels with\n # station information\n self.ax.set_yticks(self.y_axis[start:stop])\n self.ax.set_yticklabels(y_tick_labels)\n else:\n # Trying to figure out where the min or max X value is on the plot\n if loc == \"x_min\":\n ha = \"left\"\n func = min\n x_val = func(self.stats.xmin)\n elif loc == \"x_max\":\n ha = \"right\"\n func = max\n x_val = func(self.stats.xmax)\n if self.xlim_s is not None:\n x_val = func([func(self.xlim_s), x_val])\n\n # Plotting y-axis labels for absolute scales\n if len(self.y_axis) == len(self.st):\n for idx, s in zip(self.sorted_idx[start:stop], y_tick_labels):\n plt.text(x=x_val, y=self.y_axis[idx], s=s, ha=ha, c=c,\n fontsize=fontsize)\n # Plotting y-axis labels for relative scales\n elif len(self.y_axis) == len(y_tick_labels):\n for y, s in zip(self.y_axis, y_tick_labels):\n plt.text(x=x_val, y=y, s=s, ha=ha, c=c, fontsize=fontsize)\n\n if loc == \"y_axis_right\":\n self.ax.yaxis.tick_right()\n self.ax.yaxis.set_label_position(\"right\")\n\n def _plot_title(self, nwav=None, page_num=None):\n \"\"\"\n Create the title of the plot based on event and station information\n Allow dynamic creation of title based on user input parameters\n\n TODO Can we make this two-column to save space?\n\n :type nwav: int\n :param nwav: if using subset, the title needs to know how many waveforms\n it's showing on the page. self.plot() should tell it\n :type page_num: int\n :param page_num: same as nwav, we need to know what page number were on\n \"\"\"\n # Defines the number of waveforms plotted on a single page, allowing\n # for subsets per page\n if nwav is None:\n nwav = len(self.sorted_idx)\n\n # Allow appending page numbers to title\n title_top = \"RECORD SECTION\"\n if page_num:\n title_top += f\" PAGE {page_num:0>2}\"\n\n # The y-label will show baz or az depending on user choice, distinguish\n if self.sort_by is not None and \"backazimuth\" in self.sort_by:\n az_str = \"BAZ\"\n else:\n az_str = \"AZ\"\n\n # Get the unique components that have been plotted, only\n cmp = \"\".join(np.unique([self.st[i].stats.component\n for i in self.sorted_idx]))\n\n # Y_FMT will include time shift IF there are time shifts\n y_fmt = f\"Y_FMT: NET.STA.LOC.CHA|{az_str}|DIST\"\n if self.time_shift_s.sum() != 0:\n y_fmt += \"|TSHIFT\"\n\n title = \"\\n\".join([\n title_top,\n f\"{'/' * len(title_top*2)}\",\n f\"ORIGINTIME: {min([tr.stats.starttime for tr in self.st])}\",\n f\"{y_fmt}\",\n f\"NWAV: {nwav}; NEVT: {self.stats.nevents}; \"\n f\"NSTA: {self.stats.nstation}; COMP: {cmp}\",\n f\"SORT_BY: {self.sort_by}; \"\n f\"SCALE_BY: {self.scale_by} * {self.amplitude_scale_factor}\",\n f\"FILT: [{self.min_period_s}, {self.max_period_s}]s; \"\n f\"MOVE_OUT: {self.move_out or 0}{self.distance_units}/s\",\n ])\n self.ax.set_title(title)\n\n def _set_plot_aesthetic(self):\n \"\"\"\n Give a nice look to the output figure by creating thick borders on the\n axis, adjusting fontsize etc. All plot aesthetics should be placed here\n so it's easiest to find.\n\n .. note::\n This was copy-pasted from Pyatoa.visuals.insp_plot.default_axes()\n \"\"\"\n ytick_fontsize = self.kwargs.get(\"ytick_fontsize\", 8)\n xtick_fontsize = self.kwargs.get(\"xtick_fontsize\", 12)\n tick_linewidth = self.kwargs.get(\"tick_linewidth\", 1.5)\n tick_length = self.kwargs.get(\"tick_length\", 5)\n tick_direction = self.kwargs.get(\"tick_direction\", \"in\")\n label_fontsize = self.kwargs.get(\"label_fontsize\", 10)\n axis_linewidth = self.kwargs.get(\"axis_linewidth\", 2.)\n title_fontsize = self.kwargs.get(\"title_fontsize\", 10)\n xtick_minor = self.kwargs.get(\"xtick_minor\", 25)\n xtick_major = self.kwargs.get(\"xtick_major\", 100)\n spine_zorder = self.kwargs.get(\"spine_zorder\", 8)\n\n # Re-set font sizes for labels already created\n self.ax.title.set_fontsize(title_fontsize)\n self.ax.tick_params(axis=\"both\", which=\"both\", width=tick_linewidth,\n direction=tick_direction, length=tick_length)\n self.ax.tick_params(axis=\"x\", labelsize=xtick_fontsize)\n self.ax.tick_params(axis=\"y\", labelsize=ytick_fontsize)\n self.ax.xaxis.label.set_size(label_fontsize)\n\n # Thicken up the bounding axis lines\n for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n self.ax.spines[axis].set_linewidth(axis_linewidth)\n\n # Set spines above azimuth bins\n for spine in self.ax.spines.values():\n spine.set_zorder(spine_zorder)\n\n # Set xtick label major and minor which is assumed to be a time series\n self.ax.xaxis.set_major_locator(MultipleLocator(xtick_major))\n self.ax.xaxis.set_minor_locator(MultipleLocator(xtick_minor))\n\n plt.grid(visible=True, which=\"major\", axis=\"x\", alpha=0.5, linewidth=1)\n plt.grid(visible=True, which=\"minor\", axis=\"x\", alpha=0.2, linewidth=.5)\n\n\ndef plotw_rs(*args, **kwargs):\n \"\"\"\n Main call function. Run the record section plotting functions in order.\n Contains the logic for breaking up figure into multiple pages.\n \"\"\"\n _start = datetime.now()\n print(f\"STARTING RECORD SECTION PLOTTER\")\n\n rs = RecordSection(*args, **kwargs)\n rs.process_st()\n rs.get_parameters()\n # Simple case where all waveforms will fit on one page\n if len(rs.sorted_idx) <= rs.max_traces_per_rs:\n rs.plot()\n # More complicated case where we need to split onto multiple pages\n else:\n for i, start in enumerate(np.arange(0, len(rs.st),\n rs.max_traces_per_rs)):\n stop = start + rs.max_traces_per_rs\n # Case where the num waveforms is less than max_traces_per_rs\n if stop < rs.max_traces_per_rs:\n stop = len(rs.st)\n rs.plot(subset=[start, stop], page_num=i+1)\n\n _end = datetime.now()\n print(f\"FINISHED RECORD SECTION (t={_end - _start}s)\")\n\n\ndef parse_args():\n \"\"\"\n Parse command line arguments to set record section parameters dynamically\n This arg parser provides a simplified interface for working with plotw_rs\n BUT it limits the flexibility of the code because things like long lists \n are prohibitively verbose and not included in the arguments.\n\n Kwargs can be passed in in the same format thanks to:\n https://stackoverflow.com/questions/37367331/is-it-possible-to-use-\\\n argparse-to-capture-an-arbitrary-set-of-optional-arguments\n\n .. note::\n Not all parameters are set here, some are left as default values\n Also some parameters are set different than the class defaults, so that\n when the user runs record_section.py without arguments, they get a\n reasonable result\n\n .. note::\n Do NOT use the command line if you want to exploit the expanded\n capabilities of the record section plotter, rather script it or call\n from an interactive environment.\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Input basic plotw_rs params\",\n formatter_class=argparse.RawTextHelpFormatter,\n )\n\n parser.add_argument(\"--pysep_path\", default=\"./\", type=str, nargs=\"?\",\n help=\"path to Pysep output, which is expected to \"\n \"contain trace-wise SAC waveform files which will \"\n \"be read\")\n parser.add_argument(\"--sort_by\", default=\"distance\", type=str, nargs=\"?\",\n help=textwrap.dedent(\"\"\"\n How to sort the Y-axis of the record section\n - None: Not set, don't sort, just iterate directly through Stream\n - 'alphabetical': sort alphabetically\n - 'azimuth': sort by source-receiver azimuth (deg) with constant\n vertical spacing\n - 'backazimuth': sort by source-receiver backazimuth (deg) with\n constant vertical spacing. Requires `azimuth_start_deg`\n - 'distance': sort by source-receiver distance (km) with constant\n vertical spacing. Requires `azimuth_start_deg` AND\n `distance_units`\n - 'abs_distance': absolute vertical spacing of waveforms defined by\n source-receiver distance (km). Requires `distance_units`\n - 'abs_azimuth': absolute vertical spacing of waveforms defined\n by source-receiver azimuth (deg). Requires\n `azimuth_start_deg`\n - 'abs_backazimuth': absolute vertical spacing of waveforms by\n source-receiver backazimuth (deg).\n - '*_r': Add a '_r' to any of the values about to REVERSE the sort,\n e.g., alphabetical_r sort will go Z->A\"\n \"\"\")\n )\n parser.add_argument(\"--scale_by\", default=\"normalize\", type=str, nargs=\"?\",\n help=textwrap.dedent(\"\"\"\n How to sort the Y-axis of the record section\n - None: Not set, no amplitude scaling, waveforms shown raw\n - 'normalize': scale each trace by the maximum amplitude,\n i.e., > a /= max(abs(a)) # where 'a' is time series amplitudes\n - 'global_norm': scale by the largest amplitude to be displayed on\n the screen. Will not consider waveforms which have been \n excluded on other basis (e.g., wrong component)\n - 'geometric_spreading': scale amplitudes globally by predicting the\n expected geometric spreading amplitude reduction and correcting\n for this factor. Requires `geometric_spreading_factor`, optional\n `geometric_spreading_k_val`\n \"\"\")\n )\n parser.add_argument(\"--time_shift_s\", default=None, type=float, nargs=\"?\",\n help=\"Set a constant time shift in unit: seconds\")\n parser.add_argument(\"--move_out\", default=None, type=float, nargs=\"?\",\n help=\"Set a constant velocity-based move out in units:\"\n \"`distance_units`/s\")\n parser.add_argument(\"--min_period_s\", default=None, type=float, nargs=\"?\",\n help=\"Minimum filter period in unit seconds.\")\n parser.add_argument(\"--max_period_s\", default=None, type=float, nargs=\"?\",\n help=\"Maximum filter period in unit seconds.\")\n parser.add_argument(\"--max_traces_per_rs\", default=None, nargs=\"?\",\n help=\"Max waveforms to show on one page. If the number \"\n \"of waveforms to show exceeds this value, \"\n \"multiple pages will be saved\")\n parser.add_argument(\"--integrate\", default=0, type=int, nargs=\"?\",\n help=\"Integrate (positive values) or differentiate \"\n \"(negative values) `integrate` times. e.g., -2 \"\n \"will differentiate all waveforms twice.\")\n parser.add_argument(\"--xlim_s\", default=None, type=int, nargs=\"+\",\n help=\"Min and max x limits in units seconds. Input as \"\n \"a list, e.g., --xlim_s 10 200 ...\")\n parser.add_argument(\"--components\", default=\"ZRTNE12\", type=str, nargs=\"?\",\n help=\"Ordered component list specifying 1) which \"\n \"components will be shown, and in what order. \"\n \"e.g., 'ZR' will show only Z and R components \"\n \"with Z sorted above R.\")\n parser.add_argument(\"--y_label_loc\", default=\"default\", type=str, nargs=\"?\",\n help=\"Station information label location on the y-axis\")\n parser.add_argument(\"--y_axis_spacing\", default=1, type=float, nargs=\"?\",\n help=\"For relative sorting, the y-axis spacing between \"\n \"adjacent seismograms. If waveforms are \"\n \"normalized then a default value of 1 is usually \"\n \"normalized then a default value of 1 is usually \"\n \"fine\")\n parser.add_argument(\"--amplitude_scale_factor\", default=1, type=float,\n nargs=\"?\",\n help=\"A user dial allowing waveform amplitudes to be\"\n \"scaled by an arbitrary float value\")\n parser.add_argument(\"--azimuth_start_deg\", default=0, type=float,\n nargs=\"?\",\n help=\"When sorting by azimuth, choose the default \"\n \"starting value, with azimuth 0 <= az <= 360\")\n parser.add_argument(\"--distance_units\", default=\"km\", type=str,\n nargs=\"?\", help=\"Set units when sorting by distance\")\n parser.add_argument(\"--save\", default=\"./record_section.png\", type=str,\n nargs=\"?\",\n help=\"Path to save the resulting record section fig\")\n parser.add_argument(\"--overwrite\", default=False, action=\"store_true\",\n help=\"overwrite existing figure if path exists\")\n\n # Keyword arguments can be passed directly to the argparser in the same \n # format as the above kwargs (e.g., --linewidth 2), but they will not have \n # help messages or type checking\n parsed, unknown = parser.parse_known_args()\n for arg in unknown:\n if arg.startswith((\"-\", \"--\")):\n parser.add_argument(arg.split(\"=\")[0])\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n plotw_rs(**vars(parse_args()))\n\n"
] |
[
[
"numpy.array",
"matplotlib.pyplot.text",
"matplotlib.ticker.MultipleLocator",
"numpy.median",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
"numpy.mean",
"numpy.arange",
"matplotlib.pyplot.tight_layout",
"numpy.sqrt",
"numpy.abs",
"matplotlib.pyplot.show",
"numpy.unique"
]
] |
Lucs1590/panopticapi
|
[
"cf18e9a401fa0285cc5c10804fae0af1c45fee4e"
] |
[
"panopticapi/combine_semantic_and_instance_predictions.py"
] |
[
"#!/usr/bin/env python\n'''\nThe script uses a simple procedure to combine semantic segmentation and instance\nsegmentation predictions. The procedure is described in section 7 of the\npanoptic segmentation paper https://arxiv.org/pdf/1801.00868.pdf.\n\nOn top of the procedure described in the paper. This script remove from\nprediction small segments of stuff semantic classes. This addition allows to\ndecrease number of false positives.\n'''\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport os\nimport argparse\nimport numpy as np\nfrom collections import defaultdict\nimport json\nimport time\nimport multiprocessing\nimport copy\n\nfrom panopticapi.utils import IdGenerator, id2rgb, save_json\n\nimport PIL.Image as Image\n\ntry:\n from pycocotools import mask as COCOmask\nexcept Exception:\n raise Exception(\n \"Please install pycocotools module from https://github.com/cocodataset/cocoapi\")\n\n\ndef combine_to_panoptic_single_core(proc_id, img_ids, img_id2img, inst_by_image,\n sem_by_image, segmentations_folder, overlap_thr,\n stuff_area_limit, categories):\n panoptic_json = []\n id_generator = IdGenerator(categories)\n\n for idx, img_id in enumerate(img_ids):\n img = img_id2img[img_id]\n\n if idx % 100 == 0:\n print('Core: {}, {} from {} images processed.'.format(proc_id, idx,\n len(img_ids)))\n\n pan_segm_id = np.zeros((img['height'],\n img['width']), dtype=np.uint32)\n used = None\n annotation = {}\n try:\n annotation['image_id'] = int(img_id)\n except Exception:\n annotation['image_id'] = img_id\n\n annotation['file_name'] = img['file_name'].replace('.jpg', '.png')\n\n segments_info = []\n for ann in inst_by_image[img_id]:\n area = COCOmask.area(ann['segmentation'])\n if area == 0:\n continue\n if used is None:\n intersect = 0\n used = copy.deepcopy(ann['segmentation'])\n else:\n intersect = COCOmask.area(\n COCOmask.merge([used, ann['segmentation']], intersect=True)\n )\n if intersect / area > overlap_thr:\n continue\n used = COCOmask.merge([used, ann['segmentation']], intersect=False)\n\n mask = COCOmask.decode(ann['segmentation']) == 1\n if intersect != 0:\n mask = np.logical_and(pan_segm_id == 0, mask)\n segment_id = id_generator.get_id(ann['category_id'])\n panoptic_ann = {}\n panoptic_ann['id'] = segment_id\n panoptic_ann['category_id'] = ann['category_id']\n pan_segm_id[mask] = segment_id\n segments_info.append(panoptic_ann)\n\n for ann in sem_by_image[img_id]:\n mask = COCOmask.decode(ann['segmentation']) == 1\n mask_left = np.logical_and(pan_segm_id == 0, mask)\n if mask_left.sum() < stuff_area_limit:\n continue\n segment_id = id_generator.get_id(ann['category_id'])\n panoptic_ann = {}\n panoptic_ann['id'] = segment_id\n panoptic_ann['category_id'] = ann['category_id']\n pan_segm_id[mask_left] = segment_id\n segments_info.append(panoptic_ann)\n\n annotation['segments_info'] = segments_info\n panoptic_json.append(annotation)\n\n Image.fromarray(id2rgb(pan_segm_id)).save(\n os.path.join(segmentations_folder, annotation['file_name'])\n )\n\n return panoptic_json\n\n\ndef combine_to_panoptic_multi_core(img_id2img, inst_by_image,\n sem_by_image, segmentations_folder, overlap_thr,\n stuff_area_limit, categories):\n cpu_num = multiprocessing.cpu_count()\n img_ids_split = np.array_split(list(img_id2img), cpu_num)\n print(\"Number of cores: {}, images per core: {}\".format(\n cpu_num, len(img_ids_split[0])))\n workers = multiprocessing.Pool(processes=cpu_num)\n processes = []\n for proc_id, img_ids in enumerate(img_ids_split):\n p = workers.apply_async(combine_to_panoptic_single_core,\n (proc_id, img_ids, img_id2img, inst_by_image,\n sem_by_image, segmentations_folder, overlap_thr,\n stuff_area_limit, categories))\n processes.append(p)\n panoptic_json = []\n for p in processes:\n panoptic_json.extend(p.get())\n return panoptic_json\n\n\ndef combine_predictions(semseg_json_file, instseg_json_file, images_json_file,\n categories_json_file, segmentations_folder,\n panoptic_json_file, confidence_thr, overlap_thr,\n stuff_area_limit):\n start_time = time.time()\n\n with open(semseg_json_file, 'r') as f:\n sem_results = json.load(f)\n with open(instseg_json_file, 'r') as f:\n inst_results = json.load(f)\n with open(images_json_file, 'r') as f:\n images_d = json.load(f)\n img_id2img = {img['id']: img for img in images_d['images']}\n\n with open(categories_json_file, 'r') as f:\n categories_list = json.load(f)\n categories = {el['id']: el for el in categories_list}\n\n if segmentations_folder is None:\n segmentations_folder = panoptic_json_file.rsplit('.', 1)[0]\n if not os.path.isdir(segmentations_folder):\n print(\"Creating folder {} for panoptic segmentation PNGs\".format(\n segmentations_folder))\n os.mkdir(segmentations_folder)\n\n print(\"Combining:\")\n print(\"Semantic segmentation:\")\n print(\"\\tJSON file: {}\".format(semseg_json_file))\n print(\"and\")\n print(\"Instance segmentations:\")\n print(\"\\tJSON file: {}\".format(instseg_json_file))\n print(\"into\")\n print(\"Panoptic segmentations:\")\n print(\"\\tSegmentation folder: {}\".format(segmentations_folder))\n print(\"\\tJSON file: {}\".format(panoptic_json_file))\n print(\"List of images to combine is takes from {}\".format(images_json_file))\n print('\\n')\n\n inst_by_image = defaultdict(list)\n for inst in inst_results:\n if inst['score'] < confidence_thr:\n continue\n inst_by_image[inst['image_id']].append(inst)\n for img_id in inst_by_image.keys():\n inst_by_image[img_id] = sorted(\n inst_by_image[img_id], key=lambda el: -el['score'])\n\n sem_by_image = defaultdict(list)\n for sem in sem_results:\n if categories[sem['category_id']]['isthing'] == 1:\n continue\n sem_by_image[sem['image_id']].append(sem)\n\n panoptic_json = combine_to_panoptic_multi_core(\n img_id2img,\n inst_by_image,\n sem_by_image,\n segmentations_folder,\n overlap_thr,\n stuff_area_limit,\n categories\n )\n\n with open(images_json_file, 'r') as f:\n coco_d = json.load(f)\n coco_d['annotations'] = panoptic_json\n coco_d['categories'] = list(categories.values())\n save_json(coco_d, panoptic_json_file)\n\n t_delta = time.time() - start_time\n print(\"Time elapsed: {:0.2f} seconds\".format(t_delta))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"This script uses a simple procedure to combine semantic \\\n segmentation and instance segmentation predictions. See this \\\n file's head for more information.\"\n )\n parser.add_argument('--semseg_json_file', type=str,\n help=\"JSON file with semantic segmentation predictions\")\n parser.add_argument('--instseg_json_file', type=str,\n help=\"JSON file with instance segmentation predictions\")\n parser.add_argument('--images_json_file', type=str,\n help=\"JSON file with correponding image set information\")\n parser.add_argument('--categories_json_file', type=str,\n help=\"JSON file with Panoptic COCO categories information\",\n default='./panoptic_coco_categories.json')\n parser.add_argument('--panoptic_json_file', type=str,\n help=\"JSON file with resulting COCO panoptic format prediction\")\n parser.add_argument(\n '--segmentations_folder', type=str, default=None, help=\"Folder with \\\n panoptic COCO format segmentations. Default: X if panoptic_json_file is \\\n X.json\"\n )\n parser.add_argument('--confidence_thr', type=float, default=0.5,\n help=\"Predicted segments with smaller confidences than the threshold are filtered out\")\n parser.add_argument('--overlap_thr', type=float, default=0.5,\n help=\"Segments that have higher that the threshold ratio of \\\n their area being overlapped by segments with higher confidence are filtered out\")\n parser.add_argument('--stuff_area_limit', type=float, default=64*64,\n help=\"Stuff segments with area smaller that the limit are filtered out\")\n args = parser.parse_args()\n combine_predictions(args.semseg_json_file,\n args.instseg_json_file,\n args.images_json_file,\n args.categories_json_file,\n args.segmentations_folder,\n args.panoptic_json_file,\n args.confidence_thr,\n args.overlap_thr,\n args.stuff_area_limit)\n"
] |
[
[
"numpy.logical_and",
"numpy.zeros"
]
] |
nvladimus/MiraoControl
|
[
"703e825daffa7718de9e14de5d77d8a98dfaf6e4"
] |
[
"lib/Mirao52_utils.py"
] |
[
" \n# Mirao 52e ERROR codes:\n# Error codes (status)\nerrors = {}\nerrors[0] = 'MRO_OK, No error'\nerrors[1] = 'MRO_UNKNOWN_ERROR'\nerrors[2] = 'MRO_DEVICE_NOT_OPENED_ERROR, mirao 52-e is not opened.'\nerrors[3] = 'MRO_DEFECTIVE_DEVICE_ERROR, mirao 52-e has been identified as defective.'\nerrors[4] = 'MRO_DEVICE_ALREADY_OPENED_ERROR, mirao 52-e is already opened.'\nerrors[5] = 'MRO_DEVICE_IO_ERROR, a communication error has been detected.'\nerrors[6] = 'MRO_DEVICE_LOCKED_ERROR, a temperature overheat or an excess of current has lead mirao 52-e to a protection state.'\nerrors[7] = 'MRO_DEVICE_DISCONNECTED_ERROR'\nerrors[8] = 'MRO_DEVICE_DRIVER_ERROR, an internal driver malfunction'\nerrors[9] = 'MRO_FILE_EXISTS_ERROR, the file to write already exists and its not allowed to overwrite it.'\nerrors[10] = 'MRO_FILE_FORMAT_ERROR, the considered file is corrupted or has not a valid file format.'\nerrors[11] = 'MRO_FILE_IO_ERROR, an error has been detected while reading/writing a file.'\nerrors[12] = 'MRO_INVALID_COMMAND_ERROR, there are two possibilities: \\\n(1) A least one of the values of the command is out of specification (value > 1.0 or value < -1.0).\\\n(2) The sum of the absolute values of the command values is greater than 25.0.'\nerrors[13] = 'MRO_NULL_POINTER_ERROR, a null pointer has been identified as a parameter which cannot be null.'\nerrors[14] = 'MRO_OUT_OF_BOUNDS_ERROR, this happens when an index parameter is out of its possible values.'\nerrors[15] = 'MRO_OPERATION_ONGOING_ERROR, operation already in progress. The requested operation cannot be performed due to a synchronization lock.'\nerrors[16] = 'MRO_SYSTEM_ERROR, An error has been detected while calling the operating system.'\nerrors[17] = 'MRO_UNAVAILABLE_DATA_ERROR, The requested data is unavailable.\\\nThis can be due to the call of an unavailable functionality or a functionality that needs monitoring to be enabled.'\nerrors[18] = 'MRO_UNDEFINED_VALUE_ERROR, The requested value is not available. Ex: request of an undefined stock command value.'\nerrors[19] = 'MRO_OUT_OF_SPECIFICATIONS_ERROR, The value, which is not an index, is out of allowed values.'\nerrors[20] = 'MRO_FILE_FORMAT_VERSION_ERROR, The file format version is not supported. \\\nThe version of the MRO file format is not handled by this mirao 52-e API.'\nerrors[21] = 'MRO_USB_INVALID_HANDLE, This error implies either an operating system error or an internal driver error.'\nerrors[22] = 'MRO_USB_DEVICE_NOT_FOUND, mirao 52-e cannot be found among the USB ports. There may be several possibilities:\\\n(1) The device is not connected to the computer or the connection is defective, \\\n(2) The USB port is not correctly installed in the operating system,\\\n(3) The mirao 52-e device is not turned ON, \\\n(4) The mirao 52-e device is already opened by another process, \\\n(5) The mirao 52-e device is defective.'\nerrors[23] = 'MRO_USB_DEVICE_NOT_OPENED, Internal driver not opened. This error implies an operating system error.'\nerrors[24] = 'MRO_USB_IO_ERROR, Internal driver IO error. The internal driver encountered a problem for reading from \\\nor writing to the hardware device.'\nerrors[25] = 'MRO_USB_INSUFFICIENT_RESOURCES, There are insufficient system resources to perform the requested operation.'\nerrors[26] = 'MRO_USB_INVALID_BAUD_RATE, The configuration of the connection speed is not supported.'\nerrors[27] = 'MRO_USB_NOT_SUPPORTED, A functionnality is not supported by the internal driver. \\\nImplies an operating system error perhaps due to a bad USB driver version.'\nerrors[28] = 'MRO_FILE_IO_EACCES, Permission denied. A file cannot be accessed due to a permission denied error.'\nerrors[29] = 'MRO_FILE_IO_EAGAIN, No more processes. An attempt to create a new process failed.'\nerrors[30] = 'MRO_FILE_IO_EBADF, Bad file number. An invalid internal file descriptor has been used. This is an operating system error.'\nerrors[31] = 'MRO_FILE_IO_EINVAL, An internal invalid argument has been used with a file IO function. This is an operating system error.'\nerrors[32] = 'MRO_FILE_IO_EMFILE, Too many opened files. The maximum number of open files allowed by the operating system has been reached.'\nerrors[33] = 'MRO_FILE_IO_ENOENT, No such file or directory. The considered file or directory does not exists.'\nerrors[34] = 'MRO_FILE_IO_ENOMEM, Not enough memory. The operation requested cannot be performed because the process is out of memory.'\nerrors[35] = 'MRO_FILE_IO_ENOSPC, No space left on device. A file cannot be written because the hard drive lacks of space.'\n\ndef read_Mirao_commandFile(path, driver):\n '''\n Reads 52 double values from .MRO file using Mirao52e.dll API. \n Run \n import ctypes \n driver = ctypes.windll.mirao52e \n to open driver (dll) session.\n '''\n import ctypes\n import numpy as np\n import os\n byref = ctypes.byref\n status = ctypes.c_int32() \n path = path.replace('/', '\\\\')\n Cpath = ctypes.c_char_p(path)\n cmd = np.zeros(52,dtype = np.float64)\n if os.path.exists(path):\n assert driver.mro_readCommandFile(Cpath,cmd.ctypes.data,byref(status)), errors[status.value]\n else:\n print('Error: command file not found')\n return cmd\n \ndef DM_voltage_to_map(v):\n \"\"\"\n Reshape the 52-long vector v into 2D matrix representing the actual DM aperture.\n Corners of the matrix are set to None for plotting.\n Parameters:\n v - double array of length 52\n \n Returns:\n output: 8x8 ndarray of doubles.\n -------\n Author: Nikita Vladimirov\n \"\"\"\n import numpy as np\n M = np.zeros((8,8))\n M[:,:] = None\n M[2:6,0] = v[:4]\n M[1:7,1] = v[4:10]\n M[:,2] = v[10:18]\n M[:,3] = v[18:26]\n M[:,4] = v[26:34]\n M[:,5] = v[34:42]\n M[1:7,6] = v[42:48]\n M[2:6,7] = v[48:52]\n return M"
] |
[
[
"numpy.zeros"
]
] |
sustainable-computing/ODToolk
|
[
"9328b930f7e522a89d82011e8ab91286a20bf66f"
] |
[
"core/preprocessing/fill.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\ndef fill(dataset):\n \"\"\"\n Fill all nan value in the sensor data for given core.data.dataset.Dataset\n\n :parameter dataset: Dataset object that wants to fill in missing values\n :type dataset: core.data.dataset.Dataset\n\n :return: None\n \"\"\"\n from ..data import Dataset\n from numpy import isnan, where, arange, maximum, nonzero\n\n if not isinstance(dataset, Dataset):\n raise TypeError(\"Dataset has to be class core.data.dataset.Dataset\")\n\n data = dataset.data\n\n for _ in range(2):\n mask = isnan(data.T)\n idx = where(~mask, arange(mask.shape[1]), 0)\n maximum.accumulate(idx, axis=1, out=idx)\n data.T[mask] = data.T[nonzero(mask)[0], idx[mask]]\n data = data[::-1]\n\n dataset.change_values(data)\n"
] |
[
[
"numpy.isnan",
"numpy.arange",
"numpy.nonzero",
"numpy.maximum.accumulate"
]
] |
cstenkamp/skelshop
|
[
"6f4b26e28d4aa1050c8c3c15edd39ae072baca54"
] |
[
"skelshop/track/spec.py"
] |
[
"from abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import List, Optional, cast\n\nimport numpy as np\n\nfrom ..pose import PoseBase\nfrom .metrics import Metric\n\nPENALTY_WEIGHT = 1e6\n\n\n@dataclass\nclass TrackingSpec:\n \"\"\"\n A domain specific language for threshold distance-based style tracking.\n\n Candidate poses are first filtered using `cand_filter` and then `procedure`\n is executed to decide how to assign the candidates.\n \"\"\"\n\n enlarge_scale: float\n prev_frame_buf_size: int\n cand_filter: \"CandFilter\"\n procedure: \"ProcedureNode\"\n\n\nclass CandFilter(ABC):\n @abstractmethod\n def accept_pose(self, pose: PoseBase) -> bool:\n ...\n\n\n@dataclass\nclass SumConfCandFilter(CandFilter):\n min_score: float\n\n def accept_pose(self, pose: PoseBase) -> bool:\n score = cast(float, np.sum(pose.all()[:, 2]))\n return score >= self.min_score\n\n\n@dataclass\nclass MeanConfCandFilter(CandFilter):\n min_score: float\n\n def accept_pose(self, pose: PoseBase) -> bool:\n confs = pose.all()[:, 2]\n score = cast(float, np.mean(confs[confs > 0]))\n return score >= self.min_score\n\n\nclass ProcedureNode(ABC):\n @abstractmethod\n def assign(\n self, get_fresh_id, candidates, references, tracking_state,\n ):\n ...\n\n\n@dataclass\nclass OrElse(ProcedureNode):\n choices: List[ProcedureNode]\n\n def assign(\n self, get_fresh_id, candidates, references, tracking_state,\n ):\n for node in self.choices:\n node.assign(get_fresh_id, candidates, references, tracking_state)\n\n\n@dataclass\nclass AssignRemaining(ProcedureNode):\n def assign(\n self, get_fresh_id, candidates, references, tracking_state,\n ):\n for tracked_pose in tracking_state.untracked_as_tracked(candidates):\n tracked_pose.track_as(get_fresh_id())\n tracking_state.track(tracked_pose)\n\n\n@dataclass\nclass AssignMetMixin:\n metric: Metric\n thresh: Optional[float]\n\n\n@dataclass\nclass GreedyAssignMetThresh(ProcedureNode, AssignMetMixin):\n def assign(\n self, get_fresh_id, candidates, references, tracking_state,\n ):\n for cand in tracking_state.untracked_as_tracked(candidates):\n cand_rep = self.metric.preproc_pose(cand)\n min_cost = float(\"inf\")\n min_ref = None\n for ref in references:\n ref_rep = self.metric.preproc_pose(ref)\n cost = self.metric.cmp(cand_rep, ref_rep)\n if cost < min_cost:\n min_cost = cost\n min_ref = ref\n if min_ref is not None and (self.thresh is None or cost <= self.thresh):\n assert min_ref.track_id is not None\n cand.track_as(min_ref.track_id)\n tracking_state.track(cand)\n\n\n@dataclass\nclass OptAssignMetThresh(ProcedureNode, AssignMetMixin):\n def assign(\n self, get_fresh_id, candidates, references, tracking_state,\n ):\n from scipy.optimize import linear_sum_assignment\n\n # Get references/candidates as lists\n references_list = list(references)\n if not references_list:\n return\n candidates_as_tracked_list = list(\n tracking_state.untracked_as_tracked(candidates)\n )\n if not candidates_as_tracked_list:\n return\n\n # Represent them\n refs_proc = self.metric.preproc_poses(references_list)\n assert len(refs_proc) == len(references_list)\n cands_proc = self.metric.preproc_poses(candidates_as_tracked_list)\n assert len(cands_proc) == len(candidates_as_tracked_list)\n cost_mat = np.empty((len(candidates_as_tracked_list), len(references_list)))\n\n # Build cost matrix\n for cand_idx, cand_proc in enumerate(cands_proc):\n for ref_idx, ref_proc in enumerate(refs_proc):\n cost = self.metric.cmp(cand_proc, ref_proc)\n if self.thresh is not None and cost > self.thresh:\n cost_mat[cand_idx, ref_idx] = PENALTY_WEIGHT\n else:\n cost_mat[cand_idx, ref_idx] = cost\n\n # Solve\n cand_idxs, ref_idxs = linear_sum_assignment(cost_mat)\n for cand_idx, ref_idx in zip(cand_idxs, ref_idxs):\n if cost_mat[cand_idx, ref_idx] == PENALTY_WEIGHT:\n continue\n cand = candidates_as_tracked_list[cand_idx]\n cand.track_as(references_list[ref_idx].track_id)\n tracking_state.track(cand)\n\n\n@dataclass\nclass PrevFrameCascade(ProcedureNode):\n inner: ProcedureNode\n length: Optional[int] = None\n skip: Optional[int] = None\n\n def assign(\n self, get_fresh_id, candidates, reference_buf, tracking_state,\n ):\n for references in reference_buf.hist_iter(self.skip, self.length):\n # Copy references since they can be mutated within inner\n self.inner.assign(get_fresh_id, candidates, references, tracking_state)\n"
] |
[
[
"scipy.optimize.linear_sum_assignment",
"numpy.mean"
]
] |
soldierofhell/deep-text-recognition-benchmark
|
[
"74f5705a62bc1218bf9c0763eea390692f62712e"
] |
[
"train.py"
] |
[
"import os\nimport sys\nimport time\nimport random\nimport string\nimport argparse\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn.init as init\nimport torch.optim as optim\nimport torch.utils.data\nimport numpy as np\n\nfrom utils import CTCLabelConverter, AttnLabelConverter, Averager\nfrom dataset import hierarchical_dataset, AlignCollate, Batch_Balanced_Dataset\nfrom model import Model\nfrom test import validation\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef train(opt):\n \"\"\" dataset preparation \"\"\"\n if not opt.data_filtering_off:\n print('Filtering the images containing characters which are not in opt.character')\n print('Filtering the images whose label is longer than opt.batch_max_length')\n # see https://github.com/clovaai/deep-text-recognition-benchmark/blob/master/dataset.py#L130\n\n opt.select_data = opt.select_data.split('-')\n opt.batch_ratio = opt.batch_ratio.split('-')\n train_dataset = Batch_Balanced_Dataset(opt)\n\n AlignCollate_valid = AlignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio_with_pad=opt.PAD)\n valid_dataset = hierarchical_dataset(root=opt.valid_data, opt=opt)\n valid_loader = torch.utils.data.DataLoader(\n valid_dataset, batch_size=opt.batch_size,\n shuffle=True, # 'True' to check training progress with validation function.\n num_workers=int(opt.workers),\n collate_fn=AlignCollate_valid, pin_memory=True)\n print('-' * 80)\n\n \"\"\" model configuration \"\"\"\n if 'CTC' in opt.Prediction:\n converter = CTCLabelConverter(opt.character)\n else:\n converter = AttnLabelConverter(opt.character)\n opt.num_class = len(converter.character)\n\n if opt.rgb:\n opt.input_channel = 3\n model = Model(opt)\n print('model input parameters', opt.imgH, opt.imgW, opt.num_fiducial, opt.input_channel, opt.output_channel,\n opt.hidden_size, opt.num_class, opt.batch_max_length, opt.Transformation, opt.FeatureExtraction,\n opt.SequenceModeling, opt.Prediction)\n\n # weight initialization\n for name, param in model.named_parameters():\n if 'localization_fc2' in name:\n print(f'Skip {name} as it is already initialized')\n continue\n try:\n if 'bias' in name:\n init.constant_(param, 0.0)\n elif 'weight' in name:\n init.kaiming_normal_(param)\n except Exception as e: # for batchnorm.\n if 'weight' in name:\n param.data.fill_(1)\n continue\n\n # data parallel for multi-GPU\n model = torch.nn.DataParallel(model).to(device)\n model.train()\n if opt.saved_model != '':\n print(f'loading pretrained model from {opt.saved_model}')\n if opt.FT:\n model_state_dict = torch.load(opt.saved_model)\n if opt.imgW != 100: # disable GridGenerator\n for old_key in list(model_state_dict.keys()):\n if old_key.startswith('module.Transformation.GridGenerator'):\n new_key = '_' + old_key\n model_state_dict[new_key] = model_state_dict.pop(old_key)\n if opt.character != '0123456789abcdefghijklmnopqrstuvwxyz': # disable GridGenerator\n for old_key in list(model_state_dict.keys()):\n if old_key.startswith('module.Prediction.attention_cell.rnn') or old_key.startswith('module.Prediction.generator'):\n new_key = '_' + old_key\n model_state_dict[new_key] = model_state_dict.pop(old_key)\n model.load_state_dict(model_state_dict, strict=False)\n else:\n model.load_state_dict(torch.load(opt.saved_model))\n print(\"Model:\")\n print(model)\n\n \"\"\" setup loss \"\"\"\n if 'CTC' in opt.Prediction:\n criterion = torch.nn.CTCLoss(zero_infinity=True).to(device)\n else:\n criterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device) # ignore [GO] token = ignore index 0\n # loss averager\n loss_avg = Averager()\n\n # filter that only require gradient decent\n filtered_parameters = []\n params_num = []\n for p in filter(lambda p: p.requires_grad, model.parameters()):\n filtered_parameters.append(p)\n params_num.append(np.prod(p.size()))\n print('Trainable params num : ', sum(params_num))\n # [print(name, p.numel()) for name, p in filter(lambda p: p[1].requires_grad, model.named_parameters())]\n\n # setup optimizer\n if opt.adam:\n optimizer = optim.Adam(filtered_parameters, lr=opt.lr, betas=(opt.beta1, 0.999))\n else:\n optimizer = optim.Adadelta(filtered_parameters, lr=opt.lr, rho=opt.rho, eps=opt.eps)\n print(\"Optimizer:\")\n print(optimizer)\n\n \"\"\" final options \"\"\"\n # print(opt)\n with open(f'./saved_models/{opt.experiment_name}/opt.txt', 'a') as opt_file:\n opt_log = '------------ Options -------------\\n'\n args = vars(opt)\n for k, v in args.items():\n opt_log += f'{str(k)}: {str(v)}\\n'\n opt_log += '---------------------------------------\\n'\n print(opt_log)\n opt_file.write(opt_log)\n\n \"\"\" start training \"\"\"\n start_iter = 0\n if opt.saved_model != '':\n start_iter = int(opt.saved_model.split('_')[-1].split('.')[0])\n print(f'continue to train, start_iter: {start_iter}')\n\n start_time = time.time()\n best_accuracy = -1\n best_norm_ED = 1e+6\n i = start_iter\n\n while(True):\n # train part\n image_tensors, labels, _ = train_dataset.get_batch()\n image = image_tensors.to(device)\n text, length = converter.encode(labels, batch_max_length=opt.batch_max_length)\n text = text.to(device)\n length = length.to(device)\n batch_size = image.size(0)\n\n if 'CTC' in opt.Prediction:\n preds = model(image, text).log_softmax(2)\n preds_size = torch.IntTensor([preds.size(1)] * batch_size)\n preds = preds.permute(1, 0, 2)\n\n # (ctc_a) For PyTorch 1.2.0 and 1.3.0. To avoid ctc_loss issue, disabled cudnn for the computation of the ctc_loss\n # https://github.com/jpuigcerver/PyLaia/issues/16\n torch.backends.cudnn.enabled = False\n cost = criterion(preds, text.to(device), preds_size.to(device), length.to(device))\n torch.backends.cudnn.enabled = True\n\n # # (ctc_b) To reproduce our pretrained model / paper, use our previous code (below code) instead of (ctc_a).\n # # With PyTorch 1.2.0, the below code occurs NAN, so you may use PyTorch 1.1.0.\n # # Thus, the result of CTCLoss is different in PyTorch 1.1.0 and PyTorch 1.2.0.\n # # See https://github.com/clovaai/deep-text-recognition-benchmark/issues/56#issuecomment-526490707\n # cost = criterion(preds, text, preds_size, length)\n\n else:\n preds = model(image, text[:, :-1]) # align with Attention.forward\n target = text[:, 1:] # without [GO] Symbol\n cost = criterion(preds.view(-1, preds.shape[-1]), target.contiguous().view(-1))\n\n model.zero_grad()\n cost.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)\n optimizer.step()\n\n loss_avg.add(cost)\n\n # validation part\n if i % opt.valInterval == 0:\n elapsed_time = time.time() - start_time\n # for log\n with open(f'./saved_models/{opt.experiment_name}/log_train.txt', 'a') as log:\n model.eval()\n with torch.no_grad():\n\n valid_loss, current_accuracy, current_norm_ED, preds, confidence_score, labels, infer_time, length_of_data = validation(\n model, criterion, valid_loader, converter, opt)\n model.train()\n\n # training loss and validation loss\n loss_log = f'[{i}/{opt.num_iter}] Train loss: {loss_avg.val():0.5f}, Valid loss: {valid_loss:0.5f}, Elapsed_time: {elapsed_time:0.5f}'\n print(loss_log)\n log.write(loss_log + '\\n')\n loss_avg.reset()\n\n current_model_log = f'{\"Current_accuracy\":17s}: {current_accuracy:0.3f}, {\"Current_norm_ED\":17s}: {current_norm_ED:0.2f}'\n print(current_model_log)\n log.write(current_model_log + '\\n')\n\n # keep best accuracy model (on valid dataset)\n if current_accuracy > best_accuracy:\n best_accuracy = current_accuracy\n torch.save(model.state_dict(), f'./saved_models/{opt.experiment_name}/best_accuracy.pth')\n if current_norm_ED < best_norm_ED:\n best_norm_ED = current_norm_ED\n torch.save(model.state_dict(), f'./saved_models/{opt.experiment_name}/best_norm_ED.pth')\n best_model_log = f'{\"Best_accuracy\":17s}: {best_accuracy:0.3f}, {\"Best_norm_ED\":17s}: {best_norm_ED:0.2f}'\n print(best_model_log)\n log.write(best_model_log + '\\n')\n\n # show some predicted results\n print('-' * 80)\n print(f'{\"Ground Truth\":25s} | {\"Prediction\":25s} | Confidence Score & T/F')\n log.write(f'{\"Ground Truth\":25s} | {\"Prediction\":25s} | {\"Confidence Score\"}\\n')\n print('-' * 80)\n for gt, pred, confidence in zip(labels[:5], preds[:5], confidence_score[:5]):\n if 'Attn' in opt.Prediction:\n gt = gt[:gt.find('[s]')]\n pred = pred[:pred.find('[s]')]\n\n print(f'{gt:25s} | {pred:25s} | {confidence:0.4f}\\t{str(pred == gt)}')\n log.write(f'{gt:25s} | {pred:25s} | {confidence:0.4f}\\t{str(pred == gt)}\\n')\n print('-' * 80)\n\n # save model per 1e+5 iter.\n if (i + 1) % 1e+5 == 0:\n torch.save(\n model.state_dict(), f'./saved_models/{opt.experiment_name}/iter_{i+1}.pth')\n\n if i == opt.num_iter:\n print('end the training')\n sys.exit()\n i += 1\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--experiment_name', help='Where to store logs and models')\n parser.add_argument('--train_data', required=True, help='path to training dataset')\n parser.add_argument('--valid_data', required=True, help='path to validation dataset')\n parser.add_argument('--manualSeed', type=int, default=1111, help='for random seed setting')\n parser.add_argument('--workers', type=int, help='number of data loading workers', default=4)\n parser.add_argument('--batch_size', type=int, default=192, help='input batch size')\n parser.add_argument('--num_iter', type=int, default=300000, help='number of iterations to train for')\n parser.add_argument('--valInterval', type=int, default=2000, help='Interval between each validation')\n parser.add_argument('--saved_model', default='', help=\"path to model to continue training\")\n parser.add_argument('--FT', action='store_true', help='whether to do fine-tuning')\n parser.add_argument('--adam', action='store_true', help='Whether to use adam (default is Adadelta)')\n parser.add_argument('--lr', type=float, default=1, help='learning rate, default=1.0 for Adadelta')\n parser.add_argument('--beta1', type=float, default=0.9, help='beta1 for adam. default=0.9')\n parser.add_argument('--rho', type=float, default=0.95, help='decay rate rho for Adadelta. default=0.95')\n parser.add_argument('--eps', type=float, default=1e-8, help='eps for Adadelta. default=1e-8')\n parser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping value. default=5')\n \"\"\" Data processing \"\"\"\n parser.add_argument('--select_data', type=str, default='MJ-ST',\n help='select training data (default is MJ-ST, which means MJ and ST used as training data)')\n parser.add_argument('--batch_ratio', type=str, default='0.5-0.5',\n help='assign ratio for each selected data in the batch')\n parser.add_argument('--total_data_usage_ratio', type=str, default='1.0',\n help='total data usage ratio, this ratio is multiplied to total number of data.')\n parser.add_argument('--batch_max_length', type=int, default=25, help='maximum-label-length')\n parser.add_argument('--imgH', type=int, default=32, help='the height of the input image')\n parser.add_argument('--imgW', type=int, default=100, help='the width of the input image')\n parser.add_argument('--rgb', action='store_true', help='use rgb input')\n parser.add_argument('--character', type=str, default='0123456789abcdefghijklmnopqrstuvwxyz', help='character label')\n parser.add_argument('--sensitive', action='store_true', help='for sensitive character mode')\n parser.add_argument('--PAD', action='store_true', help='whether to keep ratio then pad for image resize')\n parser.add_argument('--data_filtering_off', action='store_true', help='for data_filtering_off mode')\n \"\"\" Model Architecture \"\"\"\n parser.add_argument('--Transformation', type=str, required=True, help='Transformation stage. None|TPS')\n parser.add_argument('--FeatureExtraction', type=str, required=True, help='FeatureExtraction stage. VGG|RCNN|ResNet')\n parser.add_argument('--SequenceModeling', type=str, required=True, help='SequenceModeling stage. None|BiLSTM')\n parser.add_argument('--Prediction', type=str, required=True, help='Prediction stage. CTC|Attn')\n parser.add_argument('--num_fiducial', type=int, default=20, help='number of fiducial points of TPS-STN')\n parser.add_argument('--input_channel', type=int, default=1, help='the number of input channel of Feature extractor')\n parser.add_argument('--output_channel', type=int, default=512,\n help='the number of output channel of Feature extractor')\n parser.add_argument('--hidden_size', type=int, default=256, help='the size of the LSTM hidden state')\n \n parser.add_argument('--results_path', required=True, help=\"path to save results\")\n\n opt = parser.parse_args()\n\n if not opt.experiment_name:\n opt.experiment_name = f'{opt.Transformation}-{opt.FeatureExtraction}-{opt.SequenceModeling}-{opt.Prediction}'\n opt.experiment_name += f'-Seed{opt.manualSeed}'\n # print(opt.experiment_name)\n\n os.makedirs(f'./saved_models/{opt.experiment_name}', exist_ok=True)\n\n \"\"\" vocab / character number configuration \"\"\"\n if opt.sensitive:\n # opt.character += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n opt.character = string.printable[:-6] # same with ASTER setting (use 94 char).\n\n \"\"\" Seed and GPU setting \"\"\"\n # print(\"Random Seed: \", opt.manualSeed)\n random.seed(opt.manualSeed)\n np.random.seed(opt.manualSeed)\n torch.manual_seed(opt.manualSeed)\n torch.cuda.manual_seed(opt.manualSeed)\n\n cudnn.benchmark = True\n cudnn.deterministic = True\n opt.num_gpu = torch.cuda.device_count()\n # print('device count', opt.num_gpu)\n if opt.num_gpu > 1:\n print('------ Use multi-GPU setting ------')\n print('if you stuck too long time with multi-GPU setting, try to set --workers 0')\n # check multi-GPU issue https://github.com/clovaai/deep-text-recognition-benchmark/issues/1\n opt.workers = opt.workers * opt.num_gpu\n opt.batch_size = opt.batch_size * opt.num_gpu\n\n \"\"\" previous version\n print('To equlize batch stats to 1-GPU setting, the batch_size is multiplied with num_gpu and multiplied batch_size is ', opt.batch_size)\n opt.batch_size = opt.batch_size * opt.num_gpu\n print('To equalize the number of epochs to 1-GPU setting, num_iter is divided with num_gpu by default.')\n If you dont care about it, just commnet out these line.)\n opt.num_iter = int(opt.num_iter / opt.num_gpu)\n \"\"\"\n\n train(opt)\n"
] |
[
[
"torch.cuda.manual_seed",
"torch.nn.init.constant_",
"numpy.random.seed",
"torch.no_grad",
"torch.optim.Adam",
"torch.nn.CTCLoss",
"torch.nn.init.kaiming_normal_",
"torch.optim.Adadelta",
"torch.cuda.device_count",
"torch.manual_seed",
"torch.cuda.is_available",
"torch.load",
"torch.nn.CrossEntropyLoss",
"torch.nn.DataParallel"
]
] |
mareklovci/kky-zsur
|
[
"c41fbce53aa790b1f280cbca8d274845993e74f9"
] |
[
"zsur/__main__.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Main file to test the whole project\"\"\"\n\nimport logging\nfrom zsur.readfile import readfile\nfrom matplotlib import pyplot as plt\nfrom zsur.bayes import main as bayes\nfrom zsur.chain_map import main as chmap\nfrom zsur.cluster_levels import main as cluster\nfrom zsur.kmeans import main as kmeans\nfrom zsur.linear_disc import main as lindisc\nfrom zsur.maximin import main as maximin\nfrom zsur.minimal_distance import main as mindist\nfrom zsur.nearest_neighbour import main as nearneigh\nfrom zsur.unequal_binary import main as unebin\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n__all__ = ('main',) # list of public objects of module\n\n\ndef plot_data(data: list):\n x, y = zip(*data)\n plt.scatter(x, y, color='black', marker='o')\n plt.show()\n\n\ndef main():\n data = readfile('data.txt')\n plot_data(data) # show data\n # metoda shlukove hladiny\n logging.info('metoda shlukove hladiny')\n cluster()\n # metoda retezove mapy\n logging.info('metoda retezove mapy')\n chmap()\n # metoda maximin\n logging.info('metoda maximin')\n maximin()\n # nerovnomerne binarni deleni\n logging.info('nerovnomerne binarni deleni')\n unebin()\n # kmeans\n logging.info('kmeans')\n kmeans()\n # bayesuv klasifikator\n logging.info('bayesuv klasifikator')\n bayes()\n # klasifikator podle minimalni vzdalenosti\n logging.info('klasifikator podle minimalni vzdalenosti')\n mindist()\n # klasifikator podle k-nejblizsiho souseda\n logging.info('klasifikator podle k-nejblizsiho souseda')\n nearneigh()\n # klasifikator s linearnimi diskriminacnimi funkcemi\n logging.info('klasifikator s linearnimi diskriminacnimi funkcemi')\n lindisc()\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.show"
]
] |
tennisonliu/fair-cocco
|
[
"010ad85dac7c844089af172c99e2eba95685edd7"
] |
[
"experiments/cal/students.py"
] |
[
"'''\nExperiments on student dataset.\nContinuous sensitive attribute and continuous outcome.\n'''\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport sys\nsys.path.append('.')\nimport torch\nimport torch.nn as nn\nimport torch.utils.data as data_utils\nfrom torch.utils.tensorboard import SummaryWriter\nfrom datasets import read_dataset\nimport numpy as np\nfrom fair_cocco import compute_fair_cocco\nfrom models import NetRegression\nfrom config import DEVICE\nfrom random import seed\nSEED = 0\nseed(SEED) \nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\n\nclass config:\n # NN parameters\n num_epochs = 100\n patience = 5\n batch_size = 256\n reg_batch_size = 256\n learning_rate = 1e-3\n\n # regularisation\n weight_reg = 1e-3\n fairness_reg = 0\n\n # fair_cocco\n epsilon = 1e-4\n tol = 1e-4\n max_points = 1000\n\n # model\n save_model_path = 'experiments/saved_models/cal_students.pt'\n\ndef train(verbose=True):\n x_train, x_val, x_test, y_train, y_val, y_test = read_dataset(name='students', random_state=SEED)\n input_size = x_train.shape[1]\n num_classes = 1\n\n model = NetRegression(input_size, num_classes, arch=[40, 10]).to(DEVICE)\n criterion = nn.MSELoss()\n optimiser = torch.optim.Adam(model.parameters(), lr=config.learning_rate, weight_decay=config.weight_reg)\n\n train_target = torch.tensor(y_train.values).float()\n train_data = torch.tensor(x_train.values).float()\n train_protect = torch.tensor(x_train[['age', 'sex']].values).float()\n\n train_tensor = data_utils.TensorDataset(train_data, train_target, train_protect)\n train_loader = data_utils.DataLoader(dataset=train_tensor, batch_size=config.batch_size, shuffle=True)\n \n writer = SummaryWriter()\n\n best_loss = np.inf\n training_patience = 0\n log_iter = 0\n with torch.autograd.set_detect_anomaly(True):\n for epoch in range(config.num_epochs):\n model.train()\n for i, (x, y, a) in enumerate(train_loader):\n x, y, a = x.to(DEVICE), y.to(DEVICE), a.to(DEVICE)\n\n optimiser.zero_grad()\n outputs = model(x)\n y = torch.unsqueeze(y, 1).float()\n pred_loss = criterion(outputs, y)\n\n fair_loss = config.fairness_reg * compute_fair_cocco(outputs, a, y, config.epsilon, config.tol, config.reg_batch_size)\n\n loss = pred_loss + fair_loss\n loss.backward()\n optimiser.step()\n\n if verbose:\n # acc = calc_accuracy(outputs, y)\n print('Epoch: [%d/%d], Batch: [%d/%d], Loss: %.4f, Pred Loss: %.4f, Fair Loss: %.4f' \n % (epoch+1, config.num_epochs, i, len(x_train)//config.batch_size,\n loss.item(), pred_loss.item(), fair_loss.item()))\n writer.add_scalar('Loss/train', loss.item(), log_iter)\n writer.add_scalar('PredLoss/train', pred_loss.item(), log_iter)\n writer.add_scalar('Fair-COCCO/train', fair_loss.item(), log_iter)\n log_iter += 1\n \n # validation\n with torch.no_grad():\n model.eval()\n val_target = torch.tensor(y_val.values).float().to(DEVICE)\n val_data = torch.tensor(x_val.values).float().to(DEVICE)\n val_protect = torch.tensor(x_val[['age', 'sex']].values).float().to(DEVICE)\n\n outputs = model(val_data)\n y = torch.unsqueeze(val_target, 1).float()\n pred_loss = criterion(outputs, y)\n\n fair_loss = config.fairness_reg * compute_fair_cocco(outputs, val_protect, y, config.epsilon, config.tol, 1000)\n val_loss = pred_loss + fair_loss\n\n print('\\t Validation Performance - Total Loss: %.4f, Pred Loss: %.4f, Fair-COCCO: %.4f'\n % (val_loss.item(), pred_loss.item(), fair_loss.item()))\n writer.add_scalar('Loss/val', val_loss.item(), epoch)\n writer.add_scalar('PredLoss/val', pred_loss.item(), epoch)\n writer.add_scalar('Fair-COCCO/val', fair_loss.item(), epoch)\n\n if val_loss.item() < best_loss:\n best_loss = val_loss.item()\n training_patience = 0\n torch.save(model.state_dict(), config.save_model_path)\n else:\n training_patience += 1\n if training_patience == config.patience:\n break\n\n print('\\nTraining Complete, loading best model')\n model.load_state_dict(torch.load(config.save_model_path, map_location=torch.device(DEVICE)))\n with torch.no_grad():\n model.eval()\n test_target = torch.tensor(y_test.values).float().to(DEVICE)\n test_data = torch.tensor(x_test.values).float().to(DEVICE)\n test_protect = torch.tensor(x_test[['age', 'sex']].values).float().to(DEVICE)\n\n outputs = model(test_data)\n y = torch.unsqueeze(test_target, 1).float()\n pred_loss = criterion(outputs, y)\n fair_loss = compute_fair_cocco(outputs, test_protect, y, config.epsilon, config.tol, 1000)\n test_loss = pred_loss + fair_loss\n\n print('\\t Test Performance - Total Loss: %.4f, Pred Loss: %.4f, Fair-COCCO: %.4f'\n % (test_loss.item(), pred_loss.item(), fair_loss.item()))\n writer.add_scalar('Loss/test', test_loss.item(), 0)\n writer.add_scalar('PredLoss/test', pred_loss.item(), 0)\n writer.add_scalar('Fair-COCCO/test', fair_loss.item(), 0)\n\nif __name__ == '__main__':\n train()"
] |
[
[
"torch.device",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.MSELoss",
"numpy.random.seed",
"torch.no_grad",
"torch.autograd.set_detect_anomaly",
"torch.unsqueeze",
"torch.manual_seed",
"torch.tensor",
"torch.utils.data.DataLoader",
"torch.utils.data.TensorDataset"
]
] |
Thirty-OneR/Turbulence-initial-condition
|
[
"ec8438602bdd6ec7b5985215e56ff6916b82855e"
] |
[
"convert_to_gamer_format.py"
] |
[
"import h5py\nimport numpy as np\n\ndata = {}\n\nfor field in [\"density\", \"velocity_x\", \"velocity_y\", \"velocity_z\"]:\n f = h5py.File(\"./dataset.h5\")\n data[field] = f[field][:]\n f.close()\n\n#data['density'] -= (data['density'].min() * 1.001)\ndata['density'] = (data['density']-data['density'].min())/(data['density'].max()-data['density'].min())\ndata['density']=np.maximum(data['density'],1e-16)\n\ndata[\"vx2\"] = data[\"velocity_x\"] #* (data[\"density\"]**(-1/2))\ndata[\"vy2\"] = data[\"velocity_y\"] #* (data[\"density\"]**(-1/2))\ndata[\"vz2\"] = data[\"velocity_z\"] #* (data[\"density\"]**(-1/2))\n\ndata[\"px\"] = data[\"density\"] * data[\"vx2\"]\ndata[\"py\"] = data[\"density\"] * data[\"vy2\"]\ndata[\"pz\"] = data[\"density\"] * data[\"vz2\"]\n\nN=64\ndata[\"V\"] = np.sqrt(data[\"vx2\"]**2+data[\"vy2\"]**2+data[\"vz2\"]**2)\ndata[\"P\"] = np.sqrt(data[\"px\"]**2+data[\"py\"]**2+data[\"pz\"]**2)\n#data[\"P\"] = np.ones((N,N,N))\n\ndata[\"Energy\"] = (\n 0.5 * data[\"density\"] * data[\"V\"]**2 + \n data[\"P\"]/(1.001 - 1)) \n\ndata[\"All\"] = np.asarray((data[\"density\"],data[\"px\"],data[\"py\"],data[\"pz\"],data[\"Energy\"]))\nprint(np.isnan(data[\"All\"]).sum() / data[\"All\"].size)\n\nwith open(\"UM_IC\", \"wb\") as f:\n data[\"All\"].astype(\"float32\").tofile(f)\n\n"
] |
[
[
"numpy.isnan",
"numpy.asarray",
"numpy.sqrt",
"numpy.maximum"
]
] |
aojiu/a-neural-algorithm-of-artistic-style
|
[
"6f19abf42266f61c22d7e460e5cab421e37fd8e1"
] |
[
"demo.py"
] |
[
"\nimport numpy as np\nnp.random.seed(1)\n# from tensorflow import set_random_seed\n# set_random_seed(1)\nimport tensorflow as tf\ntf.random.set_seed(1)\nfrom neural_stylization.transfer_style import Stylizer\nfrom neural_stylization.optimizers import GradientDescent, L_BFGS, Adam\nfrom neural_stylization.util.build_callback import build_callback\nfrom neural_stylization.util.img_util import load_image\nCONTENT = 'img/content/weiyao.jpg'\nload_image(CONTENT)\nsty = Stylizer(content_weight=1, style_weight=2e4)\n\nDIMS = int(1024/3), int(768/3)\n\nstarry_night = sty(\n content_path=CONTENT,\n style_path='img/styles/the-starry-night.jpg',\n optimize=L_BFGS(max_evaluations=20),\n iterations=50,\n image_size=DIMS,\n callback=build_callback('build/transfer/the-starry-night')\n)\n\nstarry_night.save('the-starry-night.png')\n\n\nscream = sty(\n content_path=CONTENT,\n style_path='img/styles/the-scream.jpg',\n optimize=L_BFGS(max_evaluations=20),\n iterations=50,\n image_size=DIMS,\n callback=build_callback('build/transfer/the-scream')\n)\n\nscream.save('the-scream.png')"
] |
[
[
"numpy.random.seed",
"tensorflow.random.set_seed"
]
] |
Rascof/tsid
|
[
"567982b46ab06522bf414cad180d941a7cc532a8"
] |
[
"exercizes/tsid_manipulator.py"
] |
[
"import pinocchio as se3\nimport tsid\nimport numpy as np\nimport numpy.matlib as matlib\nimport os\nimport gepetto.corbaserver\nimport time\nimport subprocess\n\n\nclass TsidManipulator:\n ''' Standard TSID formulation for a robot manipulator\n - end-effector task\n - Postural task\n - torque limits\n - pos/vel limits\n '''\n \n def __init__(self, conf, viewer=True):\n self.conf = conf\n vector = se3.StdVec_StdString()\n vector.extend(item for item in conf.path)\n self.robot = tsid.RobotWrapper(conf.urdf, vector, False)\n robot = self.robot\n self.model = model = robot.model()\n try:\n# q = se3.getNeutralConfiguration(model, conf.srdf, False)\n se3.loadReferenceConfigurations(model, conf.srdf, False)\n q = model.referenceConfigurations['default']\n# q = model.referenceConfigurations[\"half_sitting\"]\n except:\n q = conf.q0\n# q = np.array(np.zeros(robot.nv)).T\n v = np.zeros(robot.nv)\n \n assert model.existFrame(conf.ee_frame_name)\n \n formulation = tsid.InverseDynamicsFormulationAccForce(\"tsid\", robot, False)\n formulation.computeProblemData(0.0, q, v)\n \n postureTask = tsid.TaskJointPosture(\"task-posture\", robot)\n postureTask.setKp(conf.kp_posture * np.ones(robot.nv))\n postureTask.setKd(2.0 * np.sqrt(conf.kp_posture) * np.ones(robot.nv))\n formulation.addMotionTask(postureTask, conf.w_posture, 1, 0.0)\n \n self.eeTask = tsid.TaskSE3Equality(\"task-ee\", self.robot, self.conf.ee_frame_name)\n self.eeTask.setKp(self.conf.kp_ee * np.ones(6))\n self.eeTask.setKd(2.0 * np.sqrt(self.conf.kp_ee) * np.ones(6))\n self.eeTask.setMask(conf.ee_task_mask)\n self.eeTask.useLocalFrame(False)\n self.EE = model.getFrameId(conf.ee_frame_name)\n H_ee_ref = self.robot.framePosition(formulation.data(), self.EE)\n self.trajEE = tsid.TrajectorySE3Constant(\"traj-ee\", H_ee_ref)\n formulation.addMotionTask(self.eeTask, conf.w_ee, 1, 0.0)\n \n self.tau_max = conf.tau_max_scaling*model.effortLimit\n self.tau_min = -self.tau_max\n actuationBoundsTask = tsid.TaskActuationBounds(\"task-actuation-bounds\", robot)\n actuationBoundsTask.setBounds(self.tau_min, self.tau_max)\n if(conf.w_torque_bounds>0.0):\n formulation.addActuationTask(actuationBoundsTask, conf.w_torque_bounds, 0, 0.0)\n \n jointBoundsTask = tsid.TaskJointBounds(\"task-joint-bounds\", robot, conf.dt)\n self.v_max = conf.v_max_scaling * model.velocityLimit\n self.v_min = -self.v_max\n jointBoundsTask.setVelocityBounds(self.v_min, self.v_max)\n if(conf.w_joint_bounds>0.0):\n formulation.addMotionTask(jointBoundsTask, conf.w_joint_bounds, 0, 0.0)\n \n trajPosture = tsid.TrajectoryEuclidianConstant(\"traj_joint\", q)\n postureTask.setReference(trajPosture.computeNext())\n \n solver = tsid.SolverHQuadProgFast(\"qp solver\")\n solver.resize(formulation.nVar, formulation.nEq, formulation.nIn)\n \n self.trajPosture = trajPosture\n self.postureTask = postureTask\n self.actuationBoundsTask = actuationBoundsTask\n self.jointBoundsTask = jointBoundsTask\n self.formulation = formulation\n self.solver = solver\n self.q = q\n self.v = v\n \n # for gepetto viewer\n if(viewer):\n self.robot_display = se3.RobotWrapper.BuildFromURDF(conf.urdf, [conf.path, ])\n l = subprocess.getstatusoutput(\"ps aux |grep 'gepetto-gui'|grep -v 'grep'|wc -l\")\n if int(l[1]) == 0:\n os.system('gepetto-gui &')\n time.sleep(1)\n gepetto.corbaserver.Client()\n self.robot_display.initViewer(loadModel=True)\n self.robot_display.displayCollisions(False)\n self.robot_display.displayVisuals(True)\n self.robot_display.display(q)\n self.gui = self.robot_display.viewer.gui\n# self.gui.setCameraTransform(0, conf.CAMERA_TRANSFORM)\n \n def integrate_dv(self, q, v, dv, dt):\n v_mean = v + 0.5*dt*dv\n v += dt*dv\n q = se3.integrate(self.model, q, dt*v_mean)\n return q,v\n"
] |
[
[
"numpy.ones",
"numpy.sqrt",
"numpy.zeros"
]
] |
yss-al/dssgd
|
[
"df92025783e3589f1cd6cf6b943735d756601612"
] |
[
"models/Nets.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Python version: 3.6\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass MLP(nn.Module):\n def __init__(self, dim_in, dim_hidden, dim_out):\n super(MLP, self).__init__()\n self.layer_input = nn.Linear(dim_in, dim_hidden)\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout()\n self.layer_hidden = nn.Linear(dim_hidden, dim_out)\n\n def forward(self, x):\n x = x.view(-1, x.shape[1]*x.shape[-2]*x.shape[-1])\n x = self.layer_input(x)\n x = self.dropout(x)\n x = self.relu(x)\n x = self.layer_hidden(x)\n return x\n\n\nclass CNNMnist(nn.Module):\n def __init__(self, args):\n super(CNNMnist, self).__init__()\n self.conv1 = nn.Conv2d(args.num_channels, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, args.num_classes)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, x.shape[1]*x.shape[2]*x.shape[3])\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return x\n\n\nclass CNNCifar(nn.Module):\n def __init__(self, args):\n super(CNNCifar, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, args.num_classes)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.nn.MaxPool2d",
"torch.nn.functional.dropout",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.Dropout2d"
]
] |
telegraphic/PyGSM
|
[
"af96a21ec2d735ccada31ef2d9ad1b8895dfc613"
] |
[
"pygsm/pygsm2016.py"
] |
[
"#from .pygsm import GlobalSkyModel\n\nimport numpy as np\nfrom scipy.interpolate import interp1d, pchip\nimport h5py\nfrom astropy import units\nimport healpy as hp\nimport ephem\nfrom datetime import datetime\n\nfrom pkg_resources import resource_filename\nGSM2016_FILEPATH = resource_filename(\"pygsm\", \"gsm2016_components.h5\")\n\nkB = 1.38065e-23\nC = 2.99792e8\nh = 6.62607e-34\nT = 2.725\nhoverk = h / kB\n\ndef K_CMB2MJysr(K_CMB, nu):#in Kelvin and Hz\n B_nu = 2 * (h * nu)* (nu / C)**2 / (np.exp(hoverk * nu / T) - 1)\n conversion_factor = (B_nu * C / nu / T)**2 / 2 * np.exp(hoverk * nu / T) / kB\n return K_CMB * conversion_factor * 1e20#1e-26 for Jy and 1e6 for MJy\n\ndef K_RJ2MJysr(K_RJ, nu):#in Kelvin and Hz\n conversion_factor = 2 * (nu / C)**2 * kB\n return K_RJ * conversion_factor * 1e20#1e-26 for Jy and 1e6 for MJy\n\n\ndef rotate_map(hmap, rot_theta, rot_phi, nest=True):\n nside = hp.npix2nside(len(hmap))\n\n # Get theta, phi for non-rotated map\n t, p = hp.pix2ang(nside, np.arange(hp.nside2npix(nside)), nest= nest) # theta, phi\n\n # Define a rotator\n r = hp.Rotator(deg=False, rot=[rot_phi, rot_theta])\n\n # Get theta, phi under rotated co-ordinates\n trot, prot = r(t, p)\n\n # Inerpolate map onto these co-ordinates\n rot_map = hp.get_interp_val(hmap, trot, prot, nest= nest)\n\n return rot_map\n\n\nclass GlobalSkyModel2016(object):\n \"\"\" Global sky model (GSM) class for generating sky models.\n \"\"\"\n\n def __init__(self, freq_unit='MHz', unit='TCMB', resolution='hi', theta_rot=0, phi_rot=0):\n \"\"\" Global sky model (GSM) class for generating sky models.\n\n Upon initialization, the map PCA data are loaded into memory and interpolation\n functions are pre-computed.\n\n Parameters\n ----------\n freq_unit: 'Hz', 'MHz', or 'GHz'\n Unit of frequency. Defaults to 'MHz'.\n unit: 'MJysr', 'TCMB', 'TRJ'\n Unit of output data. MJy/Steradian, T_CMB in Kelvin, or T_RJ.\n resolution: 'hi' or 'low'\n Resolution of output map. Either 300 arcmin (low) or 24 arcmin (hi).\n For frequencies under 10 GHz, output is 48 arcmin.\n\n Notes\n -----\n\n \"\"\"\n\n if unit not in ['MJysr', 'TCMB', 'TRJ']:\n raise RuntimeError(\"UNIT ERROR: %s not supported. Only MJysr, TCMB, TRJ are allowed.\" % unit)\n\n if resolution.lower() in ('hi', 'high', 'h'):\n resolution = 'hi'\n elif resolution.lower() in ('low', 'lo', 'l'):\n resolution = 'low'\n else:\n raise RuntimeError(\"RESOLUTION ERROR: Must be either hi or low, not %s\" % resolution)\n\n self.h5 = h5py.File(GSM2016_FILEPATH, \"r\")\n self.freq_unit = freq_unit\n self.unit = unit\n self.resolution = resolution\n\n # Map data to load\n labels = ['Synchrotron', 'CMB', 'HI', 'Dust1', 'Dust2', 'Free-Free']\n self.n_comp = len(labels)\n\n if resolution=='hi':\n self.map_ni = np.array([self.h5['highres_%s_map'%lb][:] for lb in labels])\n else:\n self.map_ni = np.array(self.h5['lowres_maps'])\n\n self.spec_nf = self.h5['spectra'][:]\n\n if theta_rot or phi_rot:\n for i,map in enumerate(self.map_ni):\n self.map_ni[i] = rotate_map(map, theta_rot, phi_rot, nest=True)\n\n self.generated_map_data = None\n self.generated_map_freqs = None\n\n def generate(self, freqs):\n \"\"\" Generate a global sky model at a given frequency or frequencies\n\n Parameters\n ----------\n freqs: float or np.array\n Frequency for which to return GSM model\n\n Returns\n -------\n gsm: np.array\n Global sky model in healpix format, with NSIDE=1024. Output map\n is in galactic coordinates, ring format.\n\n \"\"\"\n\n # convert frequency values into Hz\n freqs = np.array(freqs) * units.Unit(self.freq_unit)\n freqs_ghz = freqs.to('GHz').value\n\n if isinstance(freqs_ghz, float):\n freqs_ghz = np.array([freqs_ghz])\n\n try:\n assert np.min(freqs_ghz) >= 0.01\n assert np.max(freqs_ghz) <= 5000\n except AssertionError:\n raise RuntimeError(\"Frequency values lie outside 10 MHz < f < 5 THz: %s\")\n\n map_ni = self.map_ni\n # if self.resolution == 'hi':\n # map_ni = self.map_ni_hr\n # else:\n # map_ni = self.map_ni_lr\n\n spec_nf = self.spec_nf\n nfreq = spec_nf.shape[1]\n\n output = np.zeros((len(freqs_ghz), map_ni.shape[1]), dtype='float32')\n for ifreq, freq in enumerate(freqs_ghz):\n\n left_index = -1\n for i in range(nfreq - 1):\n if spec_nf[0, i] <= freq <= spec_nf[0, i + 1]:\n left_index = i\n break\n\n # Do the interpolation\n interp_spec_nf = np.copy(spec_nf)\n interp_spec_nf[0:2] = np.log10(interp_spec_nf[0:2])\n x1 = interp_spec_nf[0, left_index]\n x2 = interp_spec_nf[0, left_index + 1]\n y1 = interp_spec_nf[1:, left_index]\n y2 = interp_spec_nf[1:, left_index + 1]\n x = np.log10(freq)\n interpolated_vals = (x * (y2 - y1) + x2 * y1 - x1 * y2) / (x2 - x1)\n output[ifreq] = np.sum(10.**interpolated_vals[0] * (interpolated_vals[1:, None] * map_ni), axis=0)\n\n output[ifreq] = hp.pixelfunc.reorder(output[ifreq], n2r=True)\n\n if self.unit == 'TCMB':\n conversion = 1. / K_CMB2MJysr(1., 1e9 * freq)\n elif self.unit == 'TRJ':\n conversion = 1. / K_RJ2MJysr(1., 1e9 * freq)\n else:\n conversion = 1.\n output[ifreq] *= conversion\n\n# output.append(result)\n\n if len(output) == 1:\n output = output[0]\n #else:\n # map_data = np.row_stack(output)\n\n self.generated_map_freqs = freqs\n self.generated_map_data = output\n\n return output\n\n\n def view(self, idx=0, logged=False):\n \"\"\" View generated map using healpy's mollweide projection.\n\n Parameters\n ----------\n idx: int\n index of map to view. Only required if you generated maps at\n multiple frequencies.\n logged: bool\n Take the log of the data before plotting. Defaults to False.\n\n \"\"\"\n\n if self.generated_map_data is None:\n raise RuntimeError(\"No GSM map has been generated yet. Run generate() first.\")\n\n if self.generated_map_data.ndim == 2:\n gmap = self.generated_map_data[idx]\n freq = self.generated_map_freqs[idx]\n else:\n gmap = self.generated_map_data\n freq = self.generated_map_freqs\n\n if logged:\n gmap = np.log2(gmap)\n\n hp.mollview(gmap, coord='G',\n title='Global Sky Model %s %s' % (str(freq), self.unit))\n if not plt:\n import pylab as plt\n plt.show()\n\n def write_fits(self, filename):\n \"\"\" Write out map data as FITS file.\n\n Parameters\n ----------\n filename: str\n file name for output FITS file\n \"\"\"\n hp.write_map(filename, self.generated_map_data, column_units=self.unit)\n\nclass GSMObserver2016(ephem.Observer):\n \"\"\" Observer of the Global Sky Model.\n\n Generates the Observed sky, for a given point on Earth.\n Applies the necessary rotations and coordinate transformations\n so that the observed 'sky' can be returned, instead of the\n full galaxy-centered GSM.\n\n This class is based on pyephem's Observer(). The GSM bit can be thought of\n as an 'add on' to ephem.Observer, adding the methods generate() and view(),\n which allows all-sky images for a given point on earth to be produced.\n \"\"\"\n\n def __init__(self):\n \"\"\" Initialize the Observer object.\n\n Calls ephem.Observer.__init__ function and adds on gsm\n \"\"\"\n super(GSMObserver2016, self).__init__()\n self.gsm = GlobalSkyModel2016(freq_unit='MHz')\n self.observed_sky = None\n\n # Generate mapping from pix <-> angles\n self.gsm.generate(1000)\n self._n_pix = hp.get_map_size(self.gsm.generated_map_data)\n self._n_side = hp.npix2nside(self._n_pix)\n self._theta, self._phi = hp.pix2ang(self._n_side, np.arange(self._n_pix))\n\n def generate(self, freq):\n \"\"\" Generate the observed sky for the observer, based on the GSM.\n\n Parameters\n ----------\n freq: float\n Frequency of map to generate, in units of MHz (default).\n\n Returns\n -------\n observed_sky: np.array\n Numpy array representing the healpix image, centered on zenith,\n with below the horizon masked.\n \"\"\"\n self.gsm.generate(freq)\n sky = self.gsm.generated_map_data\n\n # Get RA and DEC of zenith\n ra_rad, dec_rad = self.radec_of(0, np.pi/2)\n ra_deg = ra_rad / np.pi * 180\n dec_deg = dec_rad / np.pi * 180\n\n # Apply rotation\n hrot = hp.Rotator(rot=[ra_deg, dec_deg], coord=['G', 'C'], inv=True)\n g0, g1 = hrot(self._theta, self._phi)\n pix0 = hp.ang2pix(self._n_side, g0, g1)\n sky_rotated = sky[pix0]\n\n # Generate a mask for below horizon\n mask1 = self._phi + np.pi / 2 > 2 * np.pi\n mask2 = self._phi < np.pi / 2\n mask = np.invert(np.logical_or(mask1, mask2))\n\n self.observed_sky = hp.ma(sky_rotated)\n self.observed_sky.mask = mask\n\n return self.observed_sky\n\n\n def view(self, logged=False, show=False, **kwargs):\n \"\"\" View the local sky, in orthographic projection.\n\n Parameters\n ----------\n logged: bool\n Default False, return the log2 image\n \"\"\"\n sky = self.observed_sky\n if logged:\n sky = np.log2(sky)\n\n hp.orthview(sky, half_sky=True, **kwargs)\n\n if show:\n if not plt:\n import pylab as plt\n plt.show()\n\n return sky\n\n def view_observed_gsm(self, logged=False, show=False, **kwargs):\n \"\"\" View the GSM (Mollweide), with below-horizon area masked. \"\"\"\n sky = self.observed_sky\n if logged:\n sky = np.log2(sky)\n\n # Get RA and DEC of zenith\n ra_rad, dec_rad = self.radec_of(0, np.pi / 2)\n ra_deg = ra_rad / np.pi * 180\n dec_deg = dec_rad / np.pi * 180\n\n # Apply rotation\n derotate = hp.Rotator(rot=[ra_deg, dec_deg])\n g0, g1 = derotate(self._theta, self._phi)\n pix0 = hp.ang2pix(self._n_side, g0, g1)\n sky = sky[pix0]\n\n coordrotate = hp.Rotator(coord=['C', 'G'], inv=True)\n g0, g1 = coordrotate(self._theta, self._phi)\n pix0 = hp.ang2pix(self._n_side, g0, g1)\n sky = sky[pix0]\n\n hp.mollview(sky, coord='G', **kwargs)\n\n if show:\n if not plt:\n import pylab as plt\n plt.show()\n\n return sky\n\n\n"
] |
[
[
"numpy.max",
"numpy.logical_or",
"numpy.array",
"numpy.sum",
"numpy.copy",
"numpy.exp",
"numpy.min",
"numpy.arange",
"numpy.log10",
"numpy.log2"
]
] |
MPinna/epidemic_broadcast
|
[
"c8c2cbe9c6398c7ed3a68749892b438bceca629a"
] |
[
"python/test.py"
] |
[
"#!/usr/bin/env python\n\nimport scipy.stats\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef mean_confidence_interval(data, confidence=0.95):\n a = 1.0 * np.array(data)\n n = len(a)\n m, se = np.mean(a), scipy.stats.sem(a)\n h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)\n return m, m-h, m+h\ndef lorenz_curve(X):\n X_lorenz = X.cumsum() / X.sum()\n X_lorenz = np.insert(X_lorenz, 0, 0) \n X_lorenz[0], X_lorenz[-1]\n fig, ax = plt.subplots(figsize=[6,6])\n ## scatter plot of Lorenz curve\n ax.scatter(np.arange(X_lorenz.size)/(X_lorenz.size-1), X_lorenz, \n marker='.', color='darkgreen', s=100)\n ## line plot of equality\n ax.plot([0,1], [0,1], color='k')\ndf = pd.read_csv('small04-2.csv')\n\n# average number of collisions\ncollisionsDF = df[df['name'] == 'packetDropIncorrectlyReceived:count']\ncollisionsDF = collisionsDF[['run', 'module', 'name', 'value']]\ncollisionsDF = collisionsDF.groupby([\"run\", \"module\"], as_index = False)[\"value\"].first()\nusersDF = collisionsDF.groupby([\"module\"], as_index = False)[\"value\"].first()\nusers = len(usersDF.index)\ncollisionsDF = collisionsDF.groupby([\"run\"], as_index = False)[\"value\"].sum()\na, b, c = mean_confidence_interval(collisionsDF['value'])\nmes=np.array(collisionsDF['value'])\nprint(mes)\n\n# autocorrelation plot\npd.plotting.autocorrelation_plot(mes)\nplt.show()\n\n# scatterplot example\nplt.scatter(x=np.arange(1,2,0.01), y=mes)\nplt.scatter(x=np.arange(3,4,0.01), y=mes)\n#plt.show()\n\n# showing confidence inetrvals\nfig, ax = plt.subplots(figsize=[6,6])\nplt.errorbar(x=1, y=a, yerr=a-b, color=\"black\", capsize=3,\n linestyle=\"None\",\n marker=\"s\", markersize=7, mfc=\"black\", mec=\"black\")\nplt.errorbar(x=2, y=a+3, yerr=a-b, color=\"black\", capsize=3,\n linestyle=\"None\",\n marker=\"s\", markersize=7, mfc=\"black\", mec=\"black\")\n#plt.show()\n\n# histograms\nbins= plt.hist(x=mes, bins=\"auto\", color='#0504aa',\n alpha=0.7, rwidth=0.85)\nplt.grid(axis='y', alpha=0.75)\nplt.xlabel('Value')\nplt.ylabel('Frequency')\nplt.title('My Very Own Histogram')\n#plt.show()\n\n#lorenz curve\nlorenz_curve(mes)\n#plt.show()\n\n# QQ plots\nscipy.stats.probplot(np.array(collisionsDF['value']),dist=scipy.stats.chi2(df=40) , plot=plt)\n#scipy.stats.probplot(np.array(collisionsDF['value']),dist=scipy.stats.erlang(a=44) , plot=plt)\n#scipy.stats.probplot(np.array(collisionsDF['value']),dist=scipy.stats.poisson(mu=a, loc=100) , plot=plt)\n#scipy.stats.probplot(mes, fit=False,dist=scipy.stats.norm(loc=a, scale=np.std(mes)) , plot=plt)\n\n\n# percentage of covered users\ncoverageDF = df[df['name'] == 'timeCoverageStat:vector']\ncoverageDF = coverageDF[['run', 'module', 'name', 'value', 'vectime', 'vecvalue']]\nvectimeDF = coverageDF.groupby([\"run\"], as_index = False)[\"vectime\"].first()\nrepetitions = len(vectimeDF.index)\nvecvalueDF = coverageDF.groupby([\"run\"], as_index = False)[\"vecvalue\"].first()\ntotalCoverage = []\ntotalCoverageSlot = []\nfor i in range(len(vecvalueDF.index)):\n coverageList = list(map(int, vecvalueDF[\"vecvalue\"][i].split()))\n coverage = len(coverageList)\n totalCoverage.append(coverage/float(users))\n totalCoverageSlot.append(coverageList[len(coverageList)-1])\n\nd, e, f = mean_confidence_interval(totalCoverage)\n#mes=np.array(totalCoverage)\n#scipy.stats.probplot(mes,dist= , plot=plt)\n#plt.show()\ng, h, i = mean_confidence_interval(totalCoverageSlot)\n\nprint(\"REPETITIONS: \" + str(repetitions))\nprint(\"USERS: \" + str(users) + \"\\n\")\nprint(\"COLLISIONS MEAN:\")\nprint(a)\nprint(b)\nprint(c)\nprint(\"\\nCOVERAGE MEAN:\")\nprint(d)\nprint(e)\nprint(f)\nprint(\"\\nTOTAL BROADCAST TIME:\")\nprint(g)\nprint(h)\nprint(i)\n"
] |
[
[
"numpy.array",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"pandas.plotting.autocorrelation_plot",
"matplotlib.pyplot.subplots",
"numpy.mean",
"matplotlib.pyplot.hist",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show",
"pandas.read_csv",
"numpy.insert"
]
] |
lyp-deeplearning/MOS-Multi-Task-Face-Detect
|
[
"1bea754752e13fafdeb06f5fedcba1bd08e836de"
] |
[
"test_scripts/detect_picture.py"
] |
[
"from __future__ import print_function\nimport os\nimport argparse\nimport torch\nimport torch.backends.cudnn as cudnn\nfrom PIL import Image\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport numpy as np\nimport time\nfrom data.config import cfg_mobilenetv2\nfrom layers.functions.prior_box import PriorBox\nfrom utils.nms.py_cpu_nms import py_cpu_nms\nimport cv2\nfrom models.retinaface_mbv2 import RetinaFace\nimport math\nfrom math import cos, sin\nfrom utils.box_utils import decode, decode_landm\nfrom utils.timer import Timer\nimport torch.nn.functional as F\nimport matplotlib.cm\nimport copy\n\n\nfrom scipy.spatial.transform import Rotation\nfrom matplotlib import pyplot as plt\n\n\nparser = argparse.ArgumentParser(description='Test')\nparser.add_argument('-m', '--trained_model', default='/home/lyp/mos_source_code_open/MOS-Multi-Task-Face-Detect/pt17_pose_weights_mbv2/mobilenetv2_epoch_249.pth',\n type=str, help='Trained state_dict file path to open')\nparser.add_argument('--network', default='shuffle_0.5', help='Backbone network mobile0.25 or slim or RFB')\nparser.add_argument('--origin_size', default=True, type=str, help='Whether use origin image size to evaluate')\nparser.add_argument('--long_side', default=840, help='when origin_size is false, long_side is scaled size(320 or 640 for long side)')\nparser.add_argument('--save_folder', default='./widerface_evaluate/widerface_txt/', type=str, help='Dir to save txt results')\nparser.add_argument('--cpu', action=\"store_true\", default=True, help='Use cpu inference')\nparser.add_argument('--confidence_threshold', default=0.55, type=float, help='confidence_threshold')\nparser.add_argument('--top_k', default=5000, type=int, help='top_k')\nparser.add_argument('--nms_threshold', default=0.4, type=float, help='nms_threshold')\nparser.add_argument('--keep_top_k', default=750, type=int, help='keep_top_k')\nparser.add_argument('--save_image', action=\"store_true\", default=True, help='show detection results')\nparser.add_argument('--vis_thres', default=0.55, type=float, help='visualization_threshold')\nargs = parser.parse_args()\ndef get_pose(vertices, twod_landmarks, camera_intrinsics, initial_pose=None):\n threed_landmarks = vertices\n twod_landmarks = np.asarray(twod_landmarks).astype(\"float32\")\n\n # if initial_pose is provided, use it as a guess to solve new pose\n if initial_pose is not None:\n initial_pose = np.asarray(initial_pose)\n retval, rvecs, tvecs = cv2.solvePnP(\n threed_landmarks,\n twod_landmarks,\n camera_intrinsics,\n None,\n rvec=initial_pose[:3],\n tvec=initial_pose[3:],\n flags=cv2.SOLVEPNP_EPNP,\n useExtrinsicGuess=True,\n )\n else:\n retval, rvecs, tvecs = cv2.solvePnP(\n threed_landmarks,\n twod_landmarks,\n camera_intrinsics,\n None,\n flags=cv2.SOLVEPNP_EPNP,\n )\n\n rotation_mat = np.zeros(shape=(3, 3))\n R = cv2.Rodrigues(rvecs, rotation_mat)[0]\n\n RT = np.column_stack((R, tvecs))\n P = np.matmul(camera_intrinsics, RT)\n dof = np.append(rvecs, tvecs)\n\n return P, dof\ndef bbox_is_dict(bbox):\n # check if the bbox is a not dict and convert it if needed\n if not isinstance(bbox, dict):\n temp_bbox = {}\n temp_bbox[\"left\"] = bbox[0]\n temp_bbox[\"top\"] = bbox[1]\n temp_bbox[\"right\"] = bbox[2]\n temp_bbox[\"bottom\"] = bbox[3]\n bbox = temp_bbox\n\n return bbox\n\n\ndef get_bbox_intrinsics(image_intrinsics, bbox):\n # crop principle point of view\n bbox_center_x = bbox[\"left\"] + ((bbox[\"right\"] - bbox[\"left\"]) // 2)\n bbox_center_y = bbox[\"top\"] + ((bbox[\"bottom\"] - bbox[\"top\"]) // 2)\n\n # create a camera intrinsics from the bbox center\n bbox_intrinsics = image_intrinsics.copy()\n bbox_intrinsics[0, 2] = bbox_center_x\n bbox_intrinsics[1, 2] = bbox_center_y\n\n return bbox_intrinsics\n\n\ndef pose_bbox_to_full_image(pose, image_intrinsics, bbox):\n # check if bbox is np or dict\n bbox = bbox_is_dict(bbox)\n\n # rotation vector\n rvec = pose[:3].copy()\n\n # translation and scale vector\n tvec = pose[3:].copy()\n\n # get camera intrinsics using bbox\n bbox_intrinsics = get_bbox_intrinsics(image_intrinsics, bbox)\n\n # focal length\n focal_length = image_intrinsics[0, 0]\n\n # bbox_size\n bbox_width = bbox[\"right\"] - bbox[\"left\"]\n bbox_height = bbox[\"bottom\"] - bbox[\"top\"]\n bbox_size = bbox_width + bbox_height\n\n # adjust scale\n tvec[2] *= focal_length / bbox_size\n\n # project crop points using the crop camera intrinsics\n projected_point = bbox_intrinsics.dot(tvec.T)\n\n # reverse the projected points using the full image camera intrinsics\n tvec = projected_point.dot(np.linalg.inv(image_intrinsics.T))\n\n # same for rotation\n rmat = Rotation.from_rotvec(rvec).as_matrix()\n # project crop points using the crop camera intrinsics\n projected_point = bbox_intrinsics.dot(rmat)\n # reverse the projected points using the full image camera intrinsics\n rmat = np.linalg.inv(image_intrinsics).dot(projected_point)\n rvec = Rotation.from_matrix(rmat).as_rotvec()\n\n return np.concatenate([rvec, tvec])\n\ndef check_keys(model, pretrained_state_dict):\n ckpt_keys = set(pretrained_state_dict.keys())\n model_keys = set(model.state_dict().keys())\n used_pretrained_keys = model_keys & ckpt_keys\n unused_pretrained_keys = ckpt_keys - model_keys\n missing_keys = model_keys - ckpt_keys\n print('Missing keys:{}'.format(len(missing_keys)))\n print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys)))\n print('Used keys:{}'.format(len(used_pretrained_keys)))\n assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint'\n return True\n\n\ndef remove_prefix(state_dict, prefix):\n ''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''\n print('remove prefix \\'{}\\''.format(prefix))\n f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x\n return {f(key): value for key, value in state_dict.items()}\n\n\ndef load_model(model, pretrained_path, load_to_cpu):\n print('Loading pretrained model from {}'.format(pretrained_path))\n if load_to_cpu:\n pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage)\n else:\n device = torch.cuda.current_device()\n pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device))\n if \"state_dict\" in pretrained_dict.keys():\n pretrained_dict = remove_prefix(pretrained_dict['state_dict'], 'module.')\n else:\n pretrained_dict = remove_prefix(pretrained_dict, 'module.')\n check_keys(model, pretrained_dict)\n model.load_state_dict(pretrained_dict, strict=False)\n return model\n\n\ndef plot_pose_cube(img, yaw, pitch, roll, tdx=None, tdy=None, size=150.):\n # Input is a cv2 image\n # pose_params: (pitch, yaw, roll, tdx, tdy)\n # Where (tdx, tdy) is the translation of the face.\n # For pose we have [pitch yaw roll tdx tdy tdz scale_factor]\n\n p = pitch * np.pi / 180\n y = -(yaw * np.pi / 180)\n r = roll * np.pi / 180\n if tdx != None and tdy != None:\n face_x = tdx - 0.50 * size\n face_y = tdy - 0.50 * size\n else:\n height, width = img.shape[:2]\n face_x = width / 2 - 0.5 * size\n face_y = height / 2 - 0.5 * size\n\n x1 = size * (cos(y) * cos(r)) + face_x\n y1 = size * (cos(p) * sin(r) + cos(r) * sin(p) * sin(y)) + face_y\n x2 = size * (-cos(y) * sin(r)) + face_x\n y2 = size * (cos(p) * cos(r) - sin(p) * sin(y) * sin(r)) + face_y\n x3 = size * (sin(y)) + face_x\n y3 = size * (-cos(y) * sin(p)) + face_y\n\n # Draw base in red\n cv2.line(img, (int(face_x), int(face_y)), (int(x1),int(y1)),(0,0,255),3)\n cv2.line(img, (int(face_x), int(face_y)), (int(x2),int(y2)),(0,0,255),3)\n cv2.line(img, (int(x2), int(y2)), (int(x2+x1-face_x),int(y2+y1-face_y)),(0,0,255),3)\n cv2.line(img, (int(x1), int(y1)), (int(x1+x2-face_x),int(y1+y2-face_y)),(0,0,255),3)\n # Draw pillars in blue\n cv2.line(img, (int(face_x), int(face_y)), (int(x3),int(y3)),(255,0,0),2)\n cv2.line(img, (int(x1), int(y1)), (int(x1+x3-face_x),int(y1+y3-face_y)),(255,0,0),2)\n cv2.line(img, (int(x2), int(y2)), (int(x2+x3-face_x),int(y2+y3-face_y)),(255,0,0),2)\n cv2.line(img, (int(x2+x1-face_x),int(y2+y1-face_y)), (int(x3+x1+x2-2*face_x),int(y3+y2+y1-2*face_y)),(255,0,0),2)\n # Draw top in green\n cv2.line(img, (int(x3+x1-face_x),int(y3+y1-face_y)), (int(x3+x1+x2-2*face_x),int(y3+y2+y1-2*face_y)),(0,255,0),2)\n cv2.line(img, (int(x2+x3-face_x),int(y2+y3-face_y)), (int(x3+x1+x2-2*face_x),int(y3+y2+y1-2*face_y)),(0,255,0),2)\n cv2.line(img, (int(x3), int(y3)), (int(x3+x1-face_x),int(y3+y1-face_y)),(0,255,0),2)\n cv2.line(img, (int(x3), int(y3)), (int(x3+x2-face_x),int(y3+y2-face_y)),(0,255,0),2)\n\n return img\n\ndef draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size = 100):\n\n pitch = pitch * np.pi / 180\n yaw = -(yaw * np.pi / 180)\n roll = roll * np.pi / 180\n\n if tdx != None and tdy != None:\n tdx = tdx\n tdy = tdy\n else:\n height, width = img.shape[:2]\n tdx = width / 2\n tdy = height / 2\n\n # X-Axis pointing to right. drawn in red\n x1 = size * (cos(yaw) * cos(roll)) + tdx\n y1 = size * (cos(pitch) * sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) + tdy\n\n # Y-Axis | drawn in green\n # v\n x2 = size * (-cos(yaw) * sin(roll)) + tdx\n y2 = size * (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) + tdy\n\n # Z-Axis (out of the screen) drawn in blue\n x3 = size * (sin(yaw)) + tdx\n y3 = size * (-cos(yaw) * sin(pitch)) + tdy\n\n cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3)\n cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3)\n cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),4)\n\n return img\n\np_in = []\np_out = []\n\n#\ndef hook_fn(module, inputs, outputs):\n p_in.append(inputs)\n p_out.append(outputs)\n\ndef put_heatmap_on_image(ori_image, activation, colormap_name):\n \"\"\"\n ori_image (PIL image): 原始图像\n activation (numpy arr): 即上面得到的p2_logits\n colormap_name (str): 采用何种matplotlib.cm的colormap\n \"\"\"\n # colormap\n color_map = matplotlib.cm.get_cmap(colormap_name)\n # 把colormap添加到activation,即activation的以何种\n # colormap进行显示\n no_trans_heatmap = color_map(activation)\n # 添加alpha通道,即透明度\n heatmap = copy.copy(no_trans_heatmap)\n heatmap[:, :, 3] = 0.4\n heatmap = Image.fromarray((heatmap*255).astype(np.uint8))\n no_trans_heatmap = Image.fromarray((no_trans_heatmap*255).astype(np.uint8))\n #\n heatmap_on_image = Image.new(\"RGBA\", ori_image.size)\n heatmap_on_image = Image.alpha_composite(\n \t\t\t\t\theatmap_on_image, ori_image.convert(\"RGBA\"))\n heatmap_on_image = Image.alpha_composite(\n \t\t\t\t\theatmap_on_image, heatmap)\n return no_trans_heatmap, heatmap_on_image\n\n\ndef rot2Euler(imgpath, rotation_vector):\n # calculate rotation angles\n theta = cv2.norm(rotation_vector, cv2.NORM_L2)\n\n # transformed to quaterniond\n w = math.cos(theta / 2)\n x = math.sin(theta / 2) * rotation_vector[0][0] / theta\n y = math.sin(theta / 2) * rotation_vector[1][0] / theta\n z = math.sin(theta / 2) * rotation_vector[2][0] / theta\n\n ysqr = y * y\n # pitch (x-axis rotation)\n t0 = 2.0 * (w * x + y * z)\n t1 = 1.0 - 2.0 * (x * x + ysqr)\n print('t0:{}, t1:{}'.format(t0, t1))\n pitch = math.atan2(t0, t1) - 0.8356857\n\n # yaw (y-axis rotation)\n t2 = 2.0 * (w * y - z * x)\n if t2 > 1.0:\n t2 = 1.0\n if t2 < -1.0:\n t2 = -1.0\n yaw = math.asin(t2) + 0.005409\n\n # roll (z-axis rotation)\n t3 = 2.0 * (w * z + x * y)\n t4 = 1.0 - 2.0 * (ysqr + z * z)\n roll = math.atan2(t3, t4) - 2.573345436\n\n # 单位转换:将弧度转换为度\n pitch_degree = int((pitch / math.pi) * 180)\n yaw_degree = int((yaw / math.pi) * 180)\n roll_degree = int((roll / math.pi) * 180)\n\n #drawResult(imgpath, yaw, pitch, roll, save_dir)\n\n print(\"Radians:\")\n print(\"Yaw:\", yaw_degree)\n print(\"Pitch:\", pitch_degree)\n print(\"Roll:\", roll_degree)\n str_angle=[yaw_degree,pitch_degree,roll_degree]\n return str_angle\n # img = cv2.imread(imgpath)\n # draw = img.copy()\n # cv2.putText(draw, \"Yaw:\" + str(yaw), (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))\n # cv2.putText(draw, \"Pitch:\" + str(pitch), (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))\n # cv2.putText(draw, \"Roll:\" + str(roll), (20, 120), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))\n # cv2.waitKey()\n # cv2.imwrite(os.path.splitext(imgpath)[0] + '_pose_estimate1.jpg', draw)\n #\n # print(\"Degrees:\")\n # draw = img.copy()\n # if yaw_degree > 0:\n # output_yaw = \"face turns left:\" + str(abs(yaw_degree)) + \" degrees\"\n # cv2.putText(draw, output_yaw, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 0))\n # print(output_yaw)\n # if yaw_degree < 0:\n # output_yaw = \"face turns right:\" + str(abs(yaw_degree)) + \" degrees\"\n # cv2.putText(draw, output_yaw, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 0))\n # print(output_yaw)\n # if pitch_degree < 0:\n # output_pitch = \"face downwards:\" + str(abs(pitch_degree)) + \" degrees\"\n # cv2.putText(draw, output_pitch, (20, 80), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 0))\n # print(output_pitch)\n # if pitch_degree > 0:\n # output_pitch = \"face upwards:\" + str(abs(pitch_degree)) + \" degrees\"\n # cv2.putText(draw, output_pitch, (20, 80), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 0))\n # print(output_pitch)\n # if roll_degree < 0:\n # output_roll = \"face bends to the right:\" + str(abs(roll_degree)) + \" degrees\"\n # cv2.putText(draw, output_roll, (20, 120), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 0))\n # print(output_roll)\n # if roll_degree > 0:\n # output_roll = \"face bends to the left:\" + str(abs(roll_degree)) + \" degrees\"\n # cv2.putText(draw, output_roll, (20, 120), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 0))\n # print(output_roll)\n # if abs(yaw) < 0.00001 and abs(pitch) < 0.00001 and abs(roll) < 0.00001:\n # cv2.putText(draw, \"Initial ststus\", (20, 40), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 0))\n # print(\"Initial ststus\")\n # cv2.imwrite(save_dir + os.path.splitext(imgpath)[0] + '_pose_estimate2.jpg', draw)\n\ndef headPosEstimate(imgpath, landmarks):\n\n # 3D model points\n model_3d_points = np.array(([-165.0, 170.0, -115.0], # Left eye\n\t\t\t\t\t\t\t\t[165.0, 170.0, -115.0], # Right eye\n\t\t\t\t\t\t\t\t[0.0, 0.0, 0.0], # Nose tip\n\t\t\t\t\t\t\t\t[-150.0, -150.0, -125.0], # Left Mouth corner\n\t\t\t\t\t\t\t\t[150.0, -150.0, -125.0]), dtype=np.double) # Right Mouth corner)\n landmarks.dtype = np.double\n # Camera internals\n img = cv2.imread(imgpath)\n img_size = img.shape\n focal_length = img_size[1]\n center = [img_size[1]/2, img_size[0]/2]\n camera_matrix = np.array(([focal_length, 0, center[0]],\n\t\t\t\t\t\t\t[0, focal_length, center[1]],\n\t\t\t\t\t\t\t[0, 0, 1]),dtype=np.double)\n\n\n dist_coeffs = np.array([0,0,0,0], dtype=np.double)\n found, rotation_vector, translation_vector = cv2.solvePnP(model_3d_points, landmarks, camera_matrix, dist_coeffs)\n\n angle_result=rot2Euler(imgpath,rotation_vector)\n return angle_result\n\n\n\n\n\nif __name__ == '__main__':\n\n\n\n torch.set_grad_enabled(False)\n\n cfg = None\n net = None\n\n cfg = cfg_mobilenetv2\n net = RetinaFace(cfg=cfg, phase='test')\n net = load_model(net, args.trained_model, args.cpu)\n net.eval()\n print('Finished loading model!')\n #print(net)\n cudnn.benchmark = True\n #device = torch.device(\"cpu\" if args.cpu else \"cuda\")\n device=torch.device(\"cuda\")\n net = net.to(device)\n flag = True\n ##################################################\n #derface_val_dir = \"/home/lyp/paper_experiments/pre_data/code/real_test/shuffilenet_face/data/val/wider_val.txt\"\n #input1 = open(derface_val_dir)\n #lines1 = input1.readlines()\n time1 = 0\n #cap=cv2.VideoCapture(\"/home/lyp/Downloads/333.mp4\")\n #fourcc = cv2.VideoWriter_fourcc(*'XVID')\n #out = cv2.VideoWriter(\"/home/lyp/o11.avi\", fourcc, 25.0, (640, 480))\n\n\n #while(cap.isOpened()):\n # ret,frame=cap.read()\n #for i in range(1):\n #for iii in range(len(lines1)):\n #image_path = \"/home/lyp/paper_experiments/pre_data/code/real_test/shuffilenet_face/data/val/images\" + lines1[iii].strip()\n image_path = \"/home/lyp/mos_source_code_open/MOS-Multi-Task-Face-Detect/figures/4_Dancing_Dancing_4_85.jpg\"\n img_raw = cv2.imread(image_path, cv2.IMREAD_COLOR)\n img = np.float32(img_raw)\n\n # testing scale\n target_size = args.long_side\n max_size = args.long_side\n im_shape = img.shape\n im_size_min = np.min(im_shape[0:2])\n im_size_max = np.max(im_shape[0:2])\n resize = float(target_size) / float(im_size_min)\n # prevent bigger axis from being more than max_size:\n if np.round(resize * im_size_max) > max_size:\n resize = float(max_size) / float(im_size_max)\n if args.origin_size:\n resize = 1\n\n if resize != 1:\n img = cv2.resize(img, None, None, fx=resize, fy=resize, interpolation=cv2.INTER_LINEAR)\n # img = cv2.resize(img, (640,480))\n img_rgb = img_raw.copy()\n im_height, im_width, _ = img.shape\n print(im_height, im_width)\n\n scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])\n img -= (104, 117, 123)\n img = img.transpose(2, 0, 1)\n img = torch.from_numpy(img).unsqueeze(0)\n img = img.to(device)\n scale = scale.to(device)\n\n tic = time.time()\n loc, conf, landms, head_cls_y, head_cls_p, head_cls_r = net(img) # forward pass\n tic1 = time.time() - tic\n\n head_cls_y = head_cls_y.squeeze(0)\n head_cls_p = head_cls_p.squeeze(0)\n head_cls_r = head_cls_r.squeeze(0)\n idx_tensor = [idx for idx in range(66)]\n idx_tensor = torch.FloatTensor(idx_tensor).to(device)\n\n head_cls_y = torch.sum(head_cls_y * idx_tensor, 1).to(device) * 3 - 99\n head_cls_p = torch.sum(head_cls_p * idx_tensor, 1).to(device) * 3 - 99\n head_cls_r = torch.sum(head_cls_r * idx_tensor, 1).to(device) * 3 - 99\n\n priorbox = PriorBox(cfg, image_size=(im_height, im_width))\n priors = priorbox.forward()\n priors = priors.to(device)\n prior_data = priors.data\n boxes = decode(loc.data.squeeze(0), prior_data, cfg['variance'])\n boxes = boxes * scale / resize\n boxes = boxes.cpu().numpy()\n scores = conf.squeeze(0).data.cpu().numpy()[:, 1]\n landms = decode_landm(landms.data.squeeze(0), prior_data, cfg['variance'])\n\n head_cls_y = head_cls_y.cpu().numpy()\n head_cls_p = head_cls_p.cpu().numpy()\n head_cls_r = head_cls_r.cpu().numpy()\n\n scale1 = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2],\n img.shape[3], img.shape[2], img.shape[3], img.shape[2],\n img.shape[3], img.shape[2]])\n scale1 = scale1.to(device)\n landms = landms * scale1 / resize\n landms = landms.cpu().numpy()\n\n # ignore low scores\n inds = np.where(scores > args.confidence_threshold)[0]\n boxes = boxes[inds]\n landms = landms[inds]\n scores = scores[inds]\n head_cls_y = head_cls_y[inds]\n head_cls_p = head_cls_p[inds]\n head_cls_r = head_cls_r[inds]\n\n # keep top-K before NMS\n order = scores.argsort()[::-1][:args.top_k]\n boxes = boxes[order]\n landms = landms[order]\n scores = scores[order]\n head_cls_y = head_cls_y[order]\n head_cls_p = head_cls_p[order]\n head_cls_r = head_cls_r[order]\n idx_tensor = [idx for idx in range(66)]\n idx_tensor = np.array(idx_tensor)\n\n # do NMS\n dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)\n keep = py_cpu_nms(dets, args.nms_threshold)\n # keep = nms(dets, args.nms_threshold,force_cpu=args.cpu)\n dets = dets[keep, :]\n landms = landms[keep]\n yaw_predicted = head_cls_y[keep]\n pitch_predicted = head_cls_p[keep]\n roll_predicted = head_cls_r[keep]\n\n dets = dets[:args.keep_top_k, :]\n landms = landms[:args.keep_top_k, :]\n yaw_predicted = yaw_predicted[:args.keep_top_k]\n pitch_predicted = pitch_predicted[:args.keep_top_k]\n roll_predicted = roll_predicted[:args.keep_top_k]\n\n dets = np.concatenate((dets, landms), axis=1)\n # fourcc = cv2.VideoWriter_fourcc(*'XVID')\n # out = cv2.VideoWriter('/home/lyp/output.avi', fourcc, 20.0, (640, 480))\n\n # img_cv = cv2.imread(\"/home/lyp/paper_experiments/plot_paper_curve/compare_withsota/10_People_Marching_People_Marching_2_514.jpg\")\n # image_new2 = Image.fromarray(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB))\n if args.save_image:\n for i in range(len(dets)):\n b = dets[i]\n if b[4] < args.vis_thres:\n continue\n text = \"{:.4f}\".format(b[4])\n b = list(map(int, b))\n cv2.rectangle(img_rgb, (b[0], b[1]), (b[2], b[3]), (0, 0, 255), 3)\n cx = b[0]\n cy = b[1] + 12\n # cv2.putText(img_raw, text, (cx, cy),\n # cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255))\n\n ################################# transfer landmark into pose ##################################\n\n # landmark_array=np.asarray([[b[5], b[6]],[b[7], b[8]],[b[9], b[10]],[b[11], b[12]],[b[13], b[14]]]).astype(float)\n # (w, h) = image_new2.size\n # bbox_intrinsics = np.array([[w + h, 0, w // 2], [0, w + h, h // 2], [0, 0, 1]])\n # P, pose = get_pose(threed_5_points, landmark_array, bbox_intrinsics)\n # trans_vertices = renderer.transform_vertices(image_new2, [pose])\n # image_new2 = renderer.render(image_new2, trans_vertices, alpha=1)\n # image_new2 = Image.fromarray(image_new2)\n\n text = \"y:\" + str(int(yaw_predicted[i])) # + \",\" + \"p:\" + str(int(pitch_predicted[i])) + \",\" + \"r:\" + str(\n # int(roll_predicted[i]))\n\n cv2.putText(img_rgb, text, (cx - 10, cy - 25),\n cv2.FONT_HERSHEY_TRIPLEX, 0.6, (255, 0, 255))\n\n fps_text = \"FPS: \" + str(int(1 / tic1))\n cv2.putText(img_rgb, fps_text, (20, 40),\n cv2.FONT_HERSHEY_TRIPLEX, 0.6, (0, 255, 0))\n\n #\n # # landms\n # cv2.circle(img_rgb, (b[5], b[6]), 1, (0, 0, 255), 4)\n # cv2.circle(img_rgb, (b[7], b[8]), 1, (0, 255, 255), 4)\n # cv2.circle(img_rgb, (b[9], b[10]), 1, (255, 0, 255), 4)\n # cv2.circle(img_rgb, (b[11], b[12]), 1, (0, 255, 0), 4)\n # cv2.circle(img_rgb, (b[13], b[14]), 1, (255, 0, 0), 4)\n draw_axis(img_rgb, int(yaw_predicted[i]), int(pitch_predicted[i]), int(roll_predicted[i]), tdx=b[9],\n tdy=b[10], size=30)\n # plot_pose_cube(img_raw, int(yaw_predicted[i]), int(pitch_predicted[i]), int(roll_predicted[i]), tdx=b[0]+0.5*(b[2]-b[0]), tdy=b[1]+0.5*(b[3]-b[1]), size=150.)\n\n # landmark_array = np.asarray(\n # [[b[5], b[6]], [b[7], b[8]], [b[9], b[10]], [b[11], b[12]], [b[13], b[14]]]).astype(float)\n # #imgpath=\"/home/lyp/paper_experiments/pre_data/code/real_test/shuffilenet_face/data/val/images/1--Handshaking/1_Handshaking_Handshaking_1_567.jpg\"\n #\n # angle_result=headPosEstimate(image_path, landmark_array)\n # text = \"y:\" + str(int(angle_result[0]))# + \",\" + \"p:\" + str(int(angle_result[1])) + \",\" + \"r:\" + str(\n # int(angle_result[2]))\n # cv2.putText(img_rgb, text, (cx - 60, cy - 28),\n # cv2.FONT_HERSHEY_TRIPLEX, 0.8, (255, 0, 0))\n # out.write(frame)\n\n cv2.imshow(\"frame\", img_rgb)\n\n # if ret == True:\n # out.write(img_rgb)\n # else:\n # break\n #cv2.imwrite(\"/home/lyp/paper_experiments/plot_paper_curve/suppm/img/widerface/results/r68.jpg\", img_rgb)\n\n\n\n\n\n\n"
] |
[
[
"numpy.min",
"torch.cuda.current_device",
"numpy.where",
"scipy.spatial.transform.Rotation.from_matrix",
"torch.load",
"torch.sum",
"numpy.concatenate",
"numpy.max",
"torch.FloatTensor",
"numpy.append",
"numpy.column_stack",
"numpy.linalg.inv",
"torch.Tensor",
"torch.device",
"numpy.array",
"numpy.matmul",
"numpy.zeros",
"numpy.round",
"numpy.float32",
"numpy.hstack",
"scipy.spatial.transform.Rotation.from_rotvec",
"numpy.asarray",
"torch.from_numpy",
"torch.set_grad_enabled"
]
] |
swapnil3597/automl
|
[
"30807c4bac497bb6532c22fb7c5d3e8d2873de6f"
] |
[
"efficientdet/keras_repo/postprocess.py"
] |
[
"# Copyright 2020 Google Research. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\"\"\"Postprocessing for anchor-based detection.\"\"\"\nfrom typing import List, Tuple\nfrom absl import logging\nimport tensorflow as tf\n\nimport utils\nfrom keras_repo import anchors\nT = tf.Tensor # a shortcut for typing check.\nCLASS_OFFSET = 1\n\n\ndef to_list(inputs):\n if isinstance(inputs, dict):\n return [inputs[k] for k in sorted(inputs.keys())]\n if isinstance(inputs, list):\n return inputs\n raise ValueError('Unrecognized inputs : {}'.format(inputs))\n\n\ndef batch_map_fn(map_fn, inputs, *args, **kwargs):\n \"\"\"Apply map_fn at batch dimension.\"\"\"\n if isinstance(inputs[0], (list, tuple)):\n batch_size = len(inputs[0])\n else:\n batch_size = inputs[0].shape.as_list()[0]\n\n if not batch_size:\n # use tf.map_fn to handle dynamic batch_size.\n return tf.map_fn(map_fn, inputs, *args, **kwargs)\n\n outputs = []\n for i in range(batch_size):\n outputs.append(map_fn([x[i] for x in inputs]))\n return [tf.stack(y) for y in zip(*outputs)]\n\n\ndef clip_boxes(boxes: T, image_size: int) -> T:\n \"\"\"Clip boxes to fit the image size.\"\"\"\n image_size = utils.parse_image_size(image_size) * 2\n return tf.clip_by_value(boxes, [0], image_size)\n\n\ndef merge_class_box_level_outputs(params, cls_outputs: List[T],\n box_outputs: List[T]) -> Tuple[T, T]:\n \"\"\"Concatenates class and box of all levels into one tensor.\"\"\"\n cls_outputs_all, box_outputs_all = [], []\n batch_size = tf.shape(cls_outputs[0])[0]\n for level in range(0, params['max_level'] - params['min_level'] + 1):\n if params['data_format'] == 'channels_first':\n cls_outputs[level] = tf.transpose(cls_outputs[level], [0, 2, 3, 1])\n box_outputs[level] = tf.transpose(box_outputs[level], [0, 2, 3, 1])\n cls_outputs_all.append(\n tf.reshape(cls_outputs[level], [batch_size, -1, params['num_classes']]))\n box_outputs_all.append(tf.reshape(box_outputs[level], [batch_size, -1, 4]))\n return tf.concat(cls_outputs_all, 1), tf.concat(box_outputs_all, 1)\n\n\ndef topk_class_boxes(params, cls_outputs: T,\n box_outputs: T) -> Tuple[T, T, T, T]:\n \"\"\"Pick the topk class and box outputs.\"\"\"\n batch_size = tf.shape(cls_outputs)[0]\n num_classes = params['num_classes']\n\n max_nms_inputs = params['nms_configs'].get('max_nms_inputs', 0)\n if max_nms_inputs > 0:\n # Prune anchors and detections to only keep max_nms_inputs.\n # Due to some issues, top_k is currently slow in graph model.\n logging.info('use max_nms_inputs for pre-nms topk.')\n cls_outputs_reshape = tf.reshape(cls_outputs, [batch_size, -1])\n _, cls_topk_indices = tf.math.top_k(\n cls_outputs_reshape, k=max_nms_inputs, sorted=False)\n indices = cls_topk_indices // num_classes\n classes = cls_topk_indices % num_classes\n cls_indices = tf.stack([indices, classes], axis=2)\n\n cls_outputs_topk = tf.gather_nd(cls_outputs, cls_indices, batch_dims=1)\n box_outputs_topk = tf.gather_nd(\n box_outputs, tf.expand_dims(indices, 2), batch_dims=1)\n else:\n logging.info('use max_reduce for pre-nms topk.')\n # Keep all anchors, but for each anchor, just keep the max probablity for\n # each class.\n cls_outputs_idx = tf.math.argmax(cls_outputs, axis=-1, output_type=tf.int32)\n num_anchors = tf.shape(cls_outputs)[1]\n\n classes = cls_outputs_idx\n indices = tf.tile(\n tf.expand_dims(tf.range(num_anchors), axis=0), [batch_size, 1])\n cls_outputs_topk = tf.reduce_max(cls_outputs, -1)\n box_outputs_topk = box_outputs\n\n return cls_outputs_topk, box_outputs_topk, classes, indices\n\n\ndef pre_nms(params, cls_outputs, box_outputs, topk=True):\n \"\"\"Detection post processing before nms.\n\n It takes the multi-level class and box predictions from network, merge them\n into unified tensors, and compute boxes, scores, and classes.\n\n Args:\n params: a dict of parameters.\n cls_outputs: a list of tensors for classes, each tensor denotes a level of\n logits with shape [N, H, W, num_class * num_anchors].\n box_outputs: a list of tensors for boxes, each tensor ddenotes a level of\n boxes with shape [N, H, W, 4 * num_anchors].\n topk: if True, select topk before nms (mainly to speed up nms).\n\n Returns:\n A tuple of (boxes, scores, classes).\n \"\"\"\n # get boxes by apply bounding box regression to anchors.\n eval_anchors = anchors.Anchors(params['min_level'], params['max_level'],\n params['num_scales'], params['aspect_ratios'],\n params['anchor_scale'], params['image_size'])\n\n cls_outputs, box_outputs = merge_class_box_level_outputs(\n params, cls_outputs, box_outputs)\n\n if topk:\n # select topK purely based on scores before NMS, in order to speed up nms.\n cls_outputs, box_outputs, classes, indices = topk_class_boxes(\n params, cls_outputs, box_outputs)\n anchor_boxes = tf.gather(eval_anchors.boxes, indices)\n else:\n anchor_boxes = eval_anchors.boxes\n classes = None\n\n boxes = anchors.decode_box_outputs(box_outputs, anchor_boxes)\n # convert logits to scores.\n scores = tf.math.sigmoid(cls_outputs)\n return boxes, scores, classes\n\n\ndef nms(params, boxes: T, scores: T, classes: T,\n padded: bool) -> Tuple[T, T, T, T]:\n \"\"\"Non-maximum suppression.\n\n Args:\n params: a dict of parameters.\n boxes: a tensor with shape [N, 4], where N is the number of boxes. Box\n format is [y_min, x_min, y_max, x_max].\n scores: a tensor with shape [N].\n classes: a tensor with shape [N].\n padded: a bool vallue indicating whether the results are padded.\n\n Returns:\n A tuple (boxes, scores, classes, valid_lens), where valid_lens is a scalar\n denoting the valid length of boxes/scores/classes outputs.\n \"\"\"\n nms_configs = params['nms_configs']\n method = nms_configs['method']\n max_output_size = nms_configs['max_output_size']\n\n if method == 'hard' or not method:\n # hard nms.\n sigma = 0.0\n iou_thresh = nms_configs['iou_thresh'] or 0.5\n score_thresh = nms_configs['score_thresh'] or float('-inf')\n elif method == 'gaussian':\n sigma = nms_configs['sigma'] or 0.5\n iou_thresh = nms_configs['iou_thresh'] or 0.3\n score_thresh = nms_configs['score_thresh'] or 0.001\n else:\n raise ValueError('Inference has invalid nms method {}'.format(method))\n\n # TF API's sigma is twice as the paper's value, so here we divide it by 2:\n # https://github.com/tensorflow/tensorflow/issues/40253.\n nms_top_idx, nms_scores, nms_valid_lens = tf.raw_ops.NonMaxSuppressionV5(\n boxes=boxes,\n scores=scores,\n max_output_size=max_output_size,\n iou_threshold=iou_thresh,\n score_threshold=score_thresh,\n soft_nms_sigma=(sigma / 2),\n pad_to_max_output_size=padded)\n\n nms_boxes = tf.gather(boxes, nms_top_idx)\n nms_classes = tf.cast(\n tf.gather(classes, nms_top_idx) + CLASS_OFFSET, tf.float32)\n return nms_boxes, nms_scores, nms_classes, nms_valid_lens\n\n\ndef postprocess_combined(params, cls_outputs, box_outputs, image_scales=None):\n \"\"\"Post processing with combined NMS.\n\n Leverage the tf combined NMS. It is fast on TensorRT, but slow on CPU/GPU.\n\n Args:\n params: a dict of parameters.\n cls_outputs: a list of tensors for classes, each tensor denotes a level of\n logits with shape [N, H, W, num_class * num_anchors].\n box_outputs: a list of tensors for boxes, each tensor ddenotes a level of\n boxes with shape [N, H, W, 4 * num_anchors]. Each box format is [y_min,\n x_min, y_max, x_man].\n image_scales: scaling factor or the final image and bounding boxes.\n\n Returns:\n A tuple of batch level (boxes, scores, classess, valid_len) after nms.\n \"\"\"\n cls_outputs = to_list(cls_outputs)\n box_outputs = to_list(box_outputs)\n # Don't filter any outputs because combine_nms need the raw information.\n boxes, scores, _ = pre_nms(params, cls_outputs, box_outputs, topk=False)\n\n max_output_size = params['nms_configs']['max_output_size']\n score_thresh = params['nms_configs']['score_thresh'] or float('-inf')\n nms_boxes, nms_scores, nms_classes, nms_valid_len = (\n tf.image.combined_non_max_suppression(\n tf.expand_dims(boxes, axis=2),\n scores,\n max_output_size,\n max_output_size,\n score_threshold=score_thresh,\n clip_boxes=False))\n nms_classes += CLASS_OFFSET\n nms_boxes = clip_boxes(nms_boxes, params['image_size'])\n if image_scales is not None:\n scales = tf.expand_dims(tf.expand_dims(image_scales, -1), -1)\n nms_boxes = nms_boxes * tf.cast(scales, nms_boxes.dtype)\n return nms_boxes, nms_scores, nms_classes, nms_valid_len\n\n\ndef postprocess_global(params, cls_outputs, box_outputs, image_scales=None):\n \"\"\"Post processing with global NMS.\n\n A fast but less accurate version of NMS. The idea is to treat the scores for\n different classes in a unified way, and perform NMS globally for all classes.\n\n Args:\n params: a dict of parameters.\n cls_outputs: a list of tensors for classes, each tensor denotes a level of\n logits with shape [N, H, W, num_class * num_anchors].\n box_outputs: a list of tensors for boxes, each tensor ddenotes a level of\n boxes with shape [N, H, W, 4 * num_anchors]. Each box format is [y_min,\n x_min, y_max, x_man].\n image_scales: scaling factor or the final image and bounding boxes.\n\n Returns:\n A tuple of batch level (boxes, scores, classess, valid_len) after nms.\n \"\"\"\n cls_outputs = to_list(cls_outputs)\n box_outputs = to_list(box_outputs)\n boxes, scores, classes = pre_nms(params, cls_outputs, box_outputs)\n\n def single_batch_fn(element):\n return nms(params, element[0], element[1], element[2], True)\n\n dtype = scores.dtype\n nms_boxes, nms_scores, nms_classes, nms_valid_len = batch_map_fn(\n single_batch_fn,\n [boxes, scores, classes],\n dtype=(dtype, dtype, dtype, tf.int32))\n nms_boxes = clip_boxes(nms_boxes, params['image_size'])\n if image_scales is not None:\n scales = tf.expand_dims(tf.expand_dims(image_scales, -1), -1)\n nms_boxes = nms_boxes * tf.cast(scales, nms_boxes.dtype)\n return nms_boxes, nms_scores, nms_classes, nms_valid_len\n\n\ndef per_class_nms(params, boxes, scores, classes, image_scales=None):\n \"\"\"Per-class nms, a utility for postprocess_per_class.\n\n Args:\n params: a dict of parameters.\n boxes: A tensor with shape [N, K, 4], where N is batch_size, K is num_boxes.\n Box format is [y_min, x_min, y_max, x_max].\n scores: A tensor with shape [N, K].\n classes: A tensor with shape [N, K].\n image_scales: scaling factor or the final image and bounding boxes.\n\n Returns:\n A tuple of batch level (boxes, scores, classess, valid_len) after nms.\n \"\"\"\n def single_batch_fn(element):\n \"\"\"A mapping function for a single batch.\"\"\"\n boxes_i, scores_i, classes_i = element[0], element[1], element[2]\n nms_boxes_cls, nms_scores_cls, nms_classes_cls = [], [], []\n nms_valid_len_cls = []\n for cid in range(params['num_classes']):\n indices = tf.where(tf.equal(classes_i, cid))\n if indices.shape[0] == 0:\n continue\n classes_cls = tf.gather_nd(classes_i, indices)\n boxes_cls = tf.gather_nd(boxes_i, indices)\n scores_cls = tf.gather_nd(scores_i, indices)\n\n nms_boxes, nms_scores, nms_classes, nms_valid_len = nms(\n params, boxes_cls, scores_cls, classes_cls, False)\n nms_boxes_cls.append(nms_boxes)\n nms_scores_cls.append(nms_scores)\n nms_classes_cls.append(nms_classes)\n nms_valid_len_cls.append(nms_valid_len)\n\n # Pad zeros and select topk.\n max_output_size = params['nms_configs'].get('max_output_size', 100)\n nms_boxes_cls = tf.pad(\n tf.concat(nms_boxes_cls, 0), [[0, max_output_size], [0, 0]])\n nms_scores_cls = tf.pad(\n tf.concat(nms_scores_cls, 0), [[0, max_output_size]])\n nms_classes_cls = tf.pad(\n tf.concat(nms_classes_cls, 0), [[0, max_output_size]])\n nms_valid_len_cls = tf.stack(nms_valid_len_cls)\n\n _, indices = tf.math.top_k(nms_scores_cls, k=max_output_size, sorted=True)\n\n return tuple((\n tf.gather(nms_boxes_cls, indices),\n tf.gather(nms_scores_cls, indices),\n tf.gather(nms_classes_cls, indices),\n tf.minimum(max_output_size, tf.reduce_sum(nms_valid_len_cls))))\n # end of single_batch_fn\n\n dtype = scores.dtype\n nms_boxes, nms_scores, nms_classes, nms_valid_len = batch_map_fn(\n single_batch_fn,\n [boxes, scores, classes],\n dtype=(dtype, dtype, dtype, tf.int32))\n if image_scales is not None:\n scales = tf.expand_dims(tf.expand_dims(image_scales, -1), -1)\n nms_boxes = nms_boxes * tf.cast(scales, nms_boxes.dtype)\n return nms_boxes, nms_scores, nms_classes, nms_valid_len\n\n\ndef postprocess_per_class(params, cls_outputs, box_outputs, image_scales=None):\n \"\"\"Post processing with per class NMS.\n\n An accurate but relatively slow version of NMS. The idea is to perform NMS for\n each class, and then combine them.\n\n Args:\n params: a dict of parameters.\n cls_outputs: a list of tensors for classes, each tensor denotes a level of\n logits with shape [N, H, W, num_class * num_anchors].\n box_outputs: a list of tensors for boxes, each tensor ddenotes a level of\n boxes with shape [N, H, W, 4 * num_anchors]. Each box format is [y_min,\n x_min, y_max, x_man].\n image_scales: scaling factor or the final image and bounding boxes.\n\n Returns:\n A tuple of batch level (boxes, scores, classess, valid_len) after nms.\n \"\"\"\n cls_outputs = to_list(cls_outputs)\n box_outputs = to_list(box_outputs)\n boxes, scores, classes = pre_nms(params, cls_outputs, box_outputs)\n return per_class_nms(params, boxes, scores, classes, image_scales)\n\n\ndef generate_detections(params,\n cls_outputs,\n box_outputs,\n image_scales,\n image_ids,\n flip=False):\n \"\"\"A legacy interface for generating [id, x, y, w, h, score, class].\"\"\"\n nms_boxes_bs, nms_scores_bs, nms_classes_bs, _ = postprocess_per_class(\n params, cls_outputs, box_outputs, image_scales)\n\n image_ids_bs = tf.cast(tf.expand_dims(image_ids, -1), nms_scores_bs.dtype)\n if flip:\n _, width = utils.parse_image_size(params['image_size'])\n\n original_image_widths = tf.expand_dims(image_scales, -1) * width\n detections_bs = [\n image_ids_bs * tf.ones_like(nms_scores_bs),\n # the mirrored location of the left edge is the image width\n # minus the position of the right edge\n original_image_widths - nms_boxes_bs[:, :, 3],\n nms_boxes_bs[:, :, 0],\n # the mirrored location of the right edge is the image width\n # minus the position of the left edge\n original_image_widths - nms_boxes_bs[:, :, 1],\n nms_boxes_bs[:, :, 2],\n nms_scores_bs,\n nms_classes_bs,\n ]\n else:\n detections_bs = [\n image_ids_bs * tf.ones_like(nms_scores_bs),\n nms_boxes_bs[:, :, 1],\n nms_boxes_bs[:, :, 0],\n nms_boxes_bs[:, :, 3],\n nms_boxes_bs[:, :, 2],\n nms_scores_bs,\n nms_classes_bs,\n ]\n return tf.stack(detections_bs, axis=-1, name='detnections')\n\n\ndef transform_detections(detections):\n \"\"\"A transforms detections in [id, x1, y1, x2, y2, score, class] form to [id, x, y, w, h, score, class].\"\"\"\n return tf.stack([\n detections[:, :, 0],\n detections[:, :, 1],\n detections[:, :, 2],\n detections[:, :, 3] - detections[:, :, 1],\n detections[:, :, 4] - detections[:, :, 2],\n detections[:, :, 5],\n detections[:, :, 6],\n ],\n axis=-1)\n"
] |
[
[
"tensorflow.ones_like",
"tensorflow.reshape",
"tensorflow.clip_by_value",
"tensorflow.math.top_k",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.shape",
"tensorflow.raw_ops.NonMaxSuppressionV5",
"tensorflow.concat",
"tensorflow.transpose",
"tensorflow.math.argmax",
"tensorflow.range",
"tensorflow.expand_dims",
"tensorflow.math.sigmoid",
"tensorflow.gather_nd",
"tensorflow.map_fn",
"tensorflow.reduce_sum",
"tensorflow.equal",
"tensorflow.reduce_max",
"tensorflow.gather"
]
] |
cihanongun/3D-CGAN
|
[
"3e8158b6764d3d93cfec8c1f2376ec9818ae1ee4"
] |
[
"utils.py"
] |
[
"import scipy.io\nfrom os import listdir\nfrom os.path import isfile, join\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport os\nimport sys\nimport shutil\n\n# get a single 3D model from .mat file\ndef get_model(file_path): \n \n mat = scipy.io.loadmat( file_path )\n model_array = mat['instance']\n model_array = np.pad(model_array,1,'constant',constant_values=0)\n return model_array\n\n# load all models for a single rotation\ndef load_all(folder_name, contains = None):\n \n file_names = [f for f in listdir(folder_name) if isfile(join(folder_name, f))]\n \n if (contains != None):\n file_names = [s for s in file_names if contains in s]\n \n models = []\n \n for m in range(len(file_names)):\n file_path = (folder_name + '/' + file_names[m])\n models.append(get_model(file_path))\n return np.array(models)\n\n# visualize 3D voxel models, input is a list of a batch of 3D arrays to visualize all conditions together \ndef visualize_all(models , save = False, name = \"output\", fig_count = 4, fig_size = 5):\n \n fig = plt.figure()\n \n m = 0\n for model in models:\n \n if(model.dtype == bool):\n voxel = model\n else:\n voxel = np.squeeze(model) > 0.5\n \n ax = []\n colors = []\n \n for i in range(fig_count):\n ax.append( fig.add_subplot(len(models), fig_count, (m*fig_count) + i+1, projection='3d') )\n\n for i in range(fig_count):\n ax[i].voxels(voxel[i], facecolors='red', edgecolor='k', shade=False)\n ax[i].grid(False)\n ax[i].axis('off')\n \n m += 1\n \n plt.tight_layout()\n \n fig.set_figheight(fig_size)\n fig.set_figwidth(fig_size*fig_count)\n #plt.show()\n if(save):\n fig.savefig(name +'.png')\n plt.close(fig)\n fig.clear()\n else :\n plt.show()\n\n# plot loss graph \ndef plot_graph(lists, name):\n for l in lists:\n plt.plot(l)\n \n plt.savefig(name +'.png')\n plt.close()\n\n# create the log folder \ndef clear_folder(path):\n if os.path.exists(path):\n shutil.rmtree(path)\n os.mkdir(path)"
] |
[
[
"numpy.array",
"numpy.pad",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"numpy.squeeze"
]
] |
CogNLP/CogKGE
|
[
"70d851d6489600c1e90eb25b0388a3ceba2f078c"
] |
[
"tests/test_fb15k_run_distmult.py"
] |
[
"import torch\nfrom torch.utils.data import RandomSampler\nfrom pathlib import Path\nimport sys\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[0].parents[0] # CogKGE root directory\nif str(ROOT) not in sys.path:\n sys.path.append(str(ROOT)) # add CogKGE root directory to PATH\n\n\nfrom cogkge import *\ndevice=init_cogkge(device_id=\"0,1,2,3\",seed=1)\n\nloader =FB15KLoader(dataset_path=\"../dataset\",download=True)\ntrain_data, valid_data, test_data = loader.load_all_data()\nnode_lut, relation_lut= loader.load_all_lut()\n# loader.describe()\n# train_data.describe()\n# node_lut.describe()\n\nprocessor = FB15KProcessor(node_lut, relation_lut,reprocess=True)\ntrain_dataset = processor.process(train_data)\nvalid_dataset = processor.process(valid_data)\ntest_dataset = processor.process(test_data)\nnode_lut,relation_lut=processor.process_lut()\n# node_lut.print_table(front=3)\n# relation_lut.print_table(front=3)\n\ntrain_sampler = RandomSampler(train_dataset)\nvalid_sampler = RandomSampler(valid_dataset)\ntest_sampler = RandomSampler(test_dataset)\n\nmodel = DistMult(entity_dict_len=len(node_lut),\n relation_dict_len=len(relation_lut),\n embedding_dim=50)\n\nloss = NegLogLikehoodLoss(C=0.1)\n\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=0)\n\nmetric = Link_Prediction(link_prediction_raw=True,\n link_prediction_filt=False,\n batch_size=5000000,\n reverse=True)\n\nlr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer, mode='min', patience=3, threshold_mode='abs', threshold=5,\n factor=0.5, min_lr=1e-9, verbose=True\n)\n\nnegative_sampler = UnifNegativeSampler(triples=train_dataset,\n entity_dict_len=len(node_lut),\n relation_dict_len=len(relation_lut))\n\ntrainer = ScoreTrainer(\n train_dataset=train_dataset,\n valid_dataset=test_dataset,\n train_sampler=train_sampler,\n valid_sampler=test_sampler,\n model=model,\n loss=loss,\n optimizer=optimizer,\n negative_sampler=negative_sampler,\n device=device,\n output_path=\"../dataset\",\n lookuptable_E= node_lut,\n lookuptable_R= relation_lut,\n metric=metric,\n lr_scheduler=lr_scheduler,\n log=True,\n trainer_batch_size=100000,\n epoch=1000,\n visualization=False,\n apex=True,\n dataloaderX=True,\n num_workers=4,\n pin_memory=True,\n metric_step=100,\n save_step=100,\n metric_final_model=True,\n save_final_model=True,\n load_checkpoint= None\n)\ntrainer.train()\n\nevaluator = Evaluator(\n test_dataset=test_dataset,\n test_sampler=test_sampler,\n model=model,\n device=device,\n metric=metric,\n output_path=\"../dataset\",\n train_dataset=train_dataset,\n valid_dataset=valid_dataset,\n lookuptable_E= node_lut,\n lookuptable_R= relation_lut,\n log=True,\n evaluator_batch_size=50000,\n dataloaderX=True,\n num_workers= 4,\n pin_memory=True,\n trained_model_path=None\n)\nevaluator.evaluate()\n\n\n"
] |
[
[
"torch.utils.data.RandomSampler",
"torch.optim.lr_scheduler.ReduceLROnPlateau"
]
] |
clintonjwang/mmdetection
|
[
"f0d1aebdc162ab7e3748d7ac050b523476639818"
] |
[
"mmdet/models/backbones/posenc_resnet.py"
] |
[
"import torch, einops\nfrom ..builder import BACKBONES\nfrom .resnet import ResNet\n\n@BACKBONES.register_module()\nclass PositionalEncodingResNet(ResNet):\n def __init__(self, num_frequencies, in_channels=3, **kwargs):\n self.L = num_frequencies\n in_channels += self.L * 4\n super().__init__(in_channels=in_channels, **kwargs)\n\n def forward(self, x):\n x = self.add_positional_encoding(x)\n return super().forward(x)\n\n def add_positional_encoding(self, img):\n B,C,H,W = img.shape\n device = img.device\n freq = 2**torch.arange(self.L, dtype=torch.float32, device=device) * torch.pi\n\n Y,X = torch.meshgrid(torch.linspace(0,1,H, device=device),torch.linspace(0,1,W, device=device), indexing='ij')\n XY = torch.stack([X,Y], dim=0)\n\n enc = torch.cat([(XY[...,None]*freq).sin(), (XY[...,None]*freq).cos()], dim=0)\n enc = einops.rearrange(enc, 'Z H W L -> (Z L) H W').repeat(B,1,1,1)\n\n return torch.cat([img, enc], dim=1)\n"
] |
[
[
"torch.cat",
"torch.stack",
"torch.linspace",
"torch.arange"
]
] |
alexhepburn/rbig_jax
|
[
"706dd60d2049071be0fb3d311c83719121854678"
] |
[
"tests/transforms/test_conv1x1ortho.py"
] |
[
"import chex\nimport jax\nimport jax.numpy as np\nimport numpy as onp\nimport objax\nimport pytest\n\nfrom rbig_jax.transforms.conv import Conv1x1Householder\n\nseed = 123\nrng = onp.random.RandomState(123)\ngenerator = objax.random.Generator(123)\n\n\n@pytest.mark.parametrize(\"n_channels\", [1, 3, 12])\n@pytest.mark.parametrize(\"hw\", [(1, 1), (5, 5), (12, 12)])\n@pytest.mark.parametrize(\"n_samples\", [1, 5, 10])\n@pytest.mark.parametrize(\"n_reflections\", [1, 2, 10])\ndef test_conv1x1ortho_shape(n_channels, hw, n_samples, n_reflections):\n\n x = objax.random.normal((n_samples, hw[0], hw[1], n_channels), generator=generator)\n # print(x.shape)\n # create layer\n model = Conv1x1Householder(n_channels=n_channels, n_reflections=n_reflections)\n\n # forward transformation\n z, log_abs_det = model(x)\n\n # print(z.shape, log_abs_det.shape)\n\n # checks\n chex.assert_equal_shape([z, x])\n chex.assert_shape(np.atleast_1d(log_abs_det), (n_samples,))\n\n # forward transformation\n z = model.transform(x)\n\n # checks\n chex.assert_equal_shape([z, x])\n\n # inverse transformation\n x_approx = model.inverse(z)\n\n # checks\n chex.assert_equal_shape([x_approx, x])\n\n\n@pytest.mark.parametrize(\"n_channels\", [1, 3, 12])\n@pytest.mark.parametrize(\"hw\", [(1, 1), (5, 5), (12, 12)])\n@pytest.mark.parametrize(\"n_samples\", [1, 5, 10])\n@pytest.mark.parametrize(\"n_reflections\", [1, 2, 10])\ndef test_conv1x1ortho_approx(n_channels, hw, n_samples, n_reflections):\n\n x = objax.random.normal((n_samples, hw[0], hw[1], n_channels), generator=generator)\n\n # create layer\n model = Conv1x1Householder(n_channels=n_channels, n_reflections=n_reflections)\n\n # forward transformation\n z, log_abs_det = model(x)\n\n # inverse transformation\n x_approx = model.inverse(z)\n\n # checks\n chex.assert_tree_all_close(x, x_approx, atol=1e-5)\n"
] |
[
[
"numpy.random.RandomState"
]
] |
jheo4/incubator-tvm
|
[
"c4c61cb766608fb2f0fd8c9facc480a43afed3f5",
"c4c61cb766608fb2f0fd8c9facc480a43afed3f5",
"c4c61cb766608fb2f0fd8c9facc480a43afed3f5"
] |
[
"tutorials/optimize/opt_matmul_auto_tensorcore.py",
"tests/python/frontend/keras/test_forward.py",
"tests/python/unittest/test_container.py"
] |
[
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _opt-matmul-auto-tensorcore:\n\nHow to optimize matmul with Auto TensorCore CodeGen\n===================================================\n**Author**: `Minmin Sun <https://github.com/minminsun>`_, \\\n `Lanbo Li <https://github.com/Orion34C>`_, \\\n `Chenfan Jia <https://github.com/jcf94>`_, \\\n `Jun Yang <https://github.com/yangjunpro>`_\n\nIn this tutorial, we will demonstrate how to write a high performance matmul\nschedule on Volta/Turing GPUs with TVM Auto TensorCore CodeGen.\nThis is a transparent solution to generate tensorcore kernel\nwith most transformations done in ir passes.\nUsers can also write schedule with tensorization to generate TensorCore code.\nBoth solutions use the same tensorcore intrinsics.\nPlease refer to :ref:`opt-conv-tensorcore` tutorial for more details.\n\"\"\"\n\n################################################################\n# Preparation and Algorithm\n# -------------------------\n# 2 kinds of input data types are supported: float16 and int8.\n# For float16, the accumulator is float32.\n# For int8, the accumulator is int32.\n# For data layouts, 'N' means None-transpose while 'T' means Transpose.\n\nimport logging\nimport sys\n\nimport numpy as np\nimport tvm\n\nfrom tvm import autotvm\nfrom tvm.contrib import nvcc\n\ndef matmul_nn(A, B, L, dtype='float16', layout='NN'):\n k = tvm.reduce_axis((0, L), name='k')\n if dtype == 'float16':\n out_type = 'float'\n elif dtype == 'int8':\n out_type = 'int'\n elif dtype == 'int4' or dtype == 'int1':\n out_type = 'int'\n if (layout == 'NN'):\n return tvm.compute((N, M), lambda i, j: tvm.sum(A[i, k].astype(out_type) * B[k, j].astype(out_type), axis=k))\n if (layout == 'NT'):\n return tvm.compute((N, M), lambda i, j: tvm.sum(A[k, i].astype(out_type) * B[k, j].astype(out_type), axis=k))\n if (layout == 'TN'):\n return tvm.compute((N, M), lambda i, j: tvm.sum(A[i, k].astype(out_type) * B[j, k].astype(out_type), axis=k))\n if (layout == 'TT'):\n return tvm.compute((N, M), lambda i, j: tvm.sum(A[k, i].astype(out_type) * B[j, k].astype(out_type), axis=k))\n\n###############################################################################\n# Scheduling the Computation\n# --------------------------\n# This schedule is no different than a non-tensorcore matmul schedule on GPU.\n# Please refer to :ref:`opt-gemm` tutorial for basics of optimizing matmul schedule.\n# When the \"tensor_core\" pragma is set, the \"rewrite for tensorcore\" ir pass\n# will automatically transform the schedule for tensorcore codegen,\n# otherwise normal CUDA code, with lower performance but equal functionality, will be generated.\n#\n# .. note::\n#\n# *Requirements of TesnsorCore*\n#\n# Note that in the following 2 cases, even though the \"tensor_core\" pragma is set, TVM will still fall back to normal CUDA codegen:\n# (1) The m, n or k of input matrices is not multiple of 16;\n# (2) The warp tile size is not 16x16x16 on CUDA9, or not one of {16x16x16, 32x8x16, 8x32x16} on CUDA version >= 10.0.\n#\n# In this schedule, storage_align is used to reduce bank conflicts of shared memory. Please refer to this\n# `doc <https://docs.tvm.ai/api/python/schedule.html#tvm.schedule.Stage.storage_align>`_\n# for the usage of storage_align primitive. In short, we need to add an offset to some shared memory buffer\n# to reduce bank conflicts.\n# According to the `wmma doc <https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#wmma-description>`_,\n# the stride of load_matrix_sync must be a multiple of 16 bytes,\n# so we choose 8 as offset for float16 and 16 as offset for int8.\n#\n# We use AutoTVM to search for best configurations in this schedule.\n\n@autotvm.template\ndef test_gemm(N, L, M, dtype, layout):\n if (layout == \"NN\"):\n shape_a = (N, L)\n shape_b = (L, M)\n elif (layout == \"NT\"):\n shape_a = (L, N)\n shape_b = (L, M)\n elif (layout == \"TN\"):\n shape_a = (N, L)\n shape_b = (M, L)\n elif (layout == \"TT\"):\n shape_a = (L, N)\n shape_b = (M, L)\n else:\n print (\"Unsupported layout:\", layout)\n sys.exit(1);\n A = tvm.placeholder(shape_a, name='A', dtype=dtype)\n B = tvm.placeholder(shape_b, name='B', dtype=dtype)\n C = matmul_nn(A, B, L, dtype, layout)\n\n s = tvm.create_schedule(C.op)\n y, x = s[C].op.axis\n k = s[C].op.reduce_axis[0]\n\n # storage_align params\n factor = 16\n offset = 8\n if dtype == 'int8':\n factor = 32\n offset = 16\n elif dtype == 'int4':\n factor = 64\n offset = 32\n elif dtype == 'int1':\n factor = 256\n offset = 128\n\n # create cache stages\n AA = s.cache_read(A, \"shared\", [C])\n if (layout == \"NN\" or layout == \"TN\"):\n s[AA].storage_align(AA.op.axis[0], factor, offset)\n AL = s.cache_read(AA, \"local\", [C])\n BB = s.cache_read(B, \"shared\", [C])\n if (layout == \"TT\" or layout == \"NT\"):\n s[BB].storage_align(BB.op.axis[0], factor, offset)\n BL = s.cache_read(BB, \"local\", [C])\n CL = s.cache_write(C, \"local\")\n\n #autotvm search space definition\n cfg = autotvm.get_config()\n\n cfg.define_knob(\"bx\", [2, 4, 8])\n cfg.define_knob(\"by\", [8, 16, 32, 64])\n cfg.define_knob(\"step_k\", [1, 2, 4, 8, 16, 32])\n cfg.define_knob(\"v\", [4, 8, 16, 32])\n by = cfg['by'].val\n bx = cfg['bx'].val\n step_k = cfg['step_k'].val\n v = cfg['v'].val\n\n # thread tile\n TX = 8\n TY = 1\n if dtype == 'int4' or dtype == 'int1':\n TX = 2\n # warp tile\n warp_tile_m = 16 # it could also be 8 or 32 on CUDA version >= 10.0\n warp_tile_k = 16 # it must be 16 for fp16/int8 data type\n if dtype == 'int4':\n warp_tile_m = 8\n warp_tile_k = 32\n elif dtype == 'int1':\n warp_tile_m = 8\n warp_tile_k = 128\n # block tile\n tile_x = bx * TX\n tile_y = by * TY\n\n yo, ty = s[C].split(y, tile_y)\n ty, yi = s[C].split(ty, TY)\n\n # schedule for C stage\n xo, xi = s[C].split(x, tile_x)\n WX = min(warp_tile_m, tile_x)\n tz, xi = s[C].split(xi, WX)\n tx, xi = s[C].split(xi, TX)\n s[C].reorder(yo, xo, tz, ty, tx, yi, xi)\n s[C].bind(yo, tvm.thread_axis(\"blockIdx.y\"))\n s[C].bind(xo, tvm.thread_axis(\"blockIdx.x\"))\n s[C].bind(ty, tvm.thread_axis(\"threadIdx.y\"))\n s[C].bind(tz, tvm.thread_axis(\"threadIdx.z\"))\n s[C].bind(tx, tvm.thread_axis(\"threadIdx.x\"))\n\n # schedule for CL stage\n ko, ki = s[CL].split(k, step_k * warp_tile_k)\n kl, ki = s[CL].split(ki, warp_tile_k)\n s[CL].compute_at(s[C], tx)\n yo, xo = CL.op.axis\n s[CL].reorder(ko, kl, ki, yo, xo)\n\n # schedule for AA stage\n s[AA].compute_at(s[CL], ko)\n xo, xi = s[AA].split(s[AA].op.axis[1], factor=bx*v)\n tz, tx = s[AA].split(xi, factor=(WX//TX)*v)\n tx, vec = s[AA].split(tx, factor=v)\n fused = s[AA].fuse(s[AA].op.axis[0], xo)\n _, ty = s[AA].split(fused, factor=by)\n s[AA].bind(ty, tvm.thread_axis(\"threadIdx.y\"))\n s[AA].bind(tz, tvm.thread_axis(\"threadIdx.z\"))\n s[AA].bind(tx, tvm.thread_axis(\"threadIdx.x\"))\n # vectorization is very important for float16/int8 inputs\n s[AA].vectorize(vec)\n\n # schedule for BB stage\n s[BB].compute_at(s[CL], ko)\n xo, xi = s[BB].split(s[BB].op.axis[1], factor=bx*v)\n tz, tx = s[BB].split(xi, factor=(WX//TX)*v)\n tx, vec = s[BB].split(tx, factor=v)\n fused = s[BB].fuse(s[BB].op.axis[0], xo)\n _, ty = s[BB].split(fused, factor=by)\n s[BB].bind(ty, tvm.thread_axis(\"threadIdx.y\"))\n s[BB].bind(tz, tvm.thread_axis(\"threadIdx.z\"))\n s[BB].bind(tx, tvm.thread_axis(\"threadIdx.x\"))\n s[BB].vectorize(vec)\n\n s[AL].compute_at(s[CL], kl)\n s[BL].compute_at(s[CL], kl)\n\n # set the 'tensor_core' pragma for tensorcore codegen\n s[CL].pragma(ko, 'tensor_core')\n\n return s, [A, B, C]\n\n###############################################################################\n# AutoTune and Test\n# -----------------\n# Finally we use a tuner to tune the schedule, generate code with best config\n# and run the kernel to compare with numpy to check whether the results are correct.\n\n# check whether the gpu has tensorcore\nif not tvm.gpu(0).exist or not tvm.runtime.enabled(\"cuda\"):\n print(\"skip because cuda is not enabled..\")\n sys.exit(0)\n\nctx = tvm.gpu()\nif not nvcc.have_tensorcore(ctx.compute_version):\n print('the gpu has no tensorcore, skipping...')\n sys.exit(0)\n\nM, N, L = 512, 32, 512\ndtype = 'float16'\nlayout = 'NN'\nif len(sys.argv) >= 4:\n M, N, L = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])\nif len(sys.argv) >= 5:\n dtype = sys.argv[4]\nif len(sys.argv) >= 6:\n layout = sys.argv[5]\n\n# check whether current gpu arch support support current dtype's wmma codegen\ncuda_compute_capability = tvm.runtime._ffi_api.GetDeviceAttr(2, 0, 4)\nmajor, minor= nvcc.parse_compute_version(cuda_compute_capability)\nif dtype == 'int8':\n assert(major == 7 and minor >= 2)\nelif dtype == 'int4' or dtype == 'int1':\n # int4/int1 only support layout TN\n assert(major == 7 and minor == 5 and layout == 'TN')\n\ndef tune_and_evaluate(M, N, L, dtype, layout):\n task = autotvm.task.create(test_gemm, args=(N, L, M, dtype, layout), target='cuda')\n print(task.config_space)\n\n logging.getLogger('autotvm').setLevel(logging.DEBUG)\n logging.getLogger('autotvm').addHandler(logging.StreamHandler(sys.stdout))\n\n measure_option = autotvm.measure_option(\n builder='local',\n runner=autotvm.LocalRunner(number=5))\n\n tuner = autotvm.tuner.XGBTuner(task)\n tuner.tune(n_trial=1000,\n measure_option=measure_option,\n callbacks=[autotvm.callback.log_to_file('matmul.log')])\n\n dispatch_context = autotvm.apply_history_best(\"matmul.log\")\n best_config = dispatch_context.query(task.target, task.workload)\n print(\"\\nBest config:\")\n print(best_config)\n with autotvm.apply_history_best('matmul.log'):\n with tvm.target.create(\"cuda\"):\n with tvm.build_config():\n s, arg_bufs = test_gemm(N, L, M, dtype, layout)\n print(tvm.lower(s, arg_bufs, simple_mode=True))\n func = tvm.build(s, arg_bufs)\n dev_module = func.imported_modules[0]\n print(dev_module.get_source())\n\n # check correctness\n if (layout == \"NN\"):\n shape_a = (N, L)\n shape_b = (L, M)\n elif (layout == \"NT\"):\n shape_a = (L, N)\n shape_b = (L, M)\n elif (layout == \"TN\"):\n shape_a = (N, L)\n shape_b = (M, L)\n elif (layout == \"TT\"):\n shape_a = (L, N)\n shape_b = (M, L)\n\n a_np = None\n b_np = None\n c_np = None\n c_np_type = None\n if dtype == 'float16':\n c_np_type = np.float32\n a_np = np.random.uniform(size=shape_a).astype(np.float16)\n b_np = np.random.uniform(size=shape_b).astype(np.float16)\n if (layout == \"NN\"):\n c_np = np.dot(a_np, b_np)\n elif (layout == \"NT\"):\n c_np = np.dot(a_np.T, b_np)\n elif (layout == \"TN\"):\n c_np = np.dot(a_np, b_np.T)\n elif (layout == \"TT\"):\n c_np = np.dot(a_np.T, b_np.T)\n elif dtype == 'int8':\n c_np_type = np.int32\n a_np = np.random.randint(low=-128, high=127, size=shape_a).astype(np.int8)\n b_np = np.random.randint(low=-128, high=127, size=shape_b).astype(np.int8)\n if (layout == \"NN\"):\n c_np = np.dot(a_np.astype(np.int32), b_np.astype(np.int32))\n elif (layout == \"NT\"):\n c_np = np.dot(a_np.astype(np.int32).T, b_np.astype(np.int32))\n elif (layout == \"TN\"):\n c_np = np.dot(a_np.astype(np.int32), b_np.astype(np.int32).T)\n elif (layout == \"TT\"):\n c_np = np.dot(a_np.astype(np.int32).T, b_np.astype(np.int32).T)\n elif dtype == 'int4':\n c_np_type = np.int32\n a_np_int = np.random.randint(low=-8, high=7, size=shape_a).astype(np.int32)\n b_np_int = np.random.randint(low=-8, high=7, size=shape_b).astype(np.int32)\n # \"TN\"\n c_np = np.dot(a_np_int.astype(np.int32), b_np_int.astype(np.int32).T)\n a_np = np.zeros(shape=(N, int(L/8)), dtype = np.int32)\n b_np = np.zeros(shape=(M, int(L/8)), dtype = np.int32)\n # a_np --> col_major\n for i in range(N):\n for j in range(int(L/8)):\n for k in range(8):\n a_np[i, j] = a_np[i, j] | ((a_np_int[i, j * 8 + k] & 0xf) << ((7 - k) * 4))\n\n # b_np --> row_major\n for i in range(M):\n for j in range(int(L/8)):\n for k in range(8):\n b_np[i, j] = b_np[i, j] | ((b_np_int[i, j * 8 + k] & 0xf) << ((7 - k) * 4))\n elif dtype == 'int1':\n c_np_type = np.int32\n a_np_int = np.random.randint(low=0, high=1, size=shape_a).astype(np.int32)\n b_np_int = np.random.randint(low=0, high=1, size=shape_b).astype(np.int32)\n # \"TN\"\n c_np = np.dot(a_np_int.astype(np.int32), b_np_int.astype(np.int32).T)\n a_np = np.zeros(shape=(N, int(L/32)), dtype = np.int32)\n b_np = np.zeros(shape=(M, int(L/32)), dtype = np.int32)\n for i in range(N):\n for j in range(int(L/32)):\n for k in range(32):\n a_np[i, j] = a_np[i, j] | ((a_np_int[i, j * 32 + k] & 0xf) << (31 - k))\n\n for i in range(M):\n for j in range(int(L/32)):\n for k in range(32):\n b_np[i, j] = b_np[i, j] | ((b_np_int[i, j * 32 + k] & 0xf) << (31 - k))\n\n c_tvm = tvm.nd.array(np.zeros(c_np.shape, dtype=c_np_type), ctx=ctx)\n a_tvm = tvm.nd.array(a_np, ctx=ctx)\n b_tvm = tvm.nd.array(b_np, ctx=ctx)\n func(a_tvm, b_tvm, c_tvm)\n\n tvm.testing.assert_allclose(c_np, c_tvm.asnumpy(), rtol=1e-3)\n\n evaluator = func.time_evaluator(func.entry_name, ctx, number=100)\n print('Time cost of this operator: %f' % evaluator(a_tvm, b_tvm, c_tvm).mean)\n\n# We do not run the tuning in our webpage server since it takes some time.\n# Uncomment the following line to run it by yourself.\n\n# tune_and_evaluate(M, N, L, dtype, layout)\n\n######################################################################\n# Sample Output\n# -------------\n# .. code-block:: bash\n#\n# Best config:\n# [('bx', 4), ('by', 32), ('step_k', 16), ('v', 8)],,None,40\n# Finish loading 162 records\n# produce compute {\n# // attr [iter_var(blockIdx.y, , blockIdx.y)] thread_extent = 1\n# // attr [compute.local] storage_scope = \"wmma.accumulator\"\n# allocate compute.local[float32 * 256]\n# // attr [A.shared] storage_scope = \"shared\"\n# allocate A.shared[float16 * 8448]\n# // attr [B.shared] storage_scope = \"shared\"\n# allocate B.shared[float16 * 8192]\n# // attr [A.shared.local] storage_scope = \"wmma.matrix_b\"\n# allocate A.shared.local[float16 * 256]\n# // attr [B.shared.local] storage_scope = \"wmma.matrix_a\"\n# allocate B.shared.local[float16 * 256]\n# // attr [iter_var(blockIdx.x, , blockIdx.x)] thread_extent = 16\n# // attr [iter_var(threadIdx.z, , threadIdx.z)] thread_extent = 2\n# // attr [iter_var(threadIdx.y, , threadIdx.y)] thread_extent = 32\n# // attr [iter_var(threadIdx.x, , threadIdx.x)] thread_extent = 2\n# produce compute.local {\n# for (j.c.init, 0, 1) {\n# tvm_fill_fragment(compute.local, 16, 16, 16, 0, 0f)\n# }\n# // attr [iter_var(k.outer, )] pragma_tensor_core = 1\n# for (k.outer, 0, 2) {\n# produce A.shared {\n# for (ax0.ax1.outer.fused.outer, 0, 8) {\n# // attr [iter_var(threadIdx.y, , threadIdx.y)] thread_extent = 32\n# // attr [iter_var(threadIdx.z, , threadIdx.z)] thread_extent = 2\n# // attr [iter_var(threadIdx.x, , threadIdx.x)] thread_extent = 2\n# A.shared[ramp((((((ax0.ax1.outer.fused.outer*1056) + (floordiv(threadIdx.y, 8)*264)) + (floormod(threadIdx.y, 8)*32)) + (threadIdx.z*16)) + (threadIdx.x*8)), 1, 8)] = A[ramp(((((((ax0.ax1.outer.fused.outer*2048) + (floordiv(threadIdx.y, 8)*512)) + (k.outer*256)) + (floormod(threadIdx.y, 8)*32)) + (threadIdx.z*16)) + (threadIdx.x*8)), 1, 8)]\n# }\n# }\n# produce B.shared {\n# for (ax0.ax1.outer.fused.outer, 0, 8) {\n# // attr [iter_var(threadIdx.y, , threadIdx.y)] thread_extent = 32\n# // attr [iter_var(threadIdx.z, , threadIdx.z)] thread_extent = 2\n# // attr [iter_var(threadIdx.x, , threadIdx.x)] thread_extent = 2\n# B.shared[ramp(((((ax0.ax1.outer.fused.outer*1024) + (threadIdx.y*32)) + (threadIdx.z*16)) + (threadIdx.x*8)), 1, 8)] = B[ramp(((((((k.outer*131072) + (ax0.ax1.outer.fused.outer*16384)) + (threadIdx.y*512)) + (blockIdx.x*32)) + (threadIdx.z*16)) + (threadIdx.x*8)), 1, 8)]\n# }\n# }\n# for (k.inner.outer, 0, 16) {\n# produce A.shared.local {\n# for (ax1, 0, 1) {\n# tvm_load_matrix_sync(A.shared.local, 16, 16, 16, 0, &(A.shared[(((threadIdx.y/16)*4224) + (k.inner.outer*16))]), 264, \"col_major\")\n# }\n# }\n# produce B.shared.local {\n# for (ax0, 0, 1) {\n# for (ax1, 0, 1) {\n# tvm_load_matrix_sync(B.shared.local, 16, 16, 16, 0, &(B.shared[((k.inner.outer*512) + (threadIdx.z*16))]), 32, \"col_major\")\n# }\n# }\n# }\n# for (k.inner.inner, 0, 1) {\n# for (j.c, 0, 1) {\n# tvm_mma_sync(compute.local, 0, B.shared.local, 0, A.shared.local, 0, compute.local, 0)\n# }\n# }\n# }\n# }\n# }\n# for (j.inner.inner.inner, 0, 1) {\n# tvm_store_matrix_sync(compute.local, 16, 16, 16, 0, &(compute[((((threadIdx.y/16)*8192) + (blockIdx.x*32)) + (threadIdx.z*16))]), 512, \"col_major\")\n# }\n# }\n#\n# #include <cuda_fp16.h>\n# __device__ half max(const half a, const half b)\n# {\n# return __hgt(__half(a), __half(b)) ? a : b;\n# }\n# __device__ half min(const half a, const half b)\n# {\n# return __hlt(__half(a), __half(b)) ? a : b;\n# }\n# __device__ half operator+(const volatile __half &a, const volatile __half &b)\n# {\n# return __hadd(a, b);\n# }\n# __device__ half operator<=(const volatile __half &a, const volatile __half &b)\n# {\n# return __hlt(a, b);\n# }\n# __device__ half operator*(const volatile __half &a, const volatile __half &b)\n# {\n# return __hmul(a, b);\n# }\n# #include <mma.h>\n# extern \"C\" __global__ void default_function_kernel0( half* __restrict__ A, half* __restrict__ B, float* __restrict__ compute) {\n# nvcuda::wmma::fragment<nvcuda::wmma::accumulator, 16, 16, 16, float> compute_local[1];\n# __shared__ half A_shared[8448];\n# __shared__ half B_shared[8192];\n# nvcuda::wmma::fragment<nvcuda::wmma::matrix_b, 16, 16, 16, half, nvcuda::wmma::col_major> A_shared_local[1];\n# nvcuda::wmma::fragment<nvcuda::wmma::matrix_a, 16, 16, 16, half, nvcuda::wmma::col_major> B_shared_local[1];\n# for (int j_c_init = 0; j_c_init < 1; ++j_c_init) {\n# (void)nvcuda::wmma::fill_fragment(compute_local[0], 0.000000e+00f);\n# }\n# for (int k_outer = 0; k_outer < 2; ++k_outer) {\n# __syncthreads();\n# for (int ax0_ax1_outer_fused_outer = 0; ax0_ax1_outer_fused_outer < 8; ++ax0_ax1_outer_fused_outer) {\n# ((__shared__ float4*)(A_shared + (((((ax0_ax1_outer_fused_outer * 1056) + ((((int)threadIdx.y) >> 3) * 264)) + ((((int)threadIdx.y) & 7) * 32)) + (((int)threadIdx.z) * 16)) + (((int)threadIdx.x) * 8))))[0] = (( float4*)(A + ((((((ax0_ax1_outer_fused_outer * 2048) + ((((int)threadIdx.y) >> 3) * 512)) + (k_outer * 256)) + ((((int)threadIdx.y) & 7) * 32)) + (((int)threadIdx.z) * 16)) + (((int)threadIdx.x) * 8))))[0];\n# }\n# for (int ax0_ax1_outer_fused_outer1 = 0; ax0_ax1_outer_fused_outer1 < 8; ++ax0_ax1_outer_fused_outer1) {\n# ((__shared__ float4*)(B_shared + ((((ax0_ax1_outer_fused_outer1 * 1024) + (((int)threadIdx.y) * 32)) + (((int)threadIdx.z) * 16)) + (((int)threadIdx.x) * 8))))[0] = (( float4*)(B + ((((((k_outer * 131072) + (ax0_ax1_outer_fused_outer1 * 16384)) + (((int)threadIdx.y) * 512)) + (((int)blockIdx.x) * 32)) + (((int)threadIdx.z) * 16)) + (((int)threadIdx.x) * 8))))[0];\n# }\n# __syncthreads();\n# for (int k_inner_outer = 0; k_inner_outer < 16; ++k_inner_outer) {\n# for (int ax1 = 0; ax1 < 1; ++ax1) {\n# (void)nvcuda::wmma::load_matrix_sync(A_shared_local[0], &(A_shared[(((((int)threadIdx.y) / 16) * 4224) + (k_inner_outer * 16))]), 264);\n# }\n# for (int ax0 = 0; ax0 < 1; ++ax0) {\n# for (int ax11 = 0; ax11 < 1; ++ax11) {\n# (void)nvcuda::wmma::load_matrix_sync(B_shared_local[0], &(B_shared[((k_inner_outer * 512) + (((int)threadIdx.z) * 16))]), 32);\n# }\n# }\n# for (int k_inner_inner = 0; k_inner_inner < 1; ++k_inner_inner) {\n# for (int j_c = 0; j_c < 1; ++j_c) {\n# (void)nvcuda::wmma::mma_sync(compute_local[0], B_shared_local[0], A_shared_local[0], compute_local[0]);\n# }\n# }\n# }\n# }\n# for (int j_inner_inner_inner = 0; j_inner_inner_inner < 1; ++j_inner_inner_inner) {\n# (void)nvcuda::wmma::store_matrix_sync(&(compute[((((((int)threadIdx.y) / 16) * 8192) + (((int)blockIdx.x) * 32)) + (((int)threadIdx.z) * 16))]), compute_local[0], 512, nvcuda::wmma::mem_col_major);\n# }\n# }\n#\n#\n# Time cost of this operator: 0.000008\n\n###############################################################################\n# Summary\n# -------\n# This tutorial demonstrates how to use the AutoTensorCoreCodeGen of TVM\n# to generate tensorcore kernels.\n",
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib import graph_runtime\nfrom tvm.relay.testing.config import ctx_list\nimport keras\n\nimport tensorflow as tf\nfrom tensorflow import keras as tf_keras\n# prevent Keras from using up all gpu memory\nif tf.executing_eagerly():\n gpus = tf.config.list_physical_devices('GPU')\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\nelse:\n from keras.backend.tensorflow_backend import set_session\n config = tf.ConfigProto()\n config.gpu_options.per_process_gpu_memory_fraction = 0.5\n set_session(tf.Session(config=config))\n\n\ndef pytest_generate_tests(metafunc):\n # This function generates the list of tests for pytest, based\n # on scenatios that will change the parameters in which the\n # tests use to run.\n # https://docs.pytest.org/en/latest/example/parametrize.html\n idlist = []\n argvalues = []\n for scenario in metafunc.cls.scenarios:\n idlist.append(scenario[0])\n items = scenario[1].items()\n argnames = [x[0] for x in items]\n argvalues.append([x[1] for x in items])\n metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"class\")\n\n\n# Scenarios:\n# - classic keras, using keras from \"import keras\"\n# - tensorflow keras, using keras from \"from tensorflow import keras as tf_keras\"\nusing_classic_keras = (\"keras\", {\"keras\": keras})\nusing_tensorflow_keras = (\"tf_keras\", {\"keras\": tf_keras})\n\n\ndef verify_keras_frontend(keras_model, need_transpose=True, layout='NCHW'):\n # Keras frontend currently supports tensorflow backend only.\n assert(keras.backend.backend() == 'tensorflow')\n\n if layout != 'NCHW':\n need_transpose = False\n\n in_shapes = []\n for layer in keras_model._input_layers:\n if tf.executing_eagerly():\n in_shapes.append(tuple(dim if dim is not None else 1 for dim in layer.input.shape))\n else:\n in_shapes.append(tuple(dim.value if dim.value is not None else 1 for dim in layer.input.shape))\n\n\n def get_keras_output(xs, dtype='float32'):\n return keras_model.predict(xs)\n\n def get_tvm_output(xs, target, ctx, dtype='float32'):\n shape_dict = {name: x.shape for (name, x) in zip(keras_model.input_names, xs)}\n mod, params = relay.frontend.from_keras(keras_model, shape_dict, layout=layout)\n with relay.transform.build_config(opt_level=2):\n graph, lib, params = relay.build(mod,\n target,\n params=params)\n m = graph_runtime.create(graph, lib, ctx)\n for name, x in zip(keras_model.input_names, xs):\n m.set_input(name, tvm.nd.array(x.astype(dtype)))\n m.set_input(**params)\n m.run()\n return [m.get_output(i).asnumpy() for i in range(m.get_num_outputs())]\n\n def to_channels_first(arr):\n return arr.transpose([0, -1] + list(range(1, arr.ndim - 1)))\n\n def to_channels_last(arr):\n return arr.transpose([0] + list(range(2, arr.ndim)) + [1])\n\n xs = [np.random.uniform(size=shape, low=-1.0, high=1.0) for shape in in_shapes]\n keras_out = get_keras_output(xs)\n keras_out = keras_out if isinstance(keras_out, list) else [keras_out]\n for target, ctx in ctx_list():\n inputs = [to_channels_first(x) for x in xs] if need_transpose else xs\n tvm_out = get_tvm_output(inputs, target, ctx)\n for kout, tout in zip(keras_out, tvm_out):\n if need_transpose:\n tout = to_channels_last(tout)\n tvm.testing.assert_allclose(kout, tout, rtol=1e-5, atol=1e-5)\n\n\nclass TestKeras:\n scenarios = [using_classic_keras, using_tensorflow_keras]\n\n def test_forward_merge(self, keras):\n data = keras.layers.Input(shape=(32, 32, 3))\n x = keras.layers.Conv2D(8, (3, 3), padding=\"same\")(data)\n y = keras.layers.Conv2D(8, (3, 3), padding=\"same\")(x)\n z = keras.layers.Conv2D(8, (3, 3), padding=\"same\")(y)\n merge_funcs = [keras.layers.Add(),\n keras.layers.Subtract(),\n keras.layers.Multiply(),\n keras.layers.Maximum(),\n keras.layers.Average(),\n keras.layers.Concatenate()]\n for merge_func in merge_funcs:\n class_name = type(merge_func).__name__\n if class_name in ('Subtract', 'Dot'):\n out = merge_func([x, y])\n else:\n out = merge_func([x, y, z])\n keras_model = keras.models.Model(data, out)\n verify_keras_frontend(keras_model)\n\n def test_forward_merge_dot(self, keras):\n data1 = keras.layers.Input(shape=(2, 2))\n data2 = keras.layers.Input(shape=(2, 2))\n merge_funcs = [keras.layers.Dot(axes=[1, 2]),\n keras.layers.Dot(axes=[2, 1]),\n keras.layers.Dot(axes=[1, 1]),\n keras.layers.Dot(axes=[2, 2]),\n keras.layers.Dot(axes=1),\n keras.layers.Dot(axes=2)]\n for merge_func in merge_funcs:\n out = merge_func([data1, data2])\n keras_model = keras.models.Model([data1, data2], out)\n verify_keras_frontend(keras_model)\n\n def test_forward_activations(self, keras):\n data = keras.layers.Input(shape=(32, 32, 3))\n act_funcs = [keras.layers.Activation('softmax'),\n keras.layers.Softmax(),\n keras.layers.Softmax(axis=-1),\n keras.layers.Softmax(axis=1),\n keras.layers.Softmax(axis=2),\n keras.layers.Softmax(axis=3),\n keras.layers.Activation('softplus'),\n keras.layers.Activation('relu'),\n keras.layers.Activation('softsign'),\n keras.layers.Activation('hard_sigmoid'),\n keras.layers.Activation('sigmoid'),\n keras.layers.Activation('tanh'),\n keras.layers.Activation('linear'),\n keras.layers.Activation('selu'),\n keras.layers.ReLU(),\n keras.layers.ReLU(max_value=6.),\n keras.layers.ReLU(max_value=6., threshold=0.),\n keras.layers.ReLU(max_value=6., threshold=1.),\n keras.layers.ReLU(max_value=6., threshold=1., negative_slope=0.),\n keras.layers.ReLU(max_value=6., threshold=1., negative_slope=0.5),\n keras.layers.ReLU(max_value=6., threshold=1., negative_slope=1.),\n keras.layers.LeakyReLU(alpha=0.3),\n keras.layers.PReLU(weights=np.random.rand(1, 32, 32, 3)),\n keras.layers.ELU(alpha=0.5),\n keras.layers.ThresholdedReLU(theta=0.5)]\n for act_func in act_funcs:\n x = act_func(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n\n\n def test_forward_dense(self, keras):\n data = keras.layers.Input(shape=(32, 32, 1))\n x = keras.layers.Flatten()(data)\n x = keras.layers.Dropout(0.5)(x)\n x = keras.layers.Dense(10, activation='relu', kernel_initializer='uniform')(x)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n\n def test_forward_permute(self, keras):\n data = keras.layers.Input(shape=(2, 3, 4))\n x = keras.layers.Permute([2, 3, 1])(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model, need_transpose=False)\n\n def test_forward_sequential(self, keras):\n keras_model = keras.models.Sequential([\n keras.layers.Dense(16, input_dim=32, activation='relu'),\n keras.layers.Dropout(0.5),\n keras.layers.Dense(8, activation='relu'),\n keras.layers.Dropout(0.5),\n keras.layers.Dense(1, activation='sigmoid')\n ])\n verify_keras_frontend(keras_model)\n\n\n def test_forward_pool(self, keras):\n data = keras.layers.Input(shape=(32, 32, 1))\n # maxpool\n x = keras.layers.MaxPooling2D((3, 3), strides=(1, 1), padding='same')(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n # avgpool\n y = keras.layers.AveragePooling2D((3, 3), strides=(1, 1), padding='same')(data)\n keras_model = keras.models.Model(data, y)\n verify_keras_frontend(keras_model)\n\n\n def test_forward_conv(self, keras):\n data = keras.layers.Input(shape=(32, 32, 3))\n conv_funcs = [keras.layers.Conv2D(filters=10, kernel_size=(3, 3),\n strides=(2, 2), padding='same'),\n keras.layers.Conv2D(filters=10, kernel_size=(3, 3),\n dilation_rate=(2, 2), padding='same'),\n keras.layers.Conv2D(filters=1, kernel_size=(3, 3), padding='same'),\n keras.layers.DepthwiseConv2D(kernel_size=(3, 3), padding='same'),\n keras.layers.Conv2DTranspose(filters=10, kernel_size=(3, 3), padding='valid'),\n keras.layers.SeparableConv2D(filters=10, kernel_size=(3, 3), padding='same')]\n for conv_func in conv_funcs:\n x = conv_func(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n\n def test_forward_batch_norm(self, keras):\n data = keras.layers.Input(shape=(32, 32, 3))\n batch_norm_funcs = [keras.layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001,\n center=True, scale=False,\n beta_initializer='zeros',\n gamma_initializer='ones',\n moving_mean_initializer='zeros',\n moving_variance_initializer='ones'),\n keras.layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001,\n center=True, scale=True,\n beta_initializer='zeros',\n gamma_initializer='ones',\n moving_mean_initializer='zeros',\n moving_variance_initializer='ones'),\n keras.layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001,\n center=False, scale=True,\n beta_initializer='zeros',\n gamma_initializer='ones',\n moving_mean_initializer='zeros',\n moving_variance_initializer='ones'),\n keras.layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001,\n center=False, scale=False,\n beta_initializer='zeros',\n gamma_initializer='ones',\n moving_mean_initializer='zeros',\n moving_variance_initializer='ones')]\n for batch_norm_func in batch_norm_funcs:\n x = batch_norm_func(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n\n def test_forward_upsample(self, keras, interpolation='nearest'):\n data = keras.layers.Input(shape=(32, 32, 3))\n x = keras.layers.UpSampling2D(size=(3, 3), interpolation=interpolation)(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n\n\n def test_forward_reshape(self, keras):\n # input_shape len is 3, target_shape len is 3\n data = keras.layers.Input(shape=(32, 32, 3))\n x = keras.layers.Reshape(target_shape=(16, 64, 3))(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n # input_shape len is 3, target_shape len is 2\n data = keras.layers.Input(shape=(32, 8, 3))\n x = keras.layers.Reshape(target_shape=(256, 3))(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n # input_shape len is 2, target_shape len is 3\n data = keras.layers.Input(shape=(256, 3))\n x = keras.layers.Reshape(target_shape=(8, 32, 3))(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n # input_shape len is 2, target_shape len is 1\n data = keras.layers.Input(shape=(2, 8))\n x = keras.layers.Reshape(target_shape=(16,))(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model, need_transpose=False)\n # input_shape len is 1, target_shape len is 2\n data = keras.layers.Input(shape=(16,))\n x = keras.layers.Reshape(target_shape=(4, 4))(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model, need_transpose=False)\n # input_shape len is 2, target_shape len is 2\n data = keras.layers.Input(shape=(2, 8))\n x = keras.layers.Reshape(target_shape=(4, 4))(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model, need_transpose=False)\n\n\n def test_forward_crop(self, keras):\n data = keras.layers.Input(shape=(32, 32, 3))\n x = keras.layers.Cropping2D(cropping=((1, 1), (1, 1)))(data)\n x = keras.layers.Cropping2D(cropping=(1, 1))(x)\n x = keras.layers.Cropping2D(cropping=1)(x)\n x = keras.layers.Cropping2D(cropping=((0, 1), (1, 0)))(x)\n x = keras.layers.Cropping2D(cropping=(1, 0))(x)\n x = keras.layers.Cropping2D(cropping=0)(x)\n x = keras.layers.Add()([x, x])\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model)\n\n\n def test_forward_multi_inputs(self, keras):\n data1 = keras.layers.Input(shape=(32, 32, 3))\n data2 = keras.layers.Input(shape=(32, 32, 3))\n x = keras.layers.Conv2D(8, (3, 3), padding=\"same\")(data1)\n y = keras.layers.Conv2D(8, (3, 3), padding=\"same\")(data2)\n z = keras.layers.Average()([x, y])\n z = keras.layers.GlobalAveragePooling2D()(z)\n keras_model = keras.models.Model([data1, data2], z)\n verify_keras_frontend(keras_model)\n\n\n def test_forward_multi_outputs(self, keras):\n data = keras.layers.Input(shape=(32, 32, 3))\n x = keras.layers.Conv2D(8, (3, 3), padding=\"same\")(data)\n x = keras.layers.GlobalAveragePooling2D()(x)\n y = keras.layers.Conv2D(8, (3, 3), padding=\"same\")(data)\n y = keras.layers.GlobalAveragePooling2D()(y)\n keras_model = keras.models.Model(data, [x, y])\n verify_keras_frontend(keras_model)\n\n\n def test_forward_reuse_layers(self, keras):\n # reuse conv2d\n data = keras.layers.Input(shape=(32, 32, 3))\n conv2d = keras.layers.Conv2D(8, (3, 3), padding=\"same\")\n x = conv2d(data)\n y = conv2d(data)\n z = keras.layers.Add()([x, y])\n z = keras.layers.GlobalAveragePooling2D()(z)\n keras_model = keras.models.Model(data, z)\n verify_keras_frontend(keras_model)\n # reuse add\n data = keras.layers.Input(shape=(32, 32, 3))\n x = keras.layers.Conv2D(8, (3, 3), padding=\"same\")(data)\n add = keras.layers.Add()\n x = add([x, x])\n x = add([x, x])\n z = keras.layers.GlobalAveragePooling2D()(x)\n keras_model = keras.models.Model(data, z)\n verify_keras_frontend(keras_model)\n\n\n def test_forward_rnn(self,keras):\n data = keras.layers.Input(shape=(1, 32))\n rnn_funcs = [keras.layers.LSTM(units=16, return_state=False,\n recurrent_activation='sigmoid', activation='tanh'),\n keras.layers.SimpleRNN(units=16, return_state=False,\n activation='tanh'),\n keras.layers.GRU(units=16, return_state=False,\n recurrent_activation='sigmoid', activation='tanh')]\n for rnn_func in rnn_funcs:\n x = rnn_func(data)\n keras_model = keras.models.Model(data, x)\n verify_keras_frontend(keras_model, need_transpose=False)\n\n\n def test_forward_vgg16(self, keras, layout='NCHW'):\n keras_model = keras.applications.VGG16(include_top=True, weights='imagenet',\n input_shape=(224, 224, 3), classes=1000)\n verify_keras_frontend(keras_model, layout=layout)\n\n\n def test_forward_xception(self, keras, layout='NCHW'):\n keras_model = keras.applications.Xception(include_top=True, weights='imagenet',\n input_shape=(299, 299, 3), classes=1000)\n verify_keras_frontend(keras_model, layout=layout)\n\n\n def test_forward_resnet50(self, keras, layout='NCHW'):\n keras_model = keras.applications.ResNet50(include_top=True, weights='imagenet',\n input_shape=(224, 224, 3), classes=1000)\n verify_keras_frontend(keras_model, layout=layout)\n\n\n def test_forward_mobilenet(self, keras, layout='NCHW'):\n keras_model = keras.applications.MobileNet(include_top=True, weights='imagenet',\n input_shape=(224, 224, 3), classes=1000)\n verify_keras_frontend(keras_model, layout=layout)\n\n\nif __name__ == '__main__':\n for k in [keras, tf_keras]:\n sut = TestKeras()\n sut.test_forward_merge_dot(keras=k)\n sut.test_forward_merge(keras=k)\n sut.test_forward_activations(keras=k)\n sut.test_forward_dense(keras=k)\n sut.test_forward_permute(keras=k)\n sut.test_forward_sequential(keras=k)\n sut.test_forward_pool(keras=k)\n sut.test_forward_conv(keras=k)\n sut.test_forward_batch_norm(keras=k)\n sut.test_forward_upsample(keras=k, interpolation='nearest')\n sut.test_forward_upsample(keras=k, interpolation='bilinear')\n sut.test_forward_reshape(keras=k)\n sut.test_forward_crop(keras=k)\n sut.test_forward_multi_inputs(keras=k)\n sut.test_forward_multi_outputs(keras=k)\n sut.test_forward_reuse_layers(keras=k)\n sut.test_forward_rnn(keras=k)\n sut.test_forward_vgg16(keras=k)\n sut.test_forward_vgg16(keras=k, layout='NHWC')\n sut.test_forward_xception(keras=k)\n sut.test_forward_resnet50(keras=k)\n sut.test_forward_resnet50(keras=k, layout='NHWC')\n sut.test_forward_mobilenet(keras=k)\n sut.test_forward_mobilenet(keras=k, layout='NHWC')\n",
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport tvm\nfrom tvm import nd, relay\nfrom tvm.runtime import container as _container\n\n\ndef test_adt_constructor():\n arr = nd.array([1, 2, 3])\n fields = [arr, arr]\n y = _container.ADT(0, [arr, arr])\n\n assert len(y) == 2\n assert isinstance(y, _container.ADT)\n y[0:1][-1] == arr\n assert y.tag == 0\n assert isinstance(arr, nd.NDArray)\n\n\ndef test_tuple_object():\n x = relay.var(\n 'x',\n type_annotation=relay.ty.TupleType([\n relay.ty.TensorType((), 'int32'),\n relay.ty.TensorType((), 'int32')\n ]))\n\n fn = relay.Function([x], relay.expr.TupleGetItem(x, 0))\n mod = tvm.IRModule.from_expr(fn)\n\n exe = relay.create_executor(\n kind=\"vm\", mod=mod, ctx=nd.cpu(), target=\"llvm\")\n f = exe.evaluate()\n value_tuple = _container.tuple_object(\n [nd.array(np.array(11)),\n nd.array(np.array(12))])\n # pass an ADT object to evaluate\n out = f(value_tuple)\n tvm.testing.assert_allclose(out.asnumpy(), np.array(11))\n\n\nif __name__ == \"__main__\":\n test_adt_constructor()\n test_tuple_object()\n"
] |
[
[
"numpy.dot",
"numpy.random.randint",
"numpy.zeros",
"numpy.random.uniform"
],
[
"numpy.random.rand",
"tensorflow.Session",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.executing_eagerly",
"tensorflow.ConfigProto",
"numpy.random.uniform",
"tensorflow.config.list_physical_devices"
],
[
"numpy.array"
]
] |
ariekahn/nilearn
|
[
"baa77b18ecee7c4507579214af59d715cc9292f9"
] |
[
"nilearn/reporting/tests/test_reporting.py"
] |
[
"import os\n\nimport nibabel as nib\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom nibabel.tmpdirs import InTemporaryDirectory\n# Set backend to avoid DISPLAY problems\nfrom nilearn.plotting import _set_mpl_backend\n\nfrom nilearn.glm.first_level.design_matrix import make_first_level_design_matrix\nfrom nilearn.reporting import (get_clusters_table,\n plot_contrast_matrix,\n plot_event,\n plot_design_matrix,\n )\nfrom nilearn.reporting._get_clusters_table import _local_max\n\n# Avoid making pyflakes unhappy\n_set_mpl_backend\ntry:\n import matplotlib.pyplot\n # Avoid making pyflakes unhappy\n matplotlib.pyplot\nexcept ImportError:\n have_mpl = False\nelse:\n have_mpl = True\n\n\n@pytest.mark.skipif(not have_mpl,\n reason='Matplotlib not installed; required for this test')\ndef test_show_design_matrix():\n # test that the show code indeed (formally) runs\n frame_times = np.linspace(0, 127 * 1., 128)\n dmtx = make_first_level_design_matrix(\n frame_times, drift_model='polynomial', drift_order=3)\n ax = plot_design_matrix(dmtx)\n assert (ax is not None)\n with InTemporaryDirectory():\n ax = plot_design_matrix(dmtx, output_file='dmtx.png')\n assert os.path.exists('dmtx.png')\n assert (ax is None)\n plot_design_matrix(dmtx, output_file='dmtx.pdf')\n assert os.path.exists('dmtx.pdf')\n\n\n@pytest.mark.skipif(not have_mpl,\n reason='Matplotlib not installed; required for this test')\ndef test_show_event_plot():\n # test that the show code indeed (formally) runs\n onset = np.linspace(0, 19., 20)\n duration = np.full(20, 0.5)\n trial_idx = np.arange(20)\n # This makes 11 events in order to test cmap error\n trial_idx[11:] -= 10\n condition_ids = ['a', 'b', 'c', 'd', 'e', 'f',\n 'g', 'h', 'i', 'j', 'k']\n\n trial_type = np.array([condition_ids[i] for i in trial_idx])\n\n model_event = pd.DataFrame({\n 'onset': onset,\n 'duration': duration,\n 'trial_type': trial_type\n })\n # Test Dataframe\n fig = plot_event(model_event)\n assert (fig is not None)\n\n # Test List\n fig = plot_event([model_event, model_event])\n assert (fig is not None)\n \n # Test error\n with pytest.raises(ValueError):\n fig = plot_event(model_event, cmap='tab10')\n\n # Test save\n with InTemporaryDirectory():\n fig = plot_event(model_event, output_file='event.png')\n assert os.path.exists('event.png')\n assert (fig is None)\n plot_event(model_event, output_file='event.pdf')\n assert os.path.exists('event.pdf')\n \n\n@pytest.mark.skipif(not have_mpl,\n reason='Matplotlib not installed; required for this test')\ndef test_show_contrast_matrix():\n # test that the show code indeed (formally) runs\n frame_times = np.linspace(0, 127 * 1., 128)\n dmtx = make_first_level_design_matrix(\n frame_times, drift_model='polynomial', drift_order=3)\n contrast = np.ones(4)\n ax = plot_contrast_matrix(contrast, dmtx)\n assert (ax is not None)\n with InTemporaryDirectory():\n ax = plot_contrast_matrix(contrast, dmtx, output_file='contrast.png')\n assert os.path.exists('contrast.png')\n assert (ax is None)\n plot_contrast_matrix(contrast, dmtx, output_file='contrast.pdf')\n assert os.path.exists('contrast.pdf')\n\n\ndef test_local_max():\n shape = (9, 10, 11)\n data = np.zeros(shape)\n # Two maxima (one global, one local), 10 voxels apart.\n data[4, 5, :] = [4, 3, 2, 1, 1, 1, 1, 1, 2, 3, 4]\n data[5, 5, :] = [5, 4, 3, 2, 1, 1, 1, 2, 3, 4, 6]\n data[6, 5, :] = [4, 3, 2, 1, 1, 1, 1, 1, 2, 3, 4]\n affine = np.eye(4)\n\n ijk, vals = _local_max(data, affine, min_distance=9)\n assert np.array_equal(ijk, np.array([[5., 5., 10.], [5., 5., 0.]]))\n assert np.array_equal(vals, np.array([6, 5]))\n\n ijk, vals = _local_max(data, affine, min_distance=11)\n assert np.array_equal(ijk, np.array([[5., 5., 10.]]))\n assert np.array_equal(vals, np.array([6]))\n\n\ndef test_get_clusters_table():\n shape = (9, 10, 11)\n data = np.zeros(shape)\n data[2:4, 5:7, 6:8] = 5.\n stat_img = nib.Nifti1Image(data, np.eye(4))\n\n # test one cluster extracted\n cluster_table = get_clusters_table(stat_img, 4, 0)\n assert len(cluster_table) == 1\n\n # test empty table on high stat threshold\n cluster_table = get_clusters_table(stat_img, 6, 0)\n assert len(cluster_table) == 0\n\n # test empty table on high cluster threshold\n cluster_table = get_clusters_table(stat_img, 4, 9)\n assert len(cluster_table) == 0\n"
] |
[
[
"numpy.full",
"numpy.array",
"numpy.zeros",
"pandas.DataFrame",
"numpy.ones",
"numpy.eye",
"numpy.arange",
"numpy.linspace"
]
] |
yxing0225/Masked_Face_Detection-Recognition
|
[
"126c5bebcefb5b5fbbb105007f32574cb9359064"
] |
[
"Train_faceNet_model/Train+FaceNet+model/tf_slim/summaries_test.py"
] |
[
"# coding=utf-8\n# coding=utf-8\n# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tf_slim.summaries.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport glob\nimport os\nimport tempfile\nimport tensorflow.compat.v1 as tf\nfrom tf_slim import summaries\n# pylint:disable=g-direct-tensorflow-import\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.summary import summary\nfrom tensorflow.python.summary import summary_iterator\n# pylint:enable=g-direct-tensorflow-import\n\n\ndef setUpModule():\n tf.disable_eager_execution()\n\n\nclass SummariesTest(test.TestCase):\n\n def assert_scalar_summary(self, output_dir, names_to_values):\n \"\"\"Asserts that the given output directory contains written summaries.\n\n Args:\n output_dir: The output directory in which to look for even tfiles.\n names_to_values: A dictionary of summary names to values.\n \"\"\"\n # The events file may have additional entries, e.g. the event version\n # stamp, so have to parse things a bit.\n output_filepath = glob.glob(os.path.join(output_dir, '*'))\n self.assertEqual(len(output_filepath), 1)\n\n events = summary_iterator.summary_iterator(output_filepath[0])\n summaries_list = [e.summary for e in events if e.summary.value]\n values = []\n for item in summaries_list:\n for value in item.value:\n values.append(value)\n saved_results = {v.tag: v.simple_value for v in values}\n for name in names_to_values:\n self.assertAlmostEqual(names_to_values[name], saved_results[name])\n\n def testScalarSummaryIsPartOfCollectionWithNoPrint(self):\n tensor = array_ops.ones([]) * 3\n name = 'my_score'\n prefix = 'eval'\n op = summaries.add_scalar_summary(tensor, name, prefix, print_summary=False)\n self.assertIn(op, ops.get_collection(ops.GraphKeys.SUMMARIES))\n\n def testScalarSummaryIsPartOfCollectionWithPrint(self):\n tensor = array_ops.ones([]) * 3\n name = 'my_score'\n prefix = 'eval'\n op = summaries.add_scalar_summary(tensor, name, prefix, print_summary=True)\n self.assertIn(op, ops.get_collection(ops.GraphKeys.SUMMARIES))\n\n def verify_scalar_summary_is_written(self, print_summary):\n value = 3\n tensor = array_ops.ones([]) * value\n name = 'my_score'\n prefix = 'eval'\n summaries.add_scalar_summary(tensor, name, prefix, print_summary)\n\n output_dir = tempfile.mkdtemp('scalar_summary_no_print_test')\n summary_op = summary.merge_all()\n\n summary_writer = summary.FileWriter(output_dir)\n with self.cached_session() as sess:\n new_summary = sess.run(summary_op)\n summary_writer.add_summary(new_summary, 1)\n summary_writer.flush()\n\n self.assert_scalar_summary(output_dir, {\n '%s/%s' % (prefix, name): value\n })\n\n def testScalarSummaryIsWrittenWithNoPrint(self):\n self.verify_scalar_summary_is_written(print_summary=False)\n\n def testScalarSummaryIsWrittenWithPrint(self):\n self.verify_scalar_summary_is_written(print_summary=True)\n\n\nif __name__ == '__main__':\n test.main()\n"
] |
[
[
"tensorflow.python.framework.ops.get_collection",
"tensorflow.python.summary.summary.merge_all",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.summary.summary.FileWriter",
"tensorflow.python.summary.summary_iterator.summary_iterator",
"tensorflow.compat.v1.disable_eager_execution"
]
] |
dmund95/CAN-LDADA
|
[
"6efe6a6d3312f268dfb638d7ca29e80bb5966dcc"
] |
[
"solver/base_solver.py"
] |
[
"import torch\nimport torch.nn as nn\nimport os\nfrom . import utils as solver_utils \nfrom utils.utils import to_cuda, mean_accuracy, accuracy\nfrom torch import optim\nfrom math import ceil as ceil\nfrom config.config import cfg\n\nclass BaseSolver:\n def __init__(self, net, dpn, dataloader, bn_domain_map={}, resume=None, **kwargs):\n self.opt = cfg\n self.source_name = self.opt.DATASET.SOURCE_NAME\n self.target_name = self.opt.DATASET.TARGET_NAME\n\n self.net = net\n self.dpn = dpn\n self.init_data(dataloader)\n\n self.CELoss = nn.CrossEntropyLoss()\n if torch.cuda.is_available():\n self.CELoss.cuda() \n\n self.loop = 0\n self.iters = 0\n self.iters_per_loop = None\n self.history = {}\n\n self.base_lr = self.opt.TRAIN.BASE_LR\n self.momentum = self.opt.TRAIN.MOMENTUM\n\n self.bn_domain_map = bn_domain_map\n\n self.optim_state_dict = None\n self.resume = False\n if resume is not None:\n self.resume = True\n self.loop = resume['loop']\n self.iters = resume['iters']\n self.history = resume['history']\n self.optim_state_dict = resume['optimizer_state_dict']\n self.bn_domain_map = resume['bn_domain_map']\n print('Resume Training from loop %d, iters %d.' % \\\n\t\t\t(self.loop, self.iters))\n\n self.build_optimizer()\n\n def init_data(self, dataloader):\n self.train_data = {key: dict() for key in dataloader if key != 'test'}\n for key in self.train_data.keys():\n if key not in dataloader:\n continue\n cur_dataloader = dataloader[key]\n self.train_data[key]['loader'] = cur_dataloader \n self.train_data[key]['iterator'] = None\n\n if 'test' in dataloader:\n self.test_data = dict()\n self.test_data['loader'] = dataloader['test']\n \n def build_optimizer(self):\n opt = self.opt\n param_groups = solver_utils.set_param_groups(self.net, \n\t\tdict({'FC': opt.TRAIN.LR_MULT})) + solver_utils.set_param_groups(self.dpn, \n\t\tdict({'FC': opt.TRAIN.LR_MULT/10}))\n\n assert opt.TRAIN.OPTIMIZER in [\"Adam\", \"SGD\"], \\\n \"Currently do not support your specified optimizer.\"\n\n if opt.TRAIN.OPTIMIZER == \"Adam\":\n self.optimizer = optim.Adam(param_groups, \n\t\t\tlr=self.base_lr, betas=[opt.ADAM.BETA1, opt.ADAM.BETA2], \n\t\t\tweight_decay=opt.TRAIN.WEIGHT_DECAY)\n\n elif opt.TRAIN.OPTIMIZER == \"SGD\":\n self.optimizer = optim.SGD(param_groups, \n\t\t\tlr=self.base_lr, momentum=self.momentum, \n\t\t\tweight_decay=opt.TRAIN.WEIGHT_DECAY)\n\n if self.optim_state_dict is not None:\n self.optimizer.load_state_dict(self.optim_state_dict)\n\n def update_lr(self):\n iters = self.iters\n if self.opt.TRAIN.LR_SCHEDULE == 'exp':\n solver_utils.adjust_learning_rate_exp(self.base_lr, \n\t\t\tself.optimizer, iters, \n decay_rate=self.opt.EXP.LR_DECAY_RATE,\n\t\t\tdecay_step=self.opt.EXP.LR_DECAY_STEP)\n\n elif self.opt.TRAIN.LR_SCHEDULE == 'inv':\n solver_utils.adjust_learning_rate_inv(self.base_lr, self.optimizer, \n\t\t iters, self.opt.INV.ALPHA, self.opt.INV.BETA)\n\n else:\n raise NotImplementedError(\"Currently don't support the specified \\\n learning rate schedule: %s.\" % self.opt.TRAIN.LR_SCHEDULE)\n\n def logging(self, loss, accu):\n print('[loop: %d, iters: %d]: ' % (self.loop, self.iters))\n loss_names = \"\"\n loss_values = \"\"\n for key in loss:\n loss_names += key + \",\"\n loss_values += '%.4f,' % (loss[key])\n loss_names = loss_names[:-1] + ': '\n loss_values = loss_values[:-1] + ';'\n loss_str = loss_names + loss_values + (' source %s: %.4f.' % \n (self.opt.EVAL_METRIC, accu))\n print(loss_str)\n\n def model_eval(self, preds, gts):\n assert(self.opt.EVAL_METRIC in ['mean_accu', 'accuracy']), \\\n \"Currently don't support the evaluation metric you specified.\"\n\n if self.opt.EVAL_METRIC == \"mean_accu\": \n res = mean_accuracy(preds, gts)\n elif self.opt.EVAL_METRIC == \"accuracy\":\n res = accuracy(preds, gts)\n return res\n\n def save_ckpt(self):\n save_path = self.opt.SAVE_DIR\n ckpt_resume = os.path.join(save_path, 'ckpt_%d_%d.resume' % (self.loop, self.iters))\n ckpt_weights = os.path.join(save_path, 'ckpt_%d_%d.weights' % (self.loop, self.iters))\n torch.save({'loop': self.loop,\n 'iters': self.iters,\n 'model_state_dict': self.net.module.state_dict(),\n 'dpn_state_dict': self.dpn.module.state_dict(),\n 'optimizer_state_dict': self.optimizer.state_dict(),\n 'history': self.history,\n 'bn_domain_map': self.bn_domain_map\n }, ckpt_resume)\n\n torch.save({'weights': self.net.module.state_dict(),\n 'dpn_weights': self.dpn.module.state_dict(),\n 'bn_domain_map': self.bn_domain_map\n }, ckpt_weights)\n\n def complete_training(self):\n if self.loop > self.opt.TRAIN.MAX_LOOP:\n return True\n\n def register_history(self, key, value, history_len):\n if key not in self.history:\n self.history[key] = [value]\n else:\n self.history[key] += [value]\n \n if len(self.history[key]) > history_len:\n self.history[key] = \\\n self.history[key][len(self.history[key]) - history_len:]\n \n def solve(self):\n print('Training Done!')\n\n def get_samples(self, data_name):\n assert(data_name in self.train_data)\n assert('loader' in self.train_data[data_name] and \\\n 'iterator' in self.train_data[data_name])\n\n data_loader = self.train_data[data_name]['loader']\n data_iterator = self.train_data[data_name]['iterator']\n assert data_loader is not None and data_iterator is not None, \\\n 'Check your dataloader of %s.' % data_name \n\n try:\n sample = next(data_iterator)\n except StopIteration:\n data_iterator = iter(data_loader)\n sample = next(data_iterator)\n self.train_data[data_name]['iterator'] = data_iterator\n return sample\n\n def get_samples_categorical(self, data_name, category):\n assert(data_name in self.train_data)\n assert('loader' in self.train_data[data_name] and \\\n 'iterator' in self.train_data[data_name])\n\n data_loader = self.train_data[data_name]['loader'][category]\n data_iterator = self.train_data[data_name]['iterator'][category]\n assert data_loader is not None and data_iterator is not None, \\\n 'Check your dataloader of %s.' % data_name\n\n try:\n sample = next(data_iterator)\n except StopIteration:\n data_iterator = iter(data_loader)\n sample = next(data_iterator)\n self.train_data[data_name]['iterator'][category] = data_iterator\n\n return sample\n\n def test(self):\n self.net.eval()\n preds = []\n gts = []\n for sample in iter(self.test_data['loader']):\n data, gt = to_cuda(sample['Img']), to_cuda(sample['Label'])\n logits = self.net(data)['logits']\n preds += [logits]\n gts += [gt]\n\n preds = torch.cat(preds, dim=0)\n gts = torch.cat(gts, dim=0)\n\n res = self.model_eval(preds, gts)\n return res\n\n def clear_history(self, key):\n if key in self.history:\n self.history[key].clear()\n\n def solve(self):\n pass\n\n def update_network(self, **kwargs):\n pass\n\n"
] |
[
[
"torch.cat",
"torch.optim.Adam",
"torch.optim.SGD",
"torch.cuda.is_available",
"torch.nn.CrossEntropyLoss"
]
] |
pentschev/sparse
|
[
"948cee79dbfba9c69ea52f04806e0f9dc5e05032"
] |
[
"sparse/coo/core.py"
] |
[
"import copy as _copy\nimport operator\nfrom collections.abc import Iterable, Iterator, Sized\nfrom collections import defaultdict, deque\nfrom functools import reduce\nimport warnings\n\nimport numpy as np\nimport scipy.sparse\nfrom numpy.lib.mixins import NDArrayOperatorsMixin\n\nimport numba\n\nfrom .common import dot, matmul\nfrom .indexing import getitem\nfrom .umath import elemwise, broadcast_to\nfrom ..sparse_array import SparseArray\nfrom ..utils import normalize_axis, equivalent, check_zero_fill_value, _zero_of_dtype\n\n\n_reduce_super_ufunc = {\n np.add: np.multiply,\n np.multiply: np.power,\n}\n\n\nclass COO(SparseArray, NDArrayOperatorsMixin): # lgtm [py/missing-equals]\n \"\"\"\n A sparse multidimensional array.\n\n This is stored in COO format. It depends on NumPy and Scipy.sparse for\n computation, but supports arrays of arbitrary dimension.\n\n Parameters\n ----------\n coords : numpy.ndarray (COO.ndim, COO.nnz)\n An array holding the index locations of every value\n Should have shape (number of dimensions, number of non-zeros).\n data : numpy.ndarray (COO.nnz,)\n An array of Values. A scalar can also be supplied if the data is the same across\n all coordinates. If not given, defers to :obj:`as_coo`.\n shape : tuple[int] (COO.ndim,)\n The shape of the array.\n has_duplicates : bool, optional\n A value indicating whether the supplied value for :code:`coords` has\n duplicates. Note that setting this to `False` when :code:`coords` does have\n duplicates may result in undefined behaviour. See :obj:`COO.sum_duplicates`\n sorted : bool, optional\n A value indicating whether the values in `coords` are sorted. Note\n that setting this to `True` when :code:`coords` isn't sorted may\n result in undefined behaviour. See :obj:`COO.sort_indices`.\n prune : bool, optional\n A flag indicating whether or not we should prune any fill-values present in\n ``data``.\n cache : bool, optional\n Whether to enable cacheing for various operations. See\n :obj:`COO.enable_caching`\n fill_value: scalar, optional\n The fill value for this array.\n\n Attributes\n ----------\n coords : numpy.ndarray (ndim, nnz)\n An array holding the coordinates of every nonzero element.\n data : numpy.ndarray (nnz,)\n An array holding the values corresponding to :obj:`COO.coords`.\n shape : tuple[int] (ndim,)\n The dimensions of this array.\n\n See Also\n --------\n DOK : A mostly write-only sparse array.\n as_coo : Convert any given format to :obj:`COO`.\n\n Examples\n --------\n You can create :obj:`COO` objects from Numpy arrays.\n\n >>> x = np.eye(4, dtype=np.uint8)\n >>> x[2, 3] = 5\n >>> s = COO.from_numpy(x)\n >>> s\n <COO: shape=(4, 4), dtype=uint8, nnz=5, fill_value=0>\n >>> s.data # doctest: +NORMALIZE_WHITESPACE\n array([1, 1, 1, 5, 1], dtype=uint8)\n >>> s.coords # doctest: +NORMALIZE_WHITESPACE\n array([[0, 1, 2, 2, 3],\n [0, 1, 2, 3, 3]])\n\n :obj:`COO` objects support basic arithmetic and binary operations.\n\n >>> x2 = np.eye(4, dtype=np.uint8)\n >>> x2[3, 2] = 5\n >>> s2 = COO.from_numpy(x2)\n >>> (s + s2).todense() # doctest: +NORMALIZE_WHITESPACE\n array([[2, 0, 0, 0],\n [0, 2, 0, 0],\n [0, 0, 2, 5],\n [0, 0, 5, 2]], dtype=uint8)\n >>> (s * s2).todense() # doctest: +NORMALIZE_WHITESPACE\n array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]], dtype=uint8)\n\n Binary operations support broadcasting.\n\n >>> x3 = np.zeros((4, 1), dtype=np.uint8)\n >>> x3[2, 0] = 1\n >>> s3 = COO.from_numpy(x3)\n >>> (s * s3).todense() # doctest: +NORMALIZE_WHITESPACE\n array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 1, 5],\n [0, 0, 0, 0]], dtype=uint8)\n\n :obj:`COO` objects also support dot products and reductions.\n\n >>> s.dot(s.T).sum(axis=0).todense() # doctest: +NORMALIZE_WHITESPACE\n array([ 1, 1, 31, 6], dtype=uint64)\n\n You can use Numpy :code:`ufunc` operations on :obj:`COO` arrays as well.\n\n >>> np.sum(s, axis=1).todense() # doctest: +NORMALIZE_WHITESPACE\n array([1, 1, 6, 1], dtype=uint64)\n >>> np.round(np.sqrt(s, dtype=np.float64), decimals=1).todense() # doctest: +SKIP\n array([[ 1. , 0. , 0. , 0. ],\n [ 0. , 1. , 0. , 0. ],\n [ 0. , 0. , 1. , 2.2],\n [ 0. , 0. , 0. , 1. ]])\n\n Operations that will result in a dense array will usually result in a different\n fill value, such as the following.\n\n >>> np.exp(s)\n <COO: shape=(4, 4), dtype=float16, nnz=5, fill_value=1.0>\n\n You can also create :obj:`COO` arrays from coordinates and data.\n\n >>> coords = [[0, 0, 0, 1, 1],\n ... [0, 1, 2, 0, 3],\n ... [0, 3, 2, 0, 1]]\n >>> data = [1, 2, 3, 4, 5]\n >>> s4 = COO(coords, data, shape=(3, 4, 5))\n >>> s4\n <COO: shape=(3, 4, 5), dtype=int64, nnz=5, fill_value=0>\n\n If the data is same across all coordinates, you can also specify a scalar.\n\n >>> coords = [[0, 0, 0, 1, 1],\n ... [0, 1, 2, 0, 3],\n ... [0, 3, 2, 0, 1]]\n >>> data = 1\n >>> s5 = COO(coords, data, shape=(3, 4, 5))\n >>> s5\n <COO: shape=(3, 4, 5), dtype=int64, nnz=5, fill_value=0>\n\n Following scipy.sparse conventions you can also pass these as a tuple with\n rows and columns\n\n >>> rows = [0, 1, 2, 3, 4]\n >>> cols = [0, 0, 0, 1, 1]\n >>> data = [10, 20, 30, 40, 50]\n >>> z = COO((data, (rows, cols)))\n >>> z.todense() # doctest: +NORMALIZE_WHITESPACE\n array([[10, 0],\n [20, 0],\n [30, 0],\n [ 0, 40],\n [ 0, 50]])\n\n You can also pass a dictionary or iterable of index/value pairs. Repeated\n indices imply summation:\n\n >>> d = {(0, 0, 0): 1, (1, 2, 3): 2, (1, 1, 0): 3}\n >>> COO(d)\n <COO: shape=(2, 3, 4), dtype=int64, nnz=3, fill_value=0>\n >>> L = [((0, 0), 1),\n ... ((1, 1), 2),\n ... ((0, 0), 3)]\n >>> COO(L).todense() # doctest: +NORMALIZE_WHITESPACE\n array([[4, 0],\n [0, 2]])\n\n You can convert :obj:`DOK` arrays to :obj:`COO` arrays.\n\n >>> from sparse import DOK\n >>> s6 = DOK((5, 5), dtype=np.int64)\n >>> s6[1:3, 1:3] = [[4, 5], [6, 7]]\n >>> s6\n <DOK: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>\n >>> s7 = s6.asformat('coo')\n >>> s7\n <COO: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>\n >>> s7.todense() # doctest: +NORMALIZE_WHITESPACE\n array([[0, 0, 0, 0, 0],\n [0, 4, 5, 0, 0],\n [0, 6, 7, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]])\n \"\"\"\n __array_priority__ = 12\n\n def __init__(self, coords, data=None, shape=None, has_duplicates=True,\n sorted=False, prune=False, cache=False, fill_value=None):\n self._cache = None\n if cache:\n self.enable_caching()\n\n if data is None:\n arr = as_coo(coords, shape=shape, fill_value=fill_value)\n self._make_shallow_copy_of(arr)\n return\n\n self.data = np.asarray(data)\n self.coords = np.asarray(coords)\n\n if self.coords.ndim == 1:\n self.coords = self.coords[None, :]\n\n if self.data.ndim == 0:\n self.data = np.broadcast_to(self.data, self.coords.shape[1])\n\n if shape and not self.coords.size:\n self.coords = np.zeros((len(shape) if isinstance(shape, Iterable) else 1, 0), dtype=np.uint64)\n\n if shape is None:\n if self.coords.nbytes:\n shape = tuple((self.coords.max(axis=1) + 1))\n else:\n shape = ()\n\n super().__init__(shape, fill_value=fill_value)\n self.coords = self.coords.astype(np.intp)\n\n if self.shape:\n if len(self.data) != self.coords.shape[1]:\n msg = ('The data length does not match the coordinates '\n 'given.\\nlen(data) = {}, but {} coords specified.')\n raise ValueError(msg.format(len(data), self.coords.shape[1]))\n if len(self.shape) != self.coords.shape[0]:\n msg = (\"Shape specified by `shape` doesn't match the \"\n \"shape of `coords`; len(shape)={} != coords.shape[0]={}\"\n \"(and coords.shape={})\")\n raise ValueError(msg.format(len(shape),\n self.coords.shape[0],\n self.coords.shape))\n\n from .. import _AUTO_WARN_ON_TOO_DENSE\n if _AUTO_WARN_ON_TOO_DENSE and self.nbytes >= self.size * self.data.itemsize:\n warnings.warn(\"Attempting to create a sparse array that takes no less \"\n \"memory than than an equivalent dense array. You may want to \"\n \"use a dense array here instead.\", RuntimeWarning)\n\n if not sorted:\n self._sort_indices()\n\n if has_duplicates:\n self._sum_duplicates()\n\n if prune:\n self._prune()\n\n def __getstate__(self):\n return (self.coords, self.data, self.shape, self.fill_value)\n\n def __setstate__(self, state):\n self.coords, self.data, self.shape, self.fill_value = state\n self._cache = None\n\n def copy(self, deep=True):\n \"\"\"Return a copy of the array.\n\n Parameters\n ----------\n deep : boolean, optional\n If True (default), the internal coords and data arrays are also\n copied. Set to ``False`` to only make a shallow copy.\n \"\"\"\n return _copy.deepcopy(self) if deep else _copy.copy(self)\n\n def _make_shallow_copy_of(self, other):\n self.coords = other.coords\n self.data = other.data\n super().__init__(other.shape, fill_value=other.fill_value)\n\n def enable_caching(self):\n \"\"\" Enable caching of reshape, transpose, and tocsr/csc operations\n\n This enables efficient iterative workflows that make heavy use of\n csr/csc operations, such as tensordot. This maintains a cache of\n recent results of reshape and transpose so that operations like\n tensordot (which uses both internally) store efficiently stored\n representations for repeated use. This can significantly cut down on\n computational costs in common numeric algorithms.\n\n However, this also assumes that neither this object, nor the downstream\n objects will have their data mutated.\n\n Examples\n --------\n >>> s.enable_caching() # doctest: +SKIP\n >>> csr1 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr() # doctest: +SKIP\n >>> csr2 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr() # doctest: +SKIP\n >>> csr1 is csr2 # doctest: +SKIP\n True\n \"\"\"\n self._cache = defaultdict(lambda: deque(maxlen=3))\n\n @classmethod\n def from_numpy(cls, x, fill_value=None):\n \"\"\"\n Convert the given :obj:`numpy.ndarray` to a :obj:`COO` object.\n\n Parameters\n ----------\n x : np.ndarray\n The dense array to convert.\n fill_value : scalar\n The fill value of the constructed :obj:`COO` array. Zero if\n unspecified.\n\n Returns\n -------\n COO\n The converted COO array.\n\n Examples\n --------\n >>> x = np.eye(5)\n >>> s = COO.from_numpy(x)\n >>> s\n <COO: shape=(5, 5), dtype=float64, nnz=5, fill_value=0.0>\n\n >>> x[x == 0] = np.nan\n >>> COO.from_numpy(x, fill_value=np.nan)\n <COO: shape=(5, 5), dtype=float64, nnz=5, fill_value=nan>\n \"\"\"\n x = np.asanyarray(x).view(type=np.ndarray)\n\n if fill_value is None:\n fill_value = _zero_of_dtype(x.dtype)\n\n if x.shape:\n coords = np.where(~equivalent(x, fill_value))\n data = x[coords]\n coords = np.vstack(coords)\n else:\n coords = np.empty((0, 1), dtype=np.uint8)\n data = np.array(x, ndmin=1)\n return cls(coords, data, shape=x.shape, has_duplicates=False,\n sorted=True, fill_value=fill_value)\n\n def todense(self):\n \"\"\"\n Convert this :obj:`COO` array to a dense :obj:`numpy.ndarray`. Note that\n this may take a large amount of memory if the :obj:`COO` object's :code:`shape`\n is large.\n\n Returns\n -------\n numpy.ndarray\n The converted dense array.\n\n See Also\n --------\n DOK.todense : Equivalent :obj:`DOK` array method.\n scipy.sparse.coo_matrix.todense : Equivalent Scipy method.\n\n Examples\n --------\n >>> x = np.random.randint(100, size=(7, 3))\n >>> s = COO.from_numpy(x)\n >>> x2 = s.todense()\n >>> np.array_equal(x, x2)\n True\n \"\"\"\n x = np.full(self.shape, self.fill_value, self.dtype)\n\n coords = tuple([self.coords[i, :] for i in range(self.ndim)])\n data = self.data\n\n if coords != ():\n x[coords] = data\n else:\n if len(data) != 0:\n x[coords] = data\n\n return x\n\n @classmethod\n def from_scipy_sparse(cls, x):\n \"\"\"\n Construct a :obj:`COO` array from a :obj:`scipy.sparse.spmatrix`\n\n Parameters\n ----------\n x : scipy.sparse.spmatrix\n The sparse matrix to construct the array from.\n\n Returns\n -------\n COO\n The converted :obj:`COO` object.\n\n Examples\n --------\n >>> x = scipy.sparse.rand(6, 3, density=0.2)\n >>> s = COO.from_scipy_sparse(x)\n >>> np.array_equal(x.todense(), s.todense())\n True\n \"\"\"\n x = x.asformat('coo')\n coords = np.empty((2, x.nnz), dtype=x.row.dtype)\n coords[0, :] = x.row\n coords[1, :] = x.col\n return COO(coords, x.data, shape=x.shape,\n has_duplicates=not x.has_canonical_format,\n sorted=x.has_canonical_format)\n\n @classmethod\n def from_iter(cls, x, shape=None, fill_value=None):\n \"\"\"\n Converts an iterable in certain formats to a :obj:`COO` array. See examples\n for details.\n\n Parameters\n ----------\n x : Iterable or Iterator\n The iterable to convert to :obj:`COO`.\n shape : tuple[int], optional\n The shape of the array.\n fill_value : scalar\n The fill value for this array.\n\n Returns\n -------\n out : COO\n The output :obj:`COO` array.\n\n Examples\n --------\n You can convert items of the format ``[((i, j, k), value), ((i, j, k), value)]`` to :obj:`COO`.\n Here, the first part represents the coordinate and the second part represents the value.\n\n >>> x = [((0, 0), 1), ((1, 1), 1)]\n >>> s = COO.from_iter(x)\n >>> s.todense()\n array([[1, 0],\n [0, 1]])\n\n You can also have a similar format with a dictionary.\n\n >>> x = {(0, 0): 1, (1, 1): 1}\n >>> s = COO.from_iter(x)\n >>> s.todense()\n array([[1, 0],\n [0, 1]])\n\n The third supported format is ``(data, (..., row, col))``.\n\n >>> x = ([1, 1], ([0, 1], [0, 1]))\n >>> s = COO.from_iter(x)\n >>> s.todense()\n array([[1, 0],\n [0, 1]])\n\n You can also pass in a :obj:`collections.Iterator` object.\n\n >>> x = [((0, 0), 1), ((1, 1), 1)].__iter__()\n >>> s = COO.from_iter(x)\n >>> s.todense()\n array([[1, 0],\n [0, 1]])\n \"\"\"\n if isinstance(x, dict):\n x = list(x.items())\n\n if not isinstance(x, Sized):\n x = list(x)\n\n if len(x) != 2 and not all(len(item) == 2 for item in x):\n raise ValueError('Invalid iterable to convert to COO.')\n\n if not x:\n ndim = 0 if shape is None else len(shape)\n coords = np.empty((ndim, 0), dtype=np.uint8)\n data = np.empty((0,))\n shape = () if shape is None else shape\n\n elif not isinstance(x[0][0], Iterable):\n coords = np.stack(x[1], axis=0)\n data = np.asarray(x[0])\n else:\n coords = np.array([item[0] for item in x]).T\n data = np.array([item[1] for item in x])\n\n if not (coords.ndim == 2 and data.ndim == 1 and\n np.issubdtype(coords.dtype, np.integer) and np.all(coords >= 0)):\n raise ValueError('Invalid iterable to convert to COO.')\n\n return COO(coords, data, shape=shape, fill_value=fill_value)\n\n @property\n def dtype(self):\n \"\"\"\n The datatype of this array.\n\n Returns\n -------\n numpy.dtype\n The datatype of this array.\n\n See Also\n --------\n numpy.ndarray.dtype : Numpy equivalent property.\n scipy.sparse.coo_matrix.dtype : Scipy equivalent property.\n\n Examples\n --------\n >>> x = (200 * np.random.rand(5, 4)).astype(np.int32)\n >>> s = COO.from_numpy(x)\n >>> s.dtype\n dtype('int32')\n >>> x.dtype == s.dtype\n True\n \"\"\"\n return self.data.dtype\n\n @property\n def nnz(self):\n \"\"\"\n The number of nonzero elements in this array. Note that any duplicates in\n :code:`coords` are counted multiple times. To avoid this, call :obj:`COO.sum_duplicates`.\n\n Returns\n -------\n int\n The number of nonzero elements in this array.\n\n See Also\n --------\n DOK.nnz : Equivalent :obj:`DOK` array property.\n numpy.count_nonzero : A similar Numpy function.\n scipy.sparse.coo_matrix.nnz : The Scipy equivalent property.\n\n Examples\n --------\n >>> x = np.array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 0])\n >>> np.count_nonzero(x)\n 6\n >>> s = COO.from_numpy(x)\n >>> s.nnz\n 6\n >>> np.count_nonzero(x) == s.nnz\n True\n \"\"\"\n return self.coords.shape[1]\n\n @property\n def nbytes(self):\n \"\"\"\n The number of bytes taken up by this object. Note that for small arrays,\n this may undercount the number of bytes due to the large constant overhead.\n\n Returns\n -------\n int\n The approximate bytes of memory taken by this object.\n\n See Also\n --------\n numpy.ndarray.nbytes : The equivalent Numpy property.\n\n Examples\n --------\n >>> data = np.arange(6, dtype=np.uint8)\n >>> coords = np.random.randint(1000, size=(3, 6), dtype=np.uint16)\n >>> s = COO(coords, data, shape=(1000, 1000, 1000))\n >>> s.nbytes\n 150\n \"\"\"\n return self.data.nbytes + self.coords.nbytes\n\n def __len__(self):\n \"\"\"\n Get \"length\" of array, which is by definition the size of the first\n dimension.\n\n Returns\n -------\n int\n The size of the first dimension.\n\n See Also\n --------\n numpy.ndarray.__len__ : Numpy equivalent property.\n\n Examples\n --------\n >>> x = np.zeros((10, 10))\n >>> s = COO.from_numpy(x)\n >>> len(s)\n 10\n \"\"\"\n return self.shape[0]\n\n def __sizeof__(self):\n return self.nbytes\n\n __getitem__ = getitem\n\n def __str__(self):\n return '<COO: shape={!s}, dtype={!s}, nnz={:d}, fill_value={!s}>'.format(\n self.shape, self.dtype, self.nnz, self.fill_value\n )\n\n __repr__ = __str__\n\n @staticmethod\n def _reduce(method, *args, **kwargs):\n assert len(args) == 1\n\n self = args[0]\n if isinstance(self, scipy.sparse.spmatrix):\n self = COO.from_scipy_sparse(self)\n\n return self.reduce(method, **kwargs)\n\n def reduce(self, method, axis=(0,), keepdims=False, **kwargs):\n \"\"\"\n Performs a reduction operation on this array.\n\n Parameters\n ----------\n method : numpy.ufunc\n The method to use for performing the reduction.\n axis : Union[int, Iterable[int]], optional\n The axes along which to perform the reduction. Uses all axes by default.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n kwargs : dict\n Any extra arguments to pass to the reduction operation.\n\n Returns\n -------\n COO\n The result of the reduction operation.\n\n Raises\n ------\n ValueError\n If reducing an all-zero axis would produce a nonzero result.\n\n Notes\n -----\n This function internally calls :obj:`COO.sum_duplicates` to bring the array into\n canonical form.\n\n See Also\n --------\n numpy.ufunc.reduce : A similar Numpy method.\n COO.nanreduce : Similar method with ``NaN`` skipping functionality.\n\n Examples\n --------\n You can use the :obj:`COO.reduce` method to apply a reduction operation to\n any Numpy :code:`ufunc`.\n\n >>> x = np.ones((5, 5), dtype=np.int)\n >>> s = COO.from_numpy(x)\n >>> s2 = s.reduce(np.add, axis=1)\n >>> s2.todense() # doctest: +NORMALIZE_WHITESPACE\n array([5, 5, 5, 5, 5])\n\n You can also use the :code:`keepdims` argument to keep the dimensions after the\n reduction.\n\n >>> s3 = s.reduce(np.add, axis=1, keepdims=True)\n >>> s3.shape\n (5, 1)\n\n You can also pass in any keyword argument that :obj:`numpy.ufunc.reduce` supports.\n For example, :code:`dtype`. Note that :code:`out` isn't supported.\n\n >>> s4 = s.reduce(np.add, axis=1, dtype=np.float16)\n >>> s4.dtype\n dtype('float16')\n\n By default, this reduces the array by only the first axis.\n\n >>> s.reduce(np.add)\n <COO: shape=(5,), dtype=int64, nnz=5, fill_value=0>\n \"\"\"\n axis = normalize_axis(axis, self.ndim)\n zero_reduce_result = method.reduce([self.fill_value, self.fill_value], **kwargs)\n reduce_super_ufunc = None\n\n if not equivalent(zero_reduce_result, self.fill_value):\n reduce_super_ufunc = _reduce_super_ufunc.get(method, None)\n\n if reduce_super_ufunc is None:\n raise ValueError(\"Performing this reduction operation would produce \"\n \"a dense result: %s\" % str(method))\n\n if axis is None:\n axis = tuple(range(self.ndim))\n\n if not isinstance(axis, tuple):\n axis = (axis,)\n\n axis = tuple(a if a >= 0 else a + self.ndim for a in axis)\n\n neg_axis = tuple(ax for ax in range(self.ndim) if ax not in set(axis))\n\n a = self.transpose(neg_axis + axis)\n a = a.reshape((np.prod([self.shape[d] for d in neg_axis], dtype=np.intp),\n np.prod([self.shape[d] for d in axis], dtype=np.intp)))\n\n result, inv_idx, counts = _grouped_reduce(a.data, a.coords[0], method, **kwargs)\n\n result_fill_value = self.fill_value\n\n if reduce_super_ufunc is None:\n missing_counts = counts != a.shape[1]\n result[missing_counts] = method(result[missing_counts],\n self.fill_value, **kwargs)\n else:\n result = method(result, reduce_super_ufunc(self.fill_value, a.shape[1] - counts)).astype(result.dtype)\n result_fill_value = reduce_super_ufunc(self.fill_value, a.shape[1])\n coords = a.coords[0:1, inv_idx]\n\n a = COO(coords, result, shape=(a.shape[0],),\n has_duplicates=False, sorted=True, prune=True, fill_value=result_fill_value)\n\n a = a.reshape(tuple(self.shape[d] for d in neg_axis))\n result = a\n\n if keepdims:\n result = _keepdims(self, result, axis)\n\n if result.ndim == 0:\n return result[()]\n\n return result\n\n def sum(self, axis=None, keepdims=False, dtype=None, out=None):\n \"\"\"\n Performs a sum operation along the given axes. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to sum. Uses all axes by default.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n dtype: numpy.dtype\n The data type of the output array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n :obj:`numpy.sum` : Equivalent numpy function.\n scipy.sparse.coo_matrix.sum : Equivalent Scipy function.\n :obj:`nansum` : Function with ``NaN`` skipping.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the array into\n canonical form.\n\n Examples\n --------\n You can use :obj:`COO.sum` to sum an array across any dimension.\n\n >>> x = np.ones((5, 5), dtype=np.int)\n >>> s = COO.from_numpy(x)\n >>> s2 = s.sum(axis=1)\n >>> s2.todense() # doctest: +NORMALIZE_WHITESPACE\n array([5, 5, 5, 5, 5])\n\n You can also use the :code:`keepdims` argument to keep the dimensions after the\n sum.\n\n >>> s3 = s.sum(axis=1, keepdims=True)\n >>> s3.shape\n (5, 1)\n\n You can pass in an output datatype, if needed.\n\n >>> s4 = s.sum(axis=1, dtype=np.float16)\n >>> s4.dtype\n dtype('float16')\n\n By default, this reduces the array down to one number, summing along all axes.\n\n >>> s.sum()\n 25\n \"\"\"\n return np.add.reduce(self, out=out, axis=axis, keepdims=keepdims, dtype=dtype)\n\n def max(self, axis=None, keepdims=False, out=None):\n \"\"\"\n Maximize along the given axes. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to maximize. Uses all axes by default.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n dtype: numpy.dtype\n The data type of the output array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n :obj:`numpy.max` : Equivalent numpy function.\n scipy.sparse.coo_matrix.max : Equivalent Scipy function.\n :obj:`nanmax` : Function with ``NaN`` skipping.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the array into\n canonical form.\n\n Examples\n --------\n You can use :obj:`COO.max` to maximize an array across any dimension.\n\n >>> x = np.add.outer(np.arange(5), np.arange(5))\n >>> x # doctest: +NORMALIZE_WHITESPACE\n array([[0, 1, 2, 3, 4],\n [1, 2, 3, 4, 5],\n [2, 3, 4, 5, 6],\n [3, 4, 5, 6, 7],\n [4, 5, 6, 7, 8]])\n >>> s = COO.from_numpy(x)\n >>> s2 = s.max(axis=1)\n >>> s2.todense() # doctest: +NORMALIZE_WHITESPACE\n array([4, 5, 6, 7, 8])\n\n You can also use the :code:`keepdims` argument to keep the dimensions after the\n maximization.\n\n >>> s3 = s.max(axis=1, keepdims=True)\n >>> s3.shape\n (5, 1)\n\n By default, this reduces the array down to one number, maximizing along all axes.\n\n >>> s.max()\n 8\n \"\"\"\n return np.maximum.reduce(self, out=out, axis=axis, keepdims=keepdims)\n\n amax = max\n\n def any(self, axis=None, keepdims=False, out=None):\n \"\"\"\n See if any values along array are ``True``. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to minimize. Uses all axes by default.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n :obj:`numpy.all` : Equivalent numpy function.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the array into\n canonical form.\n\n Examples\n --------\n You can use :obj:`COO.min` to minimize an array across any dimension.\n\n >>> x = np.array([[False, False],\n ... [False, True ],\n ... [True, False],\n ... [True, True ]])\n >>> s = COO.from_numpy(x)\n >>> s2 = s.any(axis=1)\n >>> s2.todense() # doctest: +SKIP\n array([False, True, True, True])\n\n You can also use the :code:`keepdims` argument to keep the dimensions after the\n minimization.\n\n >>> s3 = s.any(axis=1, keepdims=True)\n >>> s3.shape\n (4, 1)\n\n By default, this reduces the array down to one number, minimizing along all axes.\n\n >>> s.any()\n True\n \"\"\"\n return np.logical_or.reduce(self, out=out, axis=axis, keepdims=keepdims)\n\n def all(self, axis=None, keepdims=False, out=None):\n \"\"\"\n See if all values in an array are ``True``. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to minimize. Uses all axes by default.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n :obj:`numpy.all` : Equivalent numpy function.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the array into\n canonical form.\n\n Examples\n --------\n You can use :obj:`COO.min` to minimize an array across any dimension.\n\n >>> x = np.array([[False, False],\n ... [False, True ],\n ... [True, False],\n ... [True, True ]])\n >>> s = COO.from_numpy(x)\n >>> s2 = s.all(axis=1)\n >>> s2.todense() # doctest: +SKIP\n array([False, False, False, True])\n\n You can also use the :code:`keepdims` argument to keep the dimensions after the\n minimization.\n\n >>> s3 = s.all(axis=1, keepdims=True)\n >>> s3.shape\n (4, 1)\n\n By default, this reduces the array down to one boolean, minimizing along all axes.\n\n >>> s.all()\n False\n \"\"\"\n return np.logical_and.reduce(self, out=out, axis=axis, keepdims=keepdims)\n\n def min(self, axis=None, keepdims=False, out=None):\n \"\"\"\n Minimize along the given axes. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to minimize. Uses all axes by default.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n dtype: numpy.dtype\n The data type of the output array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n :obj:`numpy.min` : Equivalent numpy function.\n scipy.sparse.coo_matrix.min : Equivalent Scipy function.\n :obj:`nanmin` : Function with ``NaN`` skipping.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the array into\n canonical form.\n\n Examples\n --------\n You can use :obj:`COO.min` to minimize an array across any dimension.\n\n >>> x = np.add.outer(np.arange(5), np.arange(5))\n >>> x # doctest: +NORMALIZE_WHITESPACE\n array([[0, 1, 2, 3, 4],\n [1, 2, 3, 4, 5],\n [2, 3, 4, 5, 6],\n [3, 4, 5, 6, 7],\n [4, 5, 6, 7, 8]])\n >>> s = COO.from_numpy(x)\n >>> s2 = s.min(axis=1)\n >>> s2.todense() # doctest: +NORMALIZE_WHITESPACE\n array([0, 1, 2, 3, 4])\n\n You can also use the :code:`keepdims` argument to keep the dimensions after the\n minimization.\n\n >>> s3 = s.min(axis=1, keepdims=True)\n >>> s3.shape\n (5, 1)\n\n By default, this reduces the array down to one boolean, minimizing along all axes.\n\n >>> s.min()\n 0\n \"\"\"\n return np.minimum.reduce(self, out=out, axis=axis, keepdims=keepdims)\n\n amin = min\n\n def prod(self, axis=None, keepdims=False, dtype=None, out=None):\n \"\"\"\n Performs a product operation along the given axes. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to multiply. Uses all axes by default.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n dtype: numpy.dtype\n The data type of the output array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n :obj:`numpy.prod` : Equivalent numpy function.\n :obj:`nanprod` : Function with ``NaN`` skipping.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the array into\n canonical form.\n\n Examples\n --------\n You can use :obj:`COO.prod` to multiply an array across any dimension.\n\n >>> x = np.add.outer(np.arange(5), np.arange(5))\n >>> x # doctest: +NORMALIZE_WHITESPACE\n array([[0, 1, 2, 3, 4],\n [1, 2, 3, 4, 5],\n [2, 3, 4, 5, 6],\n [3, 4, 5, 6, 7],\n [4, 5, 6, 7, 8]])\n >>> s = COO.from_numpy(x)\n >>> s2 = s.prod(axis=1)\n >>> s2.todense() # doctest: +NORMALIZE_WHITESPACE\n array([ 0, 120, 720, 2520, 6720])\n\n You can also use the :code:`keepdims` argument to keep the dimensions after the\n reduction.\n\n >>> s3 = s.prod(axis=1, keepdims=True)\n >>> s3.shape\n (5, 1)\n\n You can pass in an output datatype, if needed.\n\n >>> s4 = s.prod(axis=1, dtype=np.float16)\n >>> s4.dtype\n dtype('float16')\n\n By default, this reduces the array down to one number, multiplying along all axes.\n\n >>> s.prod()\n 0\n \"\"\"\n return np.multiply.reduce(self, out=out, axis=axis, keepdims=keepdims, dtype=dtype)\n\n def mean(self, axis=None, keepdims=False, dtype=None, out=None):\n \"\"\"\n Compute the mean along the given axes. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to compute the mean. Uses all axes by default.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n dtype: numpy.dtype\n The data type of the output array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n numpy.ndarray.mean : Equivalent numpy method.\n scipy.sparse.coo_matrix.mean : Equivalent Scipy method.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the\n array into canonical form.\n * The :code:`out` parameter is provided just for compatibility with\n Numpy and isn't actually supported.\n\n Examples\n --------\n You can use :obj:`COO.mean` to compute the mean of an array across any\n dimension.\n\n >>> x = np.array([[1, 2, 0, 0],\n ... [0, 1, 0, 0]], dtype='i8')\n >>> s = COO.from_numpy(x)\n >>> s2 = s.mean(axis=1)\n >>> s2.todense() # doctest: +SKIP\n array([0.5, 1.5, 0., 0.])\n\n You can also use the :code:`keepdims` argument to keep the dimensions\n after the mean.\n\n >>> s3 = s.mean(axis=0, keepdims=True)\n >>> s3.shape\n (1, 4)\n\n You can pass in an output datatype, if needed.\n\n >>> s4 = s.mean(axis=0, dtype=np.float16)\n >>> s4.dtype\n dtype('float16')\n\n By default, this reduces the array down to one number, computing the\n mean along all axes.\n\n >>> s.mean()\n 0.5\n \"\"\"\n if axis is None:\n axis = tuple(range(self.ndim))\n elif not isinstance(axis, tuple):\n axis = (axis,)\n den = reduce(operator.mul, (self.shape[i] for i in axis), 1)\n\n if dtype is None:\n if issubclass(self.dtype.type, (np.integer, np.bool_)):\n dtype = inter_dtype = np.dtype('f8')\n else:\n dtype = self.dtype\n inter_dtype = (np.dtype('f4')\n if issubclass(dtype.type, np.float16)\n else dtype)\n else:\n inter_dtype = dtype\n\n num = self.sum(axis=axis, keepdims=keepdims, dtype=inter_dtype)\n\n if num.ndim:\n out = np.true_divide(num, den, casting='unsafe')\n return out.astype(dtype) if out.dtype != dtype else out\n return np.divide(num, den, dtype=dtype, out=out)\n\n def var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\n \"\"\"\n Compute the variance along the gi66ven axes. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to compute the variance. Uses all axes by default.\n dtype : numpy.dtype, optional\n The output datatype.\n out: COO, optional\n The array to write the output to.\n ddof: int\n The degrees of freedom.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n numpy.ndarray.var : Equivalent numpy method.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the\n array into canonical form.\n\n Examples\n --------\n You can use :obj:`COO.var` to compute the variance of an array across any\n dimension.\n\n >>> x = np.array([[1, 2, 0, 0],\n ... [0, 1, 0, 0]], dtype='i8')\n >>> s = COO.from_numpy(x)\n >>> s2 = s.var(axis=1)\n >>> s2.todense() # doctest: +SKIP\n array([0.6875, 0.1875])\n\n You can also use the :code:`keepdims` argument to keep the dimensions\n after the variance.\n\n >>> s3 = s.var(axis=0, keepdims=True)\n >>> s3.shape\n (1, 4)\n\n You can pass in an output datatype, if needed.\n\n >>> s4 = s.var(axis=0, dtype=np.float16)\n >>> s4.dtype\n dtype('float16')\n\n By default, this reduces the array down to one number, computing the\n variance along all axes.\n\n >>> s.var()\n 0.5\n \"\"\"\n axis = normalize_axis(axis, self.ndim)\n\n if axis is None:\n axis = tuple(range(self.ndim))\n\n if not isinstance(axis, tuple):\n axis = (axis,)\n\n rcount = reduce(operator.mul, (self.shape[a] for a in axis), 1)\n # Make this warning show up on top.\n if ddof >= rcount:\n warnings.warn(\"Degrees of freedom <= 0 for slice\", RuntimeWarning)\n\n # Cast bool, unsigned int, and int to float64 by default\n if dtype is None and issubclass(self.dtype.type, (np.integer, np.bool_)):\n dtype = np.dtype('f8')\n\n arrmean = self.sum(axis, dtype=dtype, keepdims=True)\n np.divide(arrmean, rcount, out=arrmean)\n x = self - arrmean\n if issubclass(self.dtype.type, np.complexfloating):\n x = x.real * x.real + x.imag * x.imag\n else:\n x = np.multiply(x, x, out=x)\n\n ret = x.sum(axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n\n # Compute degrees of freedom and make sure it is not negative.\n rcount = max([rcount - ddof, 0])\n\n ret = ret[...]\n np.divide(ret, rcount, out=ret, casting='unsafe')\n return ret[()]\n\n def std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\n \"\"\"\n Compute the standard deviation along the given axes. Uses all axes by default.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int]], optional\n The axes along which to compute the standard deviation. Uses\n all axes by default.\n dtype : numpy.dtype, optional\n The output datatype.\n out: COO, optional\n The array to write the output to.\n ddof: int\n The degrees of freedom.\n keepdims : bool, optional\n Whether or not to keep the dimensions of the original array.\n\n Returns\n -------\n COO\n The reduced output sparse array.\n\n See Also\n --------\n numpy.ndarray.std : Equivalent numpy method.\n\n Notes\n -----\n * This function internally calls :obj:`COO.sum_duplicates` to bring the\n array into canonical form.\n\n Examples\n --------\n You can use :obj:`COO.std` to compute the standard deviation of an array\n across any dimension.\n\n >>> x = np.array([[1, 2, 0, 0],\n ... [0, 1, 0, 0]], dtype='i8')\n >>> s = COO.from_numpy(x)\n >>> s2 = s.std(axis=1)\n >>> s2.todense() # doctest: +SKIP\n array([0.8291562, 0.4330127])\n\n You can also use the :code:`keepdims` argument to keep the dimensions\n after the standard deviation.\n\n >>> s3 = s.std(axis=0, keepdims=True)\n >>> s3.shape\n (1, 4)\n\n You can pass in an output datatype, if needed.\n\n >>> s4 = s.std(axis=0, dtype=np.float16)\n >>> s4.dtype\n dtype('float16')\n\n By default, this reduces the array down to one number, computing the\n standard deviation along all axes.\n\n >>> s.std() # doctest: +SKIP\n 0.7071067811865476\n \"\"\"\n ret = self.var(axis=axis, dtype=dtype, out=out, ddof=ddof,\n keepdims=keepdims)\n\n ret = np.sqrt(ret)\n return ret\n\n def transpose(self, axes=None):\n \"\"\"\n Returns a new array which has the order of the axes switched.\n\n Parameters\n ----------\n axes : Iterable[int], optional\n The new order of the axes compared to the previous one. Reverses the axes\n by default.\n\n Returns\n -------\n COO\n The new array with the axes in the desired order.\n\n See Also\n --------\n :obj:`COO.T` : A quick property to reverse the order of the axes.\n numpy.ndarray.transpose : Numpy equivalent function.\n\n Examples\n --------\n We can change the order of the dimensions of any :obj:`COO` array with this\n function.\n\n >>> x = np.add.outer(np.arange(5), np.arange(5)[::-1])\n >>> x # doctest: +NORMALIZE_WHITESPACE\n array([[4, 3, 2, 1, 0],\n [5, 4, 3, 2, 1],\n [6, 5, 4, 3, 2],\n [7, 6, 5, 4, 3],\n [8, 7, 6, 5, 4]])\n >>> s = COO.from_numpy(x)\n >>> s.transpose((1, 0)).todense() # doctest: +NORMALIZE_WHITESPACE\n array([[4, 5, 6, 7, 8],\n [3, 4, 5, 6, 7],\n [2, 3, 4, 5, 6],\n [1, 2, 3, 4, 5],\n [0, 1, 2, 3, 4]])\n\n Note that by default, this reverses the order of the axes rather than switching\n the last and second-to-last axes as required by some linear algebra operations.\n\n >>> x = np.random.rand(2, 3, 4)\n >>> s = COO.from_numpy(x)\n >>> s.transpose().shape\n (4, 3, 2)\n \"\"\"\n if axes is None:\n axes = list(reversed(range(self.ndim)))\n\n # Normalize all axes indices to positive values\n axes = normalize_axis(axes, self.ndim)\n\n if len(np.unique(axes)) < len(axes):\n raise ValueError(\"repeated axis in transpose\")\n\n if not len(axes) == self.ndim:\n raise ValueError(\"axes don't match array\")\n\n axes = tuple(axes)\n\n if axes == tuple(range(self.ndim)):\n return self\n\n if self._cache is not None:\n for ax, value in self._cache['transpose']:\n if ax == axes:\n return value\n\n shape = tuple(self.shape[ax] for ax in axes)\n result = COO(self.coords[axes, :], self.data, shape,\n has_duplicates=False,\n cache=self._cache is not None,\n fill_value=self.fill_value)\n\n if self._cache is not None:\n self._cache['transpose'].append((axes, result))\n return result\n\n @property\n def T(self):\n \"\"\"\n Returns a new array which has the order of the axes reversed.\n\n Returns\n -------\n COO\n The new array with the axes in the desired order.\n\n See Also\n --------\n :obj:`COO.transpose` : A method where you can specify the order of the axes.\n numpy.ndarray.T : Numpy equivalent property.\n\n Examples\n --------\n We can change the order of the dimensions of any :obj:`COO` array with this\n function.\n\n >>> x = np.add.outer(np.arange(5), np.arange(5)[::-1])\n >>> x # doctest: +NORMALIZE_WHITESPACE\n array([[4, 3, 2, 1, 0],\n [5, 4, 3, 2, 1],\n [6, 5, 4, 3, 2],\n [7, 6, 5, 4, 3],\n [8, 7, 6, 5, 4]])\n >>> s = COO.from_numpy(x)\n >>> s.T.todense() # doctest: +NORMALIZE_WHITESPACE\n array([[4, 5, 6, 7, 8],\n [3, 4, 5, 6, 7],\n [2, 3, 4, 5, 6],\n [1, 2, 3, 4, 5],\n [0, 1, 2, 3, 4]])\n\n Note that by default, this reverses the order of the axes rather than switching\n the last and second-to-last axes as required by some linear algebra operations.\n\n >>> x = np.random.rand(2, 3, 4)\n >>> s = COO.from_numpy(x)\n >>> s.T.shape\n (4, 3, 2)\n \"\"\"\n return self.transpose(tuple(range(self.ndim))[::-1])\n\n @property\n def real(self):\n \"\"\"The real part of the array.\n\n Examples\n --------\n >>> x = COO.from_numpy([1 + 0j, 0 + 1j])\n >>> x.real.todense() # doctest: +SKIP\n array([1., 0.])\n >>> x.real.dtype\n dtype('float64')\n\n Returns\n -------\n out : COO\n The real component of the array elements. If the array dtype is\n real, the dtype of the array is used for the output. If the array\n is complex, the output dtype is float.\n\n See Also\n --------\n numpy.ndarray.real : NumPy equivalent attribute.\n numpy.real : NumPy equivalent function.\n \"\"\"\n return self.__array_ufunc__(np.real, '__call__', self)\n\n @property\n def imag(self):\n \"\"\"The imaginary part of the array.\n\n Examples\n --------\n >>> x = COO.from_numpy([1 + 0j, 0 + 1j])\n >>> x.imag.todense() # doctest: +SKIP\n array([0., 1.])\n >>> x.imag.dtype\n dtype('float64')\n\n Returns\n -------\n out : COO\n The imaginary component of the array elements. If the array dtype\n is real, the dtype of the array is used for the output. If the\n array is complex, the output dtype is float.\n\n See Also\n --------\n numpy.ndarray.imag : NumPy equivalent attribute.\n numpy.imag : NumPy equivalent function.\n \"\"\"\n return self.__array_ufunc__(np.imag, '__call__', self)\n\n def conj(self):\n \"\"\"Return the complex conjugate, element-wise.\n\n The complex conjugate of a complex number is obtained by changing the\n sign of its imaginary part.\n\n Examples\n --------\n >>> x = COO.from_numpy([1 + 2j, 2 - 1j])\n >>> res = x.conj()\n >>> res.todense() # doctest: +SKIP\n array([1.-2.j, 2.+1.j])\n >>> res.dtype\n dtype('complex128')\n\n Returns\n -------\n out : COO\n The complex conjugate, with same dtype as the input.\n\n See Also\n --------\n numpy.ndarray.conj : NumPy equivalent method.\n numpy.conj : NumPy equivalent function.\n \"\"\"\n return np.conj(self)\n\n def dot(self, other):\n \"\"\"\n Performs the equivalent of :code:`x.dot(y)` for :obj:`COO`.\n\n Parameters\n ----------\n other : Union[COO, numpy.ndarray, scipy.sparse.spmatrix]\n The second operand of the dot product operation.\n\n Returns\n -------\n {COO, numpy.ndarray}\n The result of the dot product. If the result turns out to be dense,\n then a dense array is returned, otherwise, a sparse array.\n\n Raises\n ------\n ValueError\n If all arguments don't have zero fill-values.\n\n See Also\n --------\n dot : Equivalent function for two arguments.\n :obj:`numpy.dot` : Numpy equivalent function.\n scipy.sparse.coo_matrix.dot : Scipy equivalent function.\n\n Examples\n --------\n >>> x = np.arange(4).reshape((2, 2))\n >>> s = COO.from_numpy(x)\n >>> s.dot(s) # doctest: +SKIP\n array([[ 2, 3],\n [ 6, 11]], dtype=int64)\n \"\"\"\n return dot(self, other)\n\n def __matmul__(self, other):\n try:\n return matmul(self, other)\n except NotImplementedError:\n return NotImplemented\n\n def __rmatmul__(self, other):\n try:\n return matmul(other, self)\n except NotImplementedError:\n return NotImplemented\n\n def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n out = kwargs.pop('out', None)\n if out is not None and not all(isinstance(x, COO) for x in out):\n return NotImplemented\n\n if out is not None:\n kwargs['dtype'] = out[0].dtype\n\n if method == '__call__':\n result = elemwise(ufunc, *inputs, **kwargs)\n elif method == 'reduce':\n result = COO._reduce(ufunc, *inputs, **kwargs)\n else:\n return NotImplemented\n\n if out is not None:\n (out,) = out\n if out.shape != result.shape:\n raise ValueError('non-broadcastable output operand with shape %s '\n 'doesn\\'t match the broadcast shape %s' % (out.shape, result.shape))\n\n out._make_shallow_copy_of(result)\n return out\n\n return result\n\n def linear_loc(self):\n \"\"\"\n The nonzero coordinates of a flattened version of this array. Note that\n the coordinates may be out of order.\n\n Parameters\n ----------\n signed : bool, optional\n Whether to use a signed datatype for the output array. :code:`False`\n by default.\n\n Returns\n -------\n numpy.ndarray\n The flattened coordinates.\n\n See Also\n --------\n :obj:`numpy.flatnonzero` : Equivalent Numpy function.\n\n Examples\n --------\n >>> x = np.eye(5)\n >>> s = COO.from_numpy(x)\n >>> s.linear_loc() # doctest: +NORMALIZE_WHITESPACE\n array([ 0, 6, 12, 18, 24])\n >>> np.array_equal(np.flatnonzero(x), s.linear_loc())\n True\n \"\"\"\n from .common import linear_loc\n return linear_loc(self.coords, self.shape)\n\n def reshape(self, shape, order='C'):\n \"\"\"\n Returns a new :obj:`COO` array that is a reshaped version of this array.\n\n Parameters\n ----------\n shape : tuple[int]\n The desired shape of the output array.\n\n Returns\n -------\n COO\n The reshaped output array.\n\n See Also\n --------\n numpy.ndarray.reshape : The equivalent Numpy function.\n\n Notes\n -----\n The :code:`order` parameter is provided just for compatibility with\n Numpy and isn't actually supported.\n\n Examples\n --------\n >>> s = COO.from_numpy(np.arange(25))\n >>> s2 = s.reshape((5, 5))\n >>> s2.todense() # doctest: +NORMALIZE_WHITESPACE\n array([[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24]])\n \"\"\"\n if isinstance(shape, Iterable):\n shape = tuple(shape)\n else:\n shape = (shape,)\n\n if order not in {'C', None}:\n raise NotImplementedError(\"The `order` parameter is not supported\")\n\n if self.shape == shape:\n return self\n if any(d == -1 for d in shape):\n extra = int(self.size /\n np.prod([d for d in shape if d != -1]))\n shape = tuple([d if d != -1 else extra for d in shape])\n\n if self.shape == shape:\n return self\n\n if self._cache is not None:\n for sh, value in self._cache['reshape']:\n if sh == shape:\n return value\n\n # TODO: this self.size enforces a 2**64 limit to array size\n linear_loc = self.linear_loc()\n\n coords = np.empty((len(shape), self.nnz), dtype=np.intp)\n strides = 1\n for i, d in enumerate(shape[::-1]):\n coords[-(i + 1), :] = (linear_loc // strides) % d\n strides *= d\n\n result = COO(coords, self.data, shape,\n has_duplicates=False,\n sorted=True, cache=self._cache is not None,\n fill_value=self.fill_value)\n\n if self._cache is not None:\n self._cache['reshape'].append((shape, result))\n return result\n\n def to_scipy_sparse(self):\n \"\"\"\n Converts this :obj:`COO` object into a :obj:`scipy.sparse.coo_matrix`.\n\n Returns\n -------\n :obj:`scipy.sparse.coo_matrix`\n The converted Scipy sparse matrix.\n\n Raises\n ------\n ValueError\n If the array is not two-dimensional.\n\n ValueError\n If all the array doesn't zero fill-values.\n\n See Also\n --------\n COO.tocsr : Convert to a :obj:`scipy.sparse.csr_matrix`.\n COO.tocsc : Convert to a :obj:`scipy.sparse.csc_matrix`.\n \"\"\"\n check_zero_fill_value(self)\n\n if self.ndim != 2:\n raise ValueError(\"Can only convert a 2-dimensional array to a Scipy sparse matrix.\")\n\n result = scipy.sparse.coo_matrix((self.data,\n (self.coords[0],\n self.coords[1])),\n shape=self.shape)\n result.has_canonical_format = True\n return result\n\n def _tocsr(self):\n if self.ndim != 2:\n raise ValueError('This array must be two-dimensional for this conversion '\n 'to work.')\n row, col = self.coords\n\n # Pass 3: count nonzeros in each row\n indptr = np.zeros(self.shape[0] + 1, dtype=np.int64)\n np.cumsum(np.bincount(row, minlength=self.shape[0]), out=indptr[1:])\n\n return scipy.sparse.csr_matrix((self.data, col, indptr), shape=self.shape)\n\n def tocsr(self):\n \"\"\"\n Converts this array to a :obj:`scipy.sparse.csr_matrix`.\n\n Returns\n -------\n scipy.sparse.csr_matrix\n The result of the conversion.\n\n Raises\n ------\n ValueError\n If the array is not two-dimensional.\n\n ValueError\n If all the array doesn't have zero fill-values.\n\n See Also\n --------\n COO.tocsc : Convert to a :obj:`scipy.sparse.csc_matrix`.\n COO.to_scipy_sparse : Convert to a :obj:`scipy.sparse.coo_matrix`.\n scipy.sparse.coo_matrix.tocsr : Equivalent Scipy function.\n \"\"\"\n check_zero_fill_value(self)\n\n if self._cache is not None:\n try:\n return self._csr\n except AttributeError:\n pass\n try:\n self._csr = self._csc.tocsr()\n return self._csr\n except AttributeError:\n pass\n\n self._csr = csr = self._tocsr()\n else:\n csr = self._tocsr()\n return csr\n\n def tocsc(self):\n \"\"\"\n Converts this array to a :obj:`scipy.sparse.csc_matrix`.\n\n Returns\n -------\n scipy.sparse.csc_matrix\n The result of the conversion.\n\n Raises\n ------\n ValueError\n If the array is not two-dimensional.\n\n ValueError\n If the array doesn't have zero fill-values.\n\n See Also\n --------\n COO.tocsr : Convert to a :obj:`scipy.sparse.csr_matrix`.\n COO.to_scipy_sparse : Convert to a :obj:`scipy.sparse.coo_matrix`.\n scipy.sparse.coo_matrix.tocsc : Equivalent Scipy function.\n \"\"\"\n check_zero_fill_value(self)\n\n if self._cache is not None:\n try:\n return self._csc\n except AttributeError:\n pass\n try:\n self._csc = self._csr.tocsc()\n return self._csc\n except AttributeError:\n pass\n\n self._csc = csc = self.tocsr().tocsc()\n else:\n csc = self.tocsr().tocsc()\n\n return csc\n\n def _sort_indices(self):\n \"\"\"\n Sorts the :obj:`COO.coords` attribute. Also sorts the data in\n :obj:`COO.data` to match.\n\n Examples\n --------\n >>> coords = np.array([[1, 2, 0]], dtype=np.uint8)\n >>> data = np.array([4, 1, 3], dtype=np.uint8)\n >>> s = COO(coords, data)\n >>> s._sort_indices()\n >>> s.coords # doctest: +NORMALIZE_WHITESPACE\n array([[0, 1, 2]])\n >>> s.data # doctest: +NORMALIZE_WHITESPACE\n array([3, 4, 1], dtype=uint8)\n \"\"\"\n linear = self.linear_loc()\n\n if (np.diff(linear) >= 0).all(): # already sorted\n return\n\n order = np.argsort(linear)\n self.coords = self.coords[:, order]\n self.data = self.data[order]\n\n def _sum_duplicates(self):\n \"\"\"\n Sums data corresponding to duplicates in :obj:`COO.coords`.\n\n See Also\n --------\n scipy.sparse.coo_matrix.sum_duplicates : Equivalent Scipy function.\n\n Examples\n --------\n >>> coords = np.array([[0, 1, 1, 2]], dtype=np.uint8)\n >>> data = np.array([6, 5, 2, 2], dtype=np.uint8)\n >>> s = COO(coords, data)\n >>> s._sum_duplicates()\n >>> s.coords # doctest: +NORMALIZE_WHITESPACE\n array([[0, 1, 2]])\n >>> s.data # doctest: +NORMALIZE_WHITESPACE\n array([6, 7, 2], dtype=uint8)\n \"\"\"\n # Inspired by scipy/sparse/coo.py::sum_duplicates\n # See https://github.com/scipy/scipy/blob/master/LICENSE.txt\n linear = self.linear_loc()\n unique_mask = np.diff(linear) != 0\n\n if unique_mask.sum() == len(unique_mask): # already unique\n return\n\n unique_mask = np.append(True, unique_mask)\n\n coords = self.coords[:, unique_mask]\n (unique_inds,) = np.nonzero(unique_mask)\n data = np.add.reduceat(self.data, unique_inds, dtype=self.data.dtype)\n\n self.data = data\n self.coords = coords\n\n def _prune(self):\n \"\"\"\n Prunes data so that if any fill-values are present, they are removed\n from both coordinates and data.\n\n Examples\n --------\n >>> coords = np.array([[0, 1, 2, 3]])\n >>> data = np.array([1, 0, 1, 2])\n >>> s = COO(coords, data)\n >>> s._prune()\n >>> s.nnz\n 3\n \"\"\"\n mask = ~equivalent(self.data, self.fill_value)\n self.coords = self.coords[:, mask]\n self.data = self.data[mask]\n\n def broadcast_to(self, shape):\n \"\"\"\n Performs the equivalent of :obj:`numpy.broadcast_to` for :obj:`COO`. Note that\n this function returns a new array instead of a view.\n\n Parameters\n ----------\n shape : tuple[int]\n The shape to broadcast the data to.\n\n Returns\n -------\n COO\n The broadcasted sparse array.\n\n Raises\n ------\n ValueError\n If the operand cannot be broadcast to the given shape.\n\n See also\n --------\n :obj:`numpy.broadcast_to` : NumPy equivalent function\n \"\"\"\n return broadcast_to(self, shape)\n\n def round(self, decimals=0, out=None):\n \"\"\"\n Evenly round to the given number of decimals.\n\n See also\n --------\n :obj:`numpy.round` : NumPy equivalent ufunc.\n :obj:`COO.elemwise`: Apply an arbitrary element-wise function to one or two\n arguments.\n \"\"\"\n if out is not None and not isinstance(out, tuple):\n out = (out,)\n return self.__array_ufunc__(np.round, '__call__', self, decimals=decimals, out=out)\n\n round_ = round\n\n def clip(self, min=None, max=None, out=None):\n \"\"\"Clip (limit) the values in the array.\n\n Return an array whose values are limited to ``[min, max]``. One of min\n or max must be given.\n\n Parameters\n ----------\n min : scalar or array_like or `None`\n Minimum value. If `None`, clipping is not performed on lower\n interval edge.\n max : scalar or array_like or `None`\n Maximum value. If `None`, clipping is not performed on upper\n interval edge.\n out : COO, optional\n If provided, the results will be placed in this array. It may be\n the input array for in-place clipping. `out` must be of the right\n shape to hold the output. Its type is preserved.\n\n Returns\n -------\n clipped_array : COO\n An array with the elements of `self`, but where values < `min` are\n replaced with `min`, and those > `max` with `max`.\n\n Examples\n --------\n >>> x = COO.from_numpy([0, 0, 0, 1, 2, 3])\n >>> x.clip(min=1).todense() # doctest: +NORMALIZE_WHITESPACE\n array([1, 1, 1, 1, 2, 3])\n >>> x.clip(max=1).todense() # doctest: +NORMALIZE_WHITESPACE\n array([0, 0, 0, 1, 1, 1])\n >>> x.clip(min=1, max=2).todense() # doctest: +NORMALIZE_WHITESPACE\n array([1, 1, 1, 1, 2, 2])\n \"\"\"\n if min is None and max is None:\n raise ValueError(\"One of max or min must be given.\")\n if out is not None and not isinstance(out, tuple):\n out = (out,)\n return self.__array_ufunc__(np.clip, '__call__', self, a_min=min,\n a_max=max, out=out)\n\n def astype(self, dtype):\n \"\"\"\n Copy of the array, cast to a specified type.\n\n See also\n --------\n scipy.sparse.coo_matrix.astype : SciPy sparse equivalent function\n numpy.ndarray.astype : NumPy equivalent ufunc.\n :obj:`COO.elemwise`: Apply an arbitrary element-wise function to one or two\n arguments.\n \"\"\"\n return self.__array_ufunc__(np.ndarray.astype, '__call__', self, dtype=dtype)\n\n def maybe_densify(self, max_size=1000, min_density=0.25):\n \"\"\"\n Converts this :obj:`COO` array to a :obj:`numpy.ndarray` if not too\n costly.\n\n Parameters\n ----------\n max_size : int\n Maximum number of elements in output\n min_density : float\n Minimum density of output\n\n Returns\n -------\n numpy.ndarray\n The dense array.\n\n Raises\n -------\n ValueError\n If the returned array would be too large.\n\n Examples\n --------\n Convert a small sparse array to a dense array.\n\n >>> s = COO.from_numpy(np.random.rand(2, 3, 4))\n >>> x = s.maybe_densify()\n >>> np.allclose(x, s.todense())\n True\n\n You can also specify the minimum allowed density or the maximum number\n of output elements. If both conditions are unmet, this method will throw\n an error.\n\n >>> x = np.zeros((5, 5), dtype=np.uint8)\n >>> x[2, 2] = 1\n >>> s = COO.from_numpy(x)\n >>> s.maybe_densify(max_size=5, min_density=0.25)\n Traceback (most recent call last):\n ...\n ValueError: Operation would require converting large sparse array to dense\n \"\"\"\n if self.size <= max_size or self.density >= min_density:\n return self.todense()\n else:\n raise ValueError(\"Operation would require converting \"\n \"large sparse array to dense\")\n\n def nonzero(self):\n \"\"\"\n Get the indices where this array is nonzero.\n\n Returns\n -------\n idx : tuple[numpy.ndarray]\n The indices where this array is nonzero.\n\n See Also\n --------\n :obj:`numpy.ndarray.nonzero` : NumPy equivalent function\n\n Raises\n ------\n ValueError\n If the array doesn't have zero fill-values.\n\n Examples\n --------\n >>> s = COO.from_numpy(np.eye(5))\n >>> s.nonzero()\n (array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4]))\n \"\"\"\n check_zero_fill_value(self)\n return tuple(self.coords)\n\n def asformat(self, format):\n \"\"\"\n Convert this sparse array to a given format.\n\n Parameters\n ----------\n format : str\n A format string.\n\n Returns\n -------\n out : SparseArray\n The converted array.\n\n Raises\n ------\n NotImplementedError\n If the format isn't supported.\n \"\"\"\n if format == 'coo' or format is COO:\n return self\n\n from ..dok import DOK\n if format == 'dok' or format is DOK:\n return DOK.from_coo(self)\n\n raise NotImplementedError('The given format is not supported.')\n\n\ndef as_coo(x, shape=None, fill_value=None):\n \"\"\"\n Converts any given format to :obj:`COO`. See the \"See Also\" section for details.\n\n Parameters\n ----------\n x : SparseArray or numpy.ndarray or scipy.sparse.spmatrix or Iterable.\n The item to convert.\n shape : tuple[int], optional\n The shape of the output array. Can only be used in case of Iterable.\n\n Returns\n -------\n out : COO\n The converted :obj:`COO` array.\n\n See Also\n --------\n SparseArray.asformat : A utility function to convert between formats in this library.\n COO.from_numpy : Convert a Numpy array to :obj:`COO`.\n COO.from_scipy_sparse : Convert a SciPy sparse matrix to :obj:`COO`.\n COO.from_iter : Convert an iterable to :obj:`COO`.\n \"\"\"\n if hasattr(x, 'shape') and shape is not None:\n raise ValueError('Cannot provide a shape in combination with something '\n 'that already has a shape.')\n\n if hasattr(x, 'fill_value') and fill_value is not None:\n raise ValueError('Cannot provide a fill-value in combination with something '\n 'that already has a fill-value.')\n\n if isinstance(x, SparseArray):\n return x.asformat('coo')\n\n if isinstance(x, np.ndarray):\n return COO.from_numpy(x, fill_value=fill_value)\n\n if isinstance(x, scipy.sparse.spmatrix):\n return COO.from_scipy_sparse(x)\n\n if isinstance(x, (Iterable, Iterator)):\n return COO.from_iter(x, shape=shape, fill_value=fill_value)\n\n raise NotImplementedError('Format not supported for conversion. Supplied type is '\n '%s, see help(sparse.as_coo) for supported formats.' % type(x))\n\n\ndef _keepdims(original, new, axis):\n shape = list(original.shape)\n for ax in axis:\n shape[ax] = 1\n return new.reshape(shape)\n\n\n@numba.jit(nopython=True, nogil=True) # pragma: no cover\ndef _calc_counts_invidx(groups):\n inv_idx = []\n counts = []\n\n if len(groups) == 0:\n return (np.array(inv_idx, dtype=groups.dtype),\n np.array(counts, dtype=groups.dtype))\n\n inv_idx.append(0)\n\n last_group = groups[0]\n for i in range(1, len(groups)):\n if groups[i] != last_group:\n counts.append(i - inv_idx[-1])\n inv_idx.append(i)\n last_group = groups[i]\n\n counts.append(len(groups) - inv_idx[-1])\n\n return (np.array(inv_idx, dtype=groups.dtype),\n np.array(counts, dtype=groups.dtype))\n\n\ndef _grouped_reduce(x, groups, method, **kwargs):\n \"\"\"\n Performs a :code:`ufunc` grouped reduce.\n\n Parameters\n ----------\n x : np.ndarray\n The data to reduce.\n groups : np.ndarray\n The groups the data belongs to. The groups must be\n contiguous.\n method : np.ufunc\n The :code:`ufunc` to use to perform the reduction.\n kwargs : dict\n The kwargs to pass to the :code:`ufunc`'s :code:`reduceat`\n function.\n\n Returns\n -------\n result : np.ndarray\n The result of the grouped reduce operation.\n inv_idx : np.ndarray\n The index of the first element where each group is found.\n counts : np.ndarray\n The number of elements in each group.\n \"\"\"\n # Partial credit to @shoyer\n # Ref: https://gist.github.com/shoyer/f538ac78ae904c936844\n inv_idx, counts = _calc_counts_invidx(groups)\n result = method.reduceat(x, inv_idx, **kwargs)\n return result, inv_idx, counts\n"
] |
[
[
"numpy.add.reduceat",
"numpy.true_divide",
"numpy.multiply",
"numpy.asanyarray",
"numpy.issubdtype",
"numpy.broadcast_to",
"numpy.dtype",
"numpy.divide",
"numpy.full",
"numpy.bincount",
"numpy.empty",
"numpy.add.reduce",
"numpy.minimum.reduce",
"numpy.nonzero",
"numpy.prod",
"numpy.conj",
"numpy.sqrt",
"numpy.append",
"numpy.vstack",
"numpy.array",
"numpy.zeros",
"numpy.diff",
"numpy.stack",
"numpy.argsort",
"numpy.logical_and.reduce",
"numpy.maximum.reduce",
"numpy.asarray",
"numpy.logical_or.reduce",
"numpy.all",
"numpy.multiply.reduce",
"numpy.unique"
]
] |
zcemjjw/MPHY0041_Segmentation
|
[
"5840eb6979bb9e3ad19898cd66e0ede8129e3680"
] |
[
"UNet_2D/training.py"
] |
[
"import tensorflow as tf\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom keras.optimizers import Adam, SGD\nfrom tqdm import tqdm\nimport random\nfrom metrics import dice_coef, dice_coef_loss\n\nimg_width = 128\nimg_height = 128\nimg_channels = 1\n\npath_to_data = './data/datasets-promise12'\npath_to_save = './result' \n\n# Load Training Data\nN = 50\nidx_slice = 15\nX_train = np.zeros((N, img_height, img_width, img_channels), dtype=np.float32)\nY_train = np.zeros((N, img_height, img_width, 1), dtype=np.float32)\n\nprint('','','')\nprint('','','')\nprint('Loading Training Data')\n\nfor n in tqdm(range(N)):\n image = np.load(os.path.join(path_to_data, \"image_train%02d.npy\" % n))\n label = np.load(os.path.join(path_to_data, \"label_train%02d.npy\" % n))\n X_train[n] = image[idx_slice,:,:, np.newaxis]\n Y_train[n] = label[idx_slice,:,:, np.newaxis]\n\nprint('Loaded Training Data')\n\n# Load Testing Data\nN_test = 30\nX_test = np.zeros((N_test, img_height, img_width, img_channels), dtype=np.float32)\n\nprint('','','')\nprint('','','')\nprint('Loading Testing Data')\n\nfor n in tqdm(range(N_test)):\n image = np.load(os.path.join(path_to_data, \"image_test%02d.npy\" % n))\n X_test[n] = image[idx_slice,:,:, np.newaxis]\n\nprint('Loaded Testing Data')\nprint('','','')\nprint('','','')\n\n# Randomly Show an Image\n\n# image_x = random.randint(0, N-1)\n# fig = plt.figure()\n# ax1 = fig.add_subplot(121)\n# plt.imshow(np.squeeze(X_train[image_x]), cmap='gray')\n# ax2 = fig.add_subplot(122)\n# ax1.title.set_text('Clinical Image')\n# plt.imshow(np.squeeze(Y_train[image_x]), cmap='gray')\n# ax2.title.set_text('Real Mask')\n# plt.show()\n\n# UNet Model\ninputs = tf.keras.layers.Input((img_width, img_height, img_channels))\n\n# Convert integers in image matrix to floating point \ns = tf.keras.layers.Lambda(lambda x: x / 255)(inputs)\n\n# Encoding\nc1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(s)\nc1 = tf.keras.layers.Dropout(0.2)(c1)\nc2 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c1)\np1 = tf.keras.layers.MaxPooling2D((2,2))(c1)\n\n\nc2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(p1)\nc2 = tf.keras.layers.Dropout(0.2)(c2)\nc2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c2)\np2 = tf.keras.layers.MaxPooling2D((2,2))(c2)\n\n\nc3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(p2)\nc3 = tf.keras.layers.Dropout(0.2)(c3)\nc3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c3)\np3 = tf.keras.layers.MaxPooling2D((2,2))(c3)\n\n\nc4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(p3)\nc4 = tf.keras.layers.Dropout(0.2)(c4)\nc4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c4)\np4 = tf.keras.layers.MaxPooling2D((2,2))(c4)\n\n\nc5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(p4)\nc5 = tf.keras.layers.Dropout(0.2)(c5)\nc5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c5)\np5 = tf.keras.layers.MaxPooling2D((2,2))(c5)\n\n# Decoding Layers\nu6 = tf.keras.layers.Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same',)(c5)\nu6 = tf.keras.layers.concatenate([u6, c4])\nc6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(u6)\nc6 = tf.keras.layers.Dropout(0.2)(c6)\nc6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c6)\n\n\nu7 = tf.keras.layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same',)(c6)\nu7 = tf.keras.layers.concatenate([u7, c3])\nc7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(u7)\nc7 = tf.keras.layers.Dropout(0.2)(c7)\nc7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c7)\n\n\nu8 = tf.keras.layers.Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same',)(c7)\nu8 = tf.keras.layers.concatenate([u8, c2])\nc8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(u8)\nc8 = tf.keras.layers.Dropout(0.2)(c8)\nc8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c8)\n\n\nu9 = tf.keras.layers.Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same',)(c8)\nu9 = tf.keras.layers.concatenate([u9, c1])\nc9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(u9)\nc9 = tf.keras.layers.Dropout(0.2)(c9)\nc9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu',\n kernel_initializer='he_normal', padding='same')(c9)\n\n\noutputs = tf.keras.layers.Conv2D(1, (1, 1), activation='sigmoid')(c9)\n\nmodel = tf.keras.Model(inputs=[inputs], outputs=[outputs])\nmodel.compile(optimizer=tf.optimizers.Adam(1e-3), loss=dice_coef_loss, metrics=[dice_coef])\n#model.summary()\n\n# Checkpoints and Callbacks\ncheckpointer = tf.keras.callbacks.ModelCheckpoint('model_pros_segmentation.h5',\n verbose=1, save_best_only=True)\ncallbacks = [\n tf.keras.callbacks.EarlyStopping(patience=20, monitor='val_loss'),\n tf.keras.callbacks.TensorBoard(log_dir='logs')]\nresults = model.fit(X_train, Y_train, validation_split=0.1, batch_size=15,\n epochs=1000, callbacks=callbacks) \n\n# Plot a Random Image when Running\n\nidx = random.randint(0, N)\n\npreds_train = model.predict(X_train[:int(X_train.shape[0]*0.9)], verbose=1)\npreds_val = model.predict(X_train[int(X_train.shape[0]*0.9):], verbose=1)\npreds_test = model.predict(X_test, verbose=1)\n\npreds_train_t = (preds_train > 0.5).astype(np.uint8)\npreds_val_t = (preds_val > 0.5).astype(np.uint8)\npreds_test_t = (preds_test > 0.5).astype(np.uint8)\n\nprint('','','')\nprint('','','')\nprint('Saving 2D Segmentation Training Masks')\n\nfor ix in tqdm(range(len(preds_train))):\n fig = plt.figure()\n fig.suptitle(f'2D Segmentation Training Masks (ix={ix+1})', fontsize=12)\n ax1 = fig.add_subplot(131)\n plt.imshow(np.squeeze(X_train[ix]))\n ax2 = fig.add_subplot(132)\n plt.imshow(np.squeeze(Y_train[ix]))\n ax3 = fig.add_subplot(133)\n plt.imshow(np.squeeze(preds_train_t[ix]))\n ax1.title.set_text('Clinical Image')\n ax2.title.set_text('Real Mask')\n ax3.title.set_text('Predicted Mask')\n plt.savefig(f'plots_training/Training_Masks_ix_{ix+1}.png')\n plt.close()\n\nprint('Finished Saving')\nprint('','','')\nprint('','','')\nprint('Saving 2D Segmentation Testing Masks')\n\nfor ix in tqdm(range(len(preds_test))):\n fig = plt.figure()\n fig.suptitle(f'2D Segmentation Testing Masks (ix={ix+1})', fontsize=12)\n ax1 = fig.add_subplot(121)\n plt.imshow(np.squeeze(X_test[ix]))\n ax3 = fig.add_subplot(122)\n plt.imshow(np.squeeze(preds_test_t[ix]))\n ax1.title.set_text('Clinical Image')\n ax2.title.set_text('Real Mask')\n ax3.title.set_text('Predicted Mask')\n plt.savefig(f'plots_testing/Testing_Masks_ix_{ix+1}.png')\n plt.close()\n\nprint('Finished Saving')\nprint('','','')\nprint('','','')\n\nprint('Training Script has sucessfully completed')"
] |
[
[
"tensorflow.keras.callbacks.TensorBoard",
"tensorflow.keras.layers.Lambda",
"tensorflow.keras.layers.Input",
"numpy.zeros",
"matplotlib.pyplot.savefig",
"tensorflow.optimizers.Adam",
"matplotlib.pyplot.close",
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.Model",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.layers.Conv2DTranspose",
"matplotlib.pyplot.figure",
"numpy.squeeze",
"tensorflow.keras.layers.concatenate",
"tensorflow.keras.callbacks.EarlyStopping"
]
] |
juldou/seldon-core
|
[
"34021ee3ead41c729ff57efd1964ab3f0d37861e"
] |
[
"components/alibi-detect-server/adserver/cd_model.py"
] |
[
"import json\nfrom typing import List, Dict, Optional, Union\nimport logging\nimport numpy as np\nfrom .numpy_encoder import NumpyEncoder\nfrom adserver.base import AlibiDetectModel, ModelResponse\nfrom alibi_detect.utils.saving import load_detector, Data\n\n\ndef _append_drift_metrcs(metrics, drift, name):\n metric_found = drift.get(name)\n\n # Assumes metric_found is always float/int or list/np.array when not none\n if metric_found is not None:\n if not isinstance(metric_found, (list, np.ndarray)):\n metric_found = [metric_found]\n\n for i, instance in enumerate(metric_found):\n metrics.append(\n {\n \"key\": f\"seldon_metric_drift_{name}\",\n \"value\": instance,\n \"type\": \"GAUGE\",\n \"tags\": {\"index\": str(i)},\n }\n )\n\n\nclass AlibiDetectConceptDriftModel(\n AlibiDetectModel\n): # pylint:disable=c-extension-no-member\n def __init__(\n self,\n name: str,\n storage_uri: str,\n model: Optional[Data] = None,\n drift_batch_size: int = 1000,\n ):\n \"\"\"\n Outlier Detection / Concept Drift Model\n\n Parameters\n ----------\n name\n The name of the model\n storage_uri\n The URI location of the model\n drift_batch_size\n The batch size to fill before checking for drift\n model\n Alibi detect model\n \"\"\"\n super().__init__(name, storage_uri, model)\n self.drift_batch_size = drift_batch_size\n self.batch: np.array = None\n self.model: Data = model\n\n def process_event(self, inputs: Union[List, Dict], headers: Dict) -> Optional[ModelResponse]:\n \"\"\"\n Process the event and return Alibi Detect score\n\n Parameters\n ----------\n inputs\n Input data\n headers\n Header options\n\n Returns\n -------\n Alibi Detect response\n\n \"\"\"\n logging.info(\"PROCESSING EVENT.\")\n logging.info(str(headers))\n logging.info(\"----\")\n try:\n X = np.array(inputs)\n except Exception as e:\n raise Exception(\n \"Failed to initialize NumPy array from inputs: %s, %s\" % (e, inputs)\n )\n\n if self.batch is None:\n self.batch = X\n else:\n self.batch = np.concatenate((self.batch, X))\n\n if self.batch.shape[0] >= self.drift_batch_size:\n logging.info(\n \"Running drift detection. Batch size is %d. Needed %d\",\n self.batch.shape[0],\n self.drift_batch_size,\n )\n\n cd_preds = self.model.predict(self.batch)\n\n logging.info(\"Ran drift test\")\n self.batch = None\n\n output = json.loads(json.dumps(cd_preds, cls=NumpyEncoder))\n\n metrics: List[Dict] = []\n drift = output.get(\"data\")\n\n if drift:\n _append_drift_metrcs(metrics, drift, \"is_drift\")\n _append_drift_metrcs(metrics, drift, \"distance\")\n _append_drift_metrcs(metrics, drift, \"p_val\")\n _append_drift_metrcs(metrics, drift, \"threshold\")\n\n return ModelResponse(data=output, metrics=metrics)\n else:\n logging.info(\n \"Not running drift detection. Batch size is %d. Need %d\",\n self.batch.shape[0],\n self.drift_batch_size,\n )\n return None\n"
] |
[
[
"numpy.concatenate",
"numpy.array"
]
] |
asd249180/similarity_and_matching
|
[
"225cbc4850a790a37ea18d4c519a4306e9db3590"
] |
[
"src/bin/plots/plot_resnet_cka_vs_crossentropy.py"
] |
[
"import pandas as pd\nfrom matplotlib import pyplot as plt\nimport os\nimport sys\nimport seaborn as sns\nimport json\nimport argparse\nfrom dotmap import DotMap\nimport numpy as np\n\n# ================================================================\n# SETTINGS\n# ================================================================\n\nsettings = DotMap()\n\n# PLOT\n# ----------------------------------------\nsettings.plot.colors = {\n 'frank_crossentropy' : '#F00',\n 'frank_cka' : '#F60',\n 'ps_inv_crossentropy' : '#00F',\n 'ps_inv_cka' : '#06F'\n}\nsettings.plot.rename_dict = {\n 'frank_crossentropy' : 'With Task Loss - Cross-entropy',\n 'ps_inv_crossentropy' : 'Linear Least Squares - Cross-entropy',\n 'frank_cka' : 'With Task Loss - CKA',\n 'ps_inv_cka' : 'Linear Least Squares - CKA'\n}\nsettings.plot.linewidth = 5\nsettings.plot.ce_linestyle = '-'\nsettings.plot.cka_linestyle = '--'\nsettings.plot.x_label = 'Layer'\nsettings.plot.y_label_left = 'CKA between stiched layers'\nsettings.plot.y_label_right = 'Cross-entropy'\n\n# MEAN & STD TABLE\n# ----------------------------------------\nsettings.mean_std_table.caption = 'Mean metrics with standard deviations in parentheses.'\nsettings.mean_std_table.column_names = ['Cross-entropy', 'CKA'] # Order cannot be changed this way\nsettings.mean_std_table.row_names = ['Ps. Inv', 'Frank'] # Order cannot be changed this way\n\n# LAYERWISE TABLE\nsettings.layerwise_table.caption = 'Effect on logits, layerwise split on Frank stitches.'\nsettings.layerwise_table.column_names = {'crossentropy' : 'Cross-entropy', 'cka' : 'CKA'}\n\n\n\n# ================================================================\n# PROCESSING\n# ================================================================\n\n\ndef parse_args(args):\n parser = argparse.ArgumentParser(description='Simple settings.')\n parser.add_argument('--csv', default=\"results/official/resnet20_w1_bn/summary.csv\")\n parser.add_argument('--out-dir', default='results/official/plots/resnet20_w1_bn_cka_vs_ce/')\n return parser.parse_args(args)\n\ndef filter_df(df):\n filters = [\n df.l1 == 0.,\n df.target_type=='soft_2',\n df.init =='ps_inv',\n (df.front_layer.str.contains('add'))|(df.front_layer=='bn1'),\n (df.end_layer.str.contains('add'))|(df.end_layer=='bn1'),\n df.front_model != df.end_model,\n df.temperature == 1.0,\n ]\n return df[np.logical_and.reduce(filters)]\n\ndef get_df(csv, out_dir):\n\n # Filter csv to relevant parts\n filtered_df = filter_df(pd.read_csv(csv))\n filtered_df['front_layer'] = filtered_df['front_layer'].str.capitalize()\n filtered_df = filtered_df.sort_values(['front_layer']).copy()\n \n # Calculate accuracies\n df = filtered_df.copy()\n df['frank_cka'] = df['cka_frank']\n df['ps_inv_cka'] = df['cka_ps_inv']\n df['frank_crossentropy'] = df['after_crossentropy']\n df['ps_inv_crossentropy'] = df['ps_inv_crossentropy']\n\n # Rename columns in local dataframe\n # df = df.rename(columns={\n # 'after_cka' : 'frank_cka'\n # })\n\n # Group values into one column with a category column\n def make_one_col(column):\n new_df = df[['front_layer', column]].copy()\n new_df['matrix'] = column\n new_df['style'] = 'crossentropy' if 'crossentropy' in column else 'cka'\n new_df = new_df.rename(columns={column : 'value'})\n return new_df\n dfs = [\n make_one_col('frank_crossentropy'),\n make_one_col('frank_cka'),\n make_one_col('ps_inv_crossentropy'),\n make_one_col('ps_inv_cka'),\n ]\n sum_df = pd.concat(dfs, ignore_index=True).reset_index(drop=True)\n \n # Save\n filtered_df.to_csv(os.path.join(out_dir, 'filtered_df.csv'), index=False)\n sum_df.to_csv(os.path.join(out_dir, 'sum_df.csv'), index=False)\n \n return filtered_df, sum_df\n\ndef save_table_mean_std(df, out_dir):\n \n global settings\n conf = settings.mean_std_table\n out_file = os.path.join(out_dir, 'overall_mean_std.tex')\n \n # Generatre mean and std\n df = df.copy()\n df = df.groupby(['matrix'])['value'].describe()[['mean', 'std']].copy()\n \n # Create table in desired format\n _mean = lambda x: f\"{df.loc[x, 'mean']:0.3f}\"\n _std = lambda x: f\"(\\pm{df.loc[x, 'std']:0.3f})\"\n _cell = lambda x: f\"{_mean(x)} {_std(x)}\"\n _row = lambda x: [_cell(x+'_crossentropy'), _cell(x+'_cka')]\n new_df = pd.DataFrame({\n conf.row_names[0] : _row('ps_inv'),\n conf.row_names[1] : _row('frank')\n }, index=conf.column_names)\n \n # Convert table to latex\n table_latex = new_df.to_latex(escape=False, column_format='l c c')\n \n # Place the latex table in a figure and add captopn\n latex = \"\\\\begin{table}\\n\\\\centering\\n\" + table_latex + \\\n \" \\\\caption{\" + conf.caption + \"}\\n\" + \\\n \" \\\\label{fig:my_label}\\n\" + \\\n \"\\\\end{table}\"\n \n # Save\n with open(out_file, \"w\") as text_file:\n print(latex, file=text_file)\n\n\ndef save_table_layerwise(df, out_dir):\n\n global settings\n conf = settings.layerwise_table\n out_file = os.path.join(out_dir, 'layerwise_mean_std.tex')\n\n df = df.copy()\n \n # Create CKA/Acc and PsInv/Frank categories\n df['mode'] = df.matrix.apply(lambda x: x.split('_')[-1])\n df['method'] = df.matrix.apply(lambda x: '_'.join(x.split('_')[:-1]))\n\n # Available layers in order\n layers = df['front_layer'].drop_duplicates().sort_values()\n \n # Create dataframe\n new_df = pd.DataFrame(index=layers)\n for layer in layers:\n for mode in df['mode'].drop_duplicates():\n\n # Filter ps_inv and frank\n subdf = df[(df.front_layer==layer)&(df['mode']==mode)]\n ps_inv = subdf[subdf.method == 'ps_inv']['value'].reset_index(drop=True)\n frank = subdf[subdf.method == 'frank']['value'].reset_index(drop=True)\n\n # Get mode spcific changes (e.g. % mark)\n mark = '\\%' if mode=='cka' else ''\n multiplier = 100 if mode=='cka' else 1\n\n # Caulculate mean and std\n mean = (frank-ps_inv).mean() * multiplier\n std = (frank-ps_inv).std() * multiplier\n\n # Insert variable in table\n val = f\"{mean:1.3f}{mark} (\\pm{std:1.3f}{mark})\"\n new_df.loc[layer, mode] = val\n\n # Final decoration on table \n new_df.index.name = None\n new_df = new_df.rename(columns=conf.column_names)\n \n # Convert table to latex\n table_latex = new_df.to_latex(escape=False, column_format='l c c')\n\n # Place the latex table in a figure and add captopn\n latex = \"\\\\begin{table}\\n\\\\centering\\n\" + table_latex + \\\n \" \\\\caption{\" + conf.caption + \"}\\n\" + \\\n \" \\\\label{fig:my_label}\\n\" + \\\n \"\\\\end{table}\"\n\n # Save\n with open(out_file, \"w\") as text_file:\n print(latex, file=text_file)\n\ndef save_diagram(df, out_dir):\n\n global settings\n conf = settings.plot\n out_file = os.path.join(out_dir,'crossentropy_vs_cka.pdf')\n\n fig = plt.figure(figsize=(16,9));\n\n subdf = df[df['style']=='cka']\n cka_ax = sns.lineplot(\n data=subdf, #kind=\"line\",\n x=\"front_layer\", y=\"value\",\n hue=\"matrix\", style='style',\n palette=conf.colors,\n linewidth=conf.linewidth);\n\n ce_ax = plt.twinx()\n subdf = df[df['style']!='cka']\n ce_ax = sns.lineplot(\n data=subdf, #kind=\"line\",\n x=\"front_layer\", y=\"value\",\n hue=\"matrix\", style='style',\n palette=conf.colors,\n linewidth=conf.linewidth, ax=ce_ax);\n\n\n xlabels = df['front_layer'].drop_duplicates().str.replace('.add', '').tolist()\n xlabels.sort()\n\n def set_linestyle(ax, linesetyle):\n\n # Remove columns from legend\n h,l = ax.get_legend_handles_labels()\n cols_to_remove = ['matrix', 'style', 'crossentropy', 'cka']\n h = [x for (x,y) in zip(h,l) if y not in cols_to_remove]\n l = [x for x in l if x not in cols_to_remove]\n\n # Set linewidth in legend\n for x in h:\n x.set_linewidth(conf.linewidth)\n\n # Set linestyles of CKA\n h[0].set_linestyle(linesetyle)\n h[1].set_linestyle(linesetyle)\n\n ax.lines[0].set_linestyle(linesetyle)\n ax.lines[1].set_linestyle(linesetyle)\n\n return h, l\n\n h1, l1 = set_linestyle(cka_ax, conf.cka_linestyle)\n h2, l2 = set_linestyle(ce_ax, conf.ce_linestyle)\n h, l = h1+h2, l1+l2\n\n cka_ax.get_legend().remove()\n ce_ax.get_legend().remove()\n\n # Remove sns default legend and set custom\n # g._legend.remove()\n legends = plt.legend(h,l,loc='center', fontsize=20)\n for i in range(4):\n legend = legends.get_texts()[i]\n title = legend.get_text()\n new_title = conf.rename_dict[title]\n legend.set_text(new_title)\n\n \n cka_ax.set_ylabel(conf.y_label_left, size = 24)\n cka_ax.set_xlabel(conf.x_label, size = 24)\n cka_ax.set_xticklabels(xlabels, size=24, rotation=-45)\n cka_ax.tick_params(axis='y', labelsize=24)\n cka_ax.set_ylim([0.6 ,1])\n\n cka_ax.xaxis.grid()\n\n # Set grids\n # plt.grid()\n\n ce_ax.set_ylabel(conf.y_label_right, size = 24)\n ce_ax.set_xlabel(conf.x_label, size = 24)\n ce_ax.set_ylim([0,0.5])\n\n ce_ax.xaxis.grid()\n\n plt.tick_params(axis='x', labelsize=24, rotation=-45)\n plt.tick_params(axis='y', labelsize=24, labelright=True)\n\n # Save\n plt.savefig(out_file, bbox_inches='tight')\n\n #plt.show()\n \n\ndef save_report(filtered_df, out_dir):\n data = DotMap()\n data.no_experiments = len(filtered_df)\n data.unique_networks = list(set(filtered_df.front_model).union(set(filtered_df.end_model)))\n data.unique_networks = [x.split('/')[-2] for x in data.unique_networks]\n data.same_networks_compared = str((filtered_df.front_model == filtered_df.end_model).any())\n \n extra_cols = ['l1', 'target_type', 'weight_decay', 'init', 'temperature']\n for col in extra_cols:\n data[col] = filtered_df[col].drop_duplicates().tolist()\n data.layers = filtered_df.front_layer.drop_duplicates().tolist()\n data.layers.sort()\n \n with open(os.path.join(out_dir, 'run_settings.json'), 'w') as fp:\n json.dump(data, fp)\n \n return data\n\n\ndef main(args=None):\n if args is None:\n args = sys.argv[1:]\n conf = parse_args(args)\n\n # Create directory if not exist\n os.makedirs(conf.out_dir, exist_ok=True)\n\n # Read in original csv\n filtered_df, df = get_df(conf.csv, conf.out_dir)\n\n # Run and save measurements\n save_table_layerwise(df, conf.out_dir)\n save_report(filtered_df, conf.out_dir)\n save_table_mean_std(df, conf.out_dir)\n save_diagram(df, conf.out_dir)\n\n print(f'Results saved at {conf.out_dir}')\n \n\nif __name__ == '__main__':\n main()"
] |
[
[
"matplotlib.pyplot.twinx",
"pandas.DataFrame",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.legend",
"numpy.logical_and.reduce",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tick_params",
"pandas.concat",
"pandas.read_csv"
]
] |
micromoon1997/ImageProcessingDSL
|
[
"fb59373267ac57ee7084631d951927e835b956fe"
] |
[
"quantize_image.py"
] |
[
"import numpy as np\r\nfrom kmeans import Kmeans\r\n\r\nclass ImageQuantizer:\r\n\r\n def __init__(self, b):\r\n self.b = b\r\n\r\n def quantize(self, img):\r\n b = self.b\r\n C, R, D = img.shape\r\n self.img = img\r\n X = np.reshape(img, (C * R, D))\r\n model = Kmeans(k=pow(2, b))\r\n model.fit(X)\r\n self.model = model\r\n return model.means\r\n\r\n def dequantize(self):\r\n model = self.model\r\n means = model.means\r\n img = self.img\r\n C, R, D = img.shape\r\n X = np.reshape(img, (C * R, D))\r\n y = model.predict(X)\r\n quantized_img = np.copy(self.img)\r\n for c in range(C):\r\n for r in range(R):\r\n quantized_img[c, r] = means[y[c * R + r]]\r\n return quantized_img\r\n"
] |
[
[
"numpy.copy",
"numpy.reshape"
]
] |
benvanwerkhoven/prnu
|
[
"57d8677e10a4f04a572c6b18b58ce640e6c4bedb"
] |
[
"prnu/pipeline.py"
] |
[
"#!/usr/bin/env python\nimport numpy\nimport kernel_tuner\n\nfrom scipy import misc\n#from matplotlib import pyplot\n\n#image = misc.imread(\"../test_small.jpg\", \"r\")\nimage = misc.imread(\"../test_small.jpg\", mode='RGB')\n\nmisc.imshow(image)\n\nprint (image.shape)\n\n\n\n\n\n\n\nexit()\n\n\nkernel_names = []\n\"\"\" pipeline overview\n\n-- fastnoisefilter --\n zeromem dxs\n zeromem dys\n convolveHorizontally dxs\n convolveVertically dys\n normalize\n zeromem input\n convolveHorizontally input\n convolveVertically input\n\n-- zeromeantotalfilter --\n computeMeanVertically\n transpose\n computeMeanVertically\n transpose\n\n-- wienerfilter\n tocomplex\n fft\n computeSquaredMagnitudes\n computeVarianceEstimates\n computeVarianceZeroMean\n scaleWithVariances\n ifft\n normalizeToReal\n\n\"\"\"\n\n\n\n\n\nwith open('fastnoisefilter.cu', 'r') as f:\n fastnoise_string = f.read()\nwith open('zeromeantotalfilter.cu', 'r') as f:\n zeromean_string = f.read()\nwith open('wienerfilter.cu', 'r') as f:\n wiener_string = f.read()\n\n\n\n\n\nheight = numpy.int32(image.shape[0])\nwidth = numpy.int32(image.shape[1])\n\nproblem_size = (width, 1)\n\nimage = numpy.random.randn(height*width).astype(numpy.float32)\n\nargs = [height, width, image]\n\ntune_params = dict()\ntune_params[\"block_size_x\"] = [32*i for i in range(1,9)]\ntune_params[\"block_size_y\"] = [2**i for i in range(6)]\n\ngrid_div_x = [\"block_size_x\"]\ngrid_div_y = None\n\nkernel_tuner.tune_kernel(kernel_name, kernel_string,\n problem_size, args, tune_params,\n grid_div_y=grid_div_y, grid_div_x=grid_div_x)\n\n\n\n\n\n\n"
] |
[
[
"scipy.misc.imread",
"numpy.int32",
"numpy.random.randn",
"scipy.misc.imshow"
]
] |
workingloong/elasticdl
|
[
"474146e4c347bab53c5f157441a6008dd204575c"
] |
[
"model_zoo/census_model_sqlflow/wide_and_deep/wide_deep_functional_keras.py"
] |
[
"import tensorflow as tf\n\nfrom elasticdl.python.elasticdl.callbacks import LearningRateScheduler\nfrom elasticdl_preprocessing.layers import SparseEmbedding\nfrom elasticdl_preprocessing.layers.concatenate_with_offset import (\n ConcatenateWithOffset,\n)\nfrom elasticdl_preprocessing.layers.discretization import Discretization\nfrom elasticdl_preprocessing.layers.hashing import Hashing\nfrom elasticdl_preprocessing.layers.index_lookup import IndexLookup\nfrom elasticdl_preprocessing.layers.to_sparse import ToSparse\nfrom model_zoo.census_model_sqlflow.wide_and_deep.feature_configs import (\n FEATURE_TRANSFORM_INFO_EXECUTE_ARRAY,\n INPUT_SCHEMAS,\n TRANSFORM_OUTPUTS,\n age_bucketize,\n capital_gain_bucketize,\n capital_loss_bucketize,\n education_hash,\n group1,\n group1_embedding_deep,\n group1_embedding_wide,\n group2,\n group2_embedding_deep,\n group2_embedding_wide,\n group3,\n group3_embedding_deep,\n hours_per_week_bucketize,\n marital_status_lookup,\n native_country_hash,\n occupation_hash,\n race_lookup,\n relationship_lookup,\n sex_lookup,\n workclass_lookup,\n)\nfrom model_zoo.census_model_sqlflow.wide_and_deep.transform_ops import (\n TransformOpType,\n)\n\n\n# The model definition from model zoo. It's functional style.\n# Input Params:\n# input_layers: The input layers dict of feature inputs\n# wide_embeddings: The embedding list for the wide part\n# deep_embeddings: The embedding list for the deep part\ndef wide_and_deep_classifier(input_layers, wide_embeddings, deep_embeddings):\n # Wide Part\n wide = tf.keras.layers.Concatenate()(wide_embeddings) # shape = (None, 3)\n\n # Deep Part\n dnn_input = tf.reshape(deep_embeddings, shape=(-1, 3 * 8))\n for i in [16, 8, 4]:\n dnn_input = tf.keras.layers.Dense(i)(dnn_input)\n\n # Output Part\n concat_input = tf.concat([wide, dnn_input], 1)\n\n logits = tf.reduce_sum(concat_input, 1, keepdims=True)\n probs = tf.reshape(tf.sigmoid(logits), shape=(-1,))\n\n return tf.keras.Model(\n inputs=input_layers,\n outputs={\"logits\": logits, \"probs\": probs},\n name=\"wide_deep\",\n )\n\n\n# Build the input layers from the schema of the input features\ndef get_input_layers(input_schemas):\n input_layers = {}\n\n for schema_info in input_schemas:\n input_layers[schema_info.name] = tf.keras.layers.Input(\n name=schema_info.name, shape=(1,), dtype=schema_info.dtype\n )\n\n return input_layers\n\n\n# Build the transform logic from the metadata in feature_configs.py.\ndef transform(inputs):\n transformed = inputs.copy()\n\n for feature_transform_info in FEATURE_TRANSFORM_INFO_EXECUTE_ARRAY:\n if feature_transform_info.op_type == TransformOpType.HASH:\n transformed[feature_transform_info.input] = ToSparse()(\n transformed[feature_transform_info.input]\n )\n transformed[feature_transform_info.output] = Hashing(\n feature_transform_info.hash_bucket_size\n )(transformed[feature_transform_info.input])\n elif feature_transform_info.op_type == TransformOpType.BUCKETIZE:\n transformed[feature_transform_info.input] = ToSparse()(\n transformed[feature_transform_info.input]\n )\n transformed[feature_transform_info.output] = Discretization(\n feature_transform_info.boundaries\n )(transformed[feature_transform_info.input])\n elif feature_transform_info.op_type == TransformOpType.LOOKUP:\n transformed[feature_transform_info.input] = ToSparse()(\n transformed[feature_transform_info.input]\n )\n transformed[feature_transform_info.output] = IndexLookup(\n feature_transform_info.vocabulary_list\n )(transformed[feature_transform_info.input])\n elif feature_transform_info.op_type == TransformOpType.CONCAT:\n inputs_to_concat = [\n transformed[name] for name in feature_transform_info.input\n ]\n transformed[feature_transform_info.output] = ConcatenateWithOffset(\n feature_transform_info.id_offsets\n )(inputs_to_concat)\n elif feature_transform_info.op_type == TransformOpType.EMBEDDING:\n transformed[feature_transform_info.output] = SparseEmbedding(\n input_dim=feature_transform_info.input_dim,\n output_dim=feature_transform_info.output_dim,\n )(transformed[feature_transform_info.input])\n elif feature_transform_info.op_type == TransformOpType.ARRAY:\n transformed[feature_transform_info.output] = [\n transformed[name] for name in feature_transform_info.input\n ]\n\n return tuple([transformed[name] for name in TRANSFORM_OUTPUTS])\n\n\n# The following code has the same logic with the `transform` function above.\n# It can be generated from the parsed meta in feature_configs using code_gen.\ndef transform_from_code_gen(source_inputs):\n inputs = source_inputs.copy()\n\n education_hash_out = Hashing(education_hash.hash_bucket_size)(\n ToSparse()(inputs[\"education\"])\n )\n occupation_hash_out = Hashing(occupation_hash.hash_bucket_size)(\n ToSparse()(inputs[\"occupation\"])\n )\n native_country_hash_out = Hashing(native_country_hash.hash_bucket_size)(\n ToSparse()(inputs[\"native_country\"])\n )\n workclass_lookup_out = IndexLookup(workclass_lookup.vocabulary_list)(\n ToSparse()(inputs[\"workclass\"])\n )\n marital_status_lookup_out = IndexLookup(\n marital_status_lookup.vocabulary_list\n )(ToSparse()(inputs[\"marital_status\"]))\n relationship_lookup_out = IndexLookup(relationship_lookup.vocabulary_list)(\n ToSparse()(inputs[\"relationship\"])\n )\n race_lookup_out = IndexLookup(race_lookup.vocabulary_list)(\n ToSparse()(inputs[\"race\"])\n )\n sex_lookup_out = IndexLookup(sex_lookup.vocabulary_list)(\n ToSparse()(inputs[\"sex\"])\n )\n age_bucketize_out = Discretization(age_bucketize.boundaries)(\n ToSparse()(inputs[\"age\"])\n )\n capital_gain_bucketize_out = Discretization(\n capital_gain_bucketize.boundaries\n )(ToSparse()(inputs[\"capital_gain\"]))\n capital_loss_bucketize_out = Discretization(\n capital_loss_bucketize.boundaries\n )(ToSparse()(inputs[\"capital_loss\"]))\n hours_per_week_bucketize_out = Discretization(\n hours_per_week_bucketize.boundaries\n )(ToSparse()(inputs[\"hours_per_week\"]))\n\n group1_out = ConcatenateWithOffset(group1.id_offsets)(\n [\n workclass_lookup_out,\n hours_per_week_bucketize_out,\n capital_gain_bucketize_out,\n capital_loss_bucketize_out,\n ]\n )\n group2_out = ConcatenateWithOffset(group2.id_offsets)(\n [\n education_hash_out,\n marital_status_lookup_out,\n relationship_lookup_out,\n occupation_hash_out,\n ]\n )\n group3_out = ConcatenateWithOffset(group3.id_offsets)(\n [\n age_bucketize_out,\n sex_lookup_out,\n race_lookup_out,\n native_country_hash_out,\n ]\n )\n\n group1_embedding_wide_out = SparseEmbedding(\n input_dim=group1_embedding_wide.input_dim,\n output_dim=group1_embedding_wide.output_dim,\n )(group1_out)\n group2_embedding_wide_out = SparseEmbedding(\n input_dim=group2_embedding_wide.input_dim,\n output_dim=group2_embedding_wide.output_dim,\n )(group2_out)\n\n group1_embedding_deep_out = SparseEmbedding(\n input_dim=group1_embedding_deep.input_dim,\n output_dim=group1_embedding_deep.output_dim,\n )(group1_out)\n group2_embedding_deep_out = SparseEmbedding(\n input_dim=group2_embedding_deep.input_dim,\n output_dim=group2_embedding_deep.output_dim,\n )(group2_out)\n group3_embedding_deep_out = SparseEmbedding(\n input_dim=group3_embedding_deep.input_dim,\n output_dim=group3_embedding_deep.output_dim,\n )(group3_out)\n\n wide_embeddings_out = [\n group1_embedding_wide_out,\n group2_embedding_wide_out,\n ]\n\n deep_embeddings_out = [\n group1_embedding_deep_out,\n group2_embedding_deep_out,\n group3_embedding_deep_out,\n ]\n\n return wide_embeddings_out, deep_embeddings_out\n\n\n# The entry point of the submitter program\ndef custom_model():\n input_layers = get_input_layers(input_schemas=INPUT_SCHEMAS)\n wide_embeddings, deep_embeddings = transform_from_code_gen(input_layers)\n\n return wide_and_deep_classifier(\n input_layers, wide_embeddings, deep_embeddings\n )\n\n\ndef loss(labels, predictions):\n logits = predictions[\"logits\"]\n return tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.cast(tf.reshape(labels, (-1, 1)), tf.float32),\n logits=logits,\n )\n )\n\n\ndef optimizer(lr=0.001):\n return tf.keras.optimizers.Adam(learning_rate=lr)\n\n\ndef eval_metrics_fn():\n return {\n \"logits\": {\n \"accuracy\": lambda labels, predictions: tf.equal(\n tf.cast(tf.reshape(predictions, [-1]) > 0.5, tf.int32),\n tf.cast(tf.reshape(labels, [-1]), tf.int32),\n )\n },\n \"probs\": {\"auc\": tf.keras.metrics.AUC()},\n }\n\n\ndef callbacks():\n def _schedule(model_version):\n if model_version < 5000:\n return 0.0003\n elif model_version < 12000:\n return 0.0002\n else:\n return 0.0001\n\n return [LearningRateScheduler(_schedule)]\n\n\nif __name__ == \"__main__\":\n model = custom_model()\n print(model.summary())\n\n output = model.call(\n {\n \"education\": tf.constant([[\"Bachelors\"]], tf.string),\n \"occupation\": tf.constant([[\"Tech-support\"]], tf.string),\n \"native_country\": tf.constant([[\"United-States\"]], tf.string),\n \"workclass\": tf.constant([[\"Private\"]], tf.string),\n \"marital_status\": tf.constant([[\"Separated\"]], tf.string),\n \"relationship\": tf.constant([[\"Husband\"]], tf.string),\n \"race\": tf.constant([[\"White\"]], tf.string),\n \"sex\": tf.constant([[\"Female\"]], tf.string),\n \"age\": tf.constant([[18]], tf.float32),\n \"capital_gain\": tf.constant([[100.0]], tf.float32),\n \"capital_loss\": tf.constant([[1.0]], tf.float32),\n \"hours_per_week\": tf.constant([[40]], tf.float32),\n }\n )\n\n print(output)\n"
] |
[
[
"tensorflow.keras.metrics.AUC",
"tensorflow.concat",
"tensorflow.keras.layers.Input",
"tensorflow.sigmoid",
"tensorflow.reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.constant",
"tensorflow.keras.Model",
"tensorflow.reduce_sum",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Concatenate"
]
] |
alexrame/domainbedresearch
|
[
"6255da9aedf4584115324f8cf3a45be6e9004602",
"6255da9aedf4584115324f8cf3a45be6e9004602",
"6255da9aedf4584115324f8cf3a45be6e9004602"
] |
[
"domainbed/lib/misc.py",
"domainbed/scripts/sweep.py",
"domainbed/scripts/train_coloredmnist_diversityshifts.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\n\"\"\"\nThings that don't belong anywhere else\n\"\"\"\n\nimport hashlib\nimport json\nimport os\nimport sys\nimport math\nfrom shutil import copyfile\nfrom collections import OrderedDict, defaultdict\nfrom numbers import Number\nimport operator\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import dataset\nfrom torch.utils.data.dataset import Dataset\nimport tqdm\nfrom collections import Counter\nimport socket\nimport copy\n\nimport itertools\nfrom statistics import mean\n\ntry:\n from torchmetrics import Precision, Recall\nexcept:\n Precision, Recall = None, None\n\n\nclass MovingAvg:\n def __init__(self, network):\n self.network = network\n self.network_mav = copy.deepcopy(network)\n self.network_mav.eval()\n self.mav_start_iter = 100\n self.global_iter = 0\n self.mav_count = 0\n self._classifier_mav = None\n self._featurizer_mav = None\n\n def update(self):\n self.global_iter += 1\n if self.global_iter>=self.mav_start_iter:\n self.mav_count += 1\n for param_q, param_k in zip(self.network.parameters(), self.network_mav.parameters()):\n param_k.data = (param_k.data* self.mav_count + param_q.data)/(1.+self.mav_count)\n else:\n for param_q, param_k in zip(self.network.parameters(), self.network_mav.parameters()):\n param_k.data = param_q.data\n\n def get_classifier(self):\n if self._classifier_mav is None:\n self._classifier_mav = list(self.network_mav.children())[-1]\n return self._classifier_mav\n\n def get_featurizer(self):\n if self._featurizer_mav is None:\n self._featurizer_mav = nn.Sequential(*list(self.network_mav.children())[:-1])\n return self._featurizer_mav\n\n\ndef get_ece(proba_pred, accurate, n_bins=15, min_pred=0, verbose=False, **args):\n \"\"\"\n Compute ECE and write to file\n \"\"\"\n if min_pred == \"minpred\":\n min_pred = min(proba_pred)\n else:\n assert min_pred >= 0\n bin_boundaries = np.linspace(min_pred, 1., n_bins + 1)\n bin_lowers = bin_boundaries[:-1]\n bin_uppers = bin_boundaries[1:]\n\n acc_in_bin_list = []\n avg_confs_in_bins = []\n list_prop_bin = []\n ece = 0.0\n\n for bin_lower, bin_upper in zip(bin_lowers, bin_uppers):\n in_bin = np.logical_and(proba_pred > bin_lower, proba_pred <= bin_upper)\n prop_in_bin = np.mean(in_bin)\n list_prop_bin.append(prop_in_bin)\n\n if prop_in_bin > 0:\n accuracy_in_bin = np.mean(accurate[in_bin])\n avg_confidence_in_bin = np.mean(proba_pred[in_bin])\n delta = avg_confidence_in_bin - accuracy_in_bin\n acc_in_bin_list.append(accuracy_in_bin)\n avg_confs_in_bins.append(avg_confidence_in_bin)\n ece += np.abs(delta) * prop_in_bin\n if verbose:\n print(\n f\"From {bin_lower:4.5} to {bin_upper:4.5} and mean {avg_confidence_in_bin:3.5}, {(prop_in_bin * 100):4.5} % samples with accuracy {accuracy_in_bin:4.5}\"\n )\n else:\n avg_confs_in_bins.append(None)\n acc_in_bin_list.append(None)\n\n return ece\n\n\ndef l2_between_dicts(dict_1, dict_2):\n assert len(dict_1) == len(dict_2)\n dict_1_values = [dict_1[key] for key in sorted(dict_1.keys())]\n dict_2_values = [dict_2[key] for key in sorted(dict_1.keys())]\n return (\n torch.cat(tuple([t.view(-1) for t in dict_1_values])) -\n torch.cat(tuple([t.view(-1) for t in dict_2_values]))\n ).pow(2).mean()\n\n\nclass MovingAverage:\n\n def __init__(self, ema, oneminusema_correction=True):\n self.ema = ema\n self.ema_data = {}\n self._updates = 0\n self._oneminusema_correction = oneminusema_correction\n\n def update(self, dict_data):\n ema_dict_data = {}\n for name, data in dict_data.items():\n data = data.view(1, -1)\n if self._updates == 0:\n previous_data = torch.zeros_like(data)\n else:\n previous_data = self.ema_data[name]\n\n ema_data = self.ema * previous_data + (1 - self.ema) * data\n if self._oneminusema_correction:\n ema_dict_data[name] = ema_data / (1 - self.ema)\n else:\n ema_dict_data[name] = ema_data\n self.ema_data[name] = ema_data.clone().detach()\n\n self._updates += 1\n return ema_dict_data\n\n def update_value(self, data):\n data = data.view(1, -1)\n if self._updates == 0:\n previous_data = torch.zeros_like(data)\n else:\n previous_data = self.ema_data\n\n ema_data = self.ema * previous_data + (1 - self.ema) * data\n\n self.ema_data = ema_data.clone().detach()\n self._updates += 1\n\n if self._oneminusema_correction:\n return ema_data / (1 - self.ema)\n return ema_data\n\n\ndef make_weights_for_balanced_classes(dataset):\n counts = Counter()\n classes = []\n for _, y in dataset:\n y = int(y)\n counts[y] += 1\n classes.append(y)\n\n n_classes = len(counts)\n\n weight_per_class = {}\n for y in counts:\n weight_per_class[y] = 1 / (counts[y] * n_classes)\n\n weights = torch.zeros(len(dataset))\n for i, y in enumerate(classes):\n weights[i] = weight_per_class[int(y)]\n\n return weights\n\ndef pdb():\n sys.stdout = sys.__stdout__\n import pdb\n print(\"Launching PDB, enter 'n' to step to parent function.\")\n pdb.set_trace()\n\ndef seed_hash(*args):\n \"\"\"\n Derive an integer hash from all args, for use as a random seed.\n \"\"\"\n args_str = str(args)\n return int(hashlib.md5(args_str.encode(\"utf-8\")).hexdigest(), 16) % (2**31)\n\ndef print_separator():\n print(\"=\"*80)\n\ndef print_row(row, colwidth=10, latex=False):\n if latex:\n sep = \" & \"\n end_ = \"\\\\\\\\\"\n else:\n sep = \" \"\n end_ = \"\"\n\n def format_val(x):\n if np.issubdtype(type(x), np.floating):\n x = \"{:.10f}\".format(x)\n return str(x).ljust(colwidth)[:colwidth]\n print(sep.join([format_val(x) for x in row]), end_)\n\nclass _SplitDataset(torch.utils.data.Dataset):\n \"\"\"Used by split_dataset\"\"\"\n def __init__(self, underlying_dataset, keys):\n super(_SplitDataset, self).__init__()\n self.underlying_dataset = underlying_dataset\n self.keys = keys\n def __getitem__(self, key):\n return self.underlying_dataset[self.keys[key]]\n def __len__(self):\n return len(self.keys)\n\ndef split_dataset(dataset, n, seed=0):\n \"\"\"\n Return a pair of datasets corresponding to a random split of the given\n dataset, with n datapoints in the first dataset and the rest in the last,\n using the given random seed\n \"\"\"\n assert(n <= len(dataset))\n keys = list(range(len(dataset)))\n np.random.RandomState(seed).shuffle(keys)\n keys_1 = keys[:n]\n keys_2 = keys[n:]\n return _SplitDataset(dataset, keys_1), _SplitDataset(dataset, keys_2)\n\ndef random_pairs_of_minibatches(minibatches):\n perm = torch.randperm(len(minibatches)).tolist()\n pairs = []\n\n for i in range(len(minibatches)):\n j = i + 1 if i < (len(minibatches) - 1) else 0\n\n xi, yi = minibatches[perm[i]][0], minibatches[perm[i]][1]\n xj, yj = minibatches[perm[j]][0], minibatches[perm[j]][1]\n\n min_n = min(len(xi), len(xj))\n\n pairs.append(((xi[:min_n], yi[:min_n]), (xj[:min_n], yj[:min_n])))\n\n return pairs\n\n\ndef compute_correct_batch(predictions, weights, y, device):\n correct = 0\n total = 0\n weights_offset = 0\n\n p = predictions\n if weights is None:\n batch_weights = torch.ones(len(y))\n else:\n batch_weights = weights[weights_offset : weights_offset + len(y)]\n weights_offset += len(y)\n batch_weights = batch_weights.to(device)\n if p.size(1) == 1:\n correct += (p.gt(0).eq(y).float() * batch_weights.view(-1, 1)).sum().item()\n else:\n correct += (p.argmax(1).eq(y).float() * batch_weights).sum().item()\n total += batch_weights.sum().item()\n return correct, total\n\ndef accuracy(network, loader, weights, device):\n network.eval()\n\n corrects = defaultdict(int) # key -> int\n totals = defaultdict(int) # key -> int\n\n with torch.no_grad():\n for batch in loader:\n x, y = batch\n x = x.to(device)\n y = y.to(device)\n logits = network.predict(x)\n if not isinstance(logits, dict):\n logits = {\"main\": logits}\n\n for key in logits:\n correct, total = compute_correct_batch(logits[key], weights, y, device)\n if key in [\"main\", \"\"]:\n key_name = \"acc\"\n else:\n key_name = key\n corrects[key_name] += correct\n totals[key_name] += total\n\n results = dict()\n for key in corrects:\n results[key] = corrects[key] / totals[key]\n\n network.train()\n\n return results\n\nclass Tee:\n def __init__(self, fname, mode=\"a\"):\n self.stdout = sys.stdout\n self.file = open(fname, mode)\n\n def write(self, message):\n self.stdout.write(message)\n self.file.write(message)\n self.flush()\n\n def flush(self):\n self.stdout.flush()\n self.file.flush()\n\nclass ParamDict(OrderedDict):\n \"\"\"Code adapted from https://github.com/Alok/rl_implementations/tree/master/reptile.\n A dictionary where the values are Tensors, meant to represent weights of\n a model. This subclass lets you perform arithmetic on weights directly.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, *kwargs)\n\n def _prototype(self, other, op):\n if isinstance(other, Number):\n return ParamDict({k: op(v, other) for k, v in self.items()})\n elif isinstance(other, dict):\n return ParamDict({k: op(self[k], other[k]) for k in self})\n else:\n raise NotImplementedError\n\n def __add__(self, other):\n return self._prototype(other, operator.add)\n\n def __rmul__(self, other):\n return self._prototype(other, operator.mul)\n\n __mul__ = __rmul__\n\n def __neg__(self):\n return ParamDict({k: -v for k, v in self.items()})\n\n def __rsub__(self, other):\n # a- b := a + (-b)\n return self.__add__(other.__neg__())\n\n __sub__ = __rsub__\n\n def __truediv__(self, other):\n return self._prototype(other, operator.truediv)\n\n\nclass CustomToRegularDataset(Dataset):\n def __init__(self, dataset):\n self.dataset = dataset\n\n def __getitem__(self, index):\n item = self.dataset[index]\n return item[\"x\"], item[\"y\"]\n\n def __len__(self) -> int:\n return len(self.dataset)\n\ndef dict_batch_to_device(batch, device):\n for key in batch:\n if isinstance(batch[key], torch.Tensor):\n batch[key] = batch[key].to(device)\n elif isinstance(batch[key], dict):\n batch[key] = dict_batch_to_device(batch[key], device)\n return batch\n\n\nclass DictDataset(Dataset):\n def __init__(self, dict):\n keys = list(dict.keys())\n self.keys = keys\n # assert all(dict[keys[0]].size(0) == dict[k].size(0) for k in keys), \"Size mismatch between tensors\"\n self.dict = dict\n\n def __getitem__(self, index):\n return {\n key: self.dict[key][index]\n for key in self.keys\n }\n def __len__(self):\n return len(self.dict[self.keys[0]])\n\ndef get_machine_name():\n return socket.gethostname()\n\n\n\ndef one_hot_embedding(labels, num_classes):\n \"\"\"Embedding labels to one-hot form.\n\n Args:\n labels: (LongTensor) class labels, sized [N,].\n num_classes: (int) number of classes.\n\n Returns:\n (tensor) encoded labels, sized [N, #classes].\n \"\"\"\n y = torch.eye(num_classes).to(device=labels.device)\n return y[labels]\n",
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\n\"\"\"\nRun sweeps\n\"\"\"\n\nimport argparse\nimport copy\nimport getpass\nimport hashlib\nimport json\nimport os\nimport random\nimport shutil\nimport time\nimport uuid\n\nimport numpy as np\nimport torch\n\nfrom domainbed import datasets\nfrom domainbed import hparams_registry\nfrom domainbed import algorithms\nfrom domainbed.lib import misc\nfrom domainbed import command_launchers\n\nimport tqdm\nimport shlex\n\nclass Job:\n NOT_LAUNCHED = 'Not launched'\n INCOMPLETE = 'Incomplete'\n DONE = 'Done'\n\n def __init__(self, train_args, sweep_output_dir):\n args_str = json.dumps(train_args, sort_keys=True)\n args_hash = hashlib.md5(args_str.encode('utf-8')).hexdigest()\n self.output_dir = os.path.join(sweep_output_dir, args_hash)\n\n self.train_args = copy.deepcopy(train_args)\n self.train_args['output_dir'] = self.output_dir\n command = ['python', '-m', 'domainbed.scripts.train']\n for k, v in sorted(self.train_args.items()):\n if k == \"hp\":\n for (name, value) in v:\n command.append(f\"--hp {name} {value}\")\n else:\n if isinstance(v, list):\n v = ' '.join([str(v_) for v_ in v])\n elif isinstance(v, str):\n v = shlex.quote(v)\n command.append(f'--{k} {v}')\n self.command_str = ' '.join(command)\n print(self.command_str)\n\n if os.path.exists(os.path.join(self.output_dir, 'done')):\n self.state = Job.DONE\n elif os.path.exists(self.output_dir):\n self.state = Job.INCOMPLETE\n else:\n self.state = Job.NOT_LAUNCHED\n\n def __str__(self):\n job_info = (self.train_args['dataset'],\n self.train_args['algorithm'],\n self.train_args['test_envs'],\n self.train_args['hparams_seed'])\n return '{}: {} {}'.format(\n self.state,\n self.output_dir,\n job_info)\n\n @staticmethod\n def launch(jobs, launcher_fn):\n print('Launching...')\n jobs = jobs.copy()\n np.random.shuffle(jobs)\n print('Making job directories:')\n for job in tqdm.tqdm(jobs, leave=False):\n os.makedirs(job.output_dir, exist_ok=True)\n commands = [job.command_str for job in jobs]\n launcher_fn(commands)\n print(f'Launched {len(jobs)} jobs!')\n\n @staticmethod\n def delete(jobs):\n print('Deleting...')\n for job in jobs:\n shutil.rmtree(job.output_dir)\n print(f'Deleted {len(jobs)} jobs!')\n\ndef all_test_env_combinations(n):\n \"\"\"\n For a dataset with n >= 3 envs, return all combinations of 1 and 2 test\n envs.\n \"\"\"\n assert(n >= 3)\n for i in range(n):\n yield [i]\n for j in range(i+1, n):\n yield [i, j]\n\ndef make_args_list(\n n_trials, dataset_names, algorithms, n_hparams_from, n_hparams, steps, data_dir, task,\n holdout_fraction, single_test_envs, hparams, test_envs, hp, sweep_id, seed\n):\n args_list = []\n for trial_seed in range(n_trials):\n trial_seed += seed\n for dataset in dataset_names:\n for algorithm in algorithms:\n if test_envs is not None:\n if not single_test_envs:\n all_test_envs = [test_envs]\n else:\n all_test_envs = test_envs\n elif single_test_envs:\n all_test_envs = [\n [i] for i in range(datasets.num_environments(dataset))]\n else:\n all_test_envs = all_test_env_combinations(\n datasets.num_environments(dataset))\n print(all_test_envs)\n for _test_envs in all_test_envs:\n for hparams_seed in range(n_hparams_from, n_hparams):\n train_args = {}\n train_args['dataset'] = dataset\n train_args['algorithm'] = algorithm\n train_args['test_envs'] = _test_envs\n train_args['holdout_fraction'] = holdout_fraction\n train_args['hparams_seed'] = hparams_seed\n train_args['data_dir'] = data_dir\n train_args['task'] = task\n train_args[\"sweep_id\"] = sweep_id\n train_args['trial_seed'] = trial_seed\n train_args['seed'] = misc.seed_hash(\n dataset, algorithm, _test_envs, hparams_seed, trial_seed\n )\n if steps is not None:\n train_args['steps'] = steps\n if hparams is not None:\n train_args['hparams'] = hparams\n if hp is not None:\n train_args[\"hp\"] = hp\n args_list.append(train_args)\n return args_list\n\ndef ask_for_confirmation():\n response = input('Are you sure? (y/n) ')\n if not response.lower().strip()[:1] == \"y\":\n print('Nevermind!')\n exit(0)\n\nDATASETS = [d for d in datasets.DATASETS if \"Debug\" not in d]\n\nif __name__ == \"__main__\":\n # --n_hparams 20 --n_trials 3\n parser = argparse.ArgumentParser(description='Run a sweep')\n parser.add_argument('command', choices=['launch', 'delete_incomplete'])\n parser.add_argument('--datasets', nargs='+', type=str, default=DATASETS)\n parser.add_argument('--algorithms', nargs='+', type=str, default=algorithms.ALGORITHMS)\n parser.add_argument('--task', type=str, default=\"domain_generalization\")\n parser.add_argument('--n_hparams_from', type=int, default=0)\n parser.add_argument('--n_hparams', type=int, default=20)\n parser.add_argument('--output_dir', type=str, required=True)\n parser.add_argument('--data_dir', type=str, default=\"default\")\n parser.add_argument('--seed', type=int, default=0)\n parser.add_argument('--n_trials', type=int, default=3)\n parser.add_argument('--command_launcher', type=str,\n default=\"local\")\n parser.add_argument('--steps', type=int, default=None)\n parser.add_argument('--hparams', type=str, default=None)\n parser.add_argument(\"--hp\", nargs=2, action=\"append\")\n parser.add_argument('--holdout_fraction', type=float, default=0.2)\n parser.add_argument('--single_test_envs', action='store_true')\n parser.add_argument('--skip_confirmation', action='store_true')\n parser.add_argument(\"--test_envs\", default=None, nargs=\"+\")\n args = parser.parse_args()\n if args.data_dir == \"default\":\n if os.environ.get(\"DATAQUICK\", \"none\") not in [None, \"none\"]:\n args.data_dir = os.path.join(os.environ.get(\"DATAQUICK\"), \"dataplace/domainbed/\")\n else:\n args.data_dir = os.path.join(\n os.environ.get(\"DATA\", \"\"),\n \"data/domainbed/\")\n args_list = make_args_list(\n n_trials=args.n_trials,\n dataset_names=args.datasets,\n algorithms=args.algorithms,\n n_hparams_from=args.n_hparams_from,\n n_hparams=args.n_hparams,\n steps=args.steps,\n data_dir=args.data_dir,\n task=args.task,\n holdout_fraction=args.holdout_fraction,\n single_test_envs=args.single_test_envs,\n hparams=args.hparams,\n test_envs=args.test_envs,\n hp=args.hp,\n sweep_id=os.path.split(args.output_dir)[-1],\n seed=args.seed\n )\n\n jobs = [Job(train_args, args.output_dir) for train_args in args_list]\n\n for job in jobs:\n print(job)\n print(\"{} jobs: {} done, {} incomplete, {} not launched.\".format(\n len(jobs),\n len([j for j in jobs if j.state == Job.DONE]),\n len([j for j in jobs if j.state == Job.INCOMPLETE]),\n len([j for j in jobs if j.state == Job.NOT_LAUNCHED]))\n )\n\n if args.command == 'launch':\n to_launch = [j for j in jobs if j.state in [Job.NOT_LAUNCHED, Job.INCOMPLETE]]\n print(f'About to launch {len(to_launch)} jobs.')\n if False and not args.skip_confirmation:\n ask_for_confirmation()\n launcher_fn = command_launchers.REGISTRY[args.command_launcher]\n Job.launch(to_launch, launcher_fn)\n\n elif args.command == 'delete_incomplete':\n to_delete = [j for j in jobs if j.state == Job.INCOMPLETE]\n print(f'About to delete {len(to_delete)} jobs.')\n if not args.skip_confirmation:\n ask_for_confirmation()\n Job.delete(to_delete)\n",
"# This script was first copied from https://github.com/facebookresearch/InvariantRiskMinimization/blob/master/code/colored_mnist/main.py\n# under the license Copyright (c) Facebook, Inc. and its affiliates.\n#\n# We included our new regularization Fishr. To do so:\n# 1. first, we compute gradient variances on each domain (see compute_grad_variance method) using the BackPACK package\n# 2. then, we compute the l2 distance between these gradient variances (see l2_between_grad_variance method)\n\nimport random\nimport argparse\nimport numpy as np\n\nimport torch\nfrom torchvision import datasets\nfrom torch import nn, optim, autograd\n\nfrom backpack import backpack, extend\nfrom backpack.extensions import BatchGrad, SumGradSquared, Variance\n\nparser = argparse.ArgumentParser(description='Colored MNIST')\n\n# Select your algorithm\nparser.add_argument(\n '--algorithm',\n type=str,\n default=\"fishr\",\n # choices=[\n # ## Four main methods, for Table 2 in Section 5.1\n # 'erm', # Empirical Risk Minimization\n # 'irm', # Invariant Risk Minimization (https://arxiv.org/abs/1907.02893)\n # 'rex', # Out-of-Distribution Generalization via Risk Extrapolation (https://icml.cc/virtual/2021/oral/9186)\n # 'fishr', # Our proposed Fishr\n # ## two Fishr variants, for Table 6 in Appendix B.2.4\n # 'fishr_offdiagonal', # Fishr but on the full covariance rather than only the diagonal\n # 'fishr_notcentered', # Fishr but without centering the gradient variances\n # ## Fishr on the full network\n # 'fishr_features_onlyfeatures',\n # 'fishr_features',\n # 'fishr_features_notcentered',\n # ## cosine distance\n # 'fishr_linearincrease',\n # ]\n)\n# Select whether you want to apply label flipping or not:\n# label_flipping_prob = 0.25 by default except in Table 5 in Appendix B.2.3 and in the right half of Table 6 in Appendix B.2.4 where label_flipping_prob = 0\nparser.add_argument('--label_flipping_prob', type=float, default=0.25)\n\n# Following hyperparameters are directly taken from:\n# https://github.com/facebookresearch/InvariantRiskMinimization/blob/master/code/colored_mnist/reproduce_paper_results.sh\n# They should not be modified except in case of a new proper hyperparameter search with an external validation dataset.\n# Overall, we compare all approaches using the hyperparameters optimized for IRM.\nparser.add_argument('--hidden_dim', type=int, default=390)\nparser.add_argument('--l2_regularizer_weight', type=float, default=0.00110794568)\nparser.add_argument('--lr', type=float, default=0.0004898536566546834)\nparser.add_argument('--penalty_anneal_iters', type=int, default=190)\nparser.add_argument('--penalty_weight', type=float, default=91257.18613115903)\nparser.add_argument('--steps', type=int, default=501)\n\n# experimental setup\nparser.add_argument('--grayscale_model', action='store_true')\nparser.add_argument('--n_restarts', type=int, default=1)\nparser.add_argument('--seed', type=int, default=0, help='Seed for everything')\n\nflags = parser.parse_args()\n\nprint('Flags:')\nfor k, v in sorted(vars(flags).items()):\n print(\"\\t{}: {}\".format(k, v))\n\nrandom.seed(flags.seed)\nnp.random.seed(flags.seed)\ntorch.manual_seed(flags.seed)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nfinal_train_accs = []\nfinal_test_accs = []\nfor restart in range(flags.n_restarts):\n print(\"Restart\", restart)\n\n # Load MNIST, make train/val splits, and shuffle train set examples\n\n mnist = datasets.MNIST('~/datasets/mnist', train=True, download=True)\n mnist_train = (mnist.data[:50000], mnist.targets[:50000])\n # mnist_train = (mnist.data[:500], mnist.targets[:500])\n mnist_val = (mnist.data[50000:], mnist.targets[50000:])\n\n rng_state = np.random.get_state()\n np.random.shuffle(mnist_train[0].numpy())\n np.random.set_state(rng_state)\n np.random.shuffle(mnist_train[1].numpy())\n\n # Build environments\n\n\n def make_environment(images, labels, e, grayscale=False, accepted_digit=None):\n\n def torch_bernoulli(p, size):\n return (torch.rand(size) < p).float()\n\n def torch_xor(a, b):\n return (a - b).abs() # Assumes both inputs are either 0 or 1\n\n # 2x subsample for computational convenience\n images = images.reshape((-1, 28, 28))[:, ::2, ::2]\n # Assign a binary label based on the digit; flip label with probability 0.25\n digits = labels.clone()\n labels = (labels < 5).float()\n labels = torch_xor(labels, torch_bernoulli(flags.label_flipping_prob, len(labels)))\n # Assign a color based on the label; flip the color with probability e\n colors = torch_xor(labels, torch_bernoulli(e, len(labels)))\n # Apply the color to the image by zeroing out the other color channel\n images = torch.stack([images, images], dim=1)\n if not grayscale:\n images[torch.tensor(range(len(images))), (1 - colors).long(), :, :] *= 0\n dict_output = {\n 'images': (images.float() / 255.).cuda(),\n 'labels': labels[:, None].cuda(),\n 'digits': digits[:, None].cuda(),}\n if accepted_digit is not None:\n idx = sum(\n [digits == int(_accepted_digit) for _accepted_digit in accepted_digit.split(\"_\")]\n ).bool()\n dict_output = {key: value[idx] for key, value in dict_output.items()}\n return dict_output\n\n envs = [\n make_environment(mnist_train[0][::2], mnist_train[1][::2], 0.2, accepted_digit=\"0_1_2_5_6\"),\n make_environment(mnist_train[0][1::2], mnist_train[1][1::2], 0.1),\n make_environment(\n mnist_val[0],\n mnist_val[1],\n 0.9,\n ),\n make_environment(\n mnist_val[0],\n mnist_val[1],\n 0.9,\n accepted_digit=\"0_1_2_5_6\",\n ),\n make_environment(\n mnist_val[0],\n mnist_val[1],\n 0.9,\n # grayscale=True\n accepted_digit=\"3_4_7_8_9\",\n ),\n ]\n\n # Define and instantiate the model\n\n\n class MLP(nn.Module):\n\n def __init__(self):\n super(MLP, self).__init__()\n if flags.grayscale_model:\n lin1 = nn.Linear(14 * 14, flags.hidden_dim)\n else:\n lin1 = nn.Linear(2 * 14 * 14, flags.hidden_dim)\n lin2 = nn.Linear(flags.hidden_dim, flags.hidden_dim)\n\n self.classifier = extend(nn.Linear(flags.hidden_dim, 1))\n for lin in [lin1, lin2, self.classifier]:\n nn.init.xavier_uniform_(lin.weight)\n nn.init.zeros_(lin.bias)\n self._main = extend(nn.Sequential(lin1, nn.ReLU(True), lin2, nn.ReLU(True)))\n self.fullnetwork = extend(\n nn.Sequential(lin1, nn.ReLU(True), lin2, nn.ReLU(True), self.classifier)\n )\n\n @staticmethod\n def prepare_input(input):\n if flags.grayscale_model:\n out = input.view(input.shape[0], 2, 14 * 14).sum(dim=1)\n else:\n out = input.view(input.shape[0], 2 * 14 * 14)\n return out\n\n def forward(self, input):\n out = self.prepare_input(input)\n features = self._main(out)\n logits = self.classifier(features)\n return features, logits\n\n mlp = MLP().cuda()\n\n # Define loss function helpers\n\n\n def mean_nll(logits, y):\n return nn.functional.binary_cross_entropy_with_logits(logits, y)\n\n def mean_accuracy(logits, y):\n preds = (logits > 0.).float()\n return ((preds - y).abs() < 1e-2).float().mean()\n\n def compute_irm_penalty(logits, y):\n scale = torch.tensor(1.).cuda().requires_grad_()\n loss = mean_nll(logits * scale, y)\n grad = autograd.grad(loss, [scale], create_graph=True)[0]\n return torch.sum(grad**2)\n\n bce_extended = extend(nn.BCEWithLogitsLoss(reduction='sum'))\n\n def compute_grad_variance(input, labels, network):\n \"\"\"\n Main Fishr method that computes the gradient variances in the classifier using the BackPACK package.\n \"\"\"\n logits = network(input)\n loss = bce_extended(logits, labels)\n # calling first-order derivatives in the network while maintaining the per-sample gradients\n\n with backpack(Variance(), SumGradSquared()):\n loss.backward(\n inputs=list(network.parameters()), retain_graph=True, create_graph=True\n )\n\n dict_grads_variance_backpack = {\n name: (\n weights.variance.clone().view(-1)\n if \"notcentered\" not in flags.algorithm.split(\"_\") else\n weights.sum_grad_squared.clone().view(-1) / input.size(0)\n ) for name, weights in network.named_parameters() if (\n \"onlyfeatures\" not in flags.algorithm.split(\"_\") or\n name not in [\"4.weight\", \"4.bias\"]\n )\n }\n\n return dict_grads_variance_backpack\n\n def l2_between_grad_variance(cov_1, cov_2):\n assert len(cov_1) == len(cov_2)\n cov_1_values = [cov_1[key] for key in sorted(cov_1.keys())]\n cov_2_values = [cov_2[key] for key in sorted(cov_1.keys())]\n return (\n torch.cat(tuple([t.view(-1) for t in cov_1_values])) -\n torch.cat(tuple([t.view(-1) for t in cov_2_values]))\n ).pow(2).sum()\n\n # Train loop\n\n def pretty_print(*values):\n col_width = 13\n\n def format_val(v):\n if not isinstance(v, str):\n v = np.array2string(v, precision=5, floatmode='fixed')\n return v.ljust(col_width)\n\n str_values = [format_val(v) for v in values]\n print(\" \".join(str_values))\n\n optimizer = optim.Adam(mlp.parameters(), lr=flags.lr)\n\n pretty_print(\n 'step',\n 'train nll',\n 'train0 acc',\n 'train1 acc',\n 'fishr penalty',\n 'rex penalty',\n 'irm penalty',\n 'test acc',\n '0_1_2_5_6',\n \"3_4_7_8_9\"\n )\n for step in range(flags.steps):\n for edx, env in enumerate(envs):\n features, logits = mlp(env['images'])\n env['nll'] = mean_nll(logits, env['labels'])\n env['acc'] = mean_accuracy(logits, env['labels'])\n if edx in [0, 1]:\n # when the dataset is in training\n optimizer.zero_grad()\n if \"classcond\" in flags.algorithm.split(\"_\"):\n env[\"grad_variance\"] = {}\n env['irm'] = {}\n env['nllrex'] = {}\n for digit in [0, 1, 2, 5, 6]:\n idx = (env['digits'] == digit).view(-1)\n assert sum(idx).bool()\n env['nllrex'][digit] = mean_nll(logits[idx], env['labels'][idx])\n env['irm'][digit] = compute_irm_penalty(logits[idx], env['labels'][idx])\n if \"fishr\" in flags.algorithm.split(\"_\"):\n if \"features\" in flags.algorithm.split(\"_\"):\n env[\"grad_variance\"][digit] = compute_grad_variance(\n mlp.prepare_input(env[\"images\"][idx]), env['labels'][idx],\n mlp.fullnetwork\n )\n else:\n env[\"grad_variance\"][digit] = compute_grad_variance(\n features[idx], env['labels'][idx], mlp.classifier\n )\n else:\n env['irm'] = compute_irm_penalty(logits, env['labels'])\n\n if \"features\" in flags.algorithm.split(\"_\"):\n env[\"grad_variance\"] = compute_grad_variance(\n mlp.prepare_input(env[\"images\"]), env['labels'], mlp.fullnetwork\n )\n else:\n env[\"grad_variance\"] = compute_grad_variance(\n features, env['labels'], mlp.classifier\n )\n\n train_nll = 1 / 3 * envs[0]['nll'] + 2 / 3 * envs[1]['nll']\n train_acc = 1 / 3 * envs[0]['acc'] + 2 / 3 * envs[1]['acc']\n\n weight_norm = torch.tensor(0.).cuda()\n for w in mlp.parameters():\n weight_norm += w.norm().pow(2)\n\n loss = train_nll.clone()\n loss += flags.l2_regularizer_weight * weight_norm\n\n if \"classcond\" in flags.algorithm.split(\"_\"):\n fishr_penalty = 0\n irm_penalty = 0\n rex_penalty = 0\n for digit in [0, 1, 2, 5, 6]:\n irm_penalty += torch.stack([envs[0]['irm'][digit], envs[1]['irm'][digit]]).mean()\n rex_penalty += (envs[0]['nllrex'][digit].mean() - envs[1]['nllrex'][digit].mean())**2\n if \"fishr\" in flags.algorithm.split(\"_\"):\n dict_grad_variance_averaged = {\n name: torch.stack(\n [\n envs[0][\"grad_variance\"][digit][name],\n envs[1][\"grad_variance\"][digit][name]\n ],\n dim=0\n ).mean(dim=0) for name in envs[0][\"grad_variance\"][0]\n }\n fishr_penalty += (\n l2_between_grad_variance(\n envs[0][\"grad_variance\"][digit], dict_grad_variance_averaged\n ) + l2_between_grad_variance(\n envs[1][\"grad_variance\"][digit], dict_grad_variance_averaged\n )\n )\n else:\n fishr_penalty = torch.tensor(0)\n else:\n irm_penalty = torch.stack([envs[0]['irm'], envs[1]['irm']]).mean()\n rex_penalty = (envs[0]['nll'].mean() - envs[1]['nll'].mean())**2\n dict_grad_variance_averaged = {\n name: torch.stack(\n [envs[0][\"grad_variance\"][name], envs[1][\"grad_variance\"][name]], dim=0\n ).mean(dim=0) for name in envs[0][\"grad_variance\"]\n }\n fishr_penalty = (\n l2_between_grad_variance(envs[0][\"grad_variance\"], dict_grad_variance_averaged) +\n l2_between_grad_variance(envs[1][\"grad_variance\"], dict_grad_variance_averaged)\n )\n\n if flags.algorithm.startswith(\"erm\"):\n pass\n else:\n # apply the selected regularization\n if flags.algorithm.startswith(\"fishr\"):\n train_penalty = fishr_penalty\n elif flags.algorithm.startswith(\"rex\"):\n train_penalty = rex_penalty\n elif flags.algorithm.startswith(\"irm\"):\n train_penalty = irm_penalty\n else:\n raise ValueError(flags.algorithm)\n penalty_weight = (flags.penalty_weight if step >= flags.penalty_anneal_iters else 1.0)\n loss += penalty_weight * train_penalty\n if penalty_weight > 1.0:\n # Rescale the entire loss to keep backpropagated gradients in a reasonable range\n loss /= penalty_weight\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n test_acc = envs[2]['acc']\n grayscale_test_acc = envs[3]['acc']\n if step % 20 == 0:\n pretty_print(\n np.int32(step),\n train_nll.detach().cpu().numpy(),\n envs[0]['acc'].detach().cpu().numpy(),\n envs[1]['acc'].detach().cpu().numpy(),\n fishr_penalty.detach().cpu().numpy(),\n rex_penalty.detach().cpu().numpy(),\n irm_penalty.detach().cpu().numpy(),\n envs[2]['acc'].detach().cpu().numpy(),\n envs[3]['acc'].detach().cpu().numpy(),\n envs[4]['acc'].detach().cpu().numpy(),\n )\n\n final_train_accs.append(train_acc.detach().cpu().numpy())\n final_test_accs.append(envs[2]['acc'].detach().cpu().numpy())\n\n print('Final train acc (mean/std across restarts so far):')\n print(np.mean(final_train_accs), np.std(final_train_accs))\n print('Final test acc (mean/std across restarts so far):')\n print(np.mean(final_test_accs), np.std(final_test_accs))\n"
] |
[
[
"numpy.random.RandomState",
"torch.no_grad",
"numpy.mean",
"numpy.logical_and",
"torch.eye",
"numpy.abs",
"torch.zeros_like",
"numpy.linspace"
],
[
"numpy.random.shuffle"
],
[
"torch.nn.Linear",
"torch.stack",
"numpy.mean",
"torch.nn.BCEWithLogitsLoss",
"torch.sum",
"torch.manual_seed",
"torch.autograd.grad",
"torch.tensor",
"numpy.int32",
"torch.nn.init.zeros_",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.nn.ReLU",
"numpy.std",
"numpy.random.set_state",
"numpy.array2string",
"torch.rand",
"numpy.random.seed",
"torch.nn.init.xavier_uniform_",
"numpy.random.get_state"
]
] |
pd0wm/nn-morse
|
[
"f6a504aeb4b414d420058092d437c780aa74ca6d",
"f6a504aeb4b414d420058092d437c780aa74ca6d"
] |
[
"main.py",
"morse.py"
] |
[
"#!/usr/bin/env python3\nimport random\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils import data\n\n\nfrom morse import ALPHABET, generate_sample\nfrom itertools import groupby\n\nnum_tags = len(ALPHABET)\n\n# 0: blank label\ntag_to_idx = {c: i + 1 for i, c in enumerate(ALPHABET)}\nidx_to_tag = {i + 1: c for i, c in enumerate(ALPHABET)}\n\n\ndef prediction_to_str(seq):\n if not isinstance(seq, list):\n seq = seq.tolist()\n\n # remove duplicates\n seq = [i[0] for i in groupby(seq)]\n\n # remove blanks\n seq = [s for s in seq if s != 0]\n\n # convert to string\n seq = \"\".join(idx_to_tag[c] for c in seq)\n\n return seq\n\n\ndef get_training_sample(*args, **kwargs):\n _, spec, y = generate_sample(*args, **kwargs)\n\n spec = torch.from_numpy(spec)\n spec = spec.permute(1, 0)\n\n y_tags = [tag_to_idx[c] for c in y]\n y_tags = torch.tensor(y_tags)\n\n return spec, y_tags\n\n\nclass Net(nn.Module):\n def __init__(self, num_tags, spectrogram_size):\n super(Net, self).__init__()\n\n num_tags = num_tags + 1 # 0: blank\n hidden_dim = 256\n lstm_dim1 = 256\n\n self.dense1 = nn.Linear(spectrogram_size, hidden_dim)\n self.dense2 = nn.Linear(hidden_dim, hidden_dim)\n self.dense3 = nn.Linear(hidden_dim, hidden_dim)\n self.dense4 = nn.Linear(hidden_dim, lstm_dim1)\n self.lstm1 = nn.LSTM(lstm_dim1, lstm_dim1, batch_first=True)\n self.dense5 = nn.Linear(lstm_dim1, num_tags)\n\n def forward(self, x):\n x = F.relu(self.dense1(x))\n x = F.relu(self.dense2(x))\n x = F.relu(self.dense3(x))\n x = F.relu(self.dense4(x))\n\n x, _ = self.lstm1(x)\n\n x = self.dense5(x)\n x = F.log_softmax(x, dim=2)\n return x\n\n def count_parameters(self):\n return sum(p.numel() for p in self.parameters() if p.requires_grad)\n\n\nclass Dataset(data.Dataset):\n def __len__(self):\n return 2048\n\n def __getitem__(self, index):\n length = random.randrange(10, 20)\n pitch = random.randrange(100, 950)\n wpm = random.randrange(10, 40)\n noise_power = random.randrange(0, 200)\n amplitude = random.randrange(10, 150)\n return get_training_sample(length, pitch, wpm, noise_power, amplitude)\n\n\ndef collate_fn_pad(batch):\n xs, ys = zip(*batch)\n\n input_lengths = torch.tensor([t.shape[0] for t in xs])\n output_lengths = torch.tensor([t.shape[0] for t in ys])\n\n seqs = nn.utils.rnn.pad_sequence(xs, batch_first=True)\n ys = nn.utils.rnn.pad_sequence(ys, batch_first=True)\n\n return input_lengths, output_lengths, seqs, ys\n\n\nif __name__ == \"__main__\":\n batch_size = 64\n spectrogram_size = generate_sample()[1].shape[0]\n\n device = torch.device(\"cuda\")\n writer = SummaryWriter()\n\n # Set up trainer & evaluator\n model = Net(num_tags, spectrogram_size).to(device)\n print(\"Number of params\", model.count_parameters())\n\n # Lower learning rate to 1e-4 after about 1500 epochs\n optimizer = optim.Adam(model.parameters(), lr=1e-3)\n ctc_loss = nn.CTCLoss()\n\n train_loader = torch.utils.data.DataLoader(\n Dataset(),\n batch_size=batch_size,\n num_workers=4,\n collate_fn=collate_fn_pad,\n )\n\n random.seed(0)\n\n epoch = 0\n\n # Resume training\n if epoch != 0:\n model.load_state_dict(torch.load(f\"models/{epoch:06}.pt\", map_location=device))\n\n model.train()\n while True:\n for (input_lengths, output_lengths, x, y) in train_loader:\n x, y = x.to(device), y.to(device)\n\n optimizer.zero_grad()\n\n y_pred = model(x)\n\n m = torch.argmax(y_pred[0], 1)\n y_pred = y_pred.permute(1, 0, 2)\n\n loss = ctc_loss(y_pred, y, input_lengths, output_lengths)\n\n loss.backward()\n optimizer.step()\n\n writer.add_scalar(\"training/loss\", loss.item(), epoch)\n\n if epoch % 10 == 0:\n torch.save(model.state_dict(), f\"models/{epoch:06}.pt\")\n\n print(prediction_to_str(y[0]))\n print(prediction_to_str(m))\n print(loss.item())\n print()\n epoch += 1\n",
"#!/usr/bin/env python3\n\nfrom scipy import signal\nimport numpy as np\nimport random\n\nSAMPLE_FREQ = 2000 # 2 Khz\n\nMORSE_CODE_DICT = {\n 'A': '.-', 'B': '-...',\n 'C': '-.-.', 'D': '-..', 'E': '.',\n 'F': '..-.', 'G': '--.', 'H': '....',\n 'I': '..', 'J': '.---', 'K': '-.-',\n 'L': '.-..', 'M': '--', 'N': '-.',\n 'O': '---', 'P': '.--.', 'Q': '--.-',\n 'R': '.-.', 'S': '...', 'T': '-',\n 'U': '..-', 'V': '...-', 'W': '.--',\n 'X': '-..-', 'Y': '-.--', 'Z': '--..',\n '1': '.----', '2': '..---', '3': '...--',\n '4': '....-', '5': '.....', '6': '-....',\n '7': '--...', '8': '---..', '9': '----.',\n '0': '-----',\n '.': '.-.-.-', ',': '--..--', '?': '..--..',\n '=': '-...-', '+': '.-.-.',\n}\nALPHABET = \" \" + \"\".join(MORSE_CODE_DICT.keys())\n\n\ndef get_spectrogram(samples):\n window_length = int(0.02 * SAMPLE_FREQ) # 20 ms windows\n _, _, s = signal.spectrogram(samples, nperseg=window_length, noverlap=0)\n return s\n\n\ndef generate_sample(text_len=10, pitch=500, wpm=20, noise_power=1, amplitude=100, s=None):\n assert pitch < SAMPLE_FREQ / 2 # Nyquist\n\n # Reference word is PARIS, 50 dots long\n dot = (60 / wpm) / 50 * SAMPLE_FREQ\n\n # Add some noise on the length of dash and dot\n def get_dot():\n scale = np.clip(np.random.normal(1, 0.2), 0.5, 2.0)\n return int(dot * scale)\n\n # The length of a dash is three times the length of a dot.\n def get_dash():\n scale = np.clip(np.random.normal(1, 0.2), 0.5, 2.0)\n return int(3 * dot * scale)\n\n # Create random string that doesn't start or end with a space\n if s is None:\n s1 = ''.join(random.choices(ALPHABET, k=text_len - 2))\n s2 = ''.join(random.choices(ALPHABET[1:], k=2))\n s = s2[0] + s1 + s2[1]\n\n out = []\n out.append(np.zeros(5 * get_dot()))\n\n # The space between two signs of the same character is equal to the length of one dot.\n # The space between two characters of the same word is three times the length of a dot.\n # The space between two words is seven times the length of a dot (or more).\n for c in s:\n if c == ' ':\n out.append(np.zeros(7 * get_dot()))\n else:\n for m in MORSE_CODE_DICT[c]:\n if m == '.':\n out.append(np.ones(get_dot()))\n out.append(np.zeros(get_dot()))\n elif m == '-':\n out.append(np.ones(get_dash()))\n out.append(np.zeros(get_dot()))\n\n out.append(np.zeros(2 * get_dot()))\n\n out.append(np.zeros(5 * get_dot()))\n out = np.hstack(out)\n\n # Modulatation\n t = np.arange(len(out)) / SAMPLE_FREQ\n sine = np.sin(2 * np.pi * t * pitch)\n out = sine * out\n\n # Add noise\n noise_power = 1e-6 * noise_power * SAMPLE_FREQ / 2\n noise = np.random.normal(scale=np.sqrt(noise_power), size=len(out))\n out = 0.5 * out + noise\n\n out *= amplitude / 100\n out = np.clip(out, -1, 1)\n\n out = out.astype(np.float32)\n\n spec = get_spectrogram(out)\n\n return out, spec, s\n\n\nif __name__ == \"__main__\":\n from scipy.io.wavfile import write\n import matplotlib.pyplot as plt\n\n length = random.randrange(10, 20)\n pitch = random.randrange(100, 950)\n wpm = random.randrange(10, 40)\n noise_power = random.randrange(0, 200)\n amplitude = random.randrange(10, 150)\n\n s = \"HELLO, WORLD\"\n samples, spec, y = generate_sample(length, pitch, wpm, noise_power, amplitude, s)\n samples = samples.astype(np.float32)\n write(\"morse.wav\", SAMPLE_FREQ, samples)\n\n print(f\"pitch: {pitch} wpm: {wpm} noise: {noise_power} amplitude: {amplitude} {y}\")\n\n plt.figure()\n plt.pcolormesh(spec)\n plt.show()\n"
] |
[
[
"torch.nn.Linear",
"torch.device",
"torch.nn.LSTM",
"torch.argmax",
"torch.nn.utils.rnn.pad_sequence",
"torch.nn.CTCLoss",
"torch.from_numpy",
"torch.nn.functional.log_softmax",
"torch.tensor",
"torch.load",
"torch.utils.tensorboard.SummaryWriter"
],
[
"numpy.random.normal",
"scipy.signal.spectrogram",
"numpy.sin",
"matplotlib.pyplot.pcolormesh",
"scipy.io.wavfile.write",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"numpy.sqrt",
"numpy.clip",
"numpy.hstack"
]
] |
yeshwanthv5/PruneFL
|
[
"ad1f7f33b0605d1d79abfbe42ef287fcc613a943"
] |
[
"bases/nn/models/leaf.py"
] |
[
"import torch\nfrom torch import nn as nn\nfrom torch.nn.functional import binary_cross_entropy_with_logits, cross_entropy\n\nfrom bases.nn.conv2d import DenseConv2d\nfrom bases.nn.linear import DenseLinear\nfrom bases.nn.models.base_model import BaseModel\nfrom bases.nn.sequential import DenseSequential\nfrom .utils import is_conv, is_fc\n\n__all__ = [\"Conv2\", \"Conv4\"]\n\n\nclass Conv2(BaseModel):\n def __init__(self, dict_module: dict = None):\n if dict_module is None:\n dict_module = dict()\n features = nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2), # 32x28x28\n nn.ReLU(inplace=True),\n nn.MaxPool2d(2, stride=2), # 32x14x14\n DenseConv2d(32, 64, kernel_size=5, padding=2), # 64x14x14\n nn.ReLU(inplace=True),\n nn.MaxPool2d(2, stride=2)) # 64x7x7\n\n classifier = DenseSequential(DenseLinear(64 * 7 * 7, 2048, mode=\"fan_out\"),\n nn.ReLU(inplace=True),\n DenseLinear(2048, 62, mode=\"fan_out\"))\n\n dict_module[\"features\"] = features\n dict_module[\"classifier\"] = classifier\n\n super(Conv2, self).__init__(binary_cross_entropy_with_logits, dict_module)\n\n def collect_layers(self):\n self.get_param_layers(self.param_layers, self.param_layer_prefixes)\n self.prunable_layers = self.param_layers\n self.prunable_layer_prefixes = self.param_layer_prefixes\n\n def forward(self, inputs):\n outputs = self.features(inputs)\n outputs = outputs.view(outputs.size(0), -1)\n outputs = self.classifier(outputs)\n return outputs\n\n def loss(self, inputs, labels) -> torch.Tensor:\n return self.loss_func(self(inputs), labels)\n\n def to_sparse(self):\n new_features = [ft.to_sparse() if isinstance(ft, DenseConv2d) else ft for ft in self.features]\n new_module_dict = {\"features\": nn.Sequential(*new_features), \"classifier\": self.classifier.to_sparse()}\n return self.__class__(new_module_dict)\n\n def remove_empty_channels(self):\n list_in_out = []\n is_transition = False\n prev_is_transition = False\n for idx, (layer, next_layer) in enumerate(zip(self.prunable_layers, self.prunable_layers[1:] + [None])):\n # works for both conv and fc\n if is_conv(layer) and is_fc(next_layer):\n is_transition = True\n\n num_out, num_in = layer.weight.size()[:2]\n\n if idx == 0 or prev_is_transition:\n list_remain_in = \"all\"\n else:\n list_remain_in = set()\n for in_id in range(num_in):\n mask_slice = layer.mask.index_select(dim=1, index=torch.tensor([in_id]))\n if not torch.equal(mask_slice, torch.zeros_like(mask_slice)):\n list_remain_in.add(in_id)\n if len(list_remain_in) == layer.weight.size()[1]:\n list_remain_in = \"all\"\n\n if next_layer is None or is_transition:\n list_remain_out = \"all\"\n else:\n list_remain_out = set()\n for out_id in range(num_out):\n mask_slice = layer.mask.index_select(dim=0, index=torch.tensor([out_id]))\n if not torch.equal(mask_slice, torch.zeros_like(mask_slice)):\n list_remain_out.add(out_id)\n if len(list_remain_out) == layer.weight.size()[0]:\n list_remain_out = \"all\"\n\n list_in_out.append((list_remain_in, list_remain_out))\n\n if prev_is_transition:\n prev_is_transition = False\n if is_transition:\n prev_is_transition = True\n is_transition = False\n\n for ((in_indices, out_indices),\n (in_indices_next, out_indices_next),\n layer,\n next_layer) in zip(list_in_out[:-1], list_in_out[1:], self.prunable_layers[:-1],\n self.prunable_layers[1:]):\n\n if out_indices == \"all\" or in_indices_next == \"all\":\n merged_indices = \"all\"\n else:\n merged_indices = list(out_indices.intersection(in_indices_next))\n\n if merged_indices != \"all\":\n layer.weight = nn.Parameter(layer.weight.index_select(dim=0, index=torch.tensor(merged_indices)))\n layer.mask = layer.mask.index_select(dim=0, index=torch.tensor(merged_indices))\n len_merged_indices = len(merged_indices)\n if layer.bias is not None:\n layer.bias = nn.Parameter(layer.bias[merged_indices])\n if is_conv(layer):\n layer.out_channels = len_merged_indices\n elif is_fc(layer):\n layer.out_features = len_merged_indices\n\n next_layer.weight = nn.Parameter(\n next_layer.weight.index_select(dim=1, index=torch.tensor(merged_indices)))\n next_layer.mask = next_layer.mask.index_select(dim=1, index=torch.tensor(merged_indices))\n if is_conv(next_layer):\n next_layer.in_channels = len_merged_indices\n elif is_fc(next_layer):\n next_layer.in_features = len_merged_indices\n\n\n# class FEMNISTModel(BaseModel):\n# def __init__(self, dict_module: dict = None):\n# if dict_module is None:\n# dict_module = dict()\n# features = nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2), # 32x28x28\n# nn.ReLU(inplace=True),\n# nn.MaxPool2d(2, stride=2), # 32x14x14\n# DenseConv2d(32, 64, kernel_size=5, padding=2), # 64x14x14\n# nn.ReLU(inplace=True),\n# nn.MaxPool2d(2, stride=2)) # 64x7x7\n#\n# classifier = DenseSequential(DenseLinear(64 * 7 * 7, 2048, init_mode=\"fan_out\"),\n# nn.ReLU(inplace=True),\n# DenseLinear(2048, 62, init_mode=\"fan_out\"))\n#\n# dict_module[\"features\"] = features\n# dict_module[\"classifier\"] = classifier\n#\n# super(FEMNISTModel, self).__init__(binary_cross_entropy_with_logits, dict_module)\n#\n# def collect_layers(self):\n# self.get_param_layers(self.param_layers, self.param_layer_prefixes)\n# self.prunable_layers = self.param_layers\n# self.prunable_layer_prefixes = self.param_layer_prefixes\n#\n# def forward(self, inputs):\n# outputs = self.features(inputs)\n# outputs = outputs.view(outputs.size(0), -1)\n# outputs = self.classifier(outputs)\n# return outputs\n#\n# def loss(self, inputs, labels) -> torch.Tensor:\n# return self.loss_func(self(inputs), labels)\n#\n# def to_sparse(self):\n# new_features = [ft.to_sparse() if isinstance(ft, DenseConv2d) else ft for ft in self.features]\n# new_module_dict = {\"features\": nn.Sequential(*new_features), \"classifier\": self.classifier.to_sparse()}\n# return self.__class__(new_module_dict)\n#\n# def remove_empty_channels(self):\n# list_in_out = []\n# is_transition = False\n# prev_is_transition = False\n# for idx, (layer, next_layer) in enumerate(zip(self.prunable_layers, self.prunable_layers[1:] + [None])):\n# # works for both conv and fc\n# if is_conv(layer) and is_fc(next_layer):\n# is_transition = True\n#\n# num_out, num_in = layer.weight.size()[:2]\n#\n# if idx == 0 or prev_is_transition:\n# list_remain_in = \"all\"\n# else:\n# list_remain_in = set()\n# for in_id in range(num_in):\n# mask_slice = layer.mask.index_select(dim=1, index=torch.tensor([in_id]))\n# if not torch.equal(mask_slice, torch.zeros_like(mask_slice)):\n# list_remain_in.add(in_id)\n# if len(list_remain_in) == layer.weight.size()[1]:\n# list_remain_in = \"all\"\n#\n# if next_layer is None or is_transition:\n# list_remain_out = \"all\"\n# else:\n# list_remain_out = set()\n# for out_id in range(num_out):\n# mask_slice = layer.mask.index_select(dim=0, index=torch.tensor([out_id]))\n# if not torch.equal(mask_slice, torch.zeros_like(mask_slice)):\n# list_remain_out.add(out_id)\n# if len(list_remain_out) == layer.weight.size()[0]:\n# list_remain_out = \"all\"\n#\n# list_in_out.append((list_remain_in, list_remain_out))\n#\n# if prev_is_transition:\n# prev_is_transition = False\n# if is_transition:\n# prev_is_transition = True\n# is_transition = False\n#\n# for ((in_indices, out_indices),\n# (in_indices_next, out_indices_next),\n# layer,\n# next_layer) in zip(list_in_out[:-1], list_in_out[1:], self.prunable_layers[:-1],\n# self.prunable_layers[1:]):\n#\n# if out_indices == \"all\" or in_indices_next == \"all\":\n# merged_indices = \"all\"\n# else:\n# merged_indices = list(out_indices.intersection(in_indices_next))\n#\n# if merged_indices != \"all\":\n# layer.weight = nn.Parameter(layer.weight.index_select(dim=0, index=torch.tensor(merged_indices)))\n# layer.mask = layer.mask.index_select(dim=0, index=torch.tensor(merged_indices))\n# len_merged_indices = len(merged_indices)\n# if layer.bias is not None:\n# layer.bias = nn.Parameter(layer.bias[merged_indices])\n# if is_conv(layer):\n# layer.out_channels = len_merged_indices\n# elif is_fc(layer):\n# layer.out_features = len_merged_indices\n#\n# next_layer.weight = nn.Parameter(\n# next_layer.weight.index_select(dim=1, index=torch.tensor(merged_indices)))\n# next_layer.mask = next_layer.mask.index_select(dim=1, index=torch.tensor(merged_indices))\n# if is_conv(next_layer):\n# next_layer.in_channels = len_merged_indices\n# elif is_fc(next_layer):\n# next_layer.in_features = len_merged_indices\n\nclass Conv4(BaseModel):\n def __init__(self, dict_module: dict = None):\n if dict_module is None:\n dict_module = dict()\n features = nn.Sequential(DenseConv2d(3, 32, kernel_size=3, padding=1),\n nn.BatchNorm2d(32),\n nn.MaxPool2d(2),\n DenseConv2d(32, 32, kernel_size=3, padding=1),\n nn.BatchNorm2d(32),\n nn.MaxPool2d(2),\n DenseConv2d(32, 32, kernel_size=3, padding=2),\n nn.BatchNorm2d(32),\n nn.MaxPool2d(2),\n DenseConv2d(32, 32, kernel_size=3, padding=2),\n nn.BatchNorm2d(32),\n nn.MaxPool2d(2))\n\n classifier = DenseLinear(in_features=32 * 6 * 6, out_features=2)\n\n dict_module[\"features\"] = features\n dict_module[\"classifier\"] = classifier\n\n super(Conv4, self).__init__(cross_entropy, dict_module)\n\n def collect_layers(self):\n self.get_param_layers(self.param_layers, self.param_layer_prefixes)\n prunable_ids = [idx for idx, layer in enumerate(self.param_layers) if not isinstance(layer, nn.BatchNorm2d)]\n self.prunable_layers = list(self.param_layers[i] for i in prunable_ids)\n self.prunable_layer_prefixes = list(self.param_layer_prefixes[i] for i in prunable_ids)\n\n def forward(self, inputs):\n outputs = self.features(inputs)\n outputs = outputs.view(outputs.size(0), -1)\n outputs = self.classifier(outputs)\n return outputs\n\n def loss(self, inputs, labels) -> torch.Tensor:\n return self.loss_func(self(inputs), labels)\n\n def to_sparse(self):\n new_features = [ft.to_sparse() if isinstance(ft, DenseConv2d) else ft for ft in self.features]\n new_module_dict = {\"features\": nn.Sequential(*new_features),\n \"classifier\": self.classifier.to_sparse(transpose=True)}\n return self.__class__(new_module_dict)\n"
] |
[
[
"torch.nn.MaxPool2d",
"torch.nn.Sequential",
"torch.nn.BatchNorm2d",
"torch.nn.Parameter",
"torch.nn.ReLU",
"torch.tensor",
"torch.zeros_like"
]
] |
anitksahu/GMRF
|
[
"2ae642589cfefac06bafbe0325154b1066fd367f"
] |
[
"gmrf_mnist.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom gmrf_utils import gradient_hessian\nfrom torchvision.datasets import MNIST\nfrom torch.utils.data import DataLoader\nfrom torchvision import models, transforms\nfrom mnist_model import Net\n\ndef inv_cov_fft(alpha, beta, gamma, H, W):\n A = torch.zeros(H,W).type_as(alpha)\n A[0,0] = alpha\n A[0,1] = A[0,-1] = A[1,0] = A[-1,0] = beta\n A[-1,-1] = A[1,1] = A[-1,1] = A[1,-1] = gamma\n return torch.rfft(A,2,onesided=False)[:,:,0]\n\ndef log_det_fft(alpha, beta, gamma, H,W):\n return inv_cov_fft(alpha, beta, gamma, H, W).log().sum()\n\n# multiplication by Lambda with optional power (includeing inverses)\ndef fft_Lambda_y(alpha, beta, gamma, H, W, Y, power=1):\n #print(Y.size())\n Y_fft = torch.rfft(Y[0,0], 2, onesided=False)\n A_fft = inv_cov_fft(alpha, beta, gamma, H, W)[:,:,None]\n return torch.irfft(A_fft**power * Y_fft, 2, onesided=False) \n\n\ndef conv_obj(alpha, beta, gamma,Y, H, W):\n m,c,H,W = Y.shape\n Y_ = torch.cat([Y[:,:,-1:,:], Y, Y[:,:,:1,:]], 2)\n Y_ = torch.cat([Y_[:,:,:,-1:], Y_, Y_[:,:,:,:1]], 3)\n K = torch.zeros(3,3).type_as(alpha)\n K[1,1] = alpha\n K[0,1] = K[1,2] = K[1,0] = K[2,1] = beta\n K[0,0] = K[2,2] = K[2,0] = K[0,2] = gamma\n K = torch.unsqueeze(torch.unsqueeze(K,0),0)\n conv_result = F.conv2d(Y_.cpu(), K, stride=1, padding=0)\n return (Y.cpu() * conv_result.view_as(Y)/m).sum()\n\ndef f_objective(alpha, beta, gamma, Y, H, W):\n return conv_obj(alpha, beta, gamma, Y, H, W) - log_det_fft(alpha, beta, gamma, H, W)\n\ndef newton(X, tol=1e-4, max_iter=50):\n m,c,H,W = X.shape\n alpha = torch.tensor(1.0, requires_grad=True)\n beta = torch.tensor(0., requires_grad=True)\n gamma = torch.tensor(0.1, requires_grad=True)\n it = 0\n g = torch.tensor(1.)\n while (g.norm().item() > 1e-4 and it < max_iter):\n f = f_objective(alpha, beta, gamma, X, H, W)\n g, H_ = gradient_hessian(f, [alpha, beta, gamma])\n dx = -H_.inverse() @ g\n \n t = 1.0\n while True:\n alpha0 = (alpha + t*dx[0]).detach()\n beta0 = (beta + t*dx[1]).detach()\n gamma0 = (gamma + t*dx[2]).detach()\n f0 = f_objective(alpha0, beta0, gamma0, X, H, W)\n if f0 < f+1000:\n break\n t = t*0.5\n \n alpha = (alpha + t*dx[0]).detach().requires_grad_()\n beta = (beta + t*dx[1]).detach().requires_grad_()\n gamma = (gamma + t*dx[2]).detach().requires_grad_()\n it += 1\n return alpha, beta, gamma\n\ndef inference_mnist():\n test_loader = DataLoader(MNIST(\".\", train=False, download=True, transform=transforms.ToTensor()), \n batch_size=100, shuffle=True)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else 'cpu')\n model = Net().to(device)\n model.load_state_dict(torch.load('lenet_mnist_model.pth'))\n epsilon = 0.1\n num = 100\n for X,y in test_loader:\n break\n X.detach_()\n G = torch.zeros_like(X)\n for j in range(num):\n pert = torch.randn(1, X.shape[1], X.shape[2], X.shape[3])\n dX = epsilon * pert\n f1 = F.nll_loss(model((X + dX).to(device)), y.to(device))\n f2 = F.nll_loss(model((X - dX).to(device)), y.to(device))\n G = G.to(device) + ((f1 - f2).view(-1,1,1,1)/(2*epsilon))*pert.to(device)\n G = G/num\n alpha, beta, gamma = newton(G)\n return alpha.item(), beta.item(), gamma.item()\n\n\n\n"
] |
[
[
"torch.rfft",
"torch.zeros",
"torch.cat",
"torch.irfft",
"torch.unsqueeze",
"torch.cuda.is_available",
"torch.tensor",
"torch.load",
"torch.zeros_like",
"torch.randn"
]
] |
houcharlie/federated
|
[
"b8b12f2f424f4c637be1e1fe8482ecc94ee3765a",
"b8b12f2f424f4c637be1e1fe8482ecc94ee3765a",
"5aaa33691ef342e8a2cf6f5b54f459a16029f336"
] |
[
"catalyst/shared/fed_avg_schedule_catalyst_test.py",
"utils/training_loop.py",
"utils/datasets/cifar100_dataset_test.py"
] |
[
"# Copyright 2019, Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"End-to-end example testing Federated Averaging against the MNIST model.\"\"\"\n\nimport collections\n\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom catalyst.shared import fed_avg_schedule_catalyst as fed_avg_schedule\n\n_Batch = collections.namedtuple('Batch', ['x', 'y'])\nTAU = 0.1\n\ndef _batch_fn(has_nan=False):\n batch = _Batch(\n x=np.ones([1, 784], dtype=np.float32), y=np.ones([1, 1], dtype=np.int64))\n if has_nan:\n batch[0][0, 0] = np.nan\n return batch\n\n\ndef _create_input_spec():\n return _Batch(\n x=tf.TensorSpec(shape=[None, 784], dtype=tf.float32),\n y=tf.TensorSpec(dtype=tf.int64, shape=[None, 1]))\n\n\ndef _uncompiled_model_builder():\n keras_model = tff.simulation.models.mnist.create_keras_model(\n compile_model=False)\n return tff.learning.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_input_spec(),\n loss=tf.keras.losses.SparseCategoricalCrossentropy())\n\n\nclass ModelDeltaProcessTest(tf.test.TestCase):\n def _run_rounds(self, iterproc, federated_data, num_rounds):\n train_outputs = []\n initial_state = iterproc.initialize()\n state = initial_state\n for round_num in range(num_rounds):\n state, metrics = iterproc.next(state, federated_data)\n train_outputs.append(metrics)\n logging.info('Round %d: %s', round_num, metrics)\n return state, train_outputs, initial_state\n\n def test_fed_avg_without_schedule_decreases_loss(self):\n federated_data = [[_batch_fn()]]\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder, TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD)\n\n _, train_outputs, _ = self._run_rounds(iterproc, federated_data, 5)\n self.assertLess(train_outputs[-1]['loss'], train_outputs[0]['loss'])\n\n def test_fed_avg_with_custom_client_weight_fn(self):\n federated_data = [[_batch_fn()]]\n\n def client_weight_fn(local_outputs):\n return 1.0/(1.0 + local_outputs['loss'][-1])\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder, TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD,\n client_weight_fn=client_weight_fn)\n\n _, train_outputs, _ = self._run_rounds(iterproc, federated_data, 5)\n self.assertLess(train_outputs[-1]['loss'], train_outputs[0]['loss'])\n\n def test_client_update_with_finite_delta(self):\n federated_data = [_batch_fn()]\n model = _uncompiled_model_builder()\n client_optimizer = tf.keras.optimizers.SGD(0.1)\n server_optimizer = tf.keras.optimizers.SGD(0.1)\n client_update = fed_avg_schedule.create_client_update_fn()\n outputs = client_update(model, federated_data, TAU,\n fed_avg_schedule._get_weights(model),\n client_optimizer,\n server_optimizer.variables())\n self.assertAllEqual(self.evaluate(outputs.client_weight), 1)\n self.assertAllEqual(\n self.evaluate(outputs.optimizer_output['num_examples']), 1)\n\n def test_client_update_with_non_finite_delta(self):\n federated_data = [_batch_fn(has_nan=True)]\n model = _uncompiled_model_builder()\n client_optimizer = tf.keras.optimizers.SGD(0.1)\n server_optimizer = tf.keras.optimizers.SGD(0.1)\n client_update = fed_avg_schedule.create_client_update_fn()\n outputs = client_update(model, federated_data, TAU,\n fed_avg_schedule._get_weights(model),\n client_optimizer,server_optimizer.variables())\n self.assertAllEqual(self.evaluate(outputs.client_weight), 0)\n\n def test_server_update_with_nan_data_is_noop(self):\n federated_data = [[_batch_fn(has_nan=True)]]\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder,TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD)\n\n state, _, initial_state = self._run_rounds(iterproc, federated_data, 1)\n self.assertAllClose(state.model.trainable, initial_state.model.trainable,\n 1e-8)\n self.assertAllClose(state.model.non_trainable,\n initial_state.model.non_trainable, 1e-8)\n\n def test_server_update_with_inf_weight_is_noop(self):\n federated_data = [[_batch_fn()]]\n client_weight_fn = lambda x: np.inf\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder,TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD,\n client_weight_fn=client_weight_fn)\n\n state, _, initial_state = self._run_rounds(iterproc, federated_data, 1)\n self.assertAllClose(state.model.trainable, initial_state.model.trainable,\n 1e-8)\n self.assertAllClose(state.model.non_trainable,\n initial_state.model.non_trainable, 1e-8)\n\n def test_fed_avg_with_client_schedule(self):\n federated_data = [[_batch_fn()]]\n\n @tf.function\n def lr_schedule(x):\n return 0.1 if x < 1.5 else 0.0\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder, TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n client_lr=lr_schedule,\n server_optimizer_fn=tf.keras.optimizers.SGD)\n\n _, train_outputs, _ = self._run_rounds(iterproc, federated_data, 4)\n self.assertLess(train_outputs[1]['loss'], train_outputs[0]['loss'])\n self.assertNear(\n train_outputs[2]['loss'], train_outputs[3]['loss'], err=1e-4)\n\n def test_fed_avg_with_server_schedule(self):\n federated_data = [[_batch_fn()]]\n\n @tf.function\n def lr_schedule(x):\n return 1.0 if x < 1.5 else 0.0\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder,TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD,\n server_lr=lr_schedule)\n\n _, train_outputs, _ = self._run_rounds(iterproc, federated_data, 4)\n self.assertLess(train_outputs[1]['loss'], train_outputs[0]['loss'])\n self.assertNear(\n train_outputs[2]['loss'], train_outputs[3]['loss'], err=1e-4)\n\n def test_fed_avg_with_client_and_server_schedules(self):\n federated_data = [[_batch_fn()]]\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder,TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n client_lr=lambda x: 0.1 / (x + 1)**2,\n server_optimizer_fn=tf.keras.optimizers.SGD,\n server_lr=lambda x: 1.0 / (x + 1)**2)\n\n _, train_outputs, _ = self._run_rounds(iterproc, federated_data, 6)\n self.assertLess(train_outputs[-1]['loss'], train_outputs[0]['loss'])\n train_gap_first_half = train_outputs[0]['loss'] - train_outputs[2]['loss']\n train_gap_second_half = train_outputs[3]['loss'] - train_outputs[5]['loss']\n self.assertLess(train_gap_second_half, train_gap_first_half)\n\n def test_build_with_preprocess_function(self):\n test_dataset = tf.data.Dataset.range(5)\n client_datasets_type = tff.type_at_clients(\n tff.SequenceType(test_dataset.element_spec))\n\n @tff.tf_computation(tff.SequenceType(test_dataset.element_spec))\n def preprocess_dataset(ds):\n\n def to_batch(x):\n return _Batch(\n tf.fill(dims=(784,), value=float(x) * 2.0),\n tf.expand_dims(tf.cast(x + 1, dtype=tf.int64), axis=0))\n\n return ds.map(to_batch).batch(2)\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder,TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD)\n\n iterproc = tff.simulation.compose_dataset_computation_with_iterative_process(\n preprocess_dataset, iterproc)\n\n with tf.Graph().as_default():\n test_model_for_types = _uncompiled_model_builder()\n\n server_state_type = tff.FederatedType(\n fed_avg_schedule.ServerState(\n model=tff.framework.type_from_tensors(\n tff.learning.ModelWeights(\n test_model_for_types.trainable_variables,\n test_model_for_types.non_trainable_variables)),\n optimizer_state=(tf.int64,),\n round_num=tf.float32,client_drift=tf.float32),\n tff.SERVER)\n metrics_type = test_model_for_types.federated_output_computation.type_signature.result\n\n expected_parameter_type = collections.OrderedDict(\n server_state=server_state_type,\n federated_dataset=client_datasets_type,\n )\n expected_result_type = (server_state_type, metrics_type)\n\n expected_type = tff.FunctionType(\n parameter=expected_parameter_type, result=expected_result_type)\n self.assertTrue(\n iterproc.next.type_signature.is_equivalent_to(expected_type),\n msg='{s}\\n!={t}'.format(\n s=iterproc.next.type_signature, t=expected_type))\n\n def test_execute_with_preprocess_function(self):\n test_dataset = tf.data.Dataset.range(1)\n\n @tff.tf_computation(tff.SequenceType(test_dataset.element_spec))\n def preprocess_dataset(ds):\n\n def to_example(x):\n del x # Unused.\n return _Batch(\n x=np.ones([784], dtype=np.float32), y=np.ones([1], dtype=np.int64))\n\n return ds.map(to_example).batch(1)\n\n iterproc = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder,TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD)\n\n iterproc = tff.simulation.compose_dataset_computation_with_iterative_process(\n preprocess_dataset, iterproc)\n\n _, train_outputs, _ = self._run_rounds(iterproc, [test_dataset], 6)\n self.assertLess(train_outputs[-1]['loss'], train_outputs[0]['loss'])\n train_gap_first_half = train_outputs[0]['loss'] - train_outputs[2]['loss']\n train_gap_second_half = train_outputs[3]['loss'] - train_outputs[5]['loss']\n self.assertLess(train_gap_second_half, train_gap_first_half)\n\n def test_get_model_weights(self):\n federated_data = [[_batch_fn()]]\n\n iterative_process = fed_avg_schedule.build_fed_avg_process(\n _uncompiled_model_builder,TAU,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD)\n state = iterative_process.initialize()\n\n self.assertIsInstance(\n iterative_process.get_model_weights(state), tff.learning.ModelWeights)\n self.assertAllClose(state.model.trainable,\n iterative_process.get_model_weights(state).trainable)\n\n for _ in range(3):\n state, _ = iterative_process.next(state, federated_data)\n self.assertIsInstance(\n iterative_process.get_model_weights(state), tff.learning.ModelWeights)\n self.assertAllClose(state.model.trainable,\n iterative_process.get_model_weights(state).trainable)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2019, Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Internal dispatcher for training loops.\"\"\"\n\nimport contextlib\nimport os.path\nimport pprint\nimport time\nfrom typing import Any, Callable, Dict, List, Optional\n\nfrom absl import logging\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\n\nclass IterativeProcessCompatibilityError(TypeError):\n pass\n\n\ndef create_if_not_exists(path):\n try:\n tf.io.gfile.makedirs(path)\n except tf.errors.OpError:\n logging.info('Skipping creation of directory [%s], already exists', path)\n\n\ndef _setup_outputs(root_output_dir,\n experiment_name,\n rounds_per_profile=0):\n \"\"\"Set up directories for experiment loops, write hyperparameters to disk.\"\"\"\n\n if not experiment_name:\n raise ValueError('experiment_name must be specified.')\n\n create_if_not_exists(root_output_dir)\n\n checkpoint_dir = os.path.join(root_output_dir, 'checkpoints', experiment_name)\n create_if_not_exists(checkpoint_dir)\n checkpoint_mngr = tff.simulation.FileCheckpointManager(checkpoint_dir)\n\n results_dir = os.path.join(root_output_dir, 'results', experiment_name)\n create_if_not_exists(results_dir)\n csv_file = os.path.join(results_dir, 'experiment.metrics.csv')\n metrics_mngr = tff.simulation.CSVMetricsManager(csv_file)\n\n summary_logdir = os.path.join(root_output_dir, 'logdir', experiment_name)\n tb_mngr = tff.simulation.TensorBoardManager(summary_dir=summary_logdir)\n\n logging.info('Writing...')\n logging.info(' checkpoints to: %s', checkpoint_dir)\n logging.info(' metrics csv to: %s', metrics_mngr.metrics_filename)\n logging.info(' summaries to: %s', summary_logdir)\n\n @contextlib.contextmanager\n def profiler(round_num):\n if (rounds_per_profile > 0 and round_num % rounds_per_profile == 0):\n with tf.profiler.experimental.Profile(summary_logdir):\n yield\n else:\n yield\n\n return checkpoint_mngr, metrics_mngr, tb_mngr, profiler\n\n\ndef _write_metrics(metrics_mngr, tb_mngr, metrics, round_num):\n \"\"\"Atomic metrics writer which inlines logic from MetricsHook class.\"\"\"\n if not isinstance(metrics, dict):\n raise TypeError('metrics should be type `dict`.')\n if not isinstance(round_num, int):\n raise TypeError('round_num should be type `int`.')\n\n logging.info('Metrics at round {:d}:\\n{!s}'.format(round_num,\n pprint.pformat(metrics)))\n\n metrics_mngr.save_metrics(metrics, round_num)\n tb_mngr.save_metrics(metrics, round_num)\n\n\ndef _compute_numpy_l2_difference(model, previous_model):\n squared_norms = tf.nest.map_structure(lambda x, y: tf.linalg.norm(x - y)**2,\n model, previous_model)\n l2_total_tensor = tf.reduce_sum(tf.nest.flatten(squared_norms))**0.5\n return l2_total_tensor.numpy()\n\n\ndef _check_iterative_process_compatibility(iterative_process):\n \"\"\"Checks the compatibility of an iterative process with the training loop.\"\"\"\n error_message = (\n 'The iterative_process argument must be of '\n 'type`tff.templates.IterativeProcess`, and must have an '\n 'attribute `get_model_weights`, which must be a `tff.Computation`. This '\n 'computation must accept as input the state of `iterative_process`, and '\n 'its output must be a nested structure of tensors matching the input '\n 'shape of `validation_fn`.')\n compatibility_error = IterativeProcessCompatibilityError(error_message)\n\n if not isinstance(iterative_process, tff.templates.IterativeProcess):\n raise compatibility_error\n if not hasattr(iterative_process, 'get_model_weights'):\n raise compatibility_error\n elif not callable(iterative_process.get_model_weights):\n raise compatibility_error\n get_model_weights_fn = iterative_process.get_model_weights\n\n if not isinstance(get_model_weights_fn, tff.Computation):\n raise compatibility_error\n input_type = get_model_weights_fn.type_signature.parameter\n server_state_type = iterative_process.state_type.member\n server_state_type.is_assignable_from(input_type)\n # TODO(b/174268978): Once we enforce federated evaluations, we can check\n # compatibility with `validation_fn` without actually running the function.\n\n\ndef run(iterative_process: tff.templates.IterativeProcess,\n client_datasets_fn: Callable[[int], List[tf.data.Dataset]],\n validation_fn: Callable[[Any, int], Dict[str, float]],\n total_rounds: int,\n experiment_name: str,\n test_fn: Optional[Callable[[Any], Dict[str, float]]] = None,\n root_output_dir: Optional[str] = '/tmp/fed_opt',\n rounds_per_eval: Optional[int] = 1,\n rounds_per_checkpoint: Optional[int] = 50,\n rounds_per_profile: Optional[int] = 0):\n \"\"\"Runs federated training for a given `tff.templates.IterativeProcess`.\n\n We assume that the iterative process has the following functional type\n signatures:\n\n * `initialize`: `( -> S@SERVER)` where `S` represents the server state.\n * `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`\n represents the server state, `{B*}` represents the client datasets,\n and `T` represents a python `Mapping` object.\n\n The iterative process must also have a callable attribute `get_model_weights`\n that takes as input the state of the iterative process, and returns a\n `tff.learning.ModelWeights` object.\n\n Args:\n iterative_process: A `tff.templates.IterativeProcess` instance to run.\n client_datasets_fn: Function accepting an integer argument (the round\n number) and returning a list of client datasets to use as federated data\n for that round.\n validation_fn: A callable accepting a `tff.learning.ModelWeights` and the\n current round number, and returning a dict of evaluation metrics. Used to\n compute validation metrics throughout the training process.\n total_rounds: The number of federated training rounds to perform.\n experiment_name: The name of the experiment being run. This will be appended\n to the `root_output_dir` for purposes of writing outputs.\n test_fn: An optional callable accepting a `tff.learning.ModelWeights` and\n returning a dict of test set metrics. Used to compute test metrics at the\n end of the training process.\n root_output_dir: The name of the root output directory for writing\n experiment outputs.\n rounds_per_eval: How often to compute validation metrics.\n rounds_per_checkpoint: How often to checkpoint the iterative process state.\n If you expect the job to restart frequently, this should be small. If no\n interruptions are expected, this can be made larger.\n rounds_per_profile: Experimental setting. If set to a value greater than 0,\n this dictates how often a TensorFlow profiler is run.\n\n Returns:\n The final `state` of the iterative process after training.\n \"\"\"\n _check_iterative_process_compatibility(iterative_process)\n if not callable(client_datasets_fn):\n raise TypeError('client_datasets_fn should be callable.')\n if not callable(validation_fn):\n raise TypeError('validation_fn should be callable.')\n if test_fn is not None and not callable(test_fn):\n raise TypeError('test_fn should be callable.')\n\n logging.info('Starting iterative_process training loop...')\n initial_state = iterative_process.initialize()\n\n checkpoint_mngr, metrics_mngr, tb_mngr, profiler = _setup_outputs(\n root_output_dir, experiment_name, rounds_per_profile)\n\n logging.info('Asking checkpoint manager to load checkpoint.')\n state, round_num = checkpoint_mngr.load_latest_checkpoint(initial_state)\n\n if state is None:\n logging.info('Initializing experiment from scratch.')\n state = initial_state\n round_num = 0\n else:\n logging.info('Restarted from checkpoint round %d', round_num)\n round_num += 1 # Increment to avoid overwriting current checkpoint\n metrics_mngr.clear_metrics(round_num)\n\n current_model = iterative_process.get_model_weights(state)\n\n loop_start_time = time.time()\n loop_start_round = round_num\n while round_num < total_rounds:\n data_prep_start_time = time.time()\n federated_train_data = client_datasets_fn(round_num)\n train_metrics = {\n 'prepare_datasets_secs': time.time() - data_prep_start_time\n }\n\n training_start_time = time.time()\n prev_model = current_model\n\n # TODO(b/145604851): This try/except is used to circumvent ambiguous TF\n # errors during training, and should be removed once the root cause is\n # determined (and possibly fixed).\n try:\n with profiler(round_num):\n state, round_metrics = iterative_process.next(state,\n federated_train_data)\n except (tf.errors.FailedPreconditionError, tf.errors.NotFoundError,\n tf.errors.InternalError) as e:\n logging.warning('Caught %s exception while running round %d:\\n\\t%s',\n type(e), round_num, e)\n continue # restart the loop without incrementing the round number\n\n current_model = iterative_process.get_model_weights(state)\n train_metrics['training_secs'] = time.time() - training_start_time\n train_metrics['model_delta_l2_norm'] = _compute_numpy_l2_difference(\n current_model, prev_model)\n train_metrics['client_drift'] = state.client_drift\n train_metrics.update(round_metrics)\n\n loop_time = time.time() - loop_start_time\n loop_rounds = (round_num - loop_start_round + 1)\n logging.info('Round {:2d}, {:.2f}s per round in average.'.format(\n round_num, loop_time / loop_rounds))\n\n if (round_num % rounds_per_checkpoint == 0 or\n round_num == total_rounds - 1):\n save_checkpoint_start_time = time.time()\n checkpoint_mngr.save_checkpoint(state, round_num)\n train_metrics['save_checkpoint_secs'] = (\n time.time() - save_checkpoint_start_time)\n\n metrics = {'train': train_metrics}\n\n if round_num % rounds_per_eval == 0:\n # Compute validation metrics\n evaluate_start_time = time.time()\n validation_metrics = validation_fn(current_model, round_num)\n validation_metrics['evaluate_secs'] = time.time() - evaluate_start_time\n metrics['eval'] = validation_metrics\n\n _write_metrics(metrics_mngr, tb_mngr, metrics, round_num)\n round_num += 1\n\n # Final metrics evaluation once the training has completed\n metrics = {}\n\n # Validation metrics\n evaluate_start_time = time.time()\n validation_metrics = validation_fn(current_model, round_num)\n validation_metrics['evaluate_secs'] = time.time() - evaluate_start_time\n metrics['eval'] = validation_metrics\n\n # Test set metrics\n if test_fn:\n test_start_time = time.time()\n test_metrics = test_fn(current_model)\n test_metrics['evaluate_secs'] = time.time() - test_start_time\n metrics['test'] = test_metrics\n _write_metrics(metrics_mngr, tb_mngr, metrics, total_rounds)\n\n return state\n",
"# Copyright 2019, Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\nfrom unittest import mock\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom utils.datasets import cifar100_dataset\n\n\nTEST_DATA = collections.OrderedDict(\n coarse_label=([tf.constant(1, dtype=tf.int64)]),\n image=([tf.zeros((32, 32, 3), dtype=tf.uint8)]),\n label=([tf.constant(1, dtype=tf.int64)]),\n)\n\n\nclass PreprocessFnTest(tf.test.TestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(\n ('crop_shape_1_no_distort', (32, 32, 3), False),\n ('crop_shape_2_no_distort', (28, 28, 3), False),\n ('crop_shape_3_no_distort', (24, 26, 3), False),\n ('crop_shape_1_distort', (32, 32, 3), True),\n ('crop_shape_2_distort', (28, 28, 3), True),\n ('crop_shape_3_distort', (24, 26, 3), True),\n )\n def test_preprocess_element_spec(self, crop_shape, distort_image):\n ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)\n preprocess_fn = cifar100_dataset.create_preprocess_fn(\n num_epochs=1,\n batch_size=1,\n shuffle_buffer_size=1,\n crop_shape=crop_shape,\n distort_image=distort_image)\n preprocessed_ds = preprocess_fn(ds)\n expected_element_shape = (None,) + crop_shape\n self.assertEqual(\n preprocessed_ds.element_spec,\n (tf.TensorSpec(shape=expected_element_shape, dtype=tf.float32),\n tf.TensorSpec(shape=(None,), dtype=tf.int64)))\n\n @parameterized.named_parameters(\n ('crop_shape_1_no_distort', (32, 32, 3), False),\n ('crop_shape_2_no_distort', (28, 28, 3), False),\n ('crop_shape_3_no_distort', (24, 26, 3), False),\n ('crop_shape_1_distort', (32, 32, 3), True),\n ('crop_shape_2_distort', (28, 28, 3), True),\n ('crop_shape_3_distort', (24, 26, 3), True),\n )\n def test_preprocess_returns_correct_element(self, crop_shape, distort_image):\n ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)\n preprocess_fn = cifar100_dataset.create_preprocess_fn(\n num_epochs=1,\n batch_size=20,\n shuffle_buffer_size=1,\n crop_shape=crop_shape,\n distort_image=distort_image)\n preprocessed_ds = preprocess_fn(ds)\n\n expected_element_shape = (1,) + crop_shape\n element = next(iter(preprocessed_ds))\n expected_element = (tf.zeros(\n shape=expected_element_shape,\n dtype=tf.float32), tf.ones(shape=(1,), dtype=tf.int32))\n self.assertAllClose(self.evaluate(element), expected_element)\n\n def test_no_op_crop(self):\n crop_shape = (1, 1, 3)\n x = tf.constant([[[1.0, -1.0, 0.0]]]) # Has shape (1, 1, 3), mean 0\n x = x / tf.math.reduce_std(x) # x now has variance 1\n simple_example = collections.OrderedDict(image=x, label=0)\n image_map = cifar100_dataset.build_image_map(crop_shape, distort=False)\n cropped_example = image_map(simple_example)\n\n self.assertEqual(cropped_example[0].shape, crop_shape)\n self.assertAllClose(x, cropped_example[0], rtol=1e-03)\n self.assertEqual(cropped_example[1], 0)\n\n\nCIFAR100_LOAD_DATA = 'tensorflow_federated.simulation.datasets.cifar100.load_data'\n\n\nclass FederatedDatasetTest(tf.test.TestCase):\n\n @mock.patch(CIFAR100_LOAD_DATA)\n def test_preprocess_applied(self, mock_load_data):\n if tf.config.list_logical_devices('GPU'):\n self.skipTest('skip GPU test')\n # Mock out the actual data loading from disk. Assert that the preprocessing\n # function is applied to the client data, and that only the ClientData\n # objects we desired are used.\n #\n # The correctness of the preprocessing function is tested in other tests.\n mock_train = mock.create_autospec(tff.simulation.ClientData)\n mock_test = mock.create_autospec(tff.simulation.ClientData)\n mock_load_data.return_value = (mock_train, mock_test)\n\n _, _ = cifar100_dataset.get_federated_datasets()\n\n mock_load_data.assert_called_once()\n\n # Assert the training and testing data are preprocessed.\n self.assertEqual(mock_train.mock_calls,\n mock.call.preprocess(mock.ANY).call_list())\n self.assertEqual(mock_test.mock_calls,\n mock.call.preprocess(mock.ANY).call_list())\n\n def test_raises_length_2_crop(self):\n with self.assertRaises(ValueError):\n cifar100_dataset.get_federated_datasets(crop_shape=(32, 32))\n\n\nclass CentralizedDatasetTest(tf.test.TestCase):\n\n @mock.patch(CIFAR100_LOAD_DATA)\n def test_preprocess_applied(self, mock_load_data):\n if tf.config.list_logical_devices('GPU'):\n self.skipTest('skip GPU test')\n # Mock out the actual data loading from disk. Assert that the preprocessing\n # function is applied to the client data, and that only the ClientData\n # objects we desired are used.\n #\n # The correctness of the preprocessing function is tested in other tests.\n sample_ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)\n\n mock_train = mock.create_autospec(tff.simulation.ClientData)\n mock_train.create_tf_dataset_from_all_clients = mock.Mock(\n return_value=sample_ds)\n\n mock_test = mock.create_autospec(tff.simulation.ClientData)\n mock_test.create_tf_dataset_from_all_clients = mock.Mock(\n return_value=sample_ds)\n\n mock_load_data.return_value = (mock_train, mock_test)\n\n _, _ = cifar100_dataset.get_centralized_datasets()\n\n mock_load_data.assert_called_once()\n\n # Assert the validation ClientData isn't used, and the train and test\n # are amalgamated into datasets single datasets over all clients.\n self.assertEqual(mock_train.mock_calls,\n mock.call.create_tf_dataset_from_all_clients().call_list())\n self.assertEqual(mock_test.mock_calls,\n mock.call.create_tf_dataset_from_all_clients().call_list())\n\n def test_raises_length_2_crop(self):\n with self.assertRaises(ValueError):\n cifar100_dataset.get_centralized_datasets(crop_shape=(32, 32))\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"tensorflow.TensorSpec",
"tensorflow.keras.optimizers.SGD",
"tensorflow.data.Dataset.range",
"tensorflow.Graph",
"numpy.ones",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.test.main",
"tensorflow.cast"
],
[
"tensorflow.profiler.experimental.Profile",
"tensorflow.linalg.norm",
"tensorflow.nest.flatten",
"tensorflow.io.gfile.makedirs"
],
[
"tensorflow.TensorSpec",
"tensorflow.zeros",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.math.reduce_std",
"tensorflow.ones",
"tensorflow.config.list_logical_devices",
"tensorflow.constant",
"tensorflow.test.main"
]
] |
umerkhan1995/testapi
|
[
"1cceefa82f30d8e4093167d8d9c1a549350db7cf"
] |
[
"main.py"
] |
[
"from fastapi import FastAPI\nimport uvicorn\nimport csv\nimport numpy as np\nimport pytest\n\n\napp = FastAPI()\n\nkwh_price = []\ngrid_fees = []\nunit_price = []\nhs_splitter = []\nzp_cde = []\ncty = []\nstrt = []\n\ndef tariff_gen(postal_code, city, street, house_number,ykc ):\n file = open('location_prices.csv', encoding=\"utf-8\")\n data_list = list(csv.reader(file))\n locations = data_list[1:]\n\n for rows in locations:\n if rows[0] == postal_code:\n zp_cde.append(rows)\n\n\n for rows in zp_cde:\n if rows[1] == city:\n cty.append(rows)\n\n for rows in cty:\n if rows[2] == street:\n strt.append(rows)\n\n for rows in strt:\n hs = rows[3]\n hs_splitter = hs.split('-', 2)\n hs_min = int(hs_splitter[0])\n hs_max = int(hs_splitter[1])\n\n def test_set_comparison():\n set1 = hs_min\n\n set2 = hs\n assert set2 > set1\n\n if hs_min <= house_number <= hs_max:\n\n for row in strt:\n kwh_price = row[-1]\n grid_fees = row[-2]\n unit_price = row[-3]\n kwh_price_np = np.array(kwh_price).astype(float)\n grid_feess_np = np.array(grid_fees).astype(float)\n grid_unitprice_np = np.array(unit_price).astype(float)\n avg_kwh_price = np.average(kwh_price_np)\n avg_grid_price = np.average(grid_feess_np)\n avg_unit_price = np.average(grid_unitprice_np)\n\n total_bill = avg_unit_price + avg_grid_price + ykc * avg_kwh_price\n\n print(avg_kwh_price)\n print(avg_grid_price)\n print(avg_unit_price)\n print(ykc)\n print(total_bill)\n result = {\n \"unit_price\": avg_unit_price,\n \"grid_fees\": avg_grid_price,\n \"kwh_price\": avg_kwh_price,\n 'total_price': total_bill\n\n }\n return(result)\n@app.get(\"/main\")\ndef post_data(postal_code: str, city: str, street: str, house_number: int,ykc: int ):\n\n return tariff_gen(postal_code, city, street, house_number, ykc)\n\nif __name__ == '__main__':\n uvicorn.run(app, host=\"127.0.0.1\", port=9000)\n"
] |
[
[
"numpy.average",
"numpy.array"
]
] |
sofiane87/pandas
|
[
"0de99558b497c5611cbe5d35d504763bd7692275",
"4071dde86e33434e1bee8304fa62074949f813cc",
"0de99558b497c5611cbe5d35d504763bd7692275"
] |
[
"pandas/tests/indexes/datetimelike.py",
"pandas/tests/series/test_rank.py",
"pandas/tests/scalar/test_nat.py"
] |
[
"\"\"\" generic datetimelike tests \"\"\"\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas.util.testing as tm\n\nfrom .common import Base\n\n\nclass DatetimeLike(Base):\n def test_argmax_axis_invalid(self):\n # GH#23081\n rng = self.create_index()\n with pytest.raises(ValueError):\n rng.argmax(axis=1)\n with pytest.raises(ValueError):\n rng.argmin(axis=2)\n with pytest.raises(ValueError):\n rng.min(axis=-2)\n with pytest.raises(ValueError):\n rng.max(axis=-3)\n\n def test_can_hold_identifiers(self):\n idx = self.create_index()\n key = idx[0]\n assert idx._can_hold_identifiers_and_holds_name(key) is False\n\n def test_shift_identity(self):\n\n idx = self.create_index()\n tm.assert_index_equal(idx, idx.shift(0))\n\n def test_str(self):\n\n # test the string repr\n idx = self.create_index()\n idx.name = \"foo\"\n assert not \"length={}\".format(len(idx)) in str(idx)\n assert \"'foo'\" in str(idx)\n assert idx.__class__.__name__ in str(idx)\n\n if hasattr(idx, \"tz\"):\n if idx.tz is not None:\n assert idx.tz in str(idx)\n if hasattr(idx, \"freq\"):\n assert \"freq='{idx.freqstr}'\".format(idx=idx) in str(idx)\n\n def test_view(self):\n i = self.create_index()\n\n i_view = i.view(\"i8\")\n result = self._holder(i)\n tm.assert_index_equal(result, i)\n\n i_view = i.view(self._holder)\n result = self._holder(i)\n tm.assert_index_equal(result, i_view)\n\n def test_map_callable(self):\n index = self.create_index()\n expected = index + index.freq\n result = index.map(lambda x: x + x.freq)\n tm.assert_index_equal(result, expected)\n\n # map to NaT\n result = index.map(lambda x: pd.NaT if x == index[0] else x)\n expected = pd.Index([pd.NaT] + index[1:].tolist())\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"mapper\",\n [\n lambda values, index: {i: e for e, i in zip(values, index)},\n lambda values, index: pd.Series(values, index),\n ],\n )\n def test_map_dictlike(self, mapper):\n index = self.create_index()\n expected = index + index.freq\n\n # don't compare the freqs\n if isinstance(expected, pd.DatetimeIndex):\n expected.freq = None\n\n result = index.map(mapper(expected, index))\n tm.assert_index_equal(result, expected)\n\n expected = pd.Index([pd.NaT] + index[1:].tolist())\n result = index.map(mapper(expected, index))\n tm.assert_index_equal(result, expected)\n\n # empty map; these map to np.nan because we cannot know\n # to re-infer things\n expected = pd.Index([np.nan] * len(index))\n result = index.map(mapper([], []))\n tm.assert_index_equal(result, expected)\n\n def test_asobject_deprecated(self):\n # GH18572\n d = self.create_index()\n with tm.assert_produces_warning(FutureWarning):\n i = d.asobject\n assert isinstance(i, pd.Index)\n",
"from itertools import chain, product\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.algos import Infinity, NegInfinity\nfrom pandas._libs.tslib import iNaT\nimport pandas.util._test_decorators as td\n\nfrom pandas import NaT, Series, Timestamp, date_range\nfrom pandas.api.types import CategoricalDtype\nimport pandas.util.testing as tm\n\n\nclass TestSeriesRank:\n s = Series([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3])\n\n results = {\n \"average\": np.array([1.5, 5.5, 7.0, 3.5, np.nan, 3.5, 1.5, 8.0, np.nan, 5.5]),\n \"min\": np.array([1, 5, 7, 3, np.nan, 3, 1, 8, np.nan, 5]),\n \"max\": np.array([2, 6, 7, 4, np.nan, 4, 2, 8, np.nan, 6]),\n \"first\": np.array([1, 5, 7, 3, np.nan, 4, 2, 8, np.nan, 6]),\n \"dense\": np.array([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]),\n }\n\n def test_rank(self, datetime_series):\n pytest.importorskip(\"scipy.stats.special\")\n rankdata = pytest.importorskip(\"scipy.stats.rankdata\")\n\n datetime_series[::2] = np.nan\n datetime_series[:10][::3] = 4.0\n\n ranks = datetime_series.rank()\n oranks = datetime_series.astype(\"O\").rank()\n\n tm.assert_series_equal(ranks, oranks)\n\n mask = np.isnan(datetime_series)\n filled = datetime_series.fillna(np.inf)\n\n # rankdata returns a ndarray\n exp = Series(rankdata(filled), index=filled.index, name=\"ts\")\n exp[mask] = np.nan\n\n tm.assert_series_equal(ranks, exp)\n\n iseries = Series(np.arange(5).repeat(2))\n\n iranks = iseries.rank()\n exp = iseries.astype(float).rank()\n tm.assert_series_equal(iranks, exp)\n iseries = Series(np.arange(5)) + 1.0\n exp = iseries / 5.0\n iranks = iseries.rank(pct=True)\n\n tm.assert_series_equal(iranks, exp)\n\n iseries = Series(np.repeat(1, 100))\n exp = Series(np.repeat(0.505, 100))\n iranks = iseries.rank(pct=True)\n tm.assert_series_equal(iranks, exp)\n\n iseries[1] = np.nan\n exp = Series(np.repeat(50.0 / 99.0, 100))\n exp[1] = np.nan\n iranks = iseries.rank(pct=True)\n tm.assert_series_equal(iranks, exp)\n\n iseries = Series(np.arange(5)) + 1.0\n iseries[4] = np.nan\n exp = iseries / 4.0\n iranks = iseries.rank(pct=True)\n tm.assert_series_equal(iranks, exp)\n\n iseries = Series(np.repeat(np.nan, 100))\n exp = iseries.copy()\n iranks = iseries.rank(pct=True)\n tm.assert_series_equal(iranks, exp)\n\n iseries = Series(np.arange(5)) + 1\n iseries[4] = np.nan\n exp = iseries / 4.0\n iranks = iseries.rank(pct=True)\n tm.assert_series_equal(iranks, exp)\n\n rng = date_range(\"1/1/1990\", periods=5)\n iseries = Series(np.arange(5), rng) + 1\n iseries.iloc[4] = np.nan\n exp = iseries / 4.0\n iranks = iseries.rank(pct=True)\n tm.assert_series_equal(iranks, exp)\n\n iseries = Series([1e-50, 1e-100, 1e-20, 1e-2, 1e-20 + 1e-30, 1e-1])\n exp = Series([2, 1, 3, 5, 4, 6.0])\n iranks = iseries.rank()\n tm.assert_series_equal(iranks, exp)\n\n # GH 5968\n iseries = Series([\"3 day\", \"1 day 10m\", \"-2 day\", NaT], dtype=\"m8[ns]\")\n exp = Series([3, 2, 1, np.nan])\n iranks = iseries.rank()\n tm.assert_series_equal(iranks, exp)\n\n values = np.array(\n [-50, -1, -1e-20, -1e-25, -1e-50, 0, 1e-40, 1e-20, 1e-10, 2, 40],\n dtype=\"float64\",\n )\n random_order = np.random.permutation(len(values))\n iseries = Series(values[random_order])\n exp = Series(random_order + 1.0, dtype=\"float64\")\n iranks = iseries.rank()\n tm.assert_series_equal(iranks, exp)\n\n def test_rank_categorical(self):\n # GH issue #15420 rank incorrectly orders ordered categories\n\n # Test ascending/descending ranking for ordered categoricals\n exp = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])\n exp_desc = Series([6.0, 5.0, 4.0, 3.0, 2.0, 1.0])\n ordered = Series(\n [\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\"]\n ).astype(\n CategoricalDtype(\n categories=[\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\"],\n ordered=True,\n )\n )\n tm.assert_series_equal(ordered.rank(), exp)\n tm.assert_series_equal(ordered.rank(ascending=False), exp_desc)\n\n # Unordered categoricals should be ranked as objects\n unordered = Series(\n [\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\"]\n ).astype(\n CategoricalDtype(\n categories=[\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\"],\n ordered=False,\n )\n )\n exp_unordered = Series([2.0, 4.0, 6.0, 3.0, 1.0, 5.0])\n res = unordered.rank()\n tm.assert_series_equal(res, exp_unordered)\n\n unordered1 = Series([1, 2, 3, 4, 5, 6]).astype(\n CategoricalDtype([1, 2, 3, 4, 5, 6], False)\n )\n exp_unordered1 = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])\n res1 = unordered1.rank()\n tm.assert_series_equal(res1, exp_unordered1)\n\n # Test na_option for rank data\n na_ser = Series(\n [\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\", np.NaN]\n ).astype(\n CategoricalDtype(\n [\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\", \"seventh\"],\n True,\n )\n )\n\n exp_top = Series([2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 1.0])\n exp_bot = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])\n exp_keep = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, np.NaN])\n\n tm.assert_series_equal(na_ser.rank(na_option=\"top\"), exp_top)\n tm.assert_series_equal(na_ser.rank(na_option=\"bottom\"), exp_bot)\n tm.assert_series_equal(na_ser.rank(na_option=\"keep\"), exp_keep)\n\n # Test na_option for rank data with ascending False\n exp_top = Series([7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0])\n exp_bot = Series([6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 7.0])\n exp_keep = Series([6.0, 5.0, 4.0, 3.0, 2.0, 1.0, np.NaN])\n\n tm.assert_series_equal(na_ser.rank(na_option=\"top\", ascending=False), exp_top)\n tm.assert_series_equal(\n na_ser.rank(na_option=\"bottom\", ascending=False), exp_bot\n )\n tm.assert_series_equal(na_ser.rank(na_option=\"keep\", ascending=False), exp_keep)\n\n # Test invalid values for na_option\n msg = \"na_option must be one of 'keep', 'top', or 'bottom'\"\n\n with pytest.raises(ValueError, match=msg):\n na_ser.rank(na_option=\"bad\", ascending=False)\n\n # invalid type\n with pytest.raises(ValueError, match=msg):\n na_ser.rank(na_option=True, ascending=False)\n\n # Test with pct=True\n na_ser = Series([\"first\", \"second\", \"third\", \"fourth\", np.NaN]).astype(\n CategoricalDtype([\"first\", \"second\", \"third\", \"fourth\"], True)\n )\n exp_top = Series([0.4, 0.6, 0.8, 1.0, 0.2])\n exp_bot = Series([0.2, 0.4, 0.6, 0.8, 1.0])\n exp_keep = Series([0.25, 0.5, 0.75, 1.0, np.NaN])\n\n tm.assert_series_equal(na_ser.rank(na_option=\"top\", pct=True), exp_top)\n tm.assert_series_equal(na_ser.rank(na_option=\"bottom\", pct=True), exp_bot)\n tm.assert_series_equal(na_ser.rank(na_option=\"keep\", pct=True), exp_keep)\n\n def test_rank_signature(self):\n s = Series([0, 1])\n s.rank(method=\"average\")\n msg = (\n \"No axis named average for object type\"\n \" <class 'pandas.core.series.Series'>\"\n )\n with pytest.raises(ValueError, match=msg):\n s.rank(\"average\")\n\n @pytest.mark.parametrize(\n \"contents,dtype\",\n [\n (\n [\n -np.inf,\n -50,\n -1,\n -1e-20,\n -1e-25,\n -1e-50,\n 0,\n 1e-40,\n 1e-20,\n 1e-10,\n 2,\n 40,\n np.inf,\n ],\n \"float64\",\n ),\n (\n [\n -np.inf,\n -50,\n -1,\n -1e-20,\n -1e-25,\n -1e-45,\n 0,\n 1e-40,\n 1e-20,\n 1e-10,\n 2,\n 40,\n np.inf,\n ],\n \"float32\",\n ),\n ([np.iinfo(np.uint8).min, 1, 2, 100, np.iinfo(np.uint8).max], \"uint8\"),\n pytest.param(\n [\n np.iinfo(np.int64).min,\n -100,\n 0,\n 1,\n 9999,\n 100000,\n 1e10,\n np.iinfo(np.int64).max,\n ],\n \"int64\",\n marks=pytest.mark.xfail(\n reason=\"iNaT is equivalent to minimum value of dtype\"\n \"int64 pending issue GH#16674\"\n ),\n ),\n ([NegInfinity(), \"1\", \"A\", \"BA\", \"Ba\", \"C\", Infinity()], \"object\"),\n ],\n )\n def test_rank_inf(self, contents, dtype):\n dtype_na_map = {\n \"float64\": np.nan,\n \"float32\": np.nan,\n \"int64\": iNaT,\n \"object\": None,\n }\n # Insert nans at random positions if underlying dtype has missing\n # value. Then adjust the expected order by adding nans accordingly\n # This is for testing whether rank calculation is affected\n # when values are interwined with nan values.\n values = np.array(contents, dtype=dtype)\n exp_order = np.array(range(len(values)), dtype=\"float64\") + 1.0\n if dtype in dtype_na_map:\n na_value = dtype_na_map[dtype]\n nan_indices = np.random.choice(range(len(values)), 5)\n values = np.insert(values, nan_indices, na_value)\n exp_order = np.insert(exp_order, nan_indices, np.nan)\n # shuffle the testing array and expected results in the same way\n random_order = np.random.permutation(len(values))\n iseries = Series(values[random_order])\n exp = Series(exp_order[random_order], dtype=\"float64\")\n iranks = iseries.rank()\n tm.assert_series_equal(iranks, exp)\n\n def test_rank_tie_methods(self):\n s = self.s\n\n def _check(s, expected, method=\"average\"):\n result = s.rank(method=method)\n tm.assert_series_equal(result, Series(expected))\n\n dtypes = [None, object]\n disabled = {(object, \"first\")}\n results = self.results\n\n for method, dtype in product(results, dtypes):\n if (dtype, method) in disabled:\n continue\n series = s if dtype is None else s.astype(dtype)\n _check(series, results[method], method=method)\n\n @td.skip_if_no_scipy\n @pytest.mark.parametrize(\"ascending\", [True, False])\n @pytest.mark.parametrize(\"method\", [\"average\", \"min\", \"max\", \"first\", \"dense\"])\n @pytest.mark.parametrize(\"na_option\", [\"top\", \"bottom\", \"keep\"])\n def test_rank_tie_methods_on_infs_nans(self, method, na_option, ascending):\n dtypes = [\n (\"object\", None, Infinity(), NegInfinity()),\n (\"float64\", np.nan, np.inf, -np.inf),\n ]\n chunk = 3\n disabled = {(\"object\", \"first\")}\n\n def _check(s, method, na_option, ascending):\n exp_ranks = {\n \"average\": ([2, 2, 2], [5, 5, 5], [8, 8, 8]),\n \"min\": ([1, 1, 1], [4, 4, 4], [7, 7, 7]),\n \"max\": ([3, 3, 3], [6, 6, 6], [9, 9, 9]),\n \"first\": ([1, 2, 3], [4, 5, 6], [7, 8, 9]),\n \"dense\": ([1, 1, 1], [2, 2, 2], [3, 3, 3]),\n }\n ranks = exp_ranks[method]\n if na_option == \"top\":\n order = [ranks[1], ranks[0], ranks[2]]\n elif na_option == \"bottom\":\n order = [ranks[0], ranks[2], ranks[1]]\n else:\n order = [ranks[0], [np.nan] * chunk, ranks[1]]\n expected = order if ascending else order[::-1]\n expected = list(chain.from_iterable(expected))\n result = s.rank(method=method, na_option=na_option, ascending=ascending)\n tm.assert_series_equal(result, Series(expected, dtype=\"float64\"))\n\n for dtype, na_value, pos_inf, neg_inf in dtypes:\n in_arr = [neg_inf] * chunk + [na_value] * chunk + [pos_inf] * chunk\n iseries = Series(in_arr, dtype=dtype)\n if (dtype, method) in disabled:\n continue\n _check(iseries, method, na_option, ascending)\n\n def test_rank_desc_mix_nans_infs(self):\n # GH 19538\n # check descending ranking when mix nans and infs\n iseries = Series([1, np.nan, np.inf, -np.inf, 25])\n result = iseries.rank(ascending=False)\n exp = Series([3, np.nan, 1, 4, 2], dtype=\"float64\")\n tm.assert_series_equal(result, exp)\n\n def test_rank_methods_series(self):\n pytest.importorskip(\"scipy.stats.special\")\n rankdata = pytest.importorskip(\"scipy.stats.rankdata\")\n\n xs = np.random.randn(9)\n xs = np.concatenate([xs[i:] for i in range(0, 9, 2)]) # add duplicates\n np.random.shuffle(xs)\n\n index = [chr(ord(\"a\") + i) for i in range(len(xs))]\n\n for vals in [xs, xs + 1e6, xs * 1e-6]:\n ts = Series(vals, index=index)\n\n for m in [\"average\", \"min\", \"max\", \"first\", \"dense\"]:\n result = ts.rank(method=m)\n sprank = rankdata(vals, m if m != \"first\" else \"ordinal\")\n expected = Series(sprank, index=index).astype(\"float64\")\n tm.assert_series_equal(result, expected)\n\n def test_rank_dense_method(self):\n dtypes = [\"O\", \"f8\", \"i8\"]\n in_out = [\n ([1], [1]),\n ([2], [1]),\n ([0], [1]),\n ([2, 2], [1, 1]),\n ([1, 2, 3], [1, 2, 3]),\n ([4, 2, 1], [3, 2, 1]),\n ([1, 1, 5, 5, 3], [1, 1, 3, 3, 2]),\n ([-5, -4, -3, -2, -1], [1, 2, 3, 4, 5]),\n ]\n\n for ser, exp in in_out:\n for dtype in dtypes:\n s = Series(ser).astype(dtype)\n result = s.rank(method=\"dense\")\n expected = Series(exp).astype(result.dtype)\n tm.assert_series_equal(result, expected)\n\n def test_rank_descending(self):\n dtypes = [\"O\", \"f8\", \"i8\"]\n\n for dtype, method in product(dtypes, self.results):\n if \"i\" in dtype:\n s = self.s.dropna()\n else:\n s = self.s.astype(dtype)\n\n res = s.rank(ascending=False)\n expected = (s.max() - s).rank()\n tm.assert_series_equal(res, expected)\n\n if method == \"first\" and dtype == \"O\":\n continue\n\n expected = (s.max() - s).rank(method=method)\n res2 = s.rank(method=method, ascending=False)\n tm.assert_series_equal(res2, expected)\n\n def test_rank_int(self):\n s = self.s.dropna().astype(\"i8\")\n\n for method, res in self.results.items():\n result = s.rank(method=method)\n expected = Series(res).dropna()\n expected.index = result.index\n tm.assert_series_equal(result, expected)\n\n def test_rank_object_bug(self):\n # GH 13445\n\n # smoke tests\n Series([np.nan] * 32).astype(object).rank(ascending=True)\n Series([np.nan] * 32).astype(object).rank(ascending=False)\n\n def test_rank_modify_inplace(self):\n # GH 18521\n # Check rank does not mutate series\n s = Series([Timestamp(\"2017-01-05 10:20:27.569000\"), NaT])\n expected = s.copy()\n\n s.rank()\n result = s\n tm.assert_series_equal(result, expected)\n\n\n# GH15630, pct should be on 100% basis when method='dense'\n\n\n@pytest.mark.parametrize(\"dtype\", [\"O\", \"f8\", \"i8\"])\n@pytest.mark.parametrize(\n \"ser, exp\",\n [\n ([1], [1.0]),\n ([1, 2], [1.0 / 2, 2.0 / 2]),\n ([2, 2], [1.0, 1.0]),\n ([1, 2, 3], [1.0 / 3, 2.0 / 3, 3.0 / 3]),\n ([1, 2, 2], [1.0 / 2, 2.0 / 2, 2.0 / 2]),\n ([4, 2, 1], [3.0 / 3, 2.0 / 3, 1.0 / 3]),\n ([1, 1, 5, 5, 3], [1.0 / 3, 1.0 / 3, 3.0 / 3, 3.0 / 3, 2.0 / 3]),\n ([1, 1, 3, 3, 5, 5], [1.0 / 3, 1.0 / 3, 2.0 / 3, 2.0 / 3, 3.0 / 3, 3.0 / 3]),\n ([-5, -4, -3, -2, -1], [1.0 / 5, 2.0 / 5, 3.0 / 5, 4.0 / 5, 5.0 / 5]),\n ],\n)\ndef test_rank_dense_pct(dtype, ser, exp):\n s = Series(ser).astype(dtype)\n result = s.rank(method=\"dense\", pct=True)\n expected = Series(exp).astype(result.dtype)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"O\", \"f8\", \"i8\"])\n@pytest.mark.parametrize(\n \"ser, exp\",\n [\n ([1], [1.0]),\n ([1, 2], [1.0 / 2, 2.0 / 2]),\n ([2, 2], [1.0 / 2, 1.0 / 2]),\n ([1, 2, 3], [1.0 / 3, 2.0 / 3, 3.0 / 3]),\n ([1, 2, 2], [1.0 / 3, 2.0 / 3, 2.0 / 3]),\n ([4, 2, 1], [3.0 / 3, 2.0 / 3, 1.0 / 3]),\n ([1, 1, 5, 5, 3], [1.0 / 5, 1.0 / 5, 4.0 / 5, 4.0 / 5, 3.0 / 5]),\n ([1, 1, 3, 3, 5, 5], [1.0 / 6, 1.0 / 6, 3.0 / 6, 3.0 / 6, 5.0 / 6, 5.0 / 6]),\n ([-5, -4, -3, -2, -1], [1.0 / 5, 2.0 / 5, 3.0 / 5, 4.0 / 5, 5.0 / 5]),\n ],\n)\ndef test_rank_min_pct(dtype, ser, exp):\n s = Series(ser).astype(dtype)\n result = s.rank(method=\"min\", pct=True)\n expected = Series(exp).astype(result.dtype)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"O\", \"f8\", \"i8\"])\n@pytest.mark.parametrize(\n \"ser, exp\",\n [\n ([1], [1.0]),\n ([1, 2], [1.0 / 2, 2.0 / 2]),\n ([2, 2], [1.0, 1.0]),\n ([1, 2, 3], [1.0 / 3, 2.0 / 3, 3.0 / 3]),\n ([1, 2, 2], [1.0 / 3, 3.0 / 3, 3.0 / 3]),\n ([4, 2, 1], [3.0 / 3, 2.0 / 3, 1.0 / 3]),\n ([1, 1, 5, 5, 3], [2.0 / 5, 2.0 / 5, 5.0 / 5, 5.0 / 5, 3.0 / 5]),\n ([1, 1, 3, 3, 5, 5], [2.0 / 6, 2.0 / 6, 4.0 / 6, 4.0 / 6, 6.0 / 6, 6.0 / 6]),\n ([-5, -4, -3, -2, -1], [1.0 / 5, 2.0 / 5, 3.0 / 5, 4.0 / 5, 5.0 / 5]),\n ],\n)\ndef test_rank_max_pct(dtype, ser, exp):\n s = Series(ser).astype(dtype)\n result = s.rank(method=\"max\", pct=True)\n expected = Series(exp).astype(result.dtype)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"O\", \"f8\", \"i8\"])\n@pytest.mark.parametrize(\n \"ser, exp\",\n [\n ([1], [1.0]),\n ([1, 2], [1.0 / 2, 2.0 / 2]),\n ([2, 2], [1.5 / 2, 1.5 / 2]),\n ([1, 2, 3], [1.0 / 3, 2.0 / 3, 3.0 / 3]),\n ([1, 2, 2], [1.0 / 3, 2.5 / 3, 2.5 / 3]),\n ([4, 2, 1], [3.0 / 3, 2.0 / 3, 1.0 / 3]),\n ([1, 1, 5, 5, 3], [1.5 / 5, 1.5 / 5, 4.5 / 5, 4.5 / 5, 3.0 / 5]),\n ([1, 1, 3, 3, 5, 5], [1.5 / 6, 1.5 / 6, 3.5 / 6, 3.5 / 6, 5.5 / 6, 5.5 / 6]),\n ([-5, -4, -3, -2, -1], [1.0 / 5, 2.0 / 5, 3.0 / 5, 4.0 / 5, 5.0 / 5]),\n ],\n)\ndef test_rank_average_pct(dtype, ser, exp):\n s = Series(ser).astype(dtype)\n result = s.rank(method=\"average\", pct=True)\n expected = Series(exp).astype(result.dtype)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"f8\", \"i8\"])\n@pytest.mark.parametrize(\n \"ser, exp\",\n [\n ([1], [1.0]),\n ([1, 2], [1.0 / 2, 2.0 / 2]),\n ([2, 2], [1.0 / 2, 2.0 / 2.0]),\n ([1, 2, 3], [1.0 / 3, 2.0 / 3, 3.0 / 3]),\n ([1, 2, 2], [1.0 / 3, 2.0 / 3, 3.0 / 3]),\n ([4, 2, 1], [3.0 / 3, 2.0 / 3, 1.0 / 3]),\n ([1, 1, 5, 5, 3], [1.0 / 5, 2.0 / 5, 4.0 / 5, 5.0 / 5, 3.0 / 5]),\n ([1, 1, 3, 3, 5, 5], [1.0 / 6, 2.0 / 6, 3.0 / 6, 4.0 / 6, 5.0 / 6, 6.0 / 6]),\n ([-5, -4, -3, -2, -1], [1.0 / 5, 2.0 / 5, 3.0 / 5, 4.0 / 5, 5.0 / 5]),\n ],\n)\ndef test_rank_first_pct(dtype, ser, exp):\n s = Series(ser).astype(dtype)\n result = s.rank(method=\"first\", pct=True)\n expected = Series(exp).astype(result.dtype)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.single\n@pytest.mark.high_memory\ndef test_pct_max_many_rows():\n # GH 18271\n s = Series(np.arange(2 ** 24 + 1))\n result = s.rank(pct=True).max()\n assert result == 1\n",
"from datetime import datetime, timedelta\nimport operator\n\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import iNaT\nimport pandas.compat as compat\n\nfrom pandas.core.dtypes.common import is_datetime64_any_dtype\n\nfrom pandas import (\n DatetimeIndex,\n Index,\n NaT,\n Period,\n Series,\n Timedelta,\n TimedeltaIndex,\n Timestamp,\n isna,\n)\nfrom pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray\nfrom pandas.core.ops import roperator\nimport pandas.util.testing as tm\n\n\n@pytest.mark.parametrize(\n \"nat,idx\",\n [\n (Timestamp(\"NaT\"), DatetimeIndex),\n (Timedelta(\"NaT\"), TimedeltaIndex),\n (Period(\"NaT\", freq=\"M\"), PeriodArray),\n ],\n)\ndef test_nat_fields(nat, idx):\n\n for field in idx._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == \"weekday\":\n continue\n\n result = getattr(NaT, field)\n assert np.isnan(result)\n\n result = getattr(nat, field)\n assert np.isnan(result)\n\n for field in idx._bool_ops:\n\n result = getattr(NaT, field)\n assert result is False\n\n result = getattr(nat, field)\n assert result is False\n\n\ndef test_nat_vector_field_access():\n idx = DatetimeIndex([\"1/1/2000\", None, None, \"1/4/2000\"])\n\n for field in DatetimeIndex._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == \"weekday\":\n continue\n\n result = getattr(idx, field)\n expected = Index([getattr(x, field) for x in idx])\n tm.assert_index_equal(result, expected)\n\n ser = Series(idx)\n\n for field in DatetimeIndex._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == \"weekday\":\n continue\n\n result = getattr(ser.dt, field)\n expected = [getattr(x, field) for x in idx]\n tm.assert_series_equal(result, Series(expected))\n\n for field in DatetimeIndex._bool_ops:\n result = getattr(ser.dt, field)\n expected = [getattr(x, field) for x in idx]\n tm.assert_series_equal(result, Series(expected))\n\n\n@pytest.mark.parametrize(\"klass\", [Timestamp, Timedelta, Period])\n@pytest.mark.parametrize(\"value\", [None, np.nan, iNaT, float(\"nan\"), NaT, \"NaT\", \"nat\"])\ndef test_identity(klass, value):\n assert klass(value) is NaT\n\n\n@pytest.mark.parametrize(\"klass\", [Timestamp, Timedelta, Period])\n@pytest.mark.parametrize(\"value\", [\"\", \"nat\", \"NAT\", None, np.nan])\ndef test_equality(klass, value):\n if klass is Period and value == \"\":\n pytest.skip(\"Period cannot parse empty string\")\n\n assert klass(value).value == iNaT\n\n\n@pytest.mark.parametrize(\"klass\", [Timestamp, Timedelta])\n@pytest.mark.parametrize(\"method\", [\"round\", \"floor\", \"ceil\"])\n@pytest.mark.parametrize(\"freq\", [\"s\", \"5s\", \"min\", \"5min\", \"h\", \"5h\"])\ndef test_round_nat(klass, method, freq):\n # see gh-14940\n ts = klass(\"nat\")\n\n round_method = getattr(ts, method)\n assert round_method(freq) is ts\n\n\n@pytest.mark.parametrize(\n \"method\",\n [\n \"astimezone\",\n \"combine\",\n \"ctime\",\n \"dst\",\n \"fromordinal\",\n \"fromtimestamp\",\n \"isocalendar\",\n \"strftime\",\n \"strptime\",\n \"time\",\n \"timestamp\",\n \"timetuple\",\n \"timetz\",\n \"toordinal\",\n \"tzname\",\n \"utcfromtimestamp\",\n \"utcnow\",\n \"utcoffset\",\n \"utctimetuple\",\n \"timestamp\",\n ],\n)\ndef test_nat_methods_raise(method):\n # see gh-9513, gh-17329\n msg = \"NaTType does not support {method}\".format(method=method)\n\n with pytest.raises(ValueError, match=msg):\n getattr(NaT, method)()\n\n\n@pytest.mark.parametrize(\"method\", [\"weekday\", \"isoweekday\"])\ndef test_nat_methods_nan(method):\n # see gh-9513, gh-17329\n assert np.isnan(getattr(NaT, method)())\n\n\n@pytest.mark.parametrize(\n \"method\", [\"date\", \"now\", \"replace\", \"today\", \"tz_convert\", \"tz_localize\"]\n)\ndef test_nat_methods_nat(method):\n # see gh-8254, gh-9513, gh-17329\n assert getattr(NaT, method)() is NaT\n\n\n@pytest.mark.parametrize(\n \"get_nat\", [lambda x: NaT, lambda x: Timedelta(x), lambda x: Timestamp(x)]\n)\ndef test_nat_iso_format(get_nat):\n # see gh-12300\n assert get_nat(\"NaT\").isoformat() == \"NaT\"\n\n\n@pytest.mark.parametrize(\n \"klass,expected\",\n [\n (Timestamp, [\"freqstr\", \"normalize\", \"to_julian_date\", \"to_period\", \"tz\"]),\n (\n Timedelta,\n [\n \"components\",\n \"delta\",\n \"is_populated\",\n \"resolution_string\",\n \"to_pytimedelta\",\n \"to_timedelta64\",\n \"view\",\n ],\n ),\n ],\n)\ndef test_missing_public_nat_methods(klass, expected):\n # see gh-17327\n #\n # NaT should have *most* of the Timestamp and Timedelta methods.\n # Here, we check which public methods NaT does not have. We\n # ignore any missing private methods.\n nat_names = dir(NaT)\n klass_names = dir(klass)\n\n missing = [x for x in klass_names if x not in nat_names and not x.startswith(\"_\")]\n missing.sort()\n\n assert missing == expected\n\n\ndef _get_overlap_public_nat_methods(klass, as_tuple=False):\n \"\"\"\n Get overlapping public methods between NaT and another class.\n\n Parameters\n ----------\n klass : type\n The class to compare with NaT\n as_tuple : bool, default False\n Whether to return a list of tuples of the form (klass, method).\n\n Returns\n -------\n overlap : list\n \"\"\"\n nat_names = dir(NaT)\n klass_names = dir(klass)\n\n overlap = [\n x\n for x in nat_names\n if x in klass_names and not x.startswith(\"_\") and callable(getattr(klass, x))\n ]\n\n # Timestamp takes precedence over Timedelta in terms of overlap.\n if klass is Timedelta:\n ts_names = dir(Timestamp)\n overlap = [x for x in overlap if x not in ts_names]\n\n if as_tuple:\n overlap = [(klass, method) for method in overlap]\n\n overlap.sort()\n return overlap\n\n\n@pytest.mark.parametrize(\n \"klass,expected\",\n [\n (\n Timestamp,\n [\n \"astimezone\",\n \"ceil\",\n \"combine\",\n \"ctime\",\n \"date\",\n \"day_name\",\n \"dst\",\n \"floor\",\n \"fromisocalendar\",\n \"fromisoformat\",\n \"fromordinal\",\n \"fromtimestamp\",\n \"isocalendar\",\n \"isoformat\",\n \"isoweekday\",\n \"month_name\",\n \"now\",\n \"replace\",\n \"round\",\n \"strftime\",\n \"strptime\",\n \"time\",\n \"timestamp\",\n \"timetuple\",\n \"timetz\",\n \"to_datetime64\",\n \"to_numpy\",\n \"to_pydatetime\",\n \"today\",\n \"toordinal\",\n \"tz_convert\",\n \"tz_localize\",\n \"tzname\",\n \"utcfromtimestamp\",\n \"utcnow\",\n \"utcoffset\",\n \"utctimetuple\",\n \"weekday\",\n ],\n ),\n (Timedelta, [\"total_seconds\"]),\n ],\n)\ndef test_overlap_public_nat_methods(klass, expected):\n # see gh-17327\n #\n # NaT should have *most* of the Timestamp and Timedelta methods.\n # In case when Timestamp, Timedelta, and NaT are overlap, the overlap\n # is considered to be with Timestamp and NaT, not Timedelta.\n\n # \"fromisoformat\" was introduced in 3.7\n if klass is Timestamp and not compat.PY37:\n expected.remove(\"fromisoformat\")\n if klass is Timestamp and not compat.PY38:\n expected.remove(\"fromisocalendar\")\n\n assert _get_overlap_public_nat_methods(klass) == expected\n\n\n@pytest.mark.parametrize(\n \"compare\",\n (\n _get_overlap_public_nat_methods(Timestamp, True)\n + _get_overlap_public_nat_methods(Timedelta, True)\n ),\n)\ndef test_nat_doc_strings(compare):\n # see gh-17327\n #\n # The docstrings for overlapping methods should match.\n klass, method = compare\n klass_doc = getattr(klass, method).__doc__\n\n nat_doc = getattr(NaT, method).__doc__\n assert klass_doc == nat_doc\n\n\n_ops = {\n \"left_plus_right\": lambda a, b: a + b,\n \"right_plus_left\": lambda a, b: b + a,\n \"left_minus_right\": lambda a, b: a - b,\n \"right_minus_left\": lambda a, b: b - a,\n \"left_times_right\": lambda a, b: a * b,\n \"right_times_left\": lambda a, b: b * a,\n \"left_div_right\": lambda a, b: a / b,\n \"right_div_left\": lambda a, b: b / a,\n}\n\n\n@pytest.mark.parametrize(\"op_name\", list(_ops.keys()))\n@pytest.mark.parametrize(\n \"value,val_type\",\n [\n (2, \"scalar\"),\n (1.5, \"floating\"),\n (np.nan, \"floating\"),\n (\"foo\", \"str\"),\n (timedelta(3600), \"timedelta\"),\n (Timedelta(\"5s\"), \"timedelta\"),\n (datetime(2014, 1, 1), \"timestamp\"),\n (Timestamp(\"2014-01-01\"), \"timestamp\"),\n (Timestamp(\"2014-01-01\", tz=\"UTC\"), \"timestamp\"),\n (Timestamp(\"2014-01-01\", tz=\"US/Eastern\"), \"timestamp\"),\n (pytz.timezone(\"Asia/Tokyo\").localize(datetime(2014, 1, 1)), \"timestamp\"),\n ],\n)\ndef test_nat_arithmetic_scalar(op_name, value, val_type):\n # see gh-6873\n invalid_ops = {\n \"scalar\": {\"right_div_left\"},\n \"floating\": {\n \"right_div_left\",\n \"left_minus_right\",\n \"right_minus_left\",\n \"left_plus_right\",\n \"right_plus_left\",\n },\n \"str\": set(_ops.keys()),\n \"timedelta\": {\"left_times_right\", \"right_times_left\"},\n \"timestamp\": {\n \"left_times_right\",\n \"right_times_left\",\n \"left_div_right\",\n \"right_div_left\",\n },\n }\n\n op = _ops[op_name]\n\n if op_name in invalid_ops.get(val_type, set()):\n if (\n val_type == \"timedelta\"\n and \"times\" in op_name\n and isinstance(value, Timedelta)\n ):\n msg = \"Cannot multiply\"\n elif val_type == \"str\":\n # un-specific check here because the message comes from str\n # and varies by method\n msg = (\n \"can only concatenate str|\"\n \"unsupported operand type|\"\n \"can't multiply sequence|\"\n \"Can't convert 'NaTType'|\"\n \"must be str, not NaTType\"\n )\n else:\n msg = \"unsupported operand type\"\n\n with pytest.raises(TypeError, match=msg):\n op(NaT, value)\n else:\n if val_type == \"timedelta\" and \"div\" in op_name:\n expected = np.nan\n else:\n expected = NaT\n\n assert op(NaT, value) is expected\n\n\n@pytest.mark.parametrize(\n \"val,expected\", [(np.nan, NaT), (NaT, np.nan), (np.timedelta64(\"NaT\"), np.nan)]\n)\ndef test_nat_rfloordiv_timedelta(val, expected):\n # see gh-#18846\n #\n # See also test_timedelta.TestTimedeltaArithmetic.test_floordiv\n td = Timedelta(hours=3, minutes=4)\n assert td // val is expected\n\n\n@pytest.mark.parametrize(\n \"op_name\",\n [\"left_plus_right\", \"right_plus_left\", \"left_minus_right\", \"right_minus_left\"],\n)\n@pytest.mark.parametrize(\n \"value\",\n [\n DatetimeIndex([\"2011-01-01\", \"2011-01-02\"], name=\"x\"),\n DatetimeIndex([\"2011-01-01\", \"2011-01-02\"], tz=\"US/Eastern\", name=\"x\"),\n DatetimeArray._from_sequence([\"2011-01-01\", \"2011-01-02\"]),\n DatetimeArray._from_sequence([\"2011-01-01\", \"2011-01-02\"], tz=\"US/Pacific\"),\n TimedeltaIndex([\"1 day\", \"2 day\"], name=\"x\"),\n ],\n)\ndef test_nat_arithmetic_index(op_name, value):\n # see gh-11718\n exp_name = \"x\"\n exp_data = [NaT] * 2\n\n if is_datetime64_any_dtype(value.dtype) and \"plus\" in op_name:\n expected = DatetimeIndex(exp_data, tz=value.tz, name=exp_name)\n else:\n expected = TimedeltaIndex(exp_data, name=exp_name)\n\n if not isinstance(value, Index):\n expected = expected.array\n\n op = _ops[op_name]\n result = op(NaT, value)\n tm.assert_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n \"op_name\",\n [\"left_plus_right\", \"right_plus_left\", \"left_minus_right\", \"right_minus_left\"],\n)\n@pytest.mark.parametrize(\"box\", [TimedeltaIndex, Series, TimedeltaArray._from_sequence])\ndef test_nat_arithmetic_td64_vector(op_name, box):\n # see gh-19124\n vec = box([\"1 day\", \"2 day\"], dtype=\"timedelta64[ns]\")\n box_nat = box([NaT, NaT], dtype=\"timedelta64[ns]\")\n tm.assert_equal(_ops[op_name](vec, NaT), box_nat)\n\n\n@pytest.mark.parametrize(\n \"dtype,op,out_dtype\",\n [\n (\"datetime64[ns]\", operator.add, \"datetime64[ns]\"),\n (\"datetime64[ns]\", roperator.radd, \"datetime64[ns]\"),\n (\"datetime64[ns]\", operator.sub, \"timedelta64[ns]\"),\n (\"datetime64[ns]\", roperator.rsub, \"timedelta64[ns]\"),\n (\"timedelta64[ns]\", operator.add, \"datetime64[ns]\"),\n (\"timedelta64[ns]\", roperator.radd, \"datetime64[ns]\"),\n (\"timedelta64[ns]\", operator.sub, \"datetime64[ns]\"),\n (\"timedelta64[ns]\", roperator.rsub, \"timedelta64[ns]\"),\n ],\n)\ndef test_nat_arithmetic_ndarray(dtype, op, out_dtype):\n other = np.arange(10).astype(dtype)\n result = op(NaT, other)\n\n expected = np.empty(other.shape, dtype=out_dtype)\n expected.fill(\"NaT\")\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_nat_pinned_docstrings():\n # see gh-17327\n assert NaT.ctime.__doc__ == datetime.ctime.__doc__\n\n\ndef test_to_numpy_alias():\n # GH 24653: alias .to_numpy() for scalars\n expected = NaT.to_datetime64()\n result = NaT.to_numpy()\n\n assert isna(expected) and isna(result)\n\n\n@pytest.mark.parametrize(\"other\", [Timedelta(0), Timestamp(0)])\ndef test_nat_comparisons(compare_operators_no_eq_ne, other):\n # GH 26039\n assert getattr(NaT, compare_operators_no_eq_ne)(other) is False\n assert getattr(other, compare_operators_no_eq_ne)(NaT) is False\n"
] |
[
[
"pandas.util.testing.assert_index_equal",
"pandas.util.testing.assert_produces_warning",
"pandas.Series"
],
[
"numpy.array",
"numpy.isnan",
"pandas.date_range",
"numpy.iinfo",
"numpy.random.randn",
"numpy.random.shuffle",
"pandas.util.testing.assert_series_equal",
"pandas.Timestamp",
"pandas.api.types.CategoricalDtype",
"numpy.arange",
"pandas._libs.algos.NegInfinity",
"pandas.Series",
"numpy.repeat",
"pandas._libs.algos.Infinity",
"numpy.insert"
],
[
"pandas.util.testing.assert_numpy_array_equal",
"pandas.NaT.to_numpy",
"numpy.isnan",
"numpy.empty",
"pandas.Timedelta",
"pandas.DatetimeIndex",
"pandas.isna",
"pandas.Period",
"pandas.util.testing.assert_index_equal",
"pandas.core.dtypes.common.is_datetime64_any_dtype",
"pandas.core.arrays.DatetimeArray._from_sequence",
"pandas.NaT.to_datetime64",
"pandas.Timestamp",
"numpy.arange",
"numpy.timedelta64",
"pandas.Series",
"pandas.TimedeltaIndex",
"pandas.util.testing.assert_equal"
]
] |
selwyn96/QuantCSGM
|
[
"cc89b361d9bded5b9e6be0f04cc1e93ce44c6e51"
] |
[
"mnist_generate/model_def_2.py"
] |
[
"# This file based on : https://jmetzen.github.io/notebooks/vae.ipynb\n# pylint: disable = C0103, C0111, C0301, R0913, R0903, R0914, R0902\n\n\nimport tensorflow as tf\nimport utils\n\n\nclass Hparams(object):\n def __init__(self):\n self.n_hidden_recog_1 = 500 # 1st layer encoder neurons\n self.n_hidden_recog_2 = 500 # 2nd layer encoder neurons\n self.n_hidden_gener_1 = 500 # 1st layer decoder neurons\n self.n_hidden_gener_2 = 500 # 2nd layer decoder neurons\n self.n_input = 784 # MNIST data input (img shape: 28*28)\n self.n_z = 20 # dimensionality of latent space\n self.transfer_fct = tf.nn.softplus\n\n\ndef encoder(hparams, x_ph, scope_name, reuse):\n with tf.variable_scope(scope_name) as scope:\n if reuse:\n scope.reuse_variables()\n\n w1 = tf.get_variable('w1', initializer=utils.xavier_init(hparams.n_input, hparams.n_hidden_recog_1))\n b1 = tf.get_variable('b1', initializer=tf.zeros([hparams.n_hidden_recog_1], dtype=tf.float32))\n hidden1 = hparams.transfer_fct(tf.matmul(x_ph, w1) + b1)\n\n w2 = tf.get_variable('w2', initializer=utils.xavier_init(hparams.n_hidden_recog_1, hparams.n_hidden_recog_2))\n b2 = tf.get_variable('b2', initializer=tf.zeros([hparams.n_hidden_recog_2], dtype=tf.float32))\n hidden2 = hparams.transfer_fct(tf.matmul(hidden1, w2) + b2)\n\n w3 = tf.get_variable('w3', initializer=utils.xavier_init(hparams.n_hidden_recog_2, hparams.n_z))\n b3 = tf.get_variable('b3', initializer=tf.zeros([hparams.n_z], dtype=tf.float32))\n z_mean = tf.matmul(hidden2, w3) + b3\n\n w4 = tf.get_variable('w4', initializer=utils.xavier_init(hparams.n_hidden_recog_2, hparams.n_z))\n b4 = tf.get_variable('b4', initializer=tf.zeros([hparams.n_z], dtype=tf.float32))\n z_log_sigma_sq = tf.matmul(hidden2, w4) + b4\n\n return z_mean, z_log_sigma_sq\n\n\ndef generator(hparams, z, scope_name, reuse):\n\n with tf.variable_scope(scope_name) as scope:\n if reuse:\n scope.reuse_variables()\n\n w1 = tf.get_variable('w1', initializer=utils.xavier_init(hparams.n_z, hparams.n_hidden_gener_1))\n b1 = tf.get_variable('b1', initializer=tf.zeros([hparams.n_hidden_gener_1], dtype=tf.float32))\n hidden1 = hparams.transfer_fct(tf.matmul(z, w1) + b1)\n\n w2 = tf.get_variable('w2', initializer=utils.xavier_init(hparams.n_hidden_gener_1, hparams.n_hidden_gener_2))\n b2 = tf.get_variable('b2', initializer=tf.zeros([hparams.n_hidden_gener_2], dtype=tf.float32))\n hidden2 = hparams.transfer_fct(tf.matmul(hidden1, w2) + b2)\n\n w3 = tf.get_variable('w3', initializer=utils.xavier_init(hparams.n_hidden_gener_2, hparams.n_input))\n b3 = tf.get_variable('b3', initializer=tf.zeros([hparams.n_input], dtype=tf.float32))\n logits = tf.matmul(hidden2, w3) + b3\n x_reconstr_mean = tf.nn.sigmoid(logits)\n\n return logits, x_reconstr_mean\n\n\ndef get_loss(x, logits, z_mean, z_log_sigma_sq):\n reconstr_losses = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(labels=x, logits=logits), 1)\n latent_losses = -0.5 * tf.reduce_sum(1 + z_log_sigma_sq - tf.square(z_mean) - tf.exp(z_log_sigma_sq), 1)\n total_loss = tf.reduce_mean(reconstr_losses + latent_losses, name='total_loss')\n return total_loss\n\n\ndef get_z_var(hparams, batch_size):\n z = tf.Variable(tf.random_normal((batch_size, hparams.n_z)), name='z')\n return z\n\n\ndef gen_restore_vars():\n restore_vars = ['gen/w1',\n 'gen/b1',\n 'gen/w2',\n 'gen/b2',\n 'gen/w3',\n 'gen/b3']\n return restore_vars\n"
] |
[
[
"tensorflow.exp",
"tensorflow.zeros",
"tensorflow.matmul",
"tensorflow.nn.sigmoid_cross_entropy_with_logits",
"tensorflow.variable_scope",
"tensorflow.nn.sigmoid",
"tensorflow.reduce_mean",
"tensorflow.square",
"tensorflow.random_normal"
]
] |
IDl0T/bionic
|
[
"8eaa868a2e7af81bb561492c045feb414f7c6326"
] |
[
"tests/test_flow/test_persistence_fuzz.py"
] |
[
"import pytest\n\nfrom numpy.random import choice\nfrom textwrap import dedent\nfrom random import Random\n\nfrom bionic.exception import CodeVersioningError\nfrom bionic import interpret\nimport bionic as bn\nfrom ..helpers import import_code\n\n\nclass SimpleFlowModel:\n \"\"\"\n Manages a simple Bionic flow where every entity value is an integer\n computed from the sum of other entity values. This wrapper class maintains\n both the Bionic flow and a parallel model that can predict what the Bionic\n flow should be doing. This can be used to generate, manipulate, and\n validate large flows.\n \"\"\"\n\n def __init__(self, builder, make_list):\n self._builder = builder\n self._current_flow = None\n self._update_flow()\n\n self._entities_by_name = {}\n self._last_called_names = make_list()\n\n def add_entity(self, dep_names, nondeterministic=False):\n name = f\"e{len(self._entities_by_name) + 1}\"\n\n self._create_entity(name, dep_names, nondeterministic)\n self._define_entity(name)\n\n return name\n\n def update_entity(\n self,\n name,\n make_func_change=False,\n make_nonfunc_change=False,\n update_major=False,\n update_minor=False,\n ):\n\n entity = self._entities_by_name[name]\n\n if make_func_change:\n entity.func_value += 1\n if make_nonfunc_change:\n entity.nonfunc_value += 1\n if update_major:\n entity.major_version += 1\n if update_minor:\n entity.minor_version += 1\n\n self._define_entity(name)\n\n def get_flow(self):\n return self._current_flow\n\n def expected_entity_value(self, name):\n entity = self._entities_by_name[name]\n dep_values_total = sum(\n self.expected_entity_value(dep_name) for dep_name in entity.dep_names\n )\n return entity.func_value + dep_values_total\n\n def entity_names(self, downstream_of=None, upstream_of=None, with_children=None):\n names = set(self._entities_by_name.keys())\n\n if upstream_of is not None:\n bot_names = interpret.str_or_seq_as_list(upstream_of)\n\n upstream_names = set()\n for bot_name in bot_names:\n bot_entity = self._entities_by_name[bot_name]\n upstream_names |= bot_entity.all_upstream_names\n\n names = names & upstream_names\n\n if downstream_of is not None:\n top_names = interpret.str_or_seq_as_list(downstream_of)\n\n downstream_names = set()\n for top_name in top_names:\n top_entity = self._entities_by_name[top_name]\n downstream_names |= top_entity.all_downstream_names\n\n names = names & downstream_names\n\n if with_children is not None:\n names_with_children = set(\n name\n for name in names\n if len(self._entities_by_name[name].child_names) > 0\n )\n if with_children:\n names = names_with_children\n else:\n names -= names_with_children\n\n return list(sorted(names))\n\n def nondeterministic_upstream_entity_names(self, upstream_of):\n bot_names = interpret.str_or_seq_as_list(upstream_of)\n\n upstream_names = set()\n for bot_name in bot_names:\n bot_entity = self._entities_by_name[bot_name]\n upstream_names |= bot_entity.all_nondeterministic_upstream_names\n\n return upstream_names\n\n def entity_has_nondeterministic_ancestor(self, entity_name):\n entity = self._entities_by_name[entity_name]\n return len(entity.all_nondeterministic_upstream_names) > 0\n\n def entity_is_nondeterministic(self, entity_name):\n return self._entities_by_name[entity_name].is_nondeterministic\n\n def called_entity_names(self):\n names = list(self._last_called_names)\n self.reset_called_entity_names()\n return names\n\n def peek_called_entity_names(self):\n names = list(self._last_called_names)\n return names\n\n def reset_called_entity_names(self):\n self._last_called_names[:] = []\n\n def _create_entity(self, name, dep_names, is_nondeterministic):\n entity = ModelEntity(\n name=name, dep_names=dep_names, is_nondeterministic=is_nondeterministic\n )\n\n entity.all_upstream_names = {name}\n if is_nondeterministic:\n entity.all_nondeterministic_upstream_names = {name}\n for dep_name in dep_names:\n dep_entity = self._entities_by_name[dep_name]\n entity.all_upstream_names.update(dep_entity.all_upstream_names)\n entity.all_nondeterministic_upstream_names.update(\n dep_entity.all_nondeterministic_upstream_names\n )\n dep_entity.child_names.append(name)\n entity.all_downstream_names = {name}\n\n self._entities_by_name[name] = entity\n for anc_name in entity.all_upstream_names:\n anc_entity = self._entities_by_name[anc_name]\n anc_entity.all_downstream_names.add(name)\n\n def _define_entity(self, name):\n entity = self._entities_by_name[name]\n\n vars_dict = {\n \"bn\": bn,\n \"builder\": self._builder,\n \"record_call\": self._last_called_names.append,\n \"noop_func\": lambda x: None,\n }\n\n e = entity\n import_code(\n dedent(\n f\"\"\"\n @builder\n @bn.changes_per_run({e.is_nondeterministic})\n @bn.version_no_warnings(major={e.major_version}, minor={e.minor_version})\n def {name}({', '.join(e.dep_names)}):\n noop_func({e.nonfunc_value})\n record_call(\"{name}\")\n return {' + '.join([str(e.func_value)] + e.dep_names)}\n \"\"\"\n ),\n vars_dict=vars_dict,\n )\n\n self._update_flow()\n\n def _update_flow(self):\n self._current_flow = self._builder.build()\n\n\nclass ModelEntity:\n \"\"\"\n Represents one entity in the SimpleFlowModel.\n \"\"\"\n\n def __init__(self, name, dep_names, is_nondeterministic):\n self.name = name\n self.dep_names = dep_names\n self.is_nondeterministic = is_nondeterministic\n\n self.major_version = 0\n self.minor_version = 0\n self.func_value = 0\n self.nonfunc_value = 0\n\n self.child_names = []\n self.all_upstream_names = set()\n self.all_nondeterministic_upstream_names = set()\n self.all_downstream_names = set()\n\n\nclass Fuzzer:\n \"\"\"\n Randomly constructs and updates a SimpleModelFlow while checking that its\n behavior is as expected.\n \"\"\"\n\n def __init__(self, builder, make_list, random_seed=0):\n self.model = SimpleFlowModel(builder, make_list)\n self._versioning_mode = \"manual\"\n self._builder = builder\n self._random = Random(random_seed)\n\n def set_versioning_mode(self, mode):\n self._builder.set(\"core__versioning_mode\", mode)\n self._versioning_mode = mode\n\n def add_entities(self, n_entities):\n for i in range(n_entities):\n all_names = self.model.entity_names()\n\n dep_names = []\n is_nondeterministic = self._random_bool_with_weighted_probability(0.05)\n for name in all_names:\n if self._random_bool():\n dep_names.append(name)\n new_name = self.model.add_entity(dep_names, is_nondeterministic)\n\n self.model.get_flow().get(new_name)\n expected_called_names = self.model.nondeterministic_upstream_entity_names(\n new_name\n )\n expected_called_names.add(new_name)\n assert sorted(self.model.called_entity_names()) == sorted(\n list(expected_called_names)\n )\n\n def run(self, n_iterations):\n for i in range(n_iterations):\n updated_name = self._random.choice(self.model.entity_names())\n affected_names = self.model.entity_names(\n downstream_of=updated_name, with_children=False\n )\n make_func_change = self._random_bool()\n make_nonfunc_change = not make_func_change\n update_version = self._random_bool()\n\n is_updated_entity_nondeterministic = self.model.entity_is_nondeterministic(\n updated_name\n )\n is_updated_entity_deterministic = not is_updated_entity_nondeterministic\n\n self.model.update_entity(\n updated_name,\n make_func_change=make_func_change,\n make_nonfunc_change=make_nonfunc_change,\n update_major=update_version and make_func_change,\n update_minor=update_version and make_nonfunc_change,\n )\n\n if not update_version:\n # If we didn't update the version, there's a potential mismatch\n # between the entity code and Bionic's understanding. How this\n # plays out will depend on the versioning mode.\n\n if self._versioning_mode == \"manual\":\n # Bionic doesn't know the code has changed, so this entity\n # should still be returning the old value.\n affected_name = self._random.choice(affected_names)\n returned_value = self.model.get_flow().get(affected_name)\n expected_value = self.model.expected_entity_value(affected_name)\n\n # When the change is functional and bionic doesn't recompute the\n # entity, the expected and returned values will be different.\n if make_func_change and is_updated_entity_deterministic:\n assert returned_value != expected_value\n else:\n assert returned_value == expected_value\n\n # We peek at the called entity names to avoid changing the results of\n # called_entity_names() later.\n actual_called_names = self.model.peek_called_entity_names()\n expects_updated_entity_value_change = (\n make_func_change and is_updated_entity_nondeterministic\n )\n expected_called_names = self._expected_called_names(\n updated_name, affected_name, expects_updated_entity_value_change\n )\n assert set(actual_called_names) == expected_called_names\n\n # Now update the version to get the flow back into a\n # \"correct\" state.\n self.model.update_entity(\n updated_name,\n update_major=make_func_change,\n update_minor=make_nonfunc_change,\n )\n\n elif self._versioning_mode == \"assist\":\n affected_name = self._random.choice(affected_names)\n\n if is_updated_entity_deterministic:\n # Bionic should detect that we forgot to update the\n # version.\n with pytest.raises(CodeVersioningError):\n self.model.get_flow().get(affected_name)\n else:\n # Version does not matter for nondeterministic entities.\n assert self.model.get_flow().get(\n affected_name\n ) == self.model.expected_entity_value(affected_name)\n\n # Now update the version to get the flow back into a\n # \"correct\" state.\n self.model.update_entity(\n updated_name,\n update_major=make_func_change,\n update_minor=make_nonfunc_change,\n )\n\n elif self._versioning_mode == \"auto\":\n # Even if we didn't update the version, Bionic should\n # do it for us and the flow should already be in a correct\n # state.\n pass\n\n else:\n raise AssertionError(\n \"Unexpected versioning mode: \" f\"{self._versioning_mode!r}\"\n )\n\n for affected_name in affected_names:\n assert self.model.get_flow().get(\n affected_name\n ) == self.model.expected_entity_value(affected_name)\n\n actual_called_names = self.model.called_entity_names()\n expected_called_names = self._expected_called_names(\n updated_name, affected_names, make_func_change\n )\n assert set(actual_called_names) == expected_called_names\n\n def _random_bool(self):\n return self._random.choice([True, False])\n\n def _random_bool_with_weighted_probability(self, prob_true):\n assert 0.0 <= prob_true <= 1.0\n return choice([True, False], p=[prob_true, 1 - prob_true])\n\n def _expected_called_names(\n self, updated_name, affected_name_or_names, expects_updated_entity_value_change\n ):\n if expects_updated_entity_value_change:\n entity_names_in_between = set(\n self.model.entity_names(\n downstream_of=updated_name,\n upstream_of=affected_name_or_names,\n )\n )\n nondeterministic_ancestors = (\n self.model.nondeterministic_upstream_entity_names(\n entity_names_in_between\n )\n )\n expected_called_names = entity_names_in_between | nondeterministic_ancestors\n\n # When the updated entity value doesn't change, we don't call anything between the\n # updated and affected entities since all the entities are persisted and use their\n # parents' value (hash) which did not change.\n else:\n expected_called_names = self.model.nondeterministic_upstream_entity_names(\n affected_name_or_names\n )\n if self._versioning_mode == \"auto\":\n expected_called_names.add(updated_name)\n\n return expected_called_names\n\n\n@pytest.fixture(scope=\"function\")\ndef fuzzer(fake_gcs_builder, make_list, tmp_path):\n return Fuzzer(fake_gcs_builder, make_list)\n\n\nforeach_mode = pytest.mark.parametrize(\"versioning_mode\", [\"manual\", \"assist\", \"auto\"])\n\n\n@foreach_mode\ndef test_small_fixed_flow_short_fuzz(fuzzer, versioning_mode):\n fuzzer.set_versioning_mode(versioning_mode)\n\n e1 = fuzzer.model.add_entity([])\n e2 = fuzzer.model.add_entity([])\n e3 = fuzzer.model.add_entity([e1])\n e4 = fuzzer.model.add_entity([e1, e2])\n e5 = fuzzer.model.add_entity([e3, e4])\n\n assert fuzzer.model.get_flow().get(e5) == fuzzer.model.expected_entity_value(e5)\n assert list(sorted(fuzzer.model.called_entity_names())) == list(\n sorted(fuzzer.model.entity_names())\n )\n\n fuzzer.run(n_iterations=30)\n\n\n@pytest.mark.slow\n@foreach_mode\ndef test_medium_random_flow_long_fuzz(fuzzer, versioning_mode):\n fuzzer.set_versioning_mode(versioning_mode)\n fuzzer.add_entities(10)\n fuzzer.run(n_iterations=100)\n\n\n@pytest.mark.slow\n@foreach_mode\ndef test_big_random_flow_medium_fuzz(fuzzer, versioning_mode):\n fuzzer.set_versioning_mode(versioning_mode)\n fuzzer.add_entities(20)\n fuzzer.run(n_iterations=50)\n"
] |
[
[
"numpy.random.choice"
]
] |
emeryberger/scale
|
[
"12cf096547d6be3d7664d482e17f6b15d55b9b9a"
] |
[
"test/issues/test-issue266.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport gc\n\ndef f():\n print('called f')\n #Uses around 4GB of memory when looped once\n df = np.ones(500000000)\n \n#Uses around 20GB of memory when looped 5 times\nfor i in range(0,5):\n f()\n"
] |
[
[
"numpy.ones"
]
] |
sky-dust-intelligence-bv/nni
|
[
"d38359e2f56603ddd5bad00ee2bcb7b38d9a88a5"
] |
[
"nni/retiarii/hub/pytorch/nasnet.py"
] |
[
"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n\"\"\"File containing NASNet-series search space.\n\nThe implementation is based on NDS.\nIt's called ``nasnet.py`` simply because NASNet is the first to propose such structure.\n\"\"\"\n\nfrom collections import OrderedDict\nfrom functools import partial\nfrom typing import Tuple, List, Union, Iterable, Dict, Callable, Optional, cast\n\ntry:\n from typing import Literal\nexcept ImportError:\n from typing_extensions import Literal\n\nimport torch\n\nimport nni.retiarii.nn.pytorch as nn\nfrom nni.retiarii import model_wrapper\n\nfrom .utils.fixed import FixedFactory\nfrom .utils.pretrained import load_pretrained_weight\n\n\n# the following are NAS operations from\n# https://github.com/facebookresearch/unnas/blob/main/pycls/models/nas/operations.py\n\nOPS = {\n 'none': lambda C, stride, affine:\n Zero(stride),\n 'avg_pool_2x2': lambda C, stride, affine:\n nn.AvgPool2d(2, stride=stride, padding=0, count_include_pad=False),\n 'avg_pool_3x3': lambda C, stride, affine:\n nn.AvgPool2d(3, stride=stride, padding=1, count_include_pad=False),\n 'avg_pool_5x5': lambda C, stride, affine:\n nn.AvgPool2d(5, stride=stride, padding=2, count_include_pad=False),\n 'max_pool_2x2': lambda C, stride, affine:\n nn.MaxPool2d(2, stride=stride, padding=0),\n 'max_pool_3x3': lambda C, stride, affine:\n nn.MaxPool2d(3, stride=stride, padding=1),\n 'max_pool_5x5': lambda C, stride, affine:\n nn.MaxPool2d(5, stride=stride, padding=2),\n 'max_pool_7x7': lambda C, stride, affine:\n nn.MaxPool2d(7, stride=stride, padding=3),\n 'skip_connect': lambda C, stride, affine:\n nn.Identity() if stride == 1 else FactorizedReduce(C, C, affine=affine),\n 'conv_1x1': lambda C, stride, affine:\n nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C, C, 1, stride=stride, padding=0, bias=False),\n nn.BatchNorm2d(C, affine=affine)\n ),\n 'conv_3x3': lambda C, stride, affine:\n nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C, C, 3, stride=stride, padding=1, bias=False),\n nn.BatchNorm2d(C, affine=affine)\n ),\n 'sep_conv_3x3': lambda C, stride, affine:\n SepConv(C, C, 3, stride, 1, affine=affine),\n 'sep_conv_5x5': lambda C, stride, affine:\n SepConv(C, C, 5, stride, 2, affine=affine),\n 'sep_conv_7x7': lambda C, stride, affine:\n SepConv(C, C, 7, stride, 3, affine=affine),\n 'dil_conv_3x3': lambda C, stride, affine:\n DilConv(C, C, 3, stride, 2, 2, affine=affine),\n 'dil_conv_5x5': lambda C, stride, affine:\n DilConv(C, C, 5, stride, 4, 2, affine=affine),\n 'dil_sep_conv_3x3': lambda C, stride, affine:\n DilSepConv(C, C, 3, stride, 2, 2, affine=affine),\n 'conv_3x1_1x3': lambda C, stride, affine:\n nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C, C, (1, 3), stride=(1, stride), padding=(0, 1), bias=False),\n nn.Conv2d(C, C, (3, 1), stride=(stride, 1), padding=(1, 0), bias=False),\n nn.BatchNorm2d(C, affine=affine)\n ),\n 'conv_7x1_1x7': lambda C, stride, affine:\n nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C, C, (1, 7), stride=(1, stride), padding=(0, 3), bias=False),\n nn.Conv2d(C, C, (7, 1), stride=(stride, 1), padding=(3, 0), bias=False),\n nn.BatchNorm2d(C, affine=affine)\n ),\n}\n\n\nclass ReLUConvBN(nn.Sequential):\n\n def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):\n super().__init__(\n nn.ReLU(inplace=False),\n nn.Conv2d(\n C_in, C_out, kernel_size, stride=stride,\n padding=padding, bias=False\n ),\n nn.BatchNorm2d(C_out, affine=affine)\n )\n\n\nclass DilConv(nn.Sequential):\n\n def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation, affine=True):\n super().__init__(\n nn.ReLU(inplace=False),\n nn.Conv2d(\n C_in, C_in, kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, groups=C_in, bias=False\n ),\n nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_out, affine=affine),\n )\n\n\nclass SepConv(nn.Sequential):\n\n def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):\n super().__init__(\n nn.ReLU(inplace=False),\n nn.Conv2d(\n C_in, C_in, kernel_size=kernel_size, stride=stride,\n padding=padding, groups=C_in, bias=False\n ),\n nn.Conv2d(C_in, C_in, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_in, affine=affine),\n nn.ReLU(inplace=False),\n nn.Conv2d(\n C_in, C_in, kernel_size=kernel_size, stride=1,\n padding=padding, groups=C_in, bias=False\n ),\n nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_out, affine=affine),\n )\n\n\nclass DilSepConv(nn.Sequential):\n\n def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation, affine=True):\n super().__init__(\n nn.ReLU(inplace=False),\n nn.Conv2d(\n C_in, C_in, kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, groups=C_in, bias=False\n ),\n nn.Conv2d(C_in, C_in, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_in, affine=affine),\n nn.ReLU(inplace=False),\n nn.Conv2d(\n C_in, C_in, kernel_size=kernel_size, stride=1,\n padding=padding, dilation=dilation, groups=C_in, bias=False\n ),\n nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_out, affine=affine),\n )\n\n\nclass Zero(nn.Module):\n\n def __init__(self, stride):\n super().__init__()\n self.stride = stride\n\n def forward(self, x):\n if self.stride == 1:\n return x.mul(0.)\n return x[:, :, ::self.stride, ::self.stride].mul(0.)\n\n\nclass FactorizedReduce(nn.Module):\n\n def __init__(self, C_in, C_out, affine=True):\n super().__init__()\n if isinstance(C_out, int):\n assert C_out % 2 == 0\n else: # is a value choice\n assert all(c % 2 == 0 for c in C_out.all_options())\n self.relu = nn.ReLU(inplace=False)\n self.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)\n self.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)\n self.bn = nn.BatchNorm2d(C_out, affine=affine)\n self.pad = nn.ConstantPad2d((0, 1, 0, 1), 0)\n\n def forward(self, x):\n x = self.relu(x)\n y = self.pad(x)\n out = torch.cat([self.conv_1(x), self.conv_2(y[:, :, 1:, 1:])], dim=1)\n out = self.bn(out)\n return out\n\n\nclass DropPath_(nn.Module):\n # https://github.com/khanrc/pt.darts/blob/0.1/models/ops.py\n def __init__(self, drop_prob=0.):\n super().__init__()\n self.drop_prob = drop_prob\n\n def forward(self, x):\n if self.training and self.drop_prob > 0.:\n keep_prob = 1. - self.drop_prob\n mask = torch.zeros((x.size(0), 1, 1, 1), dtype=torch.float, device=x.device).bernoulli_(keep_prob)\n return x.div(keep_prob).mul(mask)\n return x\n\n\nclass AuxiliaryHead(nn.Module):\n def __init__(self, C: int, num_labels: int, dataset: Literal['imagenet', 'cifar']):\n super().__init__()\n if dataset == 'imagenet':\n # assuming input size 14x14\n stride = 2\n elif dataset == 'cifar':\n stride = 3\n\n self.features = nn.Sequential(\n nn.ReLU(inplace=True),\n nn.AvgPool2d(5, stride=stride, padding=0, count_include_pad=False),\n nn.Conv2d(C, 128, 1, bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, 768, 2, bias=False),\n nn.BatchNorm2d(768),\n nn.ReLU(inplace=True)\n )\n self.classifier = nn.Linear(768, num_labels)\n\n def forward(self, x):\n x = self.features(x)\n x = self.classifier(x.view(x.size(0), -1))\n return x\n\n\nclass SequentialBreakdown(nn.Sequential):\n \"\"\"Return all layers of a sequential.\"\"\"\n\n def __init__(self, sequential: nn.Sequential):\n super().__init__(OrderedDict(sequential.named_children()))\n\n def forward(self, inputs):\n result = []\n for module in self:\n inputs = module(inputs)\n result.append(inputs)\n return result\n\n\nclass CellPreprocessor(nn.Module):\n \"\"\"\n Aligning the shape of predecessors.\n\n If the last cell is a reduction cell, ``pre0`` should be ``FactorizedReduce`` instead of ``ReLUConvBN``.\n See :class:`CellBuilder` on how to calculate those channel numbers.\n \"\"\"\n\n def __init__(self, C_pprev: nn.MaybeChoice[int], C_prev: nn.MaybeChoice[int], C: nn.MaybeChoice[int], last_cell_reduce: bool) -> None:\n super().__init__()\n\n if last_cell_reduce:\n self.pre0 = FactorizedReduce(cast(int, C_pprev), cast(int, C))\n else:\n self.pre0 = ReLUConvBN(cast(int, C_pprev), cast(int, C), 1, 1, 0)\n self.pre1 = ReLUConvBN(cast(int, C_prev), cast(int, C), 1, 1, 0)\n\n def forward(self, cells):\n assert len(cells) == 2\n pprev, prev = cells\n pprev = self.pre0(pprev)\n prev = self.pre1(prev)\n\n return [pprev, prev]\n\n\nclass CellPostprocessor(nn.Module):\n \"\"\"\n The cell outputs previous cell + this cell, so that cells can be directly chained.\n \"\"\"\n\n def forward(self, this_cell, previous_cells):\n return [previous_cells[-1], this_cell]\n\n\nclass CellBuilder:\n \"\"\"The cell builder is used in Repeat.\n Builds an cell each time it's \"called\".\n Note that the builder is ephemeral, it can only be called once for every index.\n \"\"\"\n\n def __init__(self, op_candidates: List[str],\n C_prev_in: nn.MaybeChoice[int],\n C_in: nn.MaybeChoice[int],\n C: nn.MaybeChoice[int],\n num_nodes: int,\n merge_op: Literal['all', 'loose_end'],\n first_cell_reduce: bool, last_cell_reduce: bool):\n self.C_prev_in = C_prev_in # This is the out channels of the cell before last cell.\n self.C_in = C_in # This is the out channesl of last cell.\n self.C = C # This is NOT C_out of this stage, instead, C_out = C * len(cell.output_node_indices)\n self.op_candidates = op_candidates\n self.num_nodes = num_nodes\n self.merge_op: Literal['all', 'loose_end'] = merge_op\n self.first_cell_reduce = first_cell_reduce\n self.last_cell_reduce = last_cell_reduce\n self._expect_idx = 0\n\n # It takes an index that is the index in the repeat.\n # Number of predecessors for each cell is fixed to 2.\n self.num_predecessors = 2\n\n # Number of ops per node is fixed to 2.\n self.num_ops_per_node = 2\n\n def op_factory(self, node_index: int, op_index: int, input_index: Optional[int], *,\n op: str, channels: int, is_reduction_cell: bool):\n if is_reduction_cell and (\n input_index is None or input_index < self.num_predecessors\n ): # could be none when constructing search sapce\n stride = 2\n else:\n stride = 1\n return OPS[op](channels, stride, True)\n\n def __call__(self, repeat_idx: int):\n if self._expect_idx != repeat_idx:\n raise ValueError(f'Expect index {self._expect_idx}, found {repeat_idx}')\n\n # Reduction cell means stride = 2 and channel multiplied by 2.\n is_reduction_cell = repeat_idx == 0 and self.first_cell_reduce\n\n # self.C_prev_in, self.C_in, self.last_cell_reduce are updated after each cell is built.\n preprocessor = CellPreprocessor(self.C_prev_in, self.C_in, self.C, self.last_cell_reduce)\n\n ops_factory: Dict[str, Callable[[int, int, Optional[int]], nn.Module]] = {}\n for op in self.op_candidates:\n ops_factory[op] = partial(self.op_factory, op=op, channels=cast(int, self.C), is_reduction_cell=is_reduction_cell)\n\n cell = nn.Cell(ops_factory, self.num_nodes, self.num_ops_per_node, self.num_predecessors, self.merge_op,\n preprocessor=preprocessor, postprocessor=CellPostprocessor(),\n label='reduce' if is_reduction_cell else 'normal')\n\n # update state\n self.C_prev_in = self.C_in\n self.C_in = self.C * len(cell.output_node_indices)\n self.last_cell_reduce = is_reduction_cell\n self._expect_idx += 1\n\n return cell\n\n\n_INIT_PARAMETER_DOCS = \"\"\"\n\n Parameters\n ----------\n width : int or tuple of int\n A fixed initial width or a tuple of widths to choose from.\n num_cells : int or tuple of int\n A fixed number of cells (depths) to stack, or a tuple of depths to choose from.\n dataset : \"cifar\" | \"imagenet\"\n The essential differences are in \"stem\" cells, i.e., how they process the raw image input.\n Choosing \"imagenet\" means more downsampling at the beginning of the network.\n auxiliary_loss : bool\n If true, another auxiliary classification head will produce the another prediction.\n This makes the output of network two logits in the training phase.\n\n\"\"\"\n\n\nclass NDS(nn.Module):\n __doc__ = \"\"\"\n The unified version of NASNet search space.\n\n We follow the implementation in\n `unnas <https://github.com/facebookresearch/unnas/blob/main/pycls/models/nas/nas.py>`__.\n See `On Network Design Spaces for Visual Recognition <https://arxiv.org/abs/1905.13214>`__ for details.\n\n Different NAS papers usually differ in the way that they specify ``op_candidates`` and ``merge_op``.\n ``dataset`` here is to give a hint about input resolution, so as to create reasonable stem and auxiliary heads.\n\n NDS has a speciality that it has mutable depths/widths.\n This is implemented by accepting a list of int as ``num_cells`` / ``width``.\n \"\"\" + _INIT_PARAMETER_DOCS + \"\"\"\n op_candidates : list of str\n List of operator candidates. Must be from ``OPS``.\n merge_op : ``all`` or ``loose_end``\n See :class:`~nni.retiarii.nn.pytorch.Cell`.\n num_nodes_per_cell : int\n See :class:`~nni.retiarii.nn.pytorch.Cell`.\n \"\"\"\n\n def __init__(self,\n op_candidates: List[str],\n merge_op: Literal['all', 'loose_end'] = 'all',\n num_nodes_per_cell: int = 4,\n width: Union[Tuple[int, ...], int] = 16,\n num_cells: Union[Tuple[int, ...], int] = 20,\n dataset: Literal['cifar', 'imagenet'] = 'imagenet',\n auxiliary_loss: bool = False):\n super().__init__()\n\n self.dataset = dataset\n self.num_labels = 10 if dataset == 'cifar' else 1000\n self.auxiliary_loss = auxiliary_loss\n\n # preprocess the specified width and depth\n if isinstance(width, Iterable):\n C = nn.ValueChoice(list(width), label='width')\n else:\n C = width\n\n self.num_cells: nn.MaybeChoice[int] = cast(int, num_cells)\n if isinstance(num_cells, Iterable):\n self.num_cells = nn.ValueChoice(list(num_cells), label='depth')\n num_cells_per_stage = [(i + 1) * self.num_cells // 3 - i * self.num_cells // 3 for i in range(3)]\n\n # auxiliary head is different for network targetted at different datasets\n if dataset == 'imagenet':\n self.stem0 = nn.Sequential(\n nn.Conv2d(3, cast(int, C // 2), kernel_size=3, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(cast(int, C // 2)),\n nn.ReLU(inplace=True),\n nn.Conv2d(cast(int, C // 2), cast(int, C), 3, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(C),\n )\n self.stem1 = nn.Sequential(\n nn.ReLU(inplace=True),\n nn.Conv2d(cast(int, C), cast(int, C), 3, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(C),\n )\n C_pprev = C_prev = C_curr = C\n last_cell_reduce = True\n elif dataset == 'cifar':\n self.stem = nn.Sequential(\n nn.Conv2d(3, cast(int, 3 * C), 3, padding=1, bias=False),\n nn.BatchNorm2d(cast(int, 3 * C))\n )\n C_pprev = C_prev = 3 * C\n C_curr = C\n last_cell_reduce = False\n\n self.stages = nn.ModuleList()\n for stage_idx in range(3):\n if stage_idx > 0:\n C_curr *= 2\n # For a stage, we get C_in, C_curr, and C_out.\n # C_in is only used in the first cell.\n # C_curr is number of channels for each operator in current stage.\n # C_out is usually `C * num_nodes_per_cell` because of concat operator.\n cell_builder = CellBuilder(op_candidates, C_pprev, C_prev, C_curr, num_nodes_per_cell,\n merge_op, stage_idx > 0, last_cell_reduce)\n stage = nn.Repeat(cell_builder, num_cells_per_stage[stage_idx])\n self.stages.append(stage)\n\n # C_pprev is output channel number of last second cell among all the cells already built.\n if len(stage) > 1:\n # Contains more than one cell\n C_pprev = len(cast(nn.Cell, stage[-2]).output_node_indices) * C_curr\n else:\n # Look up in the out channels of last stage.\n C_pprev = C_prev\n\n # This was originally,\n # C_prev = num_nodes_per_cell * C_curr.\n # but due to loose end, it becomes,\n C_prev = len(cast(nn.Cell, stage[-1]).output_node_indices) * C_curr\n\n # Useful in aligning the pprev and prev cell.\n last_cell_reduce = cell_builder.last_cell_reduce\n\n if stage_idx == 2:\n C_to_auxiliary = C_prev\n\n if auxiliary_loss:\n assert isinstance(self.stages[2], nn.Sequential), 'Auxiliary loss can only be enabled in retrain mode.'\n self.stages[2] = SequentialBreakdown(cast(nn.Sequential, self.stages[2]))\n self.auxiliary_head = AuxiliaryHead(C_to_auxiliary, self.num_labels, dataset=self.dataset) # type: ignore\n\n self.global_pooling = nn.AdaptiveAvgPool2d((1, 1))\n self.classifier = nn.Linear(cast(int, C_prev), self.num_labels)\n\n def forward(self, inputs):\n if self.dataset == 'imagenet':\n s0 = self.stem0(inputs)\n s1 = self.stem1(s0)\n else:\n s0 = s1 = self.stem(inputs)\n\n for stage_idx, stage in enumerate(self.stages):\n if stage_idx == 2 and self.auxiliary_loss:\n s = list(stage([s0, s1]).values())\n s0, s1 = s[-1]\n if self.training:\n # auxiliary loss is attached to the first cell of the last stage.\n logits_aux = self.auxiliary_head(s[0][1])\n else:\n s0, s1 = stage([s0, s1])\n\n out = self.global_pooling(s1)\n logits = self.classifier(out.view(out.size(0), -1))\n if self.training and self.auxiliary_loss:\n return logits, logits_aux # type: ignore\n else:\n return logits\n\n def set_drop_path_prob(self, drop_prob):\n \"\"\"\n Set the drop probability of Drop-path in the network.\n Reference: `FractalNet: Ultra-Deep Neural Networks without Residuals <https://arxiv.org/pdf/1605.07648v4.pdf>`__.\n \"\"\"\n for module in self.modules():\n if isinstance(module, DropPath_):\n module.drop_prob = drop_prob\n\n @classmethod\n def fixed_arch(cls, arch: dict) -> FixedFactory:\n return FixedFactory(cls, arch)\n\n\n@model_wrapper\nclass NASNet(NDS):\n __doc__ = \"\"\"\n Search space proposed in `Learning Transferable Architectures for Scalable Image Recognition <https://arxiv.org/abs/1707.07012>`__.\n\n It is built upon :class:`~nni.retiarii.nn.pytorch.Cell`, and implemented based on :class:`~NDS`.\n Its operator candidates are :attribute:`~NASNet.NASNET_OPS`.\n It has 5 nodes per cell, and the output is concatenation of nodes not used as input to other nodes.\n \"\"\" + _INIT_PARAMETER_DOCS\n\n NASNET_OPS = [\n 'skip_connect',\n 'conv_3x1_1x3',\n 'conv_7x1_1x7',\n 'dil_conv_3x3',\n 'avg_pool_3x3',\n 'max_pool_3x3',\n 'max_pool_5x5',\n 'max_pool_7x7',\n 'conv_1x1',\n 'conv_3x3',\n 'sep_conv_3x3',\n 'sep_conv_5x5',\n 'sep_conv_7x7',\n ]\n\n def __init__(self,\n width: Union[Tuple[int, ...], int] = (16, 24, 32),\n num_cells: Union[Tuple[int, ...], int] = (4, 8, 12, 16, 20),\n dataset: Literal['cifar', 'imagenet'] = 'cifar',\n auxiliary_loss: bool = False):\n super().__init__(self.NASNET_OPS,\n merge_op='loose_end',\n num_nodes_per_cell=5,\n width=width,\n num_cells=num_cells,\n dataset=dataset,\n auxiliary_loss=auxiliary_loss)\n\n\n@model_wrapper\nclass ENAS(NDS):\n __doc__ = \"\"\"Search space proposed in `Efficient neural architecture search via parameter sharing <https://arxiv.org/abs/1802.03268>`__.\n\n It is built upon :class:`~nni.retiarii.nn.pytorch.Cell`, and implemented based on :class:`~NDS`.\n Its operator candidates are :attribute:`~ENAS.ENAS_OPS`.\n It has 5 nodes per cell, and the output is concatenation of nodes not used as input to other nodes.\n \"\"\" + _INIT_PARAMETER_DOCS\n\n ENAS_OPS = [\n 'skip_connect',\n 'sep_conv_3x3',\n 'sep_conv_5x5',\n 'avg_pool_3x3',\n 'max_pool_3x3',\n ]\n\n def __init__(self,\n width: Union[Tuple[int, ...], int] = (16, 24, 32),\n num_cells: Union[Tuple[int, ...], int] = (4, 8, 12, 16, 20),\n dataset: Literal['cifar', 'imagenet'] = 'cifar',\n auxiliary_loss: bool = False):\n super().__init__(self.ENAS_OPS,\n merge_op='loose_end',\n num_nodes_per_cell=5,\n width=width,\n num_cells=num_cells,\n dataset=dataset,\n auxiliary_loss=auxiliary_loss)\n\n\n@model_wrapper\nclass AmoebaNet(NDS):\n __doc__ = \"\"\"Search space proposed in\n `Regularized evolution for image classifier architecture search <https://arxiv.org/abs/1802.01548>`__.\n\n It is built upon :class:`~nni.retiarii.nn.pytorch.Cell`, and implemented based on :class:`~NDS`.\n Its operator candidates are :attribute:`~AmoebaNet.AMOEBA_OPS`.\n It has 5 nodes per cell, and the output is concatenation of nodes not used as input to other nodes.\n \"\"\" + _INIT_PARAMETER_DOCS\n\n AMOEBA_OPS = [\n 'skip_connect',\n 'sep_conv_3x3',\n 'sep_conv_5x5',\n 'sep_conv_7x7',\n 'avg_pool_3x3',\n 'max_pool_3x3',\n 'dil_sep_conv_3x3',\n 'conv_7x1_1x7',\n ]\n\n def __init__(self,\n width: Union[Tuple[int, ...], int] = (16, 24, 32),\n num_cells: Union[Tuple[int, ...], int] = (4, 8, 12, 16, 20),\n dataset: Literal['cifar', 'imagenet'] = 'cifar',\n auxiliary_loss: bool = False):\n\n super().__init__(self.AMOEBA_OPS,\n merge_op='loose_end',\n num_nodes_per_cell=5,\n width=width,\n num_cells=num_cells,\n dataset=dataset,\n auxiliary_loss=auxiliary_loss)\n\n\n@model_wrapper\nclass PNAS(NDS):\n __doc__ = \"\"\"Search space proposed in\n `Progressive neural architecture search <https://arxiv.org/abs/1712.00559>`__.\n\n It is built upon :class:`~nni.retiarii.nn.pytorch.Cell`, and implemented based on :class:`~NDS`.\n Its operator candidates are :attribute:`~PNAS.PNAS_OPS`.\n It has 5 nodes per cell, and the output is concatenation of all nodes in the cell.\n \"\"\" + _INIT_PARAMETER_DOCS\n\n PNAS_OPS = [\n 'sep_conv_3x3',\n 'sep_conv_5x5',\n 'sep_conv_7x7',\n 'conv_7x1_1x7',\n 'skip_connect',\n 'avg_pool_3x3',\n 'max_pool_3x3',\n 'dil_conv_3x3',\n ]\n\n def __init__(self,\n width: Union[Tuple[int, ...], int] = (16, 24, 32),\n num_cells: Union[Tuple[int, ...], int] = (4, 8, 12, 16, 20),\n dataset: Literal['cifar', 'imagenet'] = 'cifar',\n auxiliary_loss: bool = False):\n super().__init__(self.PNAS_OPS,\n merge_op='all',\n num_nodes_per_cell=5,\n width=width,\n num_cells=num_cells,\n dataset=dataset,\n auxiliary_loss=auxiliary_loss)\n\n\n@model_wrapper\nclass DARTS(NDS):\n __doc__ = \"\"\"Search space proposed in `Darts: Differentiable architecture search <https://arxiv.org/abs/1806.09055>`__.\n\n It is built upon :class:`~nni.retiarii.nn.pytorch.Cell`, and implemented based on :class:`~NDS`.\n Its operator candidates are :attribute:`~DARTS.DARTS_OPS`.\n It has 4 nodes per cell, and the output is concatenation of all nodes in the cell.\n \"\"\" + _INIT_PARAMETER_DOCS\n\n DARTS_OPS = [\n 'none',\n 'max_pool_3x3',\n 'avg_pool_3x3',\n 'skip_connect',\n 'sep_conv_3x3',\n 'sep_conv_5x5',\n 'dil_conv_3x3',\n 'dil_conv_5x5',\n ]\n\n def __init__(self,\n width: Union[Tuple[int, ...], int] = (16, 24, 32),\n num_cells: Union[Tuple[int, ...], int] = (4, 8, 12, 16, 20),\n dataset: Literal['cifar', 'imagenet'] = 'cifar',\n auxiliary_loss: bool = False):\n super().__init__(self.DARTS_OPS,\n merge_op='all',\n num_nodes_per_cell=4,\n width=width,\n num_cells=num_cells,\n dataset=dataset,\n auxiliary_loss=auxiliary_loss)\n\n @classmethod\n def load_searched_model(\n cls, name: str,\n pretrained: bool = False, download: bool = False, progress: bool = True\n ) -> nn.Module:\n\n init_kwargs = {} # all default\n\n if name == 'darts-v2':\n init_kwargs.update(\n num_cells=20,\n width=36,\n )\n arch = {\n 'normal/op_2_0': 'sep_conv_3x3',\n 'normal/op_2_1': 'sep_conv_3x3',\n 'normal/input_2_0': 0,\n 'normal/input_2_1': 1,\n 'normal/op_3_0': 'sep_conv_3x3',\n 'normal/op_3_1': 'sep_conv_3x3',\n 'normal/input_3_0': 0,\n 'normal/input_3_1': 1,\n 'normal/op_4_0': 'sep_conv_3x3',\n 'normal/op_4_1': 'skip_connect',\n 'normal/input_4_0': 1,\n 'normal/input_4_1': 0,\n 'normal/op_5_0': 'skip_connect',\n 'normal/op_5_1': 'dil_conv_3x3',\n 'normal/input_5_0': 0,\n 'normal/input_5_1': 2,\n 'reduce/op_2_0': 'max_pool_3x3',\n 'reduce/op_2_1': 'max_pool_3x3',\n 'reduce/input_2_0': 0,\n 'reduce/input_2_1': 1,\n 'reduce/op_3_0': 'skip_connect',\n 'reduce/op_3_1': 'max_pool_3x3',\n 'reduce/input_3_0': 2,\n 'reduce/input_3_1': 1,\n 'reduce/op_4_0': 'max_pool_3x3',\n 'reduce/op_4_1': 'skip_connect',\n 'reduce/input_4_0': 0,\n 'reduce/input_4_1': 2,\n 'reduce/op_5_0': 'skip_connect',\n 'reduce/op_5_1': 'max_pool_3x3',\n 'reduce/input_5_0': 2,\n 'reduce/input_5_1': 1\n }\n\n else:\n raise ValueError(f'Unsupported architecture with name: {name}')\n\n model_factory = cls.fixed_arch(arch)\n model = model_factory(**init_kwargs)\n\n if pretrained:\n weight_file = load_pretrained_weight(name, download=download, progress=progress)\n pretrained_weights = torch.load(weight_file)\n model.load_state_dict(pretrained_weights)\n\n return model\n"
] |
[
[
"torch.load"
]
] |
rajasekar-venkatesan/MachineLearning_Python
|
[
"eaeed630edcae4aa29283d1de21fa175f0d6dec6"
] |
[
"kMeansCluster/my_kmeans.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndataset = pd.read_csv('Mall_Customers.csv')\nX = dataset.iloc[:,[3,4]].values\n\n#Using Elbow method\nfrom sklearn.cluster import KMeans\nwcss = []\nfor i in range(1,11):\n kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)\n kmeans.fit(X)\n wcss.append(kmeans.inertia_)\nplt.plot(range(1,11),wcss)\nplt.show()\n\nkmeans = KMeans(n_clusters = 5, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)\ny_kmeans = kmeans.fit_predict(X)\n\n#Visualizing\nplt.scatter(X[y_kmeans == 0,0],X[y_kmeans == 0,1],s = 100, c = 'red', label = 'Careful')\nplt.scatter(X[y_kmeans == 1,0],X[y_kmeans == 1,1],s = 100, c = 'blue', label = 'Standard')\nplt.scatter(X[y_kmeans == 2,0],X[y_kmeans == 2,1],s = 100, c = 'green', label = 'Target')\nplt.scatter(X[y_kmeans == 3,0],X[y_kmeans == 3,1],s = 100, c = 'cyan', label = 'Careless')\nplt.scatter(X[y_kmeans == 4,0],X[y_kmeans == 4,1],s = 100, c = 'magenta', label = 'Sensible')\n\nplt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s =300, c = 'yellow', label = 'Centeroids')\nplt.title('Clusters of Clients')\nplt.xlabel('Annual Income k$')\nplt.ylabel('Spending Score')\nplt.legend()\nplt.show()"
] |
[
[
"matplotlib.pyplot.xlabel",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show",
"pandas.read_csv"
]
] |
jonaschn/networkx
|
[
"7b4168bdb09275a2ed860b01b9dbb77a151d85c6"
] |
[
"networkx/algorithms/centrality/second_order.py"
] |
[
"\"\"\"Copyright (c) 2015 – Thomson Licensing, SAS\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted (subject to the limitations in the\ndisclaimer below) provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in the\ndocumentation and/or other materials provided with the distribution.\n\n* Neither the name of Thomson Licensing, or Technicolor, nor the names\nof its contributors may be used to endorse or promote products derived\nfrom this software without specific prior written permission.\n\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\nGRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT\nHOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\nIF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport networkx as nx\nfrom networkx.utils import not_implemented_for\n\n# Authors: Erwan Le Merrer (erwan.lemerrer@technicolor.com)\n\"\"\" Second order centrality measure.\"\"\"\n\n__all__ = [\"second_order_centrality\"]\n\n\n@not_implemented_for(\"directed\")\ndef second_order_centrality(G):\n \"\"\"Compute the second order centrality for nodes of G.\n\n The second order centrality of a given node is the standard deviation of\n the return times to that node of a perpetual random walk on G:\n\n Parameters\n ----------\n G : graph\n A NetworkX connected and undirected graph.\n\n Returns\n -------\n nodes : dictionary\n Dictionary keyed by node with second order centrality as the value.\n\n Examples\n --------\n >>> G = nx.star_graph(10)\n >>> soc = nx.second_order_centrality(G)\n >>> print(sorted(soc.items(), key=lambda x:x[1])[0][0]) # pick first id\n 0\n\n Raises\n ------\n NetworkXException\n If the graph G is empty, non connected or has negative weights.\n\n See Also\n --------\n betweenness_centrality\n\n Notes\n -----\n Lower values of second order centrality indicate higher centrality.\n\n The algorithm is from Kermarrec, Le Merrer, Sericola and Trédan [1]_.\n\n This code implements the analytical version of the algorithm, i.e.,\n there is no simulation of a random walk process involved. The random walk\n is here unbiased (corresponding to eq 6 of the paper [1]_), thus the\n centrality values are the standard deviations for random walk return times\n on the transformed input graph G (equal in-degree at each nodes by adding\n self-loops).\n\n Complexity of this implementation, made to run locally on a single machine,\n is O(n^3), with n the size of G, which makes it viable only for small\n graphs.\n\n References\n ----------\n .. [1] Anne-Marie Kermarrec, Erwan Le Merrer, Bruno Sericola, Gilles Trédan\n \"Second order centrality: Distributed assessment of nodes criticity in\n complex networks\", Elsevier Computer Communications 34(5):619-628, 2011.\n \"\"\"\n\n try:\n import numpy as np\n except ImportError as e:\n raise ImportError(\"Requires NumPy: http://numpy.org/\") from e\n\n n = len(G)\n\n if n == 0:\n raise nx.NetworkXException(\"Empty graph.\")\n if not nx.is_connected(G):\n raise nx.NetworkXException(\"Non connected graph.\")\n if any(d.get(\"weight\", 0) < 0 for u, v, d in G.edges(data=True)):\n raise nx.NetworkXException(\"Graph has negative edge weights.\")\n\n # balancing G for Metropolis-Hastings random walks\n G = nx.DiGraph(G)\n in_deg = dict(G.in_degree(weight=\"weight\"))\n d_max = max(in_deg.values())\n for i, deg in in_deg.items():\n if deg < d_max:\n G.add_edge(i, i, weight=d_max - deg)\n\n P = nx.to_numpy_array(G)\n P /= P.sum(axis=1)[:, np.newaxis] # to transition probability matrix\n\n def _Qj(P, j):\n P = P.copy()\n P[:, j] = 0\n return P\n\n M = np.empty([n, n])\n\n for i in range(n):\n M[:, i] = np.linalg.solve(\n np.identity(n) - _Qj(P, i), np.ones([n, 1])[:, 0]\n ) # eq 3\n\n return dict(\n zip(G.nodes, [np.sqrt(2 * np.sum(M[:, i]) - n * (n + 1)) for i in range(n)])\n ) # eq 6\n"
] |
[
[
"numpy.identity",
"numpy.sum",
"numpy.ones",
"numpy.empty"
]
] |
ucsky/opendata
|
[
"045de23706adf2166421d029ecc72456095dc76c",
"045de23706adf2166421d029ecc72456095dc76c"
] |
[
".dataset/dvfplus/setup-3-to-csv.py",
".dataset/INSEE-pop-200m-mesh/02-convert.py"
] |
[
"#!/usr/bin/env python\nfrom pdb import set_trace as bp\n\nimport json\nimport os\nimport re\nimport sys\nimport glob\n\nimport pandas as pd\nimport typer\nfrom typing import Optional\nfrom sqlalchemy import create_engine\nimport psycopg2\n\ndebug = False\nverbose = True\nuse_pandas = False\n\nif use_pandas:\n print(\"WARNING: under developpement, this will probably fail because of memory limitation.\")\n\nif debug:\n limit = 10000\n verbose = True\n\n\ndef main(\n path_cfg: str = typer.Argument(..., help=\"Data configuration file.\"),\n path_sec: Optional[str] = typer.Option(None, \"-sec\", help=\"Path to PG configuration file.\")\n):\n\n with open(path_cfg) as f_cfg:\n cfg = json.load(f_cfg)\n if verbose:\n print(cfg)\n\n\n if path_sec is None:\n pat = cfg['dbname'][0:15]\n lf = glob.glob(\n os.environ['HOME'] + '/.cred/ofm/database/'+pat+\"*.json\"\n )\n if len(lf) > 1:\n print(\"ERROR: there is more than one credential file matching.\")\n print(\" Please use -sec to pass path_sec.\")\n sys.exit(1)\n else:\n path_sec = lf[0]\n\n with open(path_sec) as f_sec:\n sec = json.load(f_sec)\n if verbose:\n print(sec)\n\n\n if not cfg['dbname'] == sec['POSTGRES_DBNAME']:\n typer.echo(\"ERROR: Something is wrong, database missmatch\")\n typer.echo(cfg['dbname'])\n typer.echo(sec['POSTGRES_DBNAME'])\n raise typer.Exit(1)\n\n output_dir = f\"{cfg['delivery']}/csv\"\n\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n\n # A long string that contains the necessary Postgres login information\n postgres_secret = ('postgresql://{username}:{password}@{ipaddress}:{port}/{dbname}'.format(\n username=sec['POSTGRES_USERNAME'],\n password=sec['POSTGRES_PASSWORD'],\n ipaddress=sec['POSTGRES_ADDRESS'],\n port=sec['POSTGRES_PORT'],\n dbname=sec['POSTGRES_DBNAME']\n ))\n # Create the engine\n engine = create_engine(postgres_secret)\n df = pd.read_sql_query('''\n SELECT *\n FROM pg_catalog.pg_tables\n WHERE schemaname != 'pg_catalog' AND \n schemaname != 'information_schema';''', engine)\n mask_dvf = (df.schemaname == 'dvf') | (df.schemaname == 'dvf_annexe')\n tablenames = (df[mask_dvf].schemaname + '.' + df[mask_dvf].tablename).tolist()\n del df\n \n conn = psycopg2.connect(host=sec['POSTGRES_ADDRESS'], port=sec['POSTGRES_PORT'], dbname=sec['POSTGRES_DBNAME'], user=sec['POSTGRES_USERNAME'], password=sec['POSTGRES_PASSWORD'])\n cur = conn.cursor()\n\n def read_write_table(tablename, conn, cur):\n\n # Because BigQuery GIS do not support EWKB (2021).\n df = pd.read_sql(f\"select * from {tablename} LIMIT 1\", conn)\n lcol = df.columns.tolist()\n for i, col in enumerate(lcol):\n if re.match(r\"^geom.*$\", col):\n \n #lcol[i] = f\"ST_AsText(ST_Transform({col}, 4326)) as {col}\"\n # If there is an importation problem try, GeoJSON\n #if col == 'geompar':\n # lcol[i] = f\"REPLACE(ST_AsGeoJSON(ST_Transform({col}, 4326)), '] ], [ [', '] ] ], [ [ [') as {col}\"\n # lcol[i] = f\"ST_AsGeoJSON(ST_MakeValid(ST_Transform({col}, 4326))) as {col}\"\n #else: \n lcol[i] = f\"ST_AsGeoJSON(ST_Transform({col}, 4326)) as {col}\"\n \n lcol = \", \".join(lcol)\n \n if debug:\n subquery = f\"SELECT {lcol} FROM {tablename} LIMIT {limit}\"\n else:\n subquery = f\"SELECT {lcol} FROM {tablename}\"\n \n # Use the COPY function on the SQL we created above.\n query = \"COPY ({0}) TO STDOUT WITH CSV HEADER\".format(subquery)\n\n # Set up a variable to store our file path and name.\n opath = output_dir+os.sep+tablename+\".csv\"\n\n try:\n with open(opath, 'w') as f_output:\n if verbose:\n print(\"dump with query:\")\n print(query)\n cur.copy_expert(query, f_output)\n if verbose:\n print(\"finish\")\n except psycopg2.Error as e:\n t_message = \"\\nERROR: \\n\" + str(e) + \\\n \"\\nsubquery: \" + \\\n subquery + \\\n \"\\nopath: \" + opath + \"\\n\\n\"\n print(t_message)\n raise\n\n def read_write_table_pd(tablename):\n if debug:\n df = pd.read_sql_query(\n f'''SELECT * FROM {tablename} LIMIT {limit}''',\n engine\n )\n else:\n df = pd.read_sql_query(\n f'''SELECT * FROM {tablename}''',\n engine\n )\n if verbose:\n print(df)\n opath = output_dir+os.sep+tablename+\".csv\"\n if verbose:\n print(opath)\n if os.path.exists(opath):\n typer.echo(f\"Skipping file {opath}\")\n else:\n if verbose:\n print(\"Writting table\")\n df.to_csv(opath, index=False)\n del df\n\n for it, tablename in enumerate(tablenames):\n if verbose:\n print(it+1, tablename)\n print(\"Loading table\")\n if use_pandas:\n read_write_table_pd(tablename)\n else:\n read_write_table(tablename, conn, cur)\n \n # Clean up: Close the database cursor and connection\n if not use_pandas:\n cur.close()\n conn.close()\n\nif __name__ == \"__main__\":\n typer.run(main)\n",
"import os\nimport json\nfrom simpledbf import Dbf5\nimport pandas as pd\nimport geopandas as gpd\n\n\nd_c = os.environ['OPENDATA_ROOT']+'/INSEE-pop-200m-mesh/200m-carreaux-metropole'\ndbf = Dbf5(f'{d_c}/car_m.dbf')\nprint(\"================================\")\nprint(\"Dataframe containing statistics:\")\ndfc0 = dbf.to_dataframe()\nprint(dfc0.head(3))\nprint(dfc0.info())\nprint(\"================================\")\nprint(\"Dataframe containing polygones:\")\ndfc1 = gpd.GeoDataFrame.from_file(f'{d_c}/car_m.mid')\nprint(dfc1.head(3))\nprint(dfc1.info())\nprint(dfc1.crs)\nprint(\"================================\")\nprint(\"Final dataframe:\")\ndf = pd.merge(dfc0, dfc1, on=['id', 'idINSPIRE'], how=\"inner\")\ndel dfc0\ndel dfc1\ngdf = gpd.GeoDataFrame(df)\ndel df\nprint(gdf.head())\nprint(gdf.info())\ngdf.to_file('carreaux.shp')\n"
] |
[
[
"pandas.read_sql",
"pandas.read_sql_query"
],
[
"pandas.merge"
]
] |
qi-zh/XenonPy
|
[
"e91c680c773022982b80686c9faaf962e304916d",
"e91c680c773022982b80686c9faaf962e304916d"
] |
[
"xenonpy/model/cgcnn.py",
"tests/datatools/test_boxcox.py"
] |
[
"# Copyright (c) 2019. TsumiNa. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nimport torch\nfrom torch import nn\n\n__all__ = ['ConvLayer', 'CrystalGraphConvNet']\n\n\nclass ConvLayer(nn.Module):\n \"\"\"\n Convolutional operation on graphs\n \"\"\"\n\n def __init__(self, atom_fea_len, nbr_fea_len):\n \"\"\"\n Initialize ConvLayer.\n\n Parameters\n ----------\n\n atom_fea_len: int\n Number of atom hidden features.\n nbr_fea_len: int\n Number of bond features.\n \"\"\"\n super(ConvLayer, self).__init__()\n self.atom_fea_len = atom_fea_len\n self.nbr_fea_len = nbr_fea_len\n self.fc_full = nn.Linear(2 * self.atom_fea_len + self.nbr_fea_len,\n 2 * self.atom_fea_len)\n self.sigmoid = nn.Sigmoid()\n self.softplus1 = nn.Softplus()\n self.bn1 = nn.BatchNorm1d(2 * self.atom_fea_len)\n self.bn2 = nn.BatchNorm1d(self.atom_fea_len)\n self.softplus2 = nn.Softplus()\n\n def forward(self, atom_in_fea, nbr_fea, nbr_fea_idx):\n \"\"\"\n Forward pass\n\n N: Total number of atoms in the batch\n M: Max number of neighbors\n\n Parameters\n ----------\n\n atom_in_fea: Variable(torch.Tensor) shape (N, atom_fea_len)\n Atom hidden features before convolution\n nbr_fea: Variable(torch.Tensor) shape (N, M, nbr_fea_len)\n Bond features of each atom's M neighbors\n nbr_fea_idx: torch.LongTensor shape (N, M)\n Indices of M neighbors of each atom\n\n Returns\n -------\n\n atom_out_fea: nn.Variable shape (N, atom_fea_len)\n Atom hidden features after convolution\n\n \"\"\"\n # TODO will there be problems with the index zero padding?\n N, M = nbr_fea_idx.shape\n # convolution\n atom_nbr_fea = atom_in_fea[nbr_fea_idx, :]\n total_nbr_fea = torch.cat(\n [atom_in_fea.unsqueeze(1).expand(N, M, self.atom_fea_len),\n atom_nbr_fea, nbr_fea], dim=2)\n total_gated_fea = self.fc_full(total_nbr_fea)\n total_gated_fea = self.bn1(total_gated_fea.view(\n -1, self.atom_fea_len * 2)).view(N, M, self.atom_fea_len * 2)\n nbr_filter, nbr_core = total_gated_fea.chunk(2, dim=2)\n nbr_filter = self.sigmoid(nbr_filter)\n nbr_core = self.softplus1(nbr_core)\n nbr_sumed = torch.sum(nbr_filter * nbr_core, dim=1)\n nbr_sumed = self.bn2(nbr_sumed)\n out = self.softplus2(atom_in_fea + nbr_sumed)\n return out\n\n\nclass CrystalGraphConvNet(nn.Module):\n \"\"\"\n Create a crystal graph convolutional neural network for predicting total\n material properties.\n\n See Also: [CGCNN]_.\n\n .. [CGCNN] `Crystal Graph Convolutional Neural Networks for an Accurate and Interpretable Prediction of Material Properties`__\n __ https://doi.org/10.1103/PhysRevLett.120.145301\n \"\"\"\n\n def __init__(self, orig_atom_fea_len, nbr_fea_len,\n atom_fea_len=64, n_conv=3, h_fea_len=128, n_h=1,\n classification=False):\n \"\"\"\n Initialize CrystalGraphConvNet.\n\n Parameters\n ----------\n\n orig_atom_fea_len: int\n Number of atom features in the input.\n nbr_fea_len: int\n Number of bond features.\n atom_fea_len: int\n Number of hidden atom features in the convolutional layers\n n_conv: int\n Number of convolutional layers\n h_fea_len: int\n Number of hidden features after pooling\n n_h: int\n Number of hidden layers after pooling\n \"\"\"\n super(CrystalGraphConvNet, self).__init__()\n self.classification = classification\n self.embedding = nn.Linear(orig_atom_fea_len, atom_fea_len)\n self.convs = nn.ModuleList([ConvLayer(atom_fea_len=atom_fea_len,\n nbr_fea_len=nbr_fea_len)\n for _ in range(n_conv)])\n self.conv_to_fc = nn.Linear(atom_fea_len, h_fea_len)\n self.conv_to_fc_softplus = nn.Softplus()\n if n_h > 1:\n self.fcs = nn.ModuleList([nn.Linear(h_fea_len, h_fea_len)\n for _ in range(n_h - 1)])\n self.softpluses = nn.ModuleList([nn.Softplus()\n for _ in range(n_h - 1)])\n if self.classification:\n self.fc_out = nn.Linear(h_fea_len, 2)\n else:\n self.fc_out = nn.Linear(h_fea_len, 1)\n if self.classification:\n self.logsoftmax = nn.LogSoftmax()\n self.dropout = nn.Dropout()\n\n def forward(self, atom_fea, nbr_fea, nbr_fea_idx, crystal_atom_idx):\n \"\"\"\n Forward pass\n\n N: Total number of atoms in the batch\n M: Max number of neighbors\n N0: Total number of crystals in the batch\n\n Parameters\n ----------\n\n atom_fea: Variable(torch.Tensor) shape (N, orig_atom_fea_len)\n Atom features from atom type\n nbr_fea: Variable(torch.Tensor) shape (N, M, nbr_fea_len)\n Bond features of each atom's M neighbors\n nbr_fea_idx: torch.LongTensor shape (N, M)\n Indices of M neighbors of each atom\n crystal_atom_idx: list of torch.LongTensor of length N0\n Mapping from the crystal idx to atom idx\n\n Returns\n -------\n\n prediction: nn.Variable shape (N, )\n Atom hidden features after convolution\n\n \"\"\"\n atom_fea = self.embedding(atom_fea)\n for conv_func in self.convs:\n atom_fea = conv_func(atom_fea, nbr_fea, nbr_fea_idx)\n crys_fea = self.pooling(atom_fea, crystal_atom_idx)\n crys_fea = self.conv_to_fc(self.conv_to_fc_softplus(crys_fea))\n crys_fea = self.conv_to_fc_softplus(crys_fea)\n if self.classification:\n crys_fea = self.dropout(crys_fea)\n if hasattr(self, 'fcs') and hasattr(self, 'softpluses'):\n for fc, softplus in zip(self.fcs, self.softpluses):\n crys_fea = softplus(fc(crys_fea))\n out = self.fc_out(crys_fea)\n if self.classification:\n out = self.logsoftmax(out)\n return out\n\n @staticmethod\n def pooling(atom_fea, crystal_atom_idx):\n \"\"\"\n Pooling the atom features to crystal features\n\n N: Total number of atoms in the batch\n N0: Total number of crystals in the batch\n\n Parameters\n ----------\n\n atom_fea: Variable(torch.Tensor) shape (N, atom_fea_len)\n Atom feature vectors of the batch\n crystal_atom_idx: list of torch.LongTensor of length N0\n Mapping from the crystal idx to atom idx\n \"\"\"\n assert sum([len(idx_map) for idx_map in crystal_atom_idx]) == \\\n atom_fea.data.shape[0]\n summed_fea = [torch.mean(atom_fea[idx_map], dim=0, keepdim=True)\n for idx_map in crystal_atom_idx]\n return torch.cat(summed_fea, dim=0)\n",
"# Copyright (c) 2019. yoshida-lab. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n\nimport numpy as np\nimport pytest\nfrom scipy.stats import boxcox\n\nfrom xenonpy.datatools.transform import BoxCox\n\n\n@pytest.fixture(scope='module')\ndef data():\n # ignore numpy warning\n import warnings\n print('ignore NumPy RuntimeWarning\\n')\n warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\n warnings.filterwarnings(\"ignore\", message=\"numpy.ndarray size changed\")\n\n # prepare test data\n raw = np.array([1., 2., 3., 4.])\n a = raw.reshape(-1, 1)\n raw_4x1 = a\n raw_4x4 = np.concatenate((a, a, a, a), axis=1)\n\n # raw_shift = raw - raw.min() + 1e-9\n a_, _ = boxcox(raw)\n a_ = a_.reshape(-1, 1)\n trans_4x1 = a_\n trans_4x4 = np.concatenate((a_, a_, a_, a_), axis=1)\n\n raw_err = np.array([1., 1., 1., 1.])\n a = raw_err.reshape(-1, 1)\n raw_err_4x1 = a\n raw_err_4x4 = np.concatenate((a, a, a, a), axis=1)\n\n a_ = np.log(raw_err)\n a_ = a_.reshape(-1, 1)\n trans_err_4x1 = a_\n trans_err_4x4 = np.concatenate((a_, a_, a_, a_), axis=1)\n yield raw_4x1, raw_4x4, trans_4x1, trans_4x4, raw_err_4x1, raw_err_4x4, trans_err_4x1, trans_err_4x4\n\n print('test over')\n\n\ndef test_transform_4x1_1(data):\n bc = BoxCox()\n trans = bc.fit_transform(data[0])\n assert np.all(trans == data[2])\n assert trans.shape == data[2].shape\n inverse = bc.inverse_transform(trans)\n assert np.allclose(inverse, data[0])\n assert inverse.shape == data[0].shape\n\n\ndef test_transform_4x1_2(data):\n from scipy.special import boxcox as bc_\n shift = 1e-5\n bc = BoxCox(shift=shift)\n _data = data[0] - 2.\n trans = bc.fit_transform(_data)\n tmp = bc_(_data + (shift - _data.min()), bc.lambda_[0])\n assert np.all(trans == tmp)\n inverse = bc.inverse_transform(trans)\n assert np.allclose(inverse, _data)\n\n\ndef test_transform_4x1_3(data):\n bc = BoxCox()\n bc.fit_transform(data[0])\n trans = bc.transform(data[0][:2])\n assert trans.shape == data[2][:2].shape\n assert np.all(trans == data[2][:2])\n inverse = bc.inverse_transform(trans)\n assert inverse.shape == data[0][:2].shape\n assert np.allclose(inverse, data[0][:2])\n\n\ndef test_transform_4x1_ravel_1(data):\n bc = BoxCox()\n trans = bc.fit_transform(data[0].ravel())\n assert np.all(trans == data[2].ravel())\n inverse = bc.inverse_transform(trans)\n assert np.allclose(inverse, data[0].ravel())\n\n\ndef test_transform_4x1_ravel_2(data):\n bc = BoxCox()\n bc.fit(data[0].ravel())\n trans = bc.transform((data[0].ravel())[:2])\n assert trans.shape == (data[2].ravel())[:2].shape\n assert np.all(trans == (data[2].ravel())[:2])\n inverse = bc.inverse_transform(trans)\n assert inverse.shape == (data[0].ravel())[:2].shape\n assert np.allclose(inverse, (data[0].ravel())[:2])\n\n\ndef test_transform_4x4_1(data):\n bc = BoxCox()\n bc.fit_transform(data[1])\n trans = bc.transform(data[1][:2])\n assert trans.shape == data[3][:2].shape\n assert np.all(trans == data[3][:2])\n inverse = bc.inverse_transform(trans)\n assert inverse.shape == data[1][:2].shape\n assert np.allclose(inverse, data[1][:2])\n\n\ndef test_transform_4x4_2(data):\n bc = BoxCox()\n trans = bc.fit_transform(data[1])\n assert np.all(trans == data[3])\n inverse = bc.inverse_transform(trans)\n assert np.allclose(inverse, data[1])\n\n\ndef test_transform_err_4x1(data):\n bc = BoxCox()\n trans = bc.fit_transform(data[4])\n assert np.all(trans == data[4])\n inverse = bc.inverse_transform(trans)\n assert np.all(inverse == data[4])\n\n\ndef test_transform_err_4x4(data):\n bc = BoxCox()\n trans = bc.fit_transform(data[5])\n assert np.all(trans == data[5])\n inverse = bc.inverse_transform(trans)\n assert np.all(inverse == data[5])\n\n\ndef test_transform_err_4x1_2(data):\n bc = BoxCox(on_err='nan')\n trans = bc.fit_transform(data[4])\n assert np.all(np.isnan(trans))\n\n\ndef test_transform_err_4x4_2(data):\n bc = BoxCox(on_err='nan')\n trans = bc.fit_transform(data[5])\n assert np.all(np.isnan(trans))\n\n\ndef test_transform_err_4x1_3(data):\n bc = BoxCox(on_err='log')\n trans = bc.fit_transform(data[4])\n assert np.all(trans == data[6])\n inverse = bc.inverse_transform(trans)\n assert np.all(inverse == data[4])\n\n\ndef test_transform_err_4x4_3(data):\n bc = BoxCox(on_err='log')\n trans = bc.fit_transform(data[5])\n assert np.all(trans == data[7])\n inverse = bc.inverse_transform(trans)\n assert np.all(inverse == data[5])\n\n\ndef test_transform_err():\n with pytest.raises(ValueError):\n bc = BoxCox(on_err='raise')\n bc.fit_transform([1, 1, 1])\n with pytest.raises(FloatingPointError):\n bc = BoxCox(on_err='raise')\n bc.fit_transform([1e20, 1, 1e20])\n\n\nif __name__ == \"__main__\":\n pytest.main()\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.LogSoftmax",
"torch.cat",
"torch.nn.Dropout",
"torch.nn.Sigmoid",
"torch.nn.BatchNorm1d",
"torch.nn.Softplus",
"torch.mean",
"torch.sum"
],
[
"numpy.concatenate",
"numpy.array",
"scipy.stats.boxcox",
"numpy.isnan",
"numpy.log",
"numpy.allclose",
"numpy.all"
]
] |
claramaine/t-recs
|
[
"b7e66eda8ab2549119e81b95388fcbd5cb387f51"
] |
[
"trecs/tests/test_components.py"
] |
[
"from trecs.models.recommender import SystemStateModule\nfrom trecs.components import PredictedUserProfiles\nimport numpy as np\n\n\nclass TestComponents:\n def test_system_state(self):\n profiles = PredictedUserProfiles(np.zeros((5, 5)))\n sys = SystemStateModule()\n sys.add_state_variable(profiles)\n\n # increment profile twice\n for _ in range(2):\n profiles.value += 1\n for component in sys._system_state:\n component.store_state()\n\n assert len(profiles.state_history) == 3\n np.testing.assert_array_equal(profiles.state_history[0], np.zeros((5, 5)))\n np.testing.assert_array_equal(profiles.state_history[1], 1 * np.ones((5, 5)))\n np.testing.assert_array_equal(profiles.state_history[2], 2 * np.ones((5, 5)))\n\n def test_closed_logger(self):\n profiles = PredictedUserProfiles(np.zeros((5, 5)))\n logger = profiles._logger.logger # pylint: disable=protected-access\n handler = profiles._logger.handler # pylint: disable=protected-access\n assert len(logger.handlers) > 0 # before garbage collection\n del profiles\n # after garbage collection, handler should be closed\n assert handler not in logger.handlers\n"
] |
[
[
"numpy.ones",
"numpy.zeros"
]
] |
cboulay/lazy_ops
|
[
"4d9f1a91cb6a42d8c804a9c3f93e7a62e841162b"
] |
[
"tests/test_dsetview.py"
] |
[
"import numpy as np\nfrom lazy_ops import DatasetView, lazy_transpose\nimport secrets\nfrom numpy.testing import assert_array_equal\nimport unittest\nimport tempfile\nfrom functools import wraps\nimport h5py\nimport zarr\nimport pytest\n\n# Define decorator to iterate over dset_list\ndef dset_iterator(f):\n @wraps(f)\n def wrapper(self, *args, **kwargs):\n for self.dset, self.dsetview in zip(self.dset_list, self.dsetview_list):\n f(self, *args, **kwargs)\n return wrapper\n\nclass LazyOpsBase(object):\n\n srand = secrets.SystemRandom()\n\n @classmethod\n def _slices(cls,shape):\n ''' find an appropriate tuple of slices '''\n return tuple(slice(cls.srand.randint(~s-1, s+1), cls.srand.randint(~s-1, s+1),\n cls.srand.randint(1, s)) for s in shape)\n\n @classmethod\n def _axis(cls,n):\n ''' find an appropriate tuple of axes given number of dimensions '''\n axes = list(range(n))\n cls.srand.shuffle(axes)\n return axes\n\n @classmethod\n def _int_indexing(cls,shape):\n ''' find an appropriate tuple of integers '''\n return tuple(cls.srand.randint(0, s-1) for s in shape)\n\n @classmethod\n def _array_indexing(cls,shape):\n ''' find an appropriate tuple with a single array index '''\n single_array_dim = cls.srand.randrange(0,len(shape))\n single_array_len = cls.srand.randrange(0,shape[single_array_dim])\n single_array_indexing = sorted(cls.srand.sample(range(shape[single_array_dim]),\n single_array_len))\n return tuple(slice(None,None,None) if i != single_array_dim else single_array_indexing\n for i in range(len(shape)))\n\n @classmethod\n def _bool_indexing(cls,shape):\n ''' find an appropriate tuple with a single array index '''\n single_array_dim = cls.srand.randrange(0,len(shape))\n single_bool_indexing = np.array(cls.srand.choices([True,False], k=shape[single_array_dim]))\n return tuple(slice(None,None,None) if i != single_array_dim else single_bool_indexing\n for i in range(len(shape)))\n\n @classmethod\n def _slices_and_int(cls,shape):\n ''' find an appropriate tuple of slices and integers '''\n return tuple(slice(cls.srand.randint(~s-1, s+1), cls.srand.randint(~s-1, s+1),\n cls.srand.randint(1, s))\n if cls.srand.choice([True, False]) else\n cls.srand.randint(0, s-1)\n for s in shape)\n\n @classmethod\n def _slices_and_array(cls,shape, single_array_dim):\n ''' find an appropriate tuple of slices and a single array index'''\n single_array_len = cls.srand.randrange(0,shape[single_array_dim])\n single_array_indexing = sorted(cls.srand.sample(range(shape[single_array_dim]),\n single_array_len))\n return tuple(slice(cls.srand.randint(~s-1, s+1), cls.srand.randint(~s-1, s+1),\n cls.srand.randint(1, s))\n if i != single_array_dim else\n single_array_indexing\n for i, s in enumerate(shape))\n\n @classmethod\n def _slices_and_bool(cls,shape, single_array_dim):\n ''' find an appropriate tuple of slices and a single array index'''\n single_bool_indexing = np.array(cls.srand.choices([True,False], k=shape[single_array_dim]))\n return tuple(slice(cls.srand.randint(~s-1, s+1), cls.srand.randint(~s-1, s+1),\n cls.srand.randint(1, s))\n if i != single_array_dim else\n single_bool_indexing\n for i, s in enumerate(shape))\n\n\n ##########################################\n # basic tests #\n ##########################################\n\n @dset_iterator\n def test_dsetview_array(self):\n # test __array__ read\n assert_array_equal(self.dset, self.dsetview)\n\n @dset_iterator\n def test_dsetview_nonlazy_slicing(self):\n # test __getitem__ read\n assert_array_equal(self.dset,self.dsetview[()])\n # test __getitem__ single slice read\n assert_array_equal(self.dset,self.dsetview[:])\n slices = self._slices(self.dset.shape)\n assert_array_equal(self.dset[slices], self.dsetview[slices])\n\n ##########################################\n # tests for single lazy operation calls #\n ##########################################\n\n @dset_iterator\n def test_dsetview_lazy_slice(self):\n # test __getitem__ read after lazy_slice\n assert_array_equal(self.dset, self.dsetview.lazy_slice[()])\n # test __getitem__ read after lazy_slice, single slice\n assert_array_equal(self.dset, self.dsetview.lazy_slice[:])\n slices = self._slices(self.dset.shape)\n assert_array_equal(self.dset[slices], self.dsetview.lazy_slice[slices])\n\n @dset_iterator\n def test_dsetview_lazy_slice_lower_dimensions(self):\n for num_slice_dims in range(1, len(self.dset.shape)+1):\n slices = self._slices(self.dset.shape[:num_slice_dims])\n # test __getitem__ read specifying lower dimensions\n assert_array_equal(self.dset[slices], self.dsetview[slices])\n # test __getitem__ read after lazy_slice, single slice read for lower dimensions\n assert_array_equal(self.dset[slices], self.dsetview.lazy_slice[slices])\n\n @dset_iterator\n def test_dsetview_lazy_slice_int_indexing(self):\n for num_slice_dims in range(1, len(self.dset.shape)+1):\n indexing = self._int_indexing(self.dset.shape[:num_slice_dims])\n # test __getitem__ read specifying lower dimensions\n assert_array_equal(self.dset[indexing], self.dsetview[indexing])\n # test __getitem__ read after lazy_slice\n # for lower and all dimensions\n # int indexing only\n assert_array_equal(self.dset[indexing], self.dsetview.lazy_slice[indexing])\n\n @dset_iterator\n def test_dsetview_lazy_iter(self):\n for axis in range(len(self.dset.shape)):\n for i,dsetview_lazy_i in enumerate(self.dsetview.lazy_iter(axis = axis)):\n assert_array_equal(self.dset[(*np.index_exp[:]*axis,i)], dsetview_lazy_i)\n\n @dset_iterator\n def test_dsetview_lazy_transpose(self):\n axis = self._axis(len(self.dset.shape))\n # test DatasetView.lazy_transpose\n assert_array_equal(self.dset[()].transpose(axis), self.dsetview.lazy_transpose(axis))\n # test lazy_ops.lazy_transpose\n assert_array_equal(np.transpose(self.dset[()], axis),lazy_transpose(self.dsetview, axis))\n\n ###########################################\n # tests for multiple lazy slice calls #\n ###########################################\n\n # multi lazy_slice using only slices\n @dset_iterator\n def test_dsetview_multi_lazy_slice(self):\n self._dsetview_multi_lazy_slice(self.dset, self.dsetview)\n\n @classmethod\n def _dsetview_multi_lazy_slice(cls, dset, dsetview):\n for num_slice_dims in range(1, len(dset.shape)+1):\n slices = cls._slices(dset.shape[:num_slice_dims])\n dset_new = dset[slices]\n dsetview_new = dsetview.lazy_slice[slices]\n # test __getitem__ read after lazy_slice for lower dimensions\n assert_array_equal(dset_new, dsetview_new)\n if np.prod(dset_new.shape) != 0:\n cls._dsetview_multi_lazy_slice(dset_new, dsetview_new)\n\n # multi lazy_slice using slices and int indexing\n @dset_iterator\n def test_dsetview_multi_lazy_slice_with_slice_and_int_indexing(self):\n self._dsetview_multi_lazy_slice_with_slice_and_int_indexing(self.dset, self.dsetview)\n\n @classmethod\n def _dsetview_multi_lazy_slice_with_slice_and_int_indexing(cls, dset, dsetview):\n for num_slice_dims in range(1, len(dset.shape)+1):\n indexing = cls._slices_and_int(dset.shape[:num_slice_dims])\n dset_new = dset[indexing]\n dsetview_new = dsetview.lazy_slice[indexing]\n # test __getitem__ read after lazy_slice\n # for lower and all dimensions\n # combination of slice and int indexing\n assert_array_equal(dset_new, dsetview_new)\n if np.prod(dset_new.shape) != 0:\n cls._dsetview_multi_lazy_slice_with_slice_and_int_indexing(dset_new, dsetview_new)\n\n ###########################################\n # tests for multiple lazy operation calls #\n ###########################################\n\n # lazy_slice with slices followed by lazy_transpose call\n @dset_iterator\n def test_dsetview_lazy_slice_lazy_transpose(self):\n for num_slice_dims in range(1, len(self.dset.shape)+1):\n slices = self._slices(self.dset.shape[:num_slice_dims])\n # test __getitem__ read after lazy_slice, single slice read for lower dimensions\n # followed by lazy_transpose\n axis = self._axis(len(self.dset[slices].shape))\n assert_array_equal(self.dset[slices].transpose(axis), self.dsetview.lazy_slice[slices].lazy_transpose(axis))\n\n # multi lazy_transpose calls\n @dset_iterator\n def test_dsetview_multi_lazy_transpose(self):\n remaining_transpose_calls = 10\n self._dsetview_multi_lazy_transpose(self.dset, self.dsetview, remaining_transpose_calls)\n\n @classmethod\n def _dsetview_multi_lazy_transpose(self, dset, dsetview, remaining_transpose_calls):\n axis = self._axis(len(dset.shape))\n dset_new = dset[()].transpose(axis)\n dsetview_new = dsetview.lazy_transpose(axis)\n # test DatasetView.lazy_transpose\n assert_array_equal(dset_new,dsetview_new)\n if remaining_transpose_calls > 0:\n self._dsetview_multi_lazy_transpose(dset_new, dsetview_new, remaining_transpose_calls - 1)\n\n # multi lazy_transpose and lazy_slice using only slices\n @dset_iterator\n def test_dsetview_multi_lazy_ops_with_slice_indexing(self):\n remaining_transpose_calls = 10\n self._dsetview_multi_lazy_ops_with_slice_indexing(self.dset, self.dsetview, remaining_transpose_calls)\n\n @classmethod\n def _dsetview_multi_lazy_ops_with_slice_indexing(cls, dset, dsetview, remaining_transpose_calls):\n for num_slice_dims in range(1, len(dset.shape)+1):\n slices = cls._slices(dset.shape[:num_slice_dims])\n dset_new = dset[slices]\n dsetview_new = dsetview.lazy_slice[slices]\n # test __getitem__ read after lazy_slice\n # for lower and all dimensions\n assert_array_equal(dset_new,dsetview_new)\n if np.prod(dset_new.shape) != 0:\n cls._dsetview_multi_lazy_ops_with_slice_indexing(dset_new,dsetview_new, remaining_transpose_calls)\n axis = cls._axis(len(dset.shape))\n dset_new = dset[()].transpose(axis)\n dsetview_new = dsetview.lazy_transpose(axis)\n # test DatasetView.lazy_transpose\n assert_array_equal(dset_new,dsetview_new)\n if remaining_transpose_calls > 0:\n cls._dsetview_multi_lazy_ops_with_slice_indexing(dset_new, dsetview_new, remaining_transpose_calls - 1)\n\n # multi lazy_transpose and lazy_slice using slices and int\n @dset_iterator\n def test_dsetview_multi_lazy_ops_with_slice_and_int_indexing(self):\n self._dsetview_multi_lazy_ops_with_slice_and_int_indexing(self.dset, self.dsetview)\n\n @classmethod\n def _dsetview_multi_lazy_ops_with_slice_and_int_indexing(cls, dset, dsetview):\n for num_slice_dims in range(1, len(dset.shape)+1):\n slices = cls._slices_and_int(dset.shape[:num_slice_dims])\n dset_new = dset[slices]\n dsetview_new = dsetview.lazy_slice[slices]\n # test __getitem__ read after lazy_slice\n # for lower and all dimensions\n # combination of slice and int indexing\n assert_array_equal(dset_new, dsetview_new)\n if np.prod(dset_new.shape) != 0:\n cls._dsetview_multi_lazy_ops_with_slice_and_int_indexing(dset_new, dsetview_new)\n\nclass LazyOpsBaseh5py(object):\n\n ###########################################################\n # tests for single lazy operation calls specific to h5py #\n ###########################################################\n\n @dset_iterator\n def test_dsetview_lazy_slice_bool(self):\n # test __getitem__ read after lazy_slice, single slice\n indexing = self._bool_indexing(self.dset.shape)\n assert_array_equal(self.dset[indexing], self.dsetview.lazy_slice[indexing])\n\n @dset_iterator\n def test_dsetview_lazy_slice_array_indexing(self):\n for num_slice_dims in range(1, len(self.dset.shape)+1):\n indexing = self._array_indexing(self.dset.shape[:num_slice_dims])\n # test __getitem__ read specifying lower dimensions\n assert_array_equal(self.dset[indexing], self.dsetview[indexing])\n # test __getitem__ read after lazy_slice\n # for lower and all dimensions\n # array indexing only\n assert_array_equal(self.dset[indexing], self.dsetview.lazy_slice[indexing])\n\n @dset_iterator\n def test_dsetview_lazy_slice_bool_indexing(self):\n for num_slice_dims in range(2, len(self.dset.shape)+1):\n # num_slice_dims starts from 2, dset[(1-D bool np.ndarray,)] is invalid in h5py\n # dset[(1-D bool np.ndarray, slice(None))] is valid\n indexing = self._bool_indexing(self.dset.shape[:num_slice_dims])\n # test __getitem__ read specifying lower dimensions\n assert_array_equal(self.dset[indexing], self.dsetview[indexing])\n # test __getitem__ read after lazy_slice\n # for lower and all dimensions\n # bool indexing only\n assert_array_equal(self.dset[indexing], self.dsetview.lazy_slice[indexing])\n\n ########################################################\n # tests for multiple lazy slice calls specific to h5py #\n ########################################################\n\n # multi lazy_slice using slices and array indexing\n @dset_iterator\n def test_dsetview_multi_lazy_slice_with_slice_and_array_indexing(self):\n remaining_slice_calls = 10\n array_dim = self.srand.randint(0, len(self.dset.shape)-1)\n self._dsetview_multi_lazy_slice_with_slice_and_array_indexing(self.dset, self.dsetview, remaining_slice_calls, array_dim)\n\n @classmethod\n def _dsetview_multi_lazy_slice_with_slice_and_array_indexing(cls, dset, dsetview, remaining_slice_calls, array_dim):\n for num_slice_dims in range(array_dim+1, len(dset.shape)+1):\n indexing = cls._slices_and_array(dset.shape[:num_slice_dims], array_dim)\n dset_new = dset[indexing]\n dsetview_new = dsetview.lazy_slice[indexing]\n # test __getitem__ read after lazy_slice\n # for lower and all dimensions\n # combination of slice and array indexing\n assert_array_equal(dset_new, dsetview_new)\n if np.prod(dset_new.shape) != 0 and remaining_slice_calls > 0:\n cls._dsetview_multi_lazy_slice_with_slice_and_array_indexing(dset_new, dsetview_new, remaining_slice_calls - 1, array_dim)\n\n # multi lazy_slice using slices and boolean array indexing\n @dset_iterator\n def test_dsetview_multi_lazy_slice_with_slice_and_bool_indexing(self):\n remaining_slice_calls = 4\n array_dim = self.srand.randint(1, len(self.dset.shape)-1)\n # array_dim starts from 1, for array_dim=0, dset[(1-D bool np.ndarray,)] is invalid in h5py\n # dset[(slice(None),1-D bool np.ndarray)] is valid\n self._dsetview_multi_lazy_slice_with_slice_and_bool_indexing(self.dset, self.dsetview, remaining_slice_calls, array_dim)\n\n @classmethod\n def _dsetview_multi_lazy_slice_with_slice_and_bool_indexing(cls, dset, dsetview, remaining_slice_calls, array_dim):\n for num_slice_dims in range(array_dim+1, len(dset.shape)+1):\n indexing = cls._slices_and_bool(dset.shape[:num_slice_dims], array_dim)\n dset_new = dset[indexing]\n dsetview_new = dsetview.lazy_slice[indexing]\n # test __getitem__ read after lazy_slice\n # for lower and all dimensions\n # combination of slice and bool indexing\n assert_array_equal(dset_new, dsetview_new)\n if np.prod(dset_new.shape) != 0 and remaining_slice_calls > 0:\n cls._dsetview_multi_lazy_slice_with_slice_and_bool_indexing(dset_new, dsetview_new, remaining_slice_calls - 1, array_dim)\n\nclass LazyOpszarrTest(LazyOpsBase,unittest.TestCase):\n ''' Class zarr array equality test '''\n\n def setUp(self):\n self.ndims = 7\n num_datasets = 3\n\n self.temp_dir_zarr = tempfile.TemporaryDirectory(suffix=\".zgroup\")\n self.zarr_group = zarr.group(store=self.temp_dir_zarr.name, overwrite=True)\n self.dset_list = list(self.zarr_group.create_dataset(name='zarray'+str(i),\n data=np.random.rand(*self.srand.choices(range(1, 90//self.ndims), k=self.ndims)))\n for i in range(num_datasets))\n self.dsetview_list = list(DatasetView(self.dset_list[i]) for i in range(num_datasets))\n print(LazyOpszarrTest)\n\n def tearDown(self):\n self.temp_dir_zarr.cleanup()\n\nclass LazyOpsh5pyTest(LazyOpsBase,LazyOpsBaseh5py,unittest.TestCase):\n ''' Class h5py dataset array equality test '''\n\n def setUp(self):\n self.temp_file = tempfile.NamedTemporaryFile(suffix=\".hdf5\", delete=False)\n self.temp_file.close()\n self.h5py_file = h5py.File(self.temp_file.name,'w')\n\n self.ndims = 7\n num_datasets = 3\n self.dset_list = list(self.h5py_file.create_dataset(name='dset'+str(i),\n data=np.random.rand(*self.srand.choices(range(1, 90//self.ndims), k=self.ndims)))\n for i in range(num_datasets))\n self.dsetview_list = list(DatasetView(self.dset_list[i]) for i in range(num_datasets))\n\n def tearDown(self):\n self.temp_file.delete = True\n self.temp_file.close()\n"
] |
[
[
"numpy.testing.assert_array_equal",
"numpy.prod",
"numpy.transpose"
]
] |
chengcchn/OpenPCDet
|
[
"a7cf5368d9cbc3969b4613c9e61ba4dcaf217517"
] |
[
"pcdet/datasets/dataset.py"
] |
[
"from collections import defaultdict\nfrom pathlib import Path\n\nimport numpy as np\nimport torch.utils.data as torch_data\n\nfrom ..utils import common_utils\nfrom .augmentor.data_augmentor import DataAugmentor\nfrom .processor.data_processor import DataProcessor\nfrom .processor.point_feature_encoder import PointFeatureEncoder\n\n\nclass DatasetTemplate(torch_data.Dataset):\n def __init__(self, dataset_cfg=None, class_names=None, training=True, root_path=None, logger=None):\n super().__init__()\n self.dataset_cfg = dataset_cfg\n self.training = training\n self.class_names = class_names\n self.logger = logger\n self.root_path = root_path if root_path is not None else Path(self.dataset_cfg.DATA_PATH)\n self.logger = logger\n if self.dataset_cfg is None or class_names is None:\n return\n\n self.point_cloud_range = np.array(self.dataset_cfg.POINT_CLOUD_RANGE, dtype=np.float32)\n self.point_feature_encoder = PointFeatureEncoder(\n self.dataset_cfg.POINT_FEATURE_ENCODING,\n point_cloud_range=self.point_cloud_range\n )\n self.data_augmentor = DataAugmentor(\n self.root_path, self.dataset_cfg.DATA_AUGMENTOR, self.class_names, logger=self.logger\n ) if self.training else None\n self.data_processor = DataProcessor(\n self.dataset_cfg.DATA_PROCESSOR, point_cloud_range=self.point_cloud_range, training=self.training\n )\n\n self.grid_size = self.data_processor.grid_size\n self.voxel_size = self.data_processor.voxel_size\n self.total_epochs = 0\n self._merge_all_iters_to_one_epoch = False\n\n @property\n def mode(self):\n return 'train' if self.training else 'test'\n\n def __getstate__(self):\n d = dict(self.__dict__)\n del d['logger']\n return d\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n\n @staticmethod\n def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None):\n \"\"\"\n To support a custom dataset, implement this function to receive the predicted results from the model, and then\n transform the unified normative coordinate to your required coordinate, and optionally save them to disk.\n\n Args:\n batch_dict: dict of original data from the dataloader\n pred_dicts: dict of predicted results from the model\n pred_boxes: (N, 7), Tensor\n pred_scores: (N), Tensor\n pred_labels: (N), Tensor\n class_names:\n output_path: if it is not None, save the results to this path\n Returns:\n\n \"\"\"\n\n def merge_all_iters_to_one_epoch(self, merge=True, epochs=None):\n if merge:\n self._merge_all_iters_to_one_epoch = True\n self.total_epochs = epochs\n else:\n self._merge_all_iters_to_one_epoch = False\n\n def __len__(self):\n raise NotImplementedError\n\n def __getitem__(self, index):\n \"\"\"\n To support a custom dataset, implement this function to load the raw data (and labels), then transform them to\n the unified normative coordinate and call the function self.prepare_data() to process the data and send them\n to the model.\n\n Args:\n index:\n\n Returns:\n\n \"\"\"\n raise NotImplementedError\n\n def prepare_data(self, data_dict):\n \"\"\"\n Args:\n data_dict:\n points: (N, 3 + C_in)\n gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...]\n gt_names: optional, (N), string\n ...\n\n Returns:\n data_dict:\n frame_id: string\n points: (N, 3 + C_in)\n gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...]\n gt_names: optional, (N), string\n use_lead_xyz: bool\n voxels: optional (num_voxels, max_points_per_voxel, 3 + C)\n voxel_coords: optional (num_voxels, 3)\n voxel_num_points: optional (num_voxels)\n ...\n \"\"\"\n if self.training:\n assert 'gt_boxes' in data_dict, 'gt_boxes should be provided for training'\n gt_boxes_mask = np.array([n in self.class_names for n in data_dict['gt_names']], dtype=np.bool_)\n\n data_dict = self.data_augmentor.forward(\n data_dict={\n **data_dict,\n 'gt_boxes_mask': gt_boxes_mask\n }\n )\n\n if data_dict.get('gt_boxes', None) is not None:\n selected = common_utils.keep_arrays_by_name(data_dict['gt_names'], self.class_names)\n data_dict['gt_boxes'] = data_dict['gt_boxes'][selected]\n data_dict['gt_names'] = data_dict['gt_names'][selected]\n gt_classes = np.array([self.class_names.index(n) + 1 for n in data_dict['gt_names']], dtype=np.int32)\n gt_boxes = np.concatenate((data_dict['gt_boxes'], gt_classes.reshape(-1, 1).astype(np.float32)), axis=1)\n data_dict['gt_boxes'] = gt_boxes\n\n data_dict = self.point_feature_encoder.forward(data_dict)\n\n data_dict = self.data_processor.forward(\n data_dict=data_dict\n )\n\n if self.training and len(data_dict['gt_boxes']) == 0:\n new_index = np.random.randint(self.__len__())\n return self.__getitem__(new_index)\n\n data_dict.pop('gt_names', None)\n\n return data_dict\n\n @staticmethod\n def collate_batch(batch_list, _unused=False):\n data_dict = defaultdict(list)\n for cur_sample in batch_list:\n for key, val in cur_sample.items():\n data_dict[key].append(val)\n batch_size = len(batch_list)\n ret = {}\n\n for key, val in data_dict.items():\n try:\n if key in ['voxels', 'voxel_num_points']:\n ret[key] = np.concatenate(val, axis=0)\n elif key in ['points', 'voxel_coords']:\n coors = []\n for i, coor in enumerate(val):\n coor_pad = np.pad(coor, ((0, 0), (1, 0)), mode='constant', constant_values=i)\n coors.append(coor_pad)\n ret[key] = np.concatenate(coors, axis=0)\n elif key in ['gt_boxes']:\n max_gt = max([len(x) for x in val])\n batch_gt_boxes3d = np.zeros((batch_size, max_gt, val[0].shape[-1]), dtype=np.float32)\n for k in range(batch_size):\n batch_gt_boxes3d[k, :val[k].__len__(), :] = val[k]\n ret[key] = batch_gt_boxes3d\n else:\n ret[key] = np.stack(val, axis=0)\n except:\n print('Error in collate_batch: key=%s' % key)\n raise TypeError\n\n ret['batch_size'] = batch_size\n return ret\n"
] |
[
[
"numpy.concatenate",
"numpy.pad",
"numpy.array",
"numpy.zeros",
"numpy.stack"
]
] |
mohi7solanki/ludwig
|
[
"fd20d91c72928a69f219dd018e0e64a7e6d6ae64"
] |
[
"ludwig/features/vector_feature.py"
] |
[
"#! /usr/bin/env python\n# coding=utf-8\n# Copyright (c) 2019 Uber Technologies, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport logging\nimport os\nfrom collections import OrderedDict\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom ludwig.constants import *\nfrom ludwig.features.base_feature import BaseFeature\nfrom ludwig.features.base_feature import InputFeature\nfrom ludwig.features.base_feature import OutputFeature\nfrom ludwig.models.modules.dense_encoders import Dense\nfrom ludwig.models.modules.initializer_modules import get_initializer\nfrom ludwig.models.modules.loss_modules import weighted_softmax_cross_entropy\nfrom ludwig.models.modules.measure_modules import \\\n absolute_error as get_absolute_error\nfrom ludwig.models.modules.measure_modules import error as get_error\nfrom ludwig.models.modules.measure_modules import r2 as get_r2\nfrom ludwig.models.modules.measure_modules import \\\n squared_error as get_squared_error\nfrom ludwig.utils.misc import get_from_registry\nfrom ludwig.utils.misc import set_default_value\n\nlogger = logging.getLogger(__name__)\n\n\nclass VectorBaseFeature(BaseFeature):\n def __init__(self, feature):\n super().__init__(feature)\n self.type = VECTOR\n\n preprocessing_defaults = {\n 'missing_value_strategy': FILL_WITH_CONST,\n 'fill_value': \"\"\n }\n\n @staticmethod\n def get_feature_meta(column, preprocessing_parameters):\n return {\n 'preprocessing': preprocessing_parameters\n }\n\n @staticmethod\n def add_feature_data(\n feature,\n dataset_df,\n data,\n metadata,\n preprocessing_parameters\n ):\n \"\"\"\n Expects all the vectors to be of the same size. The vectors need to be\n whitespace delimited strings. Missing values are not handled.\n \"\"\"\n if len(dataset_df) == 0:\n raise ValueError(\"There are no vectors in the dataset provided\")\n\n # Convert the string of features into a numpy array\n try:\n data[feature['name']] = np.array(\n [x.split() for x in dataset_df[feature['name']]],\n dtype=np.double\n )\n except ValueError:\n logger.error(\n 'Unable to read the vector data. Make sure that all the vectors'\n ' are of the same size and do not have missing/null values.'\n )\n raise\n\n # Determine vector size\n vector_size = len(data[feature['name']][0])\n if 'vector_size' in preprocessing_parameters:\n if vector_size != preprocessing_parameters['vector_size']:\n raise ValueError(\n 'The user provided value for vector size ({}) does not '\n 'match the value observed in the data: {}'.format(\n preprocessing_parameters, vector_size\n )\n )\n else:\n logger.warning('Observed vector size: {}'.format(vector_size))\n\n metadata[feature['name']]['vector_size'] = vector_size\n\n\nclass VectorInputFeature(VectorBaseFeature, InputFeature):\n def __init__(self, feature):\n super().__init__(feature)\n\n self.vector_size = 0\n self.encoder = 'fc_stack'\n\n encoder_parameters = self.overwrite_defaults(feature)\n\n self.encoder_obj = self.get_vector_encoder(encoder_parameters)\n\n def get_vector_encoder(self, encoder_parameters):\n return get_from_registry(self.encoder, vector_encoder_registry)(\n **encoder_parameters\n )\n\n def _get_input_placeholder(self):\n # None dimension is for dealing with variable batch size\n return tf.compat.v1.placeholder(\n tf.float32,\n shape=[None, self.vector_size],\n name=self.name,\n )\n\n def build_input(\n self,\n regularizer,\n dropout_rate,\n is_training=False,\n **kwargs\n ):\n placeholder = self._get_input_placeholder()\n logger.debug(' placeholder: {0}'.format(placeholder))\n\n feature_representation, feature_representation_size = self.encoder_obj(\n placeholder,\n self.vector_size,\n regularizer,\n dropout_rate,\n is_training=is_training\n )\n logger.debug(\n ' feature_representation: {0}'.format(feature_representation)\n )\n\n feature_representation = {\n 'name': self.name,\n 'type': self.type,\n 'representation': feature_representation,\n 'size': feature_representation_size,\n 'placeholder': placeholder\n }\n return feature_representation\n\n @staticmethod\n def update_model_definition_with_metadata(\n input_feature,\n feature_metadata,\n *args,\n **kwargs\n ):\n for key in ['vector_size']:\n input_feature[key] = feature_metadata[key]\n\n @staticmethod\n def populate_defaults(input_feature):\n set_default_value(input_feature, 'tied_weights', None)\n set_default_value(input_feature, 'preprocessing', {})\n\n\nclass VectorOutputFeature(VectorBaseFeature, OutputFeature):\n def __init__(self, feature):\n super().__init__(feature)\n self.type = VECTOR\n self.vector_size = 0\n\n self.loss = {'type': MEAN_SQUARED_ERROR}\n self.softmax = False\n\n _ = self.overwrite_defaults(feature)\n\n def _get_output_placeholder(self):\n return tf.compat.v1.placeholder(\n tf.float32,\n [None, self.vector_size],\n name='{}_placeholder'.format(self.name)\n )\n\n def _get_measures(self, targets, predictions):\n\n with tf.compat.v1.variable_scope('measures_{}'.format(self.name)):\n error_val = get_error(\n targets,\n predictions,\n self.name\n )\n\n absolute_error_val = tf.reduce_sum(\n get_absolute_error(targets, predictions, self.name), axis=1\n )\n\n squared_error_val = tf.reduce_sum(\n get_squared_error(targets, predictions, self.name), axis=1\n )\n\n # TODO - not sure if this is correct\n r2_val = tf.reduce_sum(get_r2(targets, predictions, self.name))\n\n return error_val, squared_error_val, absolute_error_val, r2_val\n\n def vector_loss(self, targets, predictions, logits):\n with tf.compat.v1.variable_scope('loss_{}'.format(self.name)):\n if self.loss['type'] == MEAN_SQUARED_ERROR:\n train_loss = tf.reduce_sum(\n get_squared_error(targets, predictions, self.name), axis=1\n )\n\n elif self.loss['type'] == MEAN_ABSOLUTE_ERROR:\n train_loss = tf.reduce_sum(\n get_absolute_error(targets, predictions, self.name), axis=1\n )\n\n elif self.loss['type'] == SOFTMAX_CROSS_ENTROPY:\n train_loss = weighted_softmax_cross_entropy(\n logits,\n targets,\n self.loss\n )\n\n else:\n train_mean_loss = None\n train_loss = None\n raise ValueError(\n 'Unsupported loss type {}'.format(self.loss['type'])\n )\n\n train_mean_loss = tf.reduce_mean(\n train_loss,\n name='train_mean_loss_{}'.format(self.name)\n )\n\n return train_mean_loss, train_loss\n\n def build_output(\n self,\n hidden,\n hidden_size,\n regularizer=None,\n dropout_rate=None,\n is_training=None,\n **kwargs\n ):\n train_mean_loss, eval_loss, output_tensors = self.build_vector_output(\n self._get_output_placeholder(),\n hidden,\n hidden_size,\n regularizer=regularizer,\n )\n return train_mean_loss, eval_loss, output_tensors\n\n def build_vector_output(\n self,\n targets,\n hidden,\n hidden_size,\n regularizer=None,\n ):\n feature_name = self.name\n output_tensors = {}\n\n # ================ Placeholder ================\n output_tensors['{}'.format(feature_name)] = targets\n\n # ================ Predictions ================\n logits, logits_size, predictions = self.vector_predictions(\n hidden,\n hidden_size,\n regularizer=regularizer,\n )\n\n output_tensors[PREDICTIONS + '_' + feature_name] = predictions\n\n # ================ Measures ============\n error, squared_error, absolute_error, r2 = self._get_measures(\n targets,\n predictions\n )\n\n output_tensors[ERROR + '_' + self.name] = error\n output_tensors[SQUARED_ERROR + '_' + self.name] = squared_error\n output_tensors[ABSOLUTE_ERROR + '_' + self.name] = absolute_error\n output_tensors[R2 + '_' + self.name] = r2\n\n if 'sampled' not in self.loss['type']:\n tf.compat.v1.summary.scalar(\n 'batch_train_mean_squared_error_{}'.format(self.name),\n tf.reduce_mean(squared_error)\n )\n tf.compat.v1.summary.scalar(\n 'batch_train_mean_absolute_error_{}'.format(self.name),\n tf.reduce_mean(absolute_error)\n )\n tf.compat.v1.summary.scalar(\n 'batch_train_mean_r2_{}'.format(self.name),\n tf.reduce_mean(r2)\n )\n\n # ================ Loss ================\n train_mean_loss, eval_loss = self.vector_loss(\n targets, predictions, logits\n )\n output_tensors[EVAL_LOSS + '_' + self.name] = eval_loss\n output_tensors[\n TRAIN_MEAN_LOSS + '_' + self.name] = train_mean_loss\n\n tf.compat.v1.summary.scalar(\n 'batch_train_mean_loss_{}'.format(self.name),\n train_mean_loss,\n )\n\n return train_mean_loss, eval_loss, output_tensors\n\n def vector_predictions(\n self,\n hidden,\n hidden_size,\n regularizer=None,\n ):\n with tf.compat.v1.variable_scope('predictions_{}'.format(self.name)):\n initializer_obj = get_initializer(self.initializer)\n weights = tf.compat.v1.get_variable(\n 'weights',\n initializer=initializer_obj([hidden_size, self.vector_size]),\n regularizer=regularizer\n )\n logger.debug(' projection_weights: {0}'.format(weights))\n\n biases = tf.compat.v1.get_variable(\n 'biases',\n [self.vector_size]\n )\n logger.debug(' projection_biases: {0}'.format(biases))\n\n logits = tf.matmul(hidden, weights) + biases\n logger.debug(' logits: {0}'.format(logits))\n\n if self.softmax:\n predictions = tf.nn.softmax(logits)\n else:\n predictions = logits\n\n return logits, self.vector_size, predictions\n\n default_validation_measure = LOSS\n\n output_config = OrderedDict([\n (LOSS, {\n 'output': EVAL_LOSS,\n 'aggregation': SUM,\n 'value': 0,\n 'type': MEASURE\n }),\n (MEAN_SQUARED_ERROR, {\n 'output': SQUARED_ERROR,\n 'aggregation': SUM,\n 'value': 0,\n 'type': MEASURE\n }),\n (MEAN_ABSOLUTE_ERROR, {\n 'output': ABSOLUTE_ERROR,\n 'aggregation': SUM,\n 'value': 0,\n 'type': MEASURE\n }),\n (R2, {\n 'output': R2,\n 'aggregation': SUM,\n 'value': 0,\n 'type': MEASURE\n }),\n (ERROR, {\n 'output': ERROR,\n 'aggregation': SUM,\n 'value': 0,\n 'type': MEASURE\n }),\n (PREDICTIONS, {\n 'output': PREDICTIONS,\n 'aggregation': APPEND,\n 'value': [],\n 'type': PREDICTION\n })\n ])\n\n @staticmethod\n def update_model_definition_with_metadata(\n output_feature,\n feature_metadata,\n *args,\n **kwargs\n ):\n\n output_feature['vector_size'] = feature_metadata['vector_size']\n\n @staticmethod\n def calculate_overall_stats(\n test_stats,\n output_feature,\n dataset,\n train_set_metadata\n ):\n pass\n\n @staticmethod\n def postprocess_results(\n output_feature,\n result,\n metadata,\n experiment_dir_name,\n skip_save_unprocessed_output=False,\n ):\n postprocessed = {}\n npy_filename = os.path.join(experiment_dir_name, '{}_{}.npy')\n name = output_feature['name']\n\n if PREDICTIONS in result and len(result[PREDICTIONS]) > 0:\n postprocessed[PREDICTIONS] = result[PREDICTIONS]\n if not skip_save_unprocessed_output:\n np.save(\n npy_filename.format(name, PREDICTIONS),\n result[PREDICTIONS]\n )\n del result[PREDICTIONS]\n\n return postprocessed\n\n @staticmethod\n def populate_defaults(output_feature):\n\n set_default_value(output_feature, LOSS, {})\n set_default_value(output_feature[LOSS], 'type', MEAN_SQUARED_ERROR)\n set_default_value(output_feature[LOSS], 'weight', 1)\n set_default_value(output_feature, 'reduce_input', None)\n set_default_value(output_feature, 'reduce_dependencies', None)\n set_default_value(output_feature, 'softmax', False)\n set_default_value(output_feature, 'decoder', 'fc_stack')\n set_default_value(output_feature, 'dependencies', [])\n\n\nvector_encoder_registry = {\n 'fc_stack': Dense\n}\n"
] |
[
[
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.get_variable",
"tensorflow.matmul",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean"
]
] |
bostongfx/TRAKO
|
[
"81ea3b56d4a4debf9eb5bd1aed916567ab00ef1b"
] |
[
"IPY/MICCAI/sprinter.py"
] |
[
"import numpy as np\nimport runner\n\nclass Sprinter:\n\n @staticmethod\n def createfulltable(dataset, originalsize, runs, verbose=False):\n\n print('\\\\textbf{'+dataset+'} & '+str(np.round(originalsize/1000000.,2))+'M\\\\\\\\')\n\n for r in runs.keys():\n\n selector = runs[r][0]\n rest = {r:runs[r][1:]}\n\n Sprinter.createtable(dataset, originalsize, rest, selector)\n\n\n\n @staticmethod\n def createtable(dataset, originalsize, tkoruns={}, \n selector=None, qfibruns=None, dpyruns=None, verbose=False):\n\n\n for r in tkoruns.keys():\n \n # if r != 'default':\n # continue\n \n tko_sizes = tkoruns[r][0]\n tko_errors = tkoruns[r][1]\n tko_stds = tkoruns[r][2]\n tko_advstats = tkoruns[r][3]\n\n if 0 in tko_sizes:\n tko_sizes.remove(0)\n if 0 in tko_errors:\n tko_errors.remove(0)\n if 0 in tko_stds:\n tko_stds.remove(0)\n\n run_name = r\n if run_name == 'qbponly{bits}':\n run_name = 'XYZ only'\n elif run_name == 'qbi{bits}':\n run_name = 'XYZ + Ind.'\n run_name = 'TRAKO'\n elif run_name == 'qbi_CL0_{bits}':\n run_name = 'XYZ + Ind. Level 0'\n elif run_name.endswith('binary'):\n run_name = 'XYZ + Ind. (Binary)'\n run_name = 'TRAKO (Binary)'\n elif run_name == 'qfib (8bit)':\n run_name = 'qfib (8bit)~\\\\cite{mercier2020qfib}'\n elif run_name == 'qfib (16bit)':\n run_name = 'qfib (16bit)~\\\\cite{mercier2020qfib}'\n elif run_name == 'zfib':\n run_name = 'zfib/Dipy~\\\\cite{presseau2015new}'\n compressedsize = tko_sizes[selector]\n\n c_ratio = (1-float(compressedsize)/float(originalsize))*100\n c_factor = float(originalsize) / float(compressedsize)\n\n\n if verbose:\n print('-'*20)\n print(r)\n print('size', compressedsize)\n print('ratio', c_ratio)\n print('c_factor', c_factor)\n\n\n min_e = tko_advstats[0][selector]\n if verbose:\n print('min_e', min_e)\n max_e = tko_advstats[1][selector]\n if verbose:\n print('max_e', max_e)\n if len(tko_errors) > 0:\n mean_e = tko_errors[selector]\n if verbose:\n print('mean_e', mean_e)\n std = tko_stds[selector]\n if verbose:\n print('std', std)\n else:\n mean_e = 0.\n std = 0.\n if verbose:\n print('mean_e', 0)\n if verbose:\n print('std',0)\n\n e_min_e = tko_advstats[2][selector]\n if verbose:\n print('e_min_e', e_min_e)\n e_max_e = tko_advstats[3][selector]\n if verbose:\n print('e_max_e', e_max_e)\n e_mean_e = tko_advstats[4][selector]\n if verbose:\n print('e_mean_e', e_mean_e)\n e_std = tko_advstats[5][selector]\n if verbose:\n print('e_std', e_std)\n c_time = tko_advstats[6][selector]\n if verbose:\n print('c_time', c_time)\n d_time = tko_advstats[7][selector]\n if verbose:\n print('d_time', d_time)\n if verbose:\n print('-'*20)\n\n latexline = '~~~'+run_name+' & '+ \\\n str(np.round(compressedsize/1000000.,2)) + 'M & '+ \\\n str(np.round(c_ratio,3))+'\\\\%' + ' & '+ \\\n str(np.round(c_factor,3))+'$\\\\times$' + ' & '+ \\\n str(np.round(min_e,3)) + ' & '+ \\\n str(np.round(max_e,3)) + ' & '+ \\\n str(np.round(mean_e,3)) + '$\\\\pm$' + str(np.round(std,3)) + ' & '+ \\\n str(np.round(e_min_e,3)) + ' & '+ \\\n str(np.round(e_max_e,3)) + ' & '+ \\\n str(np.round(e_mean_e,3)) + '$\\\\pm$' + str(np.round(e_std,3)) + ' & '+ \\\n str(np.round(c_time,3)) + ' & '+ \\\n str(np.round(d_time,3)) + '\\\\\\\\'\n\n print(latexline)\n\n '''\n \\\\textbf{qfib-data} & 2,017M \\\\\\\\\n ~~~qfib~\\\\cite{mercier2020qfib} & 410M & 8$\\\\times$ & 91.9 & 0.333 & 1.444 & 1.01$\\\\pm$2.22 & 0.333 & 1.444 & 1.01$\\\\pm$2.22 & 512.3 & 333.4\\\\\n ~~~zfib/dipy~\\\\cite{presseau2015new} & 410M & 8$\\times$ & 91.9 & 0.333 & 1.444 & 1.01$\\\\pm$2.22 & 0.333 & 1.444 & 1.01$\\\\pm$2.22 & 512.3 & 333.4\\\\\n ~~~TRAKO & 410M & 8$\\\\times$ & 91.9 & 0.333 & 1.444 & 1.01$\\\\pm$2.22 & 0.333 & 1.444 & 1.01$\\\\pm$2.22 & 512.3 & 333.4\\\\\n ~~~TRAKO (binary) & 410M & 8$\\times$ & 91.9 & 0.333 & 1.444 & 1.01$\\\\pm$2.22 & 0.333 & 1.444 & 1.01$\\\\pm$2.22 & 512.3 & 333.4\\\\\n '''\n\n @staticmethod\n def bitsplot(plt, tkoruns={}, tko_bits = [6,7,8,9,10,11,12,13,14], qfibruns=None, dpyruns=None, xlim=None, ylim=(0,1), filename=None):\n '''\n '''\n plt.figure(num=None, figsize=(8, 6), dpi=240, facecolor='w', edgecolor='k')\n\n\n longest_run = 0\n longest = 0\n for r in tkoruns.keys():\n \n # if r != 'default':\n # continue\n \n tko_sizes = tkoruns[r][0]\n tko_errors = tkoruns[r][1]\n tko_stds = tkoruns[r][2]\n\n if 0 in tko_sizes:\n tko_sizes.remove(0)\n if 0 in tko_errors:\n tko_errors.remove(0)\n if 0 in tko_stds:\n tko_stds.remove(0)\n\n if len(tko_sizes) > longest:\n # print('lo',r)\n longest = len(tko_sizes)\n longest_run = tko_sizes\n \n \n tko_sizes_ = np.array(tko_sizes) / 1000000\n # plt.scatter(tko_sizes_, tko_errors, s = np.array(tko_stds)*1000, alpha=1, label='TRAKO ('+r+')')\n size = 10\n if r=='default':\n size=70\n\n run_name = r\n if run_name == 'qbponly{bits}':\n run_name = 'XYZ only'\n elif run_name == 'qbi{bits}':\n run_name = 'XYZ + Ind.'\n elif run_name == 'qbi_CL0_{bits}':\n run_name = 'XYZ + Ind. Level 0'\n elif run_name.endswith('binary'):\n run_name = 'XYZ + Ind. (Binary)'\n plt.scatter(tko_sizes_, tko_errors, s = size, alpha=1, label='TRAKO ('+run_name+')')\n plt.errorbar(tko_sizes_, tko_errors, tko_stds, fmt='|', alpha=.5)\n\n\n for x,s in enumerate(longest_run):\n\n y = tko_errors[x]\n y += -0.02#y*0.05\n txt = tko_bits[x]\n x = tko_sizes_[x]\n x += x*0.01\n\n if ylim:\n if y<ylim[0]:\n continue\n if y>= ylim[1]:\n continue\n if xlim:\n if x<=xlim[0]:\n continue\n if x>=xlim[1]:\n continue\n\n\n \n plt.text(x, y, txt)\n\n\n if qfibruns:\n qfib_sizes = qfibruns[0]\n qfib_errors = qfibruns[1]\n qfib_stds = qfibruns[2]\n qfib_sizes_ = np.array(qfib_sizes) / 1000000\n plt.scatter(qfib_sizes_, qfib_errors, s = 10, color='black', alpha=1, label='QFib')\n plt.errorbar(qfib_sizes_, qfib_errors, qfib_stds, fmt='|', color='black', alpha=.5)\n plt.ticklabel_format(style='plain', axis='both', scilimits=(0, 0))\n\n import matplotlib.ticker as mticker \n plt.gca().xaxis.set_major_formatter(mticker.FormatStrFormatter('%d MB'))\n\n if ylim:\n plt.ylim(ylim[0], ylim[1])\n\n if xlim:\n plt.xlim(xlim[0], xlim[1])\n\n\n # plt.axvline(x=input_size/1000000, color='red', linestyle='--')\n\n plt.xlabel('Data Size [MB]')\n plt.ylabel('Mean Absolute Error [MAE]')\n plt.legend()\n\n if filename:\n a = plt.savefig(filename)\n\n plt.show()\n\n\n\n @staticmethod\n def run_dpy(dpy_files):\n dpy_sizes = [0]\n dpy_errors = [0]\n dpy_stds = [0]\n\n dpy_minerror = [np.inf]\n dpy_maxerror = [0]\n dpy_e_minerror = [np.inf]\n dpy_e_maxerror = [0]\n dpy_e_meanerror = [0]\n dpy_e_std = [0]\n\n dpy_ctime = [0]\n dpy_dtime = [0]\n\n for f in dpy_files:\n\n rundata = runner.Runner.dpy(f[0], f[1], force=False)\n\n\n c_time, d_time, sizestats, compressedsize, minerror, maxerror, meanerror, stderror, e_minerror, e_maxerror, e_meanerror, e_stderror = Sprinter.parse_rundata(rundata, False)\n\n\n dpy_minerror[0] = min(dpy_minerror[0], minerror)\n dpy_maxerror[0] = max(dpy_maxerror[0], maxerror)\n dpy_e_minerror[0] = min(dpy_e_minerror[0], e_minerror)\n dpy_e_maxerror[0] = max(dpy_e_maxerror[0], e_maxerror)\n dpy_e_meanerror[0] += e_meanerror\n dpy_e_std[0] += e_stderror\n\n dpy_ctime[0] += c_time\n dpy_dtime[0] += d_time\n\n dpy_sizes[0] += compressedsize\n dpy_errors[0] += meanerror\n dpy_stds[0] += stderror\n\n\n dpy_sizes[0] /= len(dpy_files)\n\n advancedstats = [dpy_minerror, dpy_maxerror, dpy_e_minerror, dpy_e_maxerror, \\\n dpy_e_meanerror, dpy_e_std, dpy_ctime, dpy_dtime]\n\n return dpy_sizes, dpy_errors, dpy_stds, advancedstats\n\n @staticmethod \n def parse_rundata(rundata, binary=False):\n '''\n '''\n c_time = rundata[0]\n d_time = rundata[1]\n \n if binary:\n sizestats = rundata[-1]\n else:\n sizestats = rundata[2]\n\n\n compressedsize = sizestats[1]\n minerror = rundata[3][0]\n maxerror = rundata[3][1]\n meanerror = rundata[3][2]\n stderror = rundata[3][3]\n\n e_minerror = rundata[4][0]\n e_maxerror = rundata[4][1]\n e_meanerror = rundata[4][2]\n e_stderror = rundata[4][3]\n\n return c_time, d_time, sizestats, compressedsize, minerror, maxerror, meanerror, stderror, e_minerror, e_maxerror, e_meanerror, e_stderror\n\n\n @staticmethod\n def run_qfib(qfib_files, qfib_bits):\n qfib_sizes = [0]*len(qfib_bits)\n qfib_errors = [0]*len(qfib_bits)\n qfib_stds = [0]*len(qfib_bits)\n\n qfib_minerror = [np.inf]*len(qfib_bits)\n qfib_maxerror = [0]*len(qfib_bits)\n qfib_e_minerror = [np.inf]*len(qfib_bits)\n qfib_e_maxerror = [0]*len(qfib_bits)\n qfib_e_meanerror = [0]*len(qfib_bits)\n qfib_e_std = [0]*len(qfib_bits)\n\n qfib_ctime = [0]*len(qfib_bits)\n qfib_dtime = [0]*len(qfib_bits)\n\n for f in qfib_files:\n for i,b in enumerate(qfib_bits):\n rundata = runner.Runner.qfib(f[0], f[1], bits=b, force=False)\n\n c_time, d_time, sizestats, compressedsize, minerror, maxerror, meanerror, stderror, e_minerror, e_maxerror, e_meanerror, e_stderror = Sprinter.parse_rundata(rundata, False)\n\n\n\n qfib_minerror[i] = min(qfib_minerror[i], minerror)\n qfib_maxerror[i] = max(qfib_maxerror[i], maxerror)\n qfib_e_minerror[i] = min(qfib_e_minerror[i], e_minerror)\n qfib_e_maxerror[i] = max(qfib_e_maxerror[i], e_maxerror)\n qfib_e_meanerror[i] += e_meanerror\n qfib_e_std[i] += e_stderror\n\n\n qfib_sizes[i] += compressedsize\n qfib_errors[i] += meanerror\n qfib_stds[i] += stderror\n\n qfib_ctime[i] += c_time\n qfib_dtime[i] += d_time\n # qfib_sizes.append(compressedsize)\n # qfib_errors.append(meanerror)\n # qfib_stds.append(stderror)\n for i,b in enumerate(qfib_bits):\n qfib_sizes[i] /= len(qfib_files)\n qfib_errors[i] /= len(qfib_files)\n qfib_stds[i] /= len(qfib_files)\n qfib_e_std[i] /= len(qfib_files)\n qfib_e_meanerror[i] /= len(qfib_files)\n\n advancedstats = [qfib_minerror, qfib_maxerror, qfib_e_minerror, qfib_e_maxerror, \\\n qfib_e_meanerror, qfib_e_std, qfib_ctime, qfib_dtime]\n\n return qfib_sizes, qfib_errors, qfib_stds, advancedstats\n\n @staticmethod\n def run_trako(config, tko_files, tko_bits, coords_only=True, binary=False):\n\n config_ = dict(config)\n\n tko_sizes = [0]*len(tko_bits)\n tko_errors = [0]*len(tko_bits)\n tko_stds = [0]*len(tko_bits)\n fails = [len(tko_files)]*len(tko_bits)\n\n tko_minerror = [np.inf]*len(tko_bits)\n tko_maxerror = [0]*len(tko_bits)\n tko_e_minerror = [np.inf]*len(tko_bits)\n tko_e_maxerror = [0]*len(tko_bits)\n tko_e_meanerror = [0]*len(tko_bits)\n tko_e_std = [0]*len(tko_bits)\n\n tko_ctime = [0]*len(tko_bits)\n tko_dtime = [0]*len(tko_bits)\n\n for j,f in enumerate(tko_files):\n for i,b in enumerate(tko_bits):\n\n config = dict(config_)\n config['name'] = config['name'].replace('{bits}', str(b)) # change name\n for c in config.keys():\n if c=='name':\n continue\n config[c]['quantization_bits'] = b # update bits for config\n \n try:\n rundata = runner.Runner.tko(f[0], f[1], config=config, coords_only=coords_only, force=False, binary=binary)\n except:\n print('Failing..')\n fails[i] -= 1\n continue\n\n c_time, d_time, sizestats, compressedsize, minerror, maxerror, meanerror, stderror, e_minerror, e_maxerror, e_meanerror, e_stderror = Sprinter.parse_rundata(rundata, binary)\n\n\n\n tko_minerror[i] = min(tko_minerror[i], minerror)\n tko_maxerror[i] = max(tko_maxerror[i], maxerror)\n tko_e_minerror[i] = min(tko_e_minerror[i], e_minerror)\n tko_e_maxerror[i] = max(tko_e_maxerror[i], e_maxerror)\n tko_e_meanerror[i] += e_meanerror\n tko_e_std[i] += e_stderror\n\n tko_sizes[i] += compressedsize\n tko_errors[i] += meanerror\n tko_stds[i] += stderror\n\n tko_ctime[i] += c_time\n tko_dtime[i] += d_time\n # tko_sizes.append(compressedsize)\n # tko_errors.append(meanerror)\n # tko_stds.append(stderror)\n\n for i,b in enumerate(tko_bits):\n if fails[i] == 0:\n continue\n tko_sizes[i] /= fails[i]#len(tko_files)\n tko_errors[i] /= fails[i]#len(tko_files)\n tko_stds[i] /= fails[i]#len(tko_files)\n tko_e_std[i] /= fails[i]\n tko_e_meanerror[i] /= fails[i]\n \n advancedstats = [tko_minerror, tko_maxerror, tko_e_minerror, tko_e_maxerror, \\\n tko_e_meanerror, tko_e_std, tko_ctime, tko_dtime]\n\n return tko_sizes, tko_errors, tko_stds, advancedstats\n\n"
] |
[
[
"numpy.round",
"numpy.array",
"matplotlib.ticker.FormatStrFormatter"
]
] |
johnjz30/Phy-Net
|
[
"8f7a610d6ed36f734dad7d2d0c9d0ffa2a29aaf1",
"8f7a610d6ed36f734dad7d2d0c9d0ffa2a29aaf1"
] |
[
"test/generate_runtime.py",
"test/generate_compression_error_plot.py"
] |
[
"\nimport os\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nimport cv2\n\nimport sys\nsys.path.append('../')\n\nfrom model.lat_net import *\nfrom model.loss import *\nfrom model.lattice import *\nfrom utils.experiment_manager import *\n\nfrom tqdm import *\n\nFLAGS = tf.app.flags.FLAGS\n\n# get restore dir\nRESTORE_DIR = make_checkpoint_path(FLAGS.base_dir, FLAGS)\n\n# shape of test simulation\nshape = FLAGS.test_dimensions.split('x')\nshape = map(int, shape)\n\ndef evaluate():\n \"\"\" Eval the system\"\"\"\n with tf.Graph().as_default():\n # make inputs\n state, boundary = inputs(empty=True, shape=shape)\n\n # unwrap\n y_1, small_boundary_mul, small_boundary_add, x_2, y_2 = continual_unroll_template(state, boundary)\n\n # make variable to iterate\n compressed_shape = [x / pow(2,FLAGS.nr_downsamples) for x in shape]\n compressed_state_1 = tf.Variable(np.zeros([1] + compressed_shape + [FLAGS.filter_size_compression], dtype=np.float32), trainable=False) \n small_boundary_mul_var = tf.Variable(np.zeros([1] + compressed_shape + [FLAGS.filter_size_compression], dtype=np.float32), trainable=False) \n small_boundary_add_var = tf.Variable(np.zeros([1] + compressed_shape + [FLAGS.filter_size_compression], dtype=np.float32), trainable=False) \n\n # make steps to init\n assign_compressed_state_step = tf.group(compressed_state_1.assign(y_1))\n assign_boundary_mul_step = tf.group(small_boundary_mul_var.assign(small_boundary_mul))\n assign_boundary_add_step = tf.group(small_boundary_add_var.assign(small_boundary_add))\n\n # computation!\n compressed_state_1_boundary = (small_boundary_mul_var * compressed_state_1) + small_boundary_add_var\n compressed_state_2 = compress_template(compressed_state_1_boundary)\n run_step = tf.group(compressed_state_1.assign(compressed_state_2))\n state_out_full = decoding_template(compressed_state_2)\n if len(shape) == 3: \n state_out_plane = decoding_template(compressed_state_2, extract_type='plane')\n state_out_line = decoding_template(compressed_state_2, extract_type='line')\n state_out_point = decoding_template(compressed_state_2, extract_type='point')\n \n # rand init\n init = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n\n # make fake zero frame to test on\n state_feed_dict = np.zeros([1]+shape+[FLAGS.lattice_size])\n boundary_feed_dict = np.zeros([1]+shape+[1])\n feed_dict = {state:state_feed_dict, boundary:boundary_feed_dict}\n\n assign_compressed_state_step.run(session=sess, feed_dict=feed_dict)\n assign_boundary_mul_step.run(session=sess, feed_dict=feed_dict)\n assign_boundary_add_step.run(session=sess, feed_dict=feed_dict)\n run_step.run(session=sess)\n\n # open file to log results (this log file will get directly copied into the paper)\n run_length = 4000\n with open(\"figs/\" + \"runtime_log.txt\", \"a\") as myfile:\n # run just compression\n t = time.time()\n for step in tqdm(xrange(run_length)):\n run_step.run(session=sess)\n elapsed = time.time() - t\n time_per_step = elapsed/run_length\n myfile.write(str(shape) + \" & %.3f ms \" % (time_per_step*1000))\n \n # run with full state out\n t = time.time()\n for step in tqdm(xrange(run_length)):\n state_out_full.eval(session=sess)\n elapsed = time.time() - t\n time_per_step = elapsed/run_length\n myfile.write(\" & %.3f ms \" % (time_per_step*1000))\n \n # run with plane out\n if len(shape) == 3: \n t = time.time()\n for step in tqdm(xrange(run_length)):\n state_out_plane.eval(session=sess)\n elapsed = time.time() - t\n time_per_step = elapsed/run_length\n myfile.write(\" & %.3f ms \" % (time_per_step*1000))\n else:\n myfile.write(\" & na\")\n \n # run with line out\n t = time.time()\n for step in tqdm(xrange(run_length)):\n state_out_line.eval(session=sess)\n elapsed = time.time() - t\n time_per_step = elapsed/run_length\n myfile.write(\" & %.3f ms \" % (time_per_step*1000))\n \n # run with point state out\n t = time.time()\n for step in tqdm(xrange(run_length)):\n state_out_point.eval(session=sess)\n elapsed = time.time() - t\n time_per_step = elapsed/run_length\n myfile.write(\" & %.3f ms \\\\\\ \\n\" % (time_per_step*1000))\n\n \ndef main(argv=None): # pylint: disable=unused-argument\n evaluate()\n\n\nif __name__ == '__main__':\n tf.app.run()\n",
"\nimport os\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nimport cv2\n\nimport sys\nsys.path.append('../')\n\nfrom model.lat_net import *\nfrom model.loss import *\nfrom model.lattice import *\nfrom utils.experiment_manager import *\n\nfrom tqdm import *\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nFLAGS = tf.app.flags.FLAGS\n\n# get restore dir\nRESTORE_DIR = make_checkpoint_path(FLAGS.base_dir, FLAGS)\n\n# shape of test simulation\nshape = FLAGS.test_dimensions.split('x')\nshape = map(int, shape)\n\n# 2d or not\nd2d = False\nif len(shape) == 2:\n d2d = True\n\ndef evaluate_compression_error():\n\n \"\"\" Eval the system\"\"\"\n with tf.Graph().as_default():\n # make inputs\n state, boundary = inputs(empty=True, shape=shape)\n\n # unwrap\n y_1, small_boundary_mul, small_boundary_add, x_2, y_2 = continual_unroll_template(state, boundary)\n\n # calc mean squared error\n mean_squared_error = tf.nn.l2_loss(state - x_2)\n x_2_add = add_lattice(x_2)\n velocity_generated = lattice_to_vel(x_2_add)\n\n # restore network\n variables_to_restore = tf.all_variables()\n saver = tf.train.Saver(variables_to_restore)\n sess = tf.Session()\n ckpt = tf.train.get_checkpoint_state(RESTORE_DIR)\n if ckpt and ckpt.model_checkpoint_path:\n print(\"restoring file from \" + ckpt.model_checkpoint_path)\n saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n print(\"no chekcpoint file found from \" + RESTORE_DIR + \", this is an error\")\n exit()\n\n # run simulations\n mse = 0.0\n for sim in tqdm(xrange(FLAGS.test_nr_runs)):\n for step in tqdm(xrange(FLAGS.test_length)):\n # get frame\n state_feed_dict, boundary_feed_dict = feed_dict(1, shape, FLAGS.lattice_size, sim, step+1)\n fd = {state:state_feed_dict, boundary:boundary_feed_dict}\n mse += sess.run(mean_squared_error, feed_dict=fd)\n mse = mse/(FLAGS.test_nr_runs*FLAGS.test_length)\n\n # calc compression factor\n compression_size = float(FLAGS.filter_size_compression*np.prod(np.array([x / pow(2,FLAGS.nr_downsamples) for x in shape])))\n flow_size = float(FLAGS.lattice_size*np.prod(np.array(shape)))\n compression_ratio = compression_size/flow_size \n\n with open(\"figs/\" + \"compression_error_log.txt\", \"a\") as myfile:\n myfile.write(str(len(shape)) + ' ' + str(mse) + ' ' + str(compression_ratio) + \"\\n\")\n \n\ndef main(argv=None): # pylint: disable=unused-argument\n evaluate_compression_error()\n\n\nif __name__ == '__main__':\n tf.app.run()\n"
] |
[
[
"numpy.zeros",
"tensorflow.Graph",
"tensorflow.Session",
"tensorflow.app.run",
"tensorflow.global_variables_initializer"
],
[
"numpy.array",
"tensorflow.Graph",
"tensorflow.Session",
"tensorflow.train.Saver",
"tensorflow.train.get_checkpoint_state",
"tensorflow.nn.l2_loss",
"tensorflow.app.run",
"tensorflow.all_variables"
]
] |
CompPsy/pytorch
|
[
"05f50309d227991659e143889e309019b648ee94"
] |
[
"test/test_linalg.py"
] |
[
"# -*- coding: utf-8 -*-\nimport torch\nimport numpy as np\n\nimport unittest\nimport itertools\nimport warnings\nimport math\nfrom math import inf, nan, isnan\nimport random\nfrom random import randrange\nfrom itertools import product\nfrom functools import reduce\n\nfrom torch.testing._internal.common_utils import \\\n (TestCase, run_tests, TEST_SCIPY, IS_MACOS, IS_WINDOWS, slowTest,\n TEST_WITH_ASAN, TEST_WITH_ROCM, IS_FBCODE, IS_REMOTE_GPU,\n iter_indices, gradcheck, gradgradcheck)\nfrom torch.testing._internal.common_device_type import \\\n (instantiate_device_type_tests, dtypes,\n onlyCPU, skipCUDAIf, skipCUDAIfNoMagma, skipCPUIfNoLapack, precisionOverride,\n skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, onlyOnCPUAndCUDA, dtypesIfCUDA,\n onlyCUDA, skipCUDAVersionIn, skipMeta, skipCUDAIfNoCusolver)\nfrom torch.testing import floating_and_complex_types, floating_types, all_types, make_tensor\nfrom torch.testing._internal.common_cuda import SM53OrLater, tf32_on_and_off, CUDA11OrLater, CUDA9\nfrom torch.distributions.binomial import Binomial\n\n# Protects against includes accidentally setting the default dtype\n# NOTE: jit_metaprogramming_utils sets the default dtype to double!\ntorch.set_default_dtype(torch.float32)\nassert torch.get_default_dtype() is torch.float32\n\nif TEST_SCIPY:\n import scipy\n\nclass TestLinalg(TestCase):\n def setUp(self):\n super(self.__class__, self).setUp()\n torch.backends.cuda.matmul.allow_tf32 = False\n\n def tearDown(self):\n torch.backends.cuda.matmul.allow_tf32 = True\n super(self.__class__, self).tearDown()\n\n exact_dtype = True\n\n @dtypes(torch.float, torch.cfloat)\n @precisionOverride({torch.float: 1e-06, torch.cfloat: 1e-06})\n @tf32_on_and_off(5e-3)\n def test_inner(self, device, dtype):\n def check(a_sizes_, b_sizes_):\n for a_sizes, b_sizes in ((a_sizes_, b_sizes_), (b_sizes_, a_sizes_)):\n a = torch.randn(a_sizes, dtype=dtype, device=device)\n b = torch.randn(b_sizes, dtype=dtype, device=device)\n res = torch.inner(a, b)\n ref = np.inner(a.cpu().numpy(), b.cpu().numpy())\n self.assertEqual(res.cpu(), torch.from_numpy(np.array(ref)))\n out = torch.zeros_like(res)\n torch.inner(a, b, out=out)\n self.assertEqual(res, out)\n\n check([], []) # scalar x scalar\n check([], [0]) # scalar x empty\n check([], [3]) # scalar x 1D\n check([], [2, 3, 4]) # scalar x 3D\n\n check([0], [0]) # empty x empty\n check([0], [2, 0]) # empty x 2D\n\n check([2], [2]) # 1D x 1D\n check([2], [3, 1, 2]) # 1D x 3D\n check([2], [3, 0, 2]) # 1D x 3D empty\n\n check([1, 2], [3, 2]) # 2D x 2D\n check([1, 2], [3, 4, 2]) # 2D x 3D\n check([2, 1, 3, 2], [1, 3, 2, 2]) # 4D x 4D\n\n # Test noncontiguous input\n a = torch.randn(3, 2, device=device, dtype=dtype).transpose_(0, 1)\n b = torch.randn(4, 3, device=device, dtype=dtype)[::2, :]\n self.assertFalse(a.is_contiguous() or b.is_contiguous())\n self.assertEqual(a.inner(b).cpu().numpy(), np.inner(a.cpu().numpy(), b.cpu().numpy()))\n\n # Test error message\n with self.assertRaisesRegex(RuntimeError,\n r\"inner\\(\\) the last dimension must match on both \"\n r\"input tensors but got shapes \\[2, 3\\] and \\[2, 2\\]\"):\n torch.randn(2, 3, device=device, dtype=dtype).inner(torch.randn(2, 2, device=device, dtype=dtype))\n\n # Tests torch.outer, and its alias, torch.ger, vs. NumPy\n @precisionOverride({torch.bfloat16: 1e-1})\n @dtypes(*(torch.testing.get_all_dtypes()))\n def test_outer(self, device, dtype):\n def run_test_case(a, b):\n if dtype == torch.bfloat16:\n a_np = a.to(torch.double).cpu().numpy()\n b_np = b.to(torch.double).cpu().numpy()\n exact_dtype = False\n else:\n a_np = a.cpu().numpy()\n b_np = b.cpu().numpy()\n exact_dtype = True\n expected = np.outer(a_np, b_np)\n\n self.assertEqual(torch.outer(a, b), expected, exact_dtype=False)\n self.assertEqual(torch.Tensor.outer(a, b), expected, exact_dtype=False)\n\n self.assertEqual(torch.ger(a, b), expected, exact_dtype=False)\n self.assertEqual(torch.Tensor.ger(a, b), expected, exact_dtype=False)\n\n # test out variant\n out = torch.empty(a.size(0), b.size(0), device=device, dtype=dtype)\n torch.outer(a, b, out=out)\n self.assertEqual(out, expected, exact_dtype=False)\n\n out = torch.empty(a.size(0), b.size(0), device=device, dtype=dtype)\n torch.ger(a, b, out=out)\n self.assertEqual(out, expected, exact_dtype=False)\n\n a = torch.randn(50).to(device=device, dtype=dtype)\n b = torch.randn(50).to(device=device, dtype=dtype)\n run_test_case(a, b)\n\n # test 0 strided tensor\n zero_strided = torch.randn(1).to(device=device, dtype=dtype).expand(50)\n run_test_case(zero_strided, b)\n run_test_case(a, zero_strided)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_linalg_lstsq(self, device, dtype):\n from torch.testing._internal.common_utils import random_well_conditioned_matrix\n if self.device_type == 'cpu':\n drivers = ('gels', 'gelsy', 'gelsd', 'gelss', None)\n else:\n drivers = ('gels', None)\n\n def check_solution_correctness(a, b, sol):\n sol2 = a.pinverse() @ b\n self.assertEqual(sol, sol2, atol=1e-5, rtol=1e-5)\n\n def check_correctness_ref(a, b, res, ref, driver=\"default\"):\n def apply_if_not_empty(t, f):\n if t.numel():\n return f(t)\n else:\n return t\n\n def select_if_not_empty(t, i):\n selected = apply_if_not_empty(t, lambda x: x.select(0, i))\n return selected\n\n m = a.size(-2)\n n = a.size(-1)\n nrhs = b.size(-1)\n batch_size = int(np.prod(a.shape[:-2]))\n if batch_size == 0:\n batch_size = 1\n a_3d = a.view(batch_size, m, n)\n b_3d = b.view(batch_size, m, nrhs)\n\n solution_3d = res.solution.view(batch_size, n, nrhs)\n residuals_2d = apply_if_not_empty(res.residuals, lambda t: t.view(-1, nrhs))\n rank_1d = apply_if_not_empty(res.rank, lambda t: t.view(-1))\n singular_values_2d = res.singular_values.view(batch_size, res.singular_values.shape[-1])\n\n if a.numel() > 0:\n for i in range(batch_size):\n sol, residuals, rank, singular_values = ref(\n a_3d.select(0, i).numpy(),\n b_3d.select(0, i).numpy()\n )\n # Singular values are None when lapack_driver='gelsy' in SciPy\n if singular_values is None:\n singular_values = []\n self.assertEqual(sol, solution_3d.select(0, i), atol=1e-5, rtol=1e-5)\n self.assertEqual(rank, select_if_not_empty(rank_1d, i), atol=1e-5, rtol=1e-5)\n self.assertEqual(singular_values, singular_values_2d.select(0, i), atol=1e-5, rtol=1e-5)\n\n # SciPy and NumPy operate only on non-batched input and\n # return an empty array with shape (0,) if rank(a) != n\n # in PyTorch the batched inputs are supported and\n # matrices in the batched input can have different ranks\n # we compute residuals only if all matrices have rank == n\n # see https://github.com/pytorch/pytorch/issues/56483\n if m > n:\n if torch.all(rank_1d == n):\n self.assertEqual(\n residuals, select_if_not_empty(residuals_2d, i), atol=1e-5, rtol=1e-5, exact_dtype=False\n )\n else:\n self.assertTrue(residuals_2d.numel() == 0)\n\n else:\n self.assertEqual(res.solution.shape, (*a.shape[:-2], n, nrhs))\n self.assertEqual(res.rank.shape, a.shape[:-2])\n\n # residuals are not always computed (and have non-zero shape)\n if m > n and driver != \"gelsy\":\n self.assertEqual(res.residuals.shape, (*a.shape[:-2], 0))\n else:\n self.assertEqual(res.residuals.shape, (0, ))\n\n # singular_values are not always computed (and have non-zero shape)\n if driver == \"default\" or driver == \"gelsd\" or driver == \"gelss\":\n self.assertEqual(res.singular_values.shape, (*a.shape[:-2], min(m, n)))\n else:\n self.assertEqual(res.singular_values.shape, (0, ))\n\n def check_correctness_scipy(a, b, res, driver, cond):\n # SciPy provides 3 driver options: gelsd, gelss, gelsy\n if TEST_SCIPY and driver in ('gelsd', 'gelss', 'gelsy'):\n import scipy.linalg\n\n def scipy_ref(a, b):\n return scipy.linalg.lstsq(a, b, lapack_driver=driver, cond=cond)\n check_correctness_ref(a, b, res, scipy_ref, driver=driver)\n\n def check_correctness_numpy(a, b, res, driver, rcond):\n # NumPy uses only gelsd routine\n if driver == 'gelsd':\n\n def numpy_ref(a, b):\n return np.linalg.lstsq(a, b, rcond=rcond)\n check_correctness_ref(a, b, res, numpy_ref)\n\n version = torch.testing._internal.common_cuda._get_torch_cuda_version()\n cusolver_available = (version >= (10, 2))\n\n ms = [2 ** i for i in range(5)]\n m_ge_n_sizes = [(m, m // 2) for m in ms] + [(m, m) for m in ms]\n # cases m < n are only supported on CPU and for cuSOLVER path on CUDA\n m_l_n_sizes = [(m // 2, m) for m in ms]\n include_m_l_n_case = (cusolver_available or device == 'cpu')\n matrix_sizes = m_ge_n_sizes + (m_l_n_sizes if include_m_l_n_case else [])\n batches = [(), (2,), (2, 2), (2, 2, 2)]\n # we generate matrices with singular values sampled from a normal distribution,\n # that is why we use `cond=1.0`, the mean to cut roughly half of all\n # the singular values and compare whether torch.linalg.lstsq agrees with\n # SciPy and NumPy.\n # if rcond is True then set value for it based on the used algorithm\n # rcond == -1 or any other negative value forces LAPACK to use machine precision tolerance\n rconds = (None, True, -1)\n\n for batch, matrix_size, driver, rcond in itertools.product(batches, matrix_sizes, drivers, rconds):\n # keep the rcond value if it is None or -1, set the driver specific value if it is True\n if rcond and rcond != -1:\n if driver in ('gelss', 'gelsd'):\n # SVD based algorithm; set to zero roughly half of all the singular values\n rcond = 1.0\n else:\n # driver == 'gelsy'\n # QR based algorithm; setting the value too high might lead to non-unique solutions and flaky tests\n rcond = 1e-4\n\n # specifying rcond value has no effect for gels driver so no need to run the tests again\n if driver == 'gels' and rcond is not None:\n continue\n\n shape = batch + matrix_size\n a = random_well_conditioned_matrix(*shape, dtype=dtype, device=device)\n b = torch.rand(*shape, dtype=dtype, device=device)\n\n m = a.size(-2)\n n = a.size(-1)\n res = torch.linalg.lstsq(a, b, rcond=rcond, driver=driver)\n sol = res.solution\n\n # Only checks gelsd, gelss, gelsy drivers\n check_correctness_scipy(a, b, res, driver, rcond)\n\n # Only checks gelsd driver\n check_correctness_numpy(a, b, res, driver, rcond)\n\n # gels driver is not checked by comparing to NumPy or SciPy implementation\n # because NumPy and SciPy do not implement this driver\n if driver == 'gels' and rcond is None:\n check_solution_correctness(a, b, sol)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_linalg_lstsq_batch_broadcasting(self, device, dtype):\n from torch.testing._internal.common_utils import random_well_conditioned_matrix\n\n def check_correctness(a, b):\n sol = torch.linalg.lstsq(a, b).solution\n sol2 = a.pinverse() @ b\n self.assertEqual(sol, sol2, rtol=1e-5, atol=1e-5)\n\n ms = [2 ** i for i in range(5)]\n batches = [(), (0,), (2,), (2, 2), (2, 2, 2)]\n # the case when a single matrix is batch-broadcasted over the rhs\n for m, batch in itertools.product(ms, batches):\n a = random_well_conditioned_matrix(m, m, dtype=dtype, device=device).view(*([1] * len(batch)), m, m)\n b = torch.rand(*(batch + (m, m)), dtype=dtype, device=device)\n check_correctness(a, b)\n\n # cases with broadcastable shapes\n for m in ms:\n a = random_well_conditioned_matrix(1, 3, 1, 3, m, m, dtype=dtype, device=device)\n b = torch.rand(3, 1, 3, 1, m, m // 2, dtype=dtype, device=device)\n check_correctness(a, b)\n\n # rhs are vectors, not matrices in this test\n b = torch.rand(3, 1, 3, 1, m, dtype=dtype, device=device)\n # unsqueeze for b because `check_correctness` checks against\n # a.pinverse() @ b, which requires b to be a matrix\n check_correctness(a, b.unsqueeze(-1))\n\n a = random_well_conditioned_matrix(3, 1, 3, 1, m, m, dtype=dtype, device=device)\n b = torch.rand(1, 3, 1, 3, m, m // 2, dtype=dtype, device=device)\n check_correctness(a, b)\n\n # rhs are vectors, not matrices in this test\n b = torch.rand(1, 3, 1, 3, m, dtype=dtype, device=device)\n check_correctness(a, b.unsqueeze(-1))\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_linalg_lstsq_input_checks(self, device, dtype):\n # check empty inputs\n # empty batches\n a = torch.rand(0, 0, 3, 3, dtype=dtype, device=device)\n b = torch.rand(0, 0, 3, 2, dtype=dtype, device=device)\n self.assertEqual(\n torch.linalg.lstsq(a, b)[0],\n torch.zeros(0, 0, 3, 2, dtype=dtype, device=device)\n )\n # empty a and b\n a = torch.rand(2, 2, 0, 0, dtype=dtype, device=device)\n b = torch.rand(2, 2, 0, 0, dtype=dtype, device=device)\n self.assertEqual(\n torch.linalg.lstsq(a, b)[0],\n torch.zeros(2, 2, 0, 0, dtype=dtype, device=device)\n )\n # empty a and b\n a = torch.rand(2, 2, 3, 0, dtype=dtype, device=device)\n b = torch.rand(2, 2, 3, 0, dtype=dtype, device=device)\n self.assertEqual(\n torch.linalg.lstsq(a, b)[0],\n torch.zeros(2, 2, 0, 0, dtype=dtype, device=device)\n )\n # empty a but not b\n a = torch.rand(2, 2, 3, 0, dtype=dtype, device=device)\n b = torch.rand(2, 2, 3, 2, dtype=dtype, device=device)\n self.assertEqual(\n torch.linalg.lstsq(a, b)[0],\n torch.zeros(2, 2, 0, 2, dtype=dtype, device=device)\n )\n\n # empty a and b\n if torch.device(device).type == 'cpu':\n # only CPU since CUDA does not support overdetermined systems\n a = torch.rand(2, 2, 0, 3, dtype=dtype, device=device)\n b = torch.rand(2, 2, 0, 3, dtype=dtype, device=device)\n self.assertEqual(\n torch.linalg.lstsq(a, b)[0],\n torch.zeros(2, 2, 3, 3, dtype=dtype, device=device)\n )\n\n a = torch.rand(2, 3, dtype=dtype, device=device)\n b = torch.rand(3, dtype=dtype, device=device)\n\n with self.assertRaisesRegex(RuntimeError, 'input must have at least 2 dimensions'):\n torch.linalg.lstsq(b, b)\n\n with self.assertRaisesRegex(RuntimeError, 'other must have at least 1 dimension'):\n torch.linalg.lstsq(a, torch.tensor(1, dtype=dtype, device=device))\n\n with self.assertRaisesRegex(RuntimeError, r'input.size\\(-2\\) should match other.size\\(-1\\)'):\n torch.linalg.lstsq(a, b)\n\n with self.assertRaisesRegex(RuntimeError, r'input.size\\(-2\\) should match other.size\\(-2\\)'):\n torch.linalg.lstsq(a, b.unsqueeze(-1))\n\n def complement_device(device):\n if device == 'cpu' and torch.cuda.is_available():\n return 'cuda'\n else:\n return 'cpu'\n\n a = torch.rand(2, 2, 2, 2, dtype=dtype, device=device)\n b = torch.rand(2, 2, 2, dtype=dtype, device=complement_device(device))\n if a.device != b.device:\n with self.assertRaisesRegex(RuntimeError, 'be on the same device'):\n torch.linalg.lstsq(a, b)\n\n b = (torch.rand(2, 2, 2, dtype=dtype, device=device) * 100).long()\n with self.assertRaisesRegex(RuntimeError, 'the same dtype'):\n torch.linalg.lstsq(a, b)\n\n a = torch.rand(2, 2, 2, 2, dtype=dtype, device=device)\n b = torch.rand(2, 2, 2, dtype=dtype, device=device)\n\n if device != 'cpu':\n with self.assertRaisesRegex(RuntimeError, '`driver` other than `gels` is not supported on CUDA'):\n torch.linalg.lstsq(a, b, driver='fictitious_driver')\n # if on cpu\n else:\n with self.assertRaisesRegex(RuntimeError, r'parameter `driver` should be one of \\(gels, gelsy, gelsd, gelss\\)'):\n torch.linalg.lstsq(a, b, driver='fictitious_driver')\n\n # cuSOLVER path supports underdetermined systems\n version = torch.testing._internal.common_cuda._get_torch_cuda_version()\n cusolver_not_available = (version < (10, 1))\n\n if device != 'cpu' and cusolver_not_available:\n a = torch.rand(2, 3, dtype=dtype, device=device)\n b = torch.rand(2, 1, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, r'only overdetermined systems'):\n torch.linalg.lstsq(a, b)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n def run_test(shape, batch, contiguous):\n A = random_hermitian_pd_matrix(shape, *batch, dtype=dtype, device=device)\n if A.numel() > 0 and not contiguous:\n A = A.transpose(-2, -1)\n self.assertFalse(A.is_contiguous())\n expected_L = np.linalg.cholesky(A.cpu().numpy())\n actual_L = torch.linalg.cholesky(A)\n\n # For fp32 individual entries in matrices can differ between PyTorch and NumPy\n # Let's compare the norms of matrices instead\n if A.numel() > 0 and dtype in [torch.float32, torch.complex64]:\n # axis is specified to calculate matrix norm for batched input\n expected_norm = np.linalg.norm(expected_L, ord=1, axis=(-2, -1))\n actual_norm = torch.linalg.norm(actual_L, ord=1, axis=(-2, -1))\n # Compare the norms with standard tolerances\n self.assertEqual(actual_norm, expected_norm)\n # and individual values with a higher tolerance\n self.assertEqual(actual_L, expected_L, atol=1e-2, rtol=1e-5)\n else:\n self.assertEqual(actual_L, expected_L)\n\n shapes = (0, 3, 5)\n batches = ((), (3, ), (2, 2))\n larger_input_case = [(100, (5, ), True)]\n for shape, batch, contiguous in list(itertools.product(shapes, batches, (True, False))) + larger_input_case:\n run_test(shape, batch, contiguous)\n\n # check the out= variant\n A = random_hermitian_pd_matrix(3, 3, dtype=dtype, device=device)\n out = torch.empty_like(A)\n ans = torch.linalg.cholesky(A, out=out)\n self.assertEqual(ans, out)\n expected = torch.linalg.cholesky(A)\n self.assertEqual(expected, out)\n\n # check the upper= variant\n expected = torch.linalg.cholesky(A).transpose(-2, -1).conj()\n actual = torch.linalg.cholesky(A, upper=True)\n self.assertEqual(expected, actual)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky_errors_and_warnings(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n # cholesky requires the input to be a square matrix or batch of square matrices\n A = torch.randn(2, 3, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, r'must be batches of square matrices'):\n torch.linalg.cholesky(A)\n A = torch.randn(2, 2, 3, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, r'must be batches of square matrices'):\n torch.linalg.cholesky(A)\n with self.assertRaisesRegex(np.linalg.LinAlgError, r'Last 2 dimensions of the array must be square'):\n np.linalg.cholesky(A.cpu().numpy())\n\n # cholesky requires the input to be at least 2 dimensional tensor\n A = torch.randn(2, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, r'must have at least 2 dimensions'):\n torch.linalg.cholesky(A)\n with self.assertRaisesRegex(np.linalg.LinAlgError,\n r'1-dimensional array given\\. Array must be at least two-dimensional'):\n np.linalg.cholesky(A.cpu().numpy())\n\n # if the input matrix is singular, an error should be raised\n A = torch.eye(3, 3, dtype=dtype, device=device)\n A[-1, -1] = 0 # Now A is singular\n with self.assertRaisesRegex(RuntimeError, r'U\\(3,3\\) is zero, singular U\\.'):\n torch.linalg.cholesky(A)\n with self.assertRaisesRegex(np.linalg.LinAlgError, r'Matrix is not positive definite'):\n np.linalg.cholesky(A.cpu().numpy())\n\n # if at least one matrix in the batch is singular, an error should be raised\n A = torch.eye(3, 3, dtype=dtype, device=device)\n A = A.reshape((1, 3, 3))\n A = A.repeat(5, 1, 1)\n A[4, -1, -1] = 0 # Now A[4] is singular\n with self.assertRaisesRegex(RuntimeError, r'For batch 4: U\\(3,3\\) is zero, singular U\\.'):\n torch.linalg.cholesky(A)\n\n # if out tensor with wrong shape is passed a warning is given\n A = random_hermitian_pd_matrix(3, dtype=dtype, device=device)\n out = torch.empty(2, 3, dtype=dtype, device=device)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.cholesky(A, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out = torch.empty(*A.shape, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.linalg.cholesky(A, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, device=wrong_device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"Expected result and input tensors to be on the same device\"):\n torch.linalg.cholesky(A, out=out)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float64, torch.complex128)\n def test_cholesky_hermitian_grad(self, device, dtype):\n # Check that the gradient is Hermitian (or symmetric)\n def run_test(shape):\n root = torch.rand(*shape, dtype=dtype, device=device)\n root = torch.matmul(root, root.transpose(-1, -2).conj())\n root.requires_grad_()\n chol = torch.linalg.cholesky(root).sum().backward()\n self.assertEqual(root.grad, root.grad.transpose(-1, -2).conj())\n\n shapes = ((3, 3), (1, 1, 3, 3))\n for shape in shapes:\n run_test(shape)\n\n # NOTE: old_cholesky* tests were moved here from test_torch.py and test_autograd.py\n @slowTest\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double)\n def test_old_cholesky_batched_many_batches(self, device, dtype):\n from torch.testing._internal.common_utils import random_symmetric_pd_matrix\n\n def cholesky_test_helper(n, batchsize, device, upper):\n A = random_symmetric_pd_matrix(n, batchsize, dtype=dtype, device=device)\n chol_fact = torch.cholesky(A, upper=upper)\n if upper:\n # Correctness check\n self.assertEqual(A, chol_fact.transpose(-2, -1).matmul(chol_fact))\n # Upper triangular check\n self.assertEqual(chol_fact, chol_fact.triu())\n else:\n # Correctness check\n self.assertEqual(A, chol_fact.matmul(chol_fact.transpose(-2, -1)))\n # Lower triangular check\n self.assertEqual(chol_fact, chol_fact.tril())\n\n for upper, batchsize in itertools.product([True, False], [262144, 524288]):\n cholesky_test_helper(2, batchsize, device, upper)\n\n @precisionOverride({torch.float32: 1e-4, torch.complex64: 1e-4})\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_cholesky_batched(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n def cholesky_test_helper(n, batch_dims, upper):\n A = random_hermitian_pd_matrix(n, *batch_dims, dtype=dtype, device=device)\n cholesky_exp = torch.stack([m.cholesky(upper=upper) for m in A.reshape(-1, n, n)])\n cholesky_exp = cholesky_exp.reshape_as(A)\n self.assertEqual(cholesky_exp, torch.cholesky(A, upper=upper))\n\n for upper, batchsize in itertools.product([True, False], [(3,), (3, 4), (2, 3, 4)]):\n cholesky_test_helper(3, batchsize, upper)\n\n @precisionOverride({torch.float32: 1e-4, torch.complex64: 1e-4})\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @tf32_on_and_off(0.01)\n def test_old_cholesky(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n A = random_hermitian_pd_matrix(10, dtype=dtype, device=device)\n\n # default Case\n C = torch.cholesky(A)\n B = torch.mm(C, C.t().conj())\n self.assertEqual(A, B, atol=1e-14, rtol=0)\n\n # test Upper Triangular\n U = torch.cholesky(A, True)\n B = torch.mm(U.t().conj(), U)\n self.assertEqual(A, B, atol=1e-14, rtol=0, msg='cholesky (upper) did not allow rebuilding the original matrix')\n\n # test Lower Triangular\n L = torch.cholesky(A, False)\n B = torch.mm(L, L.t().conj())\n self.assertEqual(A, B, atol=1e-14, rtol=0, msg='cholesky (lower) did not allow rebuilding the original matrix')\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_cholesky_empty(self, device, dtype):\n def run_test(upper):\n A = torch.empty(0, 0, dtype=dtype, device=device)\n chol = torch.cholesky(A, upper)\n chol_A = torch.matmul(chol, chol.t().conj())\n self.assertEqual(A, chol_A)\n for upper in [True, False]:\n run_test(upper)\n\n # Test for issue\n # https://github.com/pytorch/pytorch/issues/57032\n # torch.cholesky with upper=True for batched CUDA inputs was wrong\n # it was using the lower triangular part instead of the upper one\n @onlyCUDA\n @skipCUDAIfNoMagma\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_cholesky_batched_upper(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n batchsize = 2\n A = random_hermitian_pd_matrix(3, batchsize, dtype=dtype, device=device)\n A_triu = A.triu() # fill the lower triangular part with zero\n\n U = torch.cholesky(A_triu, upper=True)\n\n reconstruct_A = U.conj().transpose(-2, -1) @ U\n self.assertEqual(A, reconstruct_A)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky_ex(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n def run_test(n, batch):\n A = random_hermitian_pd_matrix(n, *batch, dtype=dtype, device=device)\n expected_L = np.linalg.cholesky(A.cpu().numpy())\n expected_info = torch.zeros(A.shape[:-2], dtype=torch.int32, device=device)\n actual_L, actual_info = torch.linalg.cholesky_ex(A)\n\n # For fp32 individual entries in matrices can differ between PyTorch and NumPy\n # Let's compare the norms of matrices instead\n if A.numel() > 0 and dtype in [torch.float32, torch.complex64]:\n # axis is specified to calculate matrix norm for batched input\n expected_norm = np.linalg.norm(expected_L, ord=1, axis=(-2, -1))\n actual_norm = torch.linalg.norm(actual_L, ord=1, axis=(-2, -1))\n # Compare the norms with standard tolerances\n self.assertEqual(actual_norm, expected_norm)\n # and individual values with a higher tolerance\n self.assertEqual(actual_L, expected_L, atol=1e-2, rtol=1e-5)\n else:\n self.assertEqual(actual_L, expected_L)\n self.assertEqual(actual_info, expected_info)\n\n ns = (0, 3, 5)\n batches = ((), (2, ), (2, 1))\n for n, batch in itertools.product(ns, batches):\n run_test(n, batch)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky_ex_non_pd(self, device, dtype):\n # if the input matrix is not positive definite, info with positive integer is returned\n A = torch.eye(3, 3, dtype=dtype, device=device)\n A[-1, -1] = 0 # Now A is singular\n _, info = torch.linalg.cholesky_ex(A)\n self.assertEqual(info, 3)\n with self.assertRaisesRegex(RuntimeError, r'U\\(3,3\\) is zero, singular U\\.'):\n torch.linalg.cholesky_ex(A, check_errors=True)\n\n # if at least one matrix in the batch is not positive definite,\n # batched info with positive integer for the corresponding matrix is returned\n A = torch.eye(3, 3, dtype=dtype, device=device)\n A = A.reshape((1, 3, 3))\n A = A.repeat(5, 1, 1)\n A[3, -2, -2] = 0 # Now A[3] is singular\n _, info = torch.linalg.cholesky_ex(A)\n\n expected_info = torch.zeros(A.shape[:-2], dtype=torch.int32, device=device)\n expected_info[3] = 2\n self.assertEqual(info, expected_info)\n with self.assertRaisesRegex(RuntimeError, r'For batch 3: U\\(2,2\\) is zero, singular U\\.'):\n torch.linalg.cholesky_ex(A, check_errors=True)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky_ex_out_info_error(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n # dtype for info must be torch.int32\n A = random_hermitian_pd_matrix(3, dtype=dtype, device=device)\n L = torch.empty(A.shape, dtype=dtype, device=device)\n info = torch.empty(A.shape[:-2], dtype=torch.int64, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got info with dtype Long\"):\n torch.linalg.cholesky_ex(A, out=(L, info))\n\n @onlyCPU\n @skipCPUIfNoLapack\n @dtypes(torch.float64, torch.complex128)\n def test_old_cholesky_autograd(self, device, dtype):\n def func(root, upper):\n x = 0.5 * (root + root.transpose(-1, -2).conj())\n return torch.cholesky(x, upper)\n\n def run_test(upper, dims):\n root = torch.rand(*dims, dtype=dtype, device=device, requires_grad=True)\n root = root + torch.eye(dims[-1])\n\n gradcheck(func, [root, upper])\n gradgradcheck(func, [root, upper])\n\n root = torch.rand(*dims, dtype=dtype, device=device)\n root = torch.matmul(root, root.transpose(-1, -2).conj())\n root.requires_grad_()\n chol = root.cholesky().sum().backward()\n self.assertEqual(root.grad, root.grad.transpose(-1, -2).conj()) # Check the gradient is hermitian\n\n for upper, dims in itertools.product([True, False], [(3, 3), (4, 3, 2, 2)]):\n run_test(upper, dims)\n\n def _test_addr_vs_numpy(self, device, dtype, beta=1, alpha=1):\n def check(m, a, b, beta, alpha):\n if dtype == torch.bfloat16:\n a_np = a.to(torch.double).cpu().numpy()\n b_np = b.to(torch.double).cpu().numpy()\n m_np = m.to(torch.double).cpu().numpy()\n exact_dtype = False\n else:\n a_np = a.cpu().numpy()\n b_np = b.cpu().numpy()\n m_np = m.cpu().numpy()\n exact_dtype = True\n if beta == 0:\n expected = alpha * np.outer(a_np, b_np)\n else:\n expected = beta * m_np + alpha * np.outer(a_np, b_np)\n\n res = torch.addr(m, a, b, beta=beta, alpha=alpha)\n self.assertEqual(res, expected, exact_dtype=exact_dtype)\n\n # Test out variant\n out = torch.empty_like(res)\n torch.addr(m, a, b, beta=beta, alpha=alpha, out=out)\n self.assertEqual(out, expected, exact_dtype=exact_dtype)\n\n m = make_tensor((50, 50), device=device, dtype=dtype, low=-2, high=2)\n a = make_tensor((50,), device=device, dtype=dtype, low=-2, high=2)\n b = make_tensor((50,), device=device, dtype=dtype, low=-2, high=2)\n\n check(m, a, b, beta, alpha)\n\n # test transpose\n m_transpose = torch.transpose(m, 0, 1)\n check(m_transpose, a, b, beta, alpha)\n\n # test 0 strided tensor\n zero_strided = make_tensor((1,), device=device, dtype=dtype, low=-2, high=2).expand(50)\n check(m, zero_strided, b, beta, alpha)\n\n # test scalar\n m_scalar = torch.tensor(1, device=device, dtype=dtype)\n check(m_scalar, a, b, beta, alpha)\n\n # test nans and infs are not propagated to the output when beta == 0\n float_and_complex_dtypes = torch.testing.get_all_fp_dtypes() + torch.testing.get_all_complex_dtypes()\n if beta == 0 and dtype in float_and_complex_dtypes:\n m[0][10] = m[10][10] = m[20][20] = float('inf')\n m[1][10] = m[11][10] = m[21][20] = float('nan')\n check(m, a, b, 0, alpha)\n\n @dtypes(torch.bool)\n def test_addr_bool(self, device, dtype):\n self._test_addr_vs_numpy(device, dtype, beta=True, alpha=False)\n self._test_addr_vs_numpy(device, dtype, beta=False, alpha=True)\n self._test_addr_vs_numpy(device, dtype, beta=False, alpha=False)\n self._test_addr_vs_numpy(device, dtype, beta=True, alpha=True)\n\n @dtypes(*(torch.testing.get_all_int_dtypes()))\n def test_addr_integral(self, device, dtype):\n with self.assertRaisesRegex(RuntimeError,\n 'argument beta must not be a floating point number.'):\n self._test_addr_vs_numpy(device, dtype, beta=2., alpha=1)\n with self.assertRaisesRegex(RuntimeError,\n 'argument alpha must not be a floating point number.'):\n self._test_addr_vs_numpy(device, dtype, beta=2, alpha=1.)\n with self.assertRaisesRegex(RuntimeError,\n 'Boolean beta only supported for Boolean results.'):\n self._test_addr_vs_numpy(device, dtype, beta=True, alpha=1)\n with self.assertRaisesRegex(RuntimeError,\n 'Boolean alpha only supported for Boolean results.'):\n self._test_addr_vs_numpy(device, dtype, beta=2, alpha=True)\n\n # when beta is zero\n self._test_addr_vs_numpy(device, dtype, beta=0, alpha=2)\n # when beta is not zero\n self._test_addr_vs_numpy(device, dtype, beta=2, alpha=2)\n\n @precisionOverride({torch.bfloat16: 1e-1})\n @dtypes(*(torch.testing.get_all_fp_dtypes() + torch.testing.get_all_complex_dtypes()))\n def test_addr_float_and_complex(self, device, dtype):\n with self.assertRaisesRegex(RuntimeError,\n 'Boolean beta only supported for Boolean results.'):\n self._test_addr_vs_numpy(device, dtype, beta=True, alpha=1)\n with self.assertRaisesRegex(RuntimeError,\n 'Boolean alpha only supported for Boolean results.'):\n self._test_addr_vs_numpy(device, dtype, beta=2, alpha=True)\n\n # when beta is zero\n self._test_addr_vs_numpy(device, dtype, beta=0., alpha=2)\n # when beta is not zero\n self._test_addr_vs_numpy(device, dtype, beta=0.5, alpha=2)\n if dtype in torch.testing.get_all_complex_dtypes():\n self._test_addr_vs_numpy(device, dtype, beta=(0 + 0.1j), alpha=(0.2 - 0.2j))\n\n @dtypes(*itertools.product(torch.testing.get_all_dtypes(),\n torch.testing.get_all_dtypes()))\n def test_outer_type_promotion(self, device, dtypes):\n a = torch.randn(5).to(device=device, dtype=dtypes[0])\n b = torch.randn(5).to(device=device, dtype=dtypes[1])\n for op in (torch.outer, torch.Tensor.outer, torch.ger, torch.Tensor.ger):\n result = op(a, b)\n self.assertEqual(result.dtype, torch.result_type(a, b))\n\n @dtypes(*itertools.product(torch.testing.get_all_dtypes(),\n torch.testing.get_all_dtypes(),\n torch.testing.get_all_dtypes()))\n def test_addr_type_promotion(self, device, dtypes):\n a = make_tensor((5,), device=device, dtype=dtypes[0], low=-2, high=2)\n b = make_tensor((5,), device=device, dtype=dtypes[1], low=-2, high=2)\n m = make_tensor((5, 5), device=device, dtype=dtypes[2], low=-2, high=2)\n\n desired_dtype = torch.promote_types(torch.promote_types(dtypes[0], dtypes[1]),\n dtypes[2])\n for op in (torch.addr, torch.Tensor.addr):\n result = op(m, a, b)\n self.assertEqual(result.dtype, desired_dtype)\n\n # Tests migrated from test_torch.py\n # 1) test the shape of the result tensor when there is empty input tensor\n # 2) test the Runtime Exception when there is scalar input tensor\n def test_outer_ger_addr_legacy_tests(self, device):\n for size in ((0, 0), (0, 5), (5, 0)):\n a = torch.rand(size[0], device=device)\n b = torch.rand(size[1], device=device)\n\n self.assertEqual(torch.outer(a, b).shape, size)\n self.assertEqual(torch.ger(a, b).shape, size)\n\n m = torch.empty(size, device=device)\n self.assertEqual(torch.addr(m, a, b).shape, size)\n\n m = torch.randn(5, 6, device=device)\n a = torch.randn(5, device=device)\n b = torch.tensor(6, device=device)\n self.assertRaises(RuntimeError, lambda: torch.outer(a, b))\n self.assertRaises(RuntimeError, lambda: torch.outer(b, a))\n self.assertRaises(RuntimeError, lambda: torch.ger(a, b))\n self.assertRaises(RuntimeError, lambda: torch.ger(b, a))\n self.assertRaises(RuntimeError, lambda: torch.addr(m, a, b))\n self.assertRaises(RuntimeError, lambda: torch.addr(m, b, a))\n\n # Tests torch.det and its alias, torch.linalg.det, vs. NumPy\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double, torch.cdouble)\n def test_det(self, device, dtype):\n tensors = (\n torch.randn((2, 2), device=device, dtype=dtype),\n torch.randn((129, 129), device=device, dtype=dtype),\n torch.randn((3, 52, 52), device=device, dtype=dtype),\n torch.randn((4, 2, 26, 26), device=device, dtype=dtype))\n\n\n ops = (torch.det, torch.Tensor.det,\n torch.linalg.det)\n for t in tensors:\n expected = np.linalg.det(t.cpu().numpy())\n for op in ops:\n actual = op(t)\n self.assertEqual(actual, expected)\n self.compare_with_numpy(op, np.linalg.det, t)\n\n # NOTE: det requires a 2D+ tensor\n t = torch.randn(1, device=device, dtype=dtype)\n with self.assertRaises(RuntimeError):\n op(t)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-4, torch.complex64: 1e-4})\n def test_eigh(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_matrix\n\n def run_test(shape, batch, uplo):\n matrix = random_hermitian_matrix(shape, *batch, dtype=dtype, device=device)\n expected_w, expected_v = np.linalg.eigh(matrix.cpu().numpy(), UPLO=uplo)\n actual_w, actual_v = torch.linalg.eigh(matrix, UPLO=uplo)\n self.assertEqual(actual_w, expected_w)\n # sign of eigenvectors is not unique and therefore absolute values are compared\n self.assertEqual(abs(actual_v), abs(expected_v))\n # additionally we can multiply the eigenvector with a phase factor e^{i\\phi} and then compare the values\n # let's choose the convention that the first element of the eigenvectors from torch and numpy be the same\n # for real inputs, this phase factor is plus or minus one\n if matrix.numel() > 0:\n phase = torch.from_numpy(expected_v[..., 0, :]).to(device=device).div(actual_v[..., 0, :])\n actual_v_rotated = actual_v * phase.unsqueeze(-2).expand_as(actual_v)\n self.assertEqual(actual_v_rotated, expected_v)\n\n # check the out= variant\n out_w = torch.empty_like(actual_w)\n out_v = torch.empty_like(actual_v)\n ans_w, ans_v = torch.linalg.eigh(matrix, UPLO=uplo, out=(out_w, out_v))\n self.assertEqual(ans_w, out_w)\n self.assertEqual(ans_v, out_v)\n self.assertEqual(ans_w, actual_w)\n self.assertEqual(abs(ans_v), abs(actual_v))\n\n shapes = (0, 3, 5)\n batches = ((), (3, ), (2, 2))\n uplos = [\"U\", \"L\"]\n for shape, batch, uplo in itertools.product(shapes, batches, uplos):\n run_test(shape, batch, uplo)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-4, torch.complex64: 1e-4})\n def test_eigh_lower_uplo(self, device, dtype):\n def run_test(shape, batch, uplo):\n # check lower case uplo\n # use non-symmetric input to check whether uplo argument is working as intended\n matrix = torch.randn(shape, shape, *batch, dtype=dtype, device=device)\n expected_w, expected_v = np.linalg.eigh(matrix.cpu().numpy(), UPLO=uplo)\n actual_w, actual_v = torch.linalg.eigh(matrix, UPLO=uplo)\n self.assertEqual(actual_w, expected_w)\n self.assertEqual(abs(actual_v), abs(expected_v))\n\n uplos = [\"u\", \"l\"]\n for uplo in uplos:\n run_test(3, (2, 2), uplo)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_eigh_errors_and_warnings(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_matrix\n\n # eigh requires a square matrix\n t = torch.randn(2, 3, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"must be batches of square matrices\"):\n torch.linalg.eigh(t)\n\n # eigh requires 'uplo' parameter to be 'U' or 'L'\n t = torch.randn(3, 3, device=device, dtype=dtype)\n for uplo in [\"a\", \"wrong\"]:\n with self.assertRaisesRegex(RuntimeError, \"be \\'L\\' or \\'U\\'\"):\n torch.linalg.eigh(t, UPLO=uplo)\n with self.assertRaisesRegex(ValueError, \"be \\'L\\' or \\'U\\'\"):\n np.linalg.eigh(t.cpu().numpy(), UPLO=uplo)\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = random_hermitian_matrix(3, dtype=dtype, device=device)\n real_dtype = a.real.dtype if dtype.is_complex else dtype\n out_w = torch.empty(7, 7, dtype=real_dtype, device=device)\n out_v = torch.empty(7, 7, dtype=dtype, device=device)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.eigh(a, out=(out_w, out_v))\n # Check warning occurs\n self.assertEqual(len(w), 2)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-2].message))\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out_w = torch.empty(0, dtype=real_dtype, device=device)\n out_v = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got eigenvectors with dtype Int\"):\n torch.linalg.eigh(a, out=(out_w, out_v))\n\n out_w = torch.empty(0, dtype=torch.int, device=device)\n out_v = torch.empty(0, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got eigenvalues with dtype Int\"):\n torch.linalg.eigh(a, out=(out_w, out_v))\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out_w = torch.empty(0, device=wrong_device, dtype=dtype)\n out_v = torch.empty(0, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.eigh(a, out=(out_w, out_v))\n out_w = torch.empty(0, device=device, dtype=dtype)\n out_v = torch.empty(0, device=wrong_device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.eigh(a, out=(out_w, out_v))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-4, torch.complex64: 1e-4})\n def test_eigh_non_contiguous(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_matrix\n\n def run_test(matrix, uplo):\n self.assertFalse(matrix.is_contiguous())\n expected_w, expected_v = np.linalg.eigh(matrix.cpu().numpy(), UPLO=uplo)\n actual_w, actual_v = torch.linalg.eigh(matrix, UPLO=uplo)\n self.assertEqual(actual_w, expected_w)\n # sign of eigenvectors is not unique and therefore absolute values are compared\n self.assertEqual(abs(actual_v), abs(expected_v))\n\n def run_test_permuted(shape, batch, uplo):\n # check for permuted / transposed inputs\n matrix = random_hermitian_matrix(shape, *batch, dtype=dtype, device=device)\n matrix = matrix.transpose(-2, -1)\n run_test(matrix, uplo)\n\n def run_test_skipped_elements(shape, batch, uplo):\n # check for inputs with skipped elements\n matrix = random_hermitian_matrix(shape, *batch, dtype=dtype, device=device)\n matrix = matrix[::2]\n run_test(matrix, uplo)\n\n shapes = (3, 5)\n batches = ((4, ), (4, 2))\n uplos = [\"U\", \"L\"]\n for shape, batch, uplo in itertools.product(shapes, batches, uplos):\n run_test_permuted(shape, batch, uplo)\n run_test_skipped_elements(shape, batch, uplo)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float64, torch.complex128)\n def test_eigh_hermitian_grad(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_matrix\n\n def run_test(dims, uplo):\n x = random_hermitian_matrix(dims[-1], *dims[:-2]).requires_grad_()\n w, v = torch.linalg.eigh(x)\n (w.sum() + abs(v).sum()).backward()\n self.assertEqual(x.grad, x.grad.conj().transpose(-1, -2)) # Check the gradient is Hermitian\n\n for dims, uplo in itertools.product([(3, 3), (1, 1, 3, 3)], [\"L\", \"U\"]):\n run_test(dims, uplo)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-4, torch.complex64: 1e-4})\n def test_eigvalsh(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_matrix\n\n def run_test(shape, batch, uplo):\n matrix = random_hermitian_matrix(shape, *batch, dtype=dtype, device=device)\n expected_w = np.linalg.eigvalsh(matrix.cpu().numpy(), UPLO=uplo)\n actual_w = torch.linalg.eigvalsh(matrix, UPLO=uplo)\n self.assertEqual(actual_w, expected_w)\n\n # check the out= variant\n out = torch.empty_like(actual_w)\n ans = torch.linalg.eigvalsh(matrix, UPLO=uplo, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, actual_w)\n\n shapes = (0, 3, 5)\n batches = ((), (3, ), (2, 2))\n uplos = [\"U\", \"L\"]\n for shape, batch, uplo in itertools.product(shapes, batches, uplos):\n run_test(shape, batch, uplo)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_eigvalsh_errors_and_warnings(self, device, dtype):\n # eigvalsh requires a square matrix\n t = torch.randn(2, 3, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"must be batches of square matrices\"):\n torch.linalg.eigvalsh(t)\n\n # eigvalsh requires 'uplo' parameter to be 'U' or 'L'\n t = torch.randn(3, 3, device=device, dtype=dtype)\n for uplo in [\"a\", \"wrong\"]:\n with self.assertRaisesRegex(RuntimeError, \"be \\'L\\' or \\'U\\'\"):\n torch.linalg.eigvalsh(t, UPLO=uplo)\n with self.assertRaisesRegex(ValueError, \"be \\'L\\' or \\'U\\'\"):\n np.linalg.eigvalsh(t.cpu().numpy(), UPLO=uplo)\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n real_dtype = t.real.dtype if dtype.is_complex else dtype\n out = torch.empty_like(t).to(real_dtype)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.eigvalsh(t, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.linalg.eigvalsh(t, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, device=wrong_device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.eigvalsh(t, out=out)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-4, torch.complex64: 1e-4})\n def test_eigvalsh_non_contiguous(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_matrix\n\n def run_test(matrix, uplo):\n self.assertFalse(matrix.is_contiguous())\n expected_w = np.linalg.eigvalsh(matrix.cpu().numpy(), UPLO=uplo)\n actual_w = torch.linalg.eigvalsh(matrix, UPLO=uplo)\n self.assertEqual(actual_w, expected_w)\n\n def run_test_permuted(shape, batch, uplo):\n # check for permuted / transposed inputs\n matrix = random_hermitian_matrix(shape, *batch, dtype=dtype, device=device)\n matrix = matrix.transpose(-2, -1)\n run_test(matrix, uplo)\n\n def run_test_skipped_elements(shape, batch, uplo):\n # check for inputs with skipped elements\n matrix = random_hermitian_matrix(shape, *batch, dtype=dtype, device=device)\n matrix = matrix[::2]\n run_test(matrix, uplo)\n\n shapes = (3, 5)\n batches = ((4, ), (4, 2))\n uplos = [\"U\", \"L\"]\n for shape, batch, uplo in itertools.product(shapes, batches, uplos):\n run_test_permuted(shape, batch, uplo)\n run_test_skipped_elements(shape, batch, uplo)\n\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_kron(self, device, dtype):\n\n def run_test_case(a_shape, b_shape):\n a = torch.rand(a_shape, dtype=dtype, device=device)\n b = torch.rand(b_shape, dtype=dtype, device=device)\n\n expected = np.kron(a.cpu().numpy(), b.cpu().numpy())\n result = torch.kron(a, b)\n self.assertEqual(result, expected)\n\n # check the out= variant\n out = torch.empty_like(result)\n ans = torch.kron(a, b, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, result)\n\n shapes = [(4,), (2, 2), (1, 2, 3), (1, 2, 3, 3)]\n for a_shape, b_shape in itertools.product(shapes, reversed(shapes)):\n run_test_case(a_shape, b_shape)\n\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_kron_non_contiguous(self, device, dtype):\n\n def run_test_transposed(a_shape, b_shape):\n # check for transposed case\n a = torch.rand(a_shape, dtype=dtype, device=device).transpose(-2, -1)\n b = torch.rand(b_shape, dtype=dtype, device=device).transpose(-2, -1)\n self.assertFalse(a.is_contiguous())\n self.assertFalse(b.is_contiguous())\n\n expected = np.kron(a.cpu().numpy(), b.cpu().numpy())\n result = torch.kron(a, b)\n self.assertEqual(result, expected)\n\n # check the out= variant\n out = torch.empty(result.transpose(-2, -1).shape, dtype=dtype, device=device).transpose(-2, -1)\n self.assertFalse(out.is_contiguous())\n ans = torch.kron(a, b, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, result)\n\n def run_test_skipped_elements(a_shape, b_shape):\n # check for transposed case\n a = torch.rand(2 * a_shape[0], *a_shape[1:], dtype=dtype, device=device)[::2]\n b = torch.rand(2 * b_shape[0], *b_shape[1:], dtype=dtype, device=device)[::2]\n self.assertFalse(a.is_contiguous())\n self.assertFalse(b.is_contiguous())\n\n expected = np.kron(a.cpu().numpy(), b.cpu().numpy())\n result = torch.kron(a, b)\n self.assertEqual(result, expected)\n\n # check the out= variant\n out = torch.empty(2 * result.shape[0], *result.shape[1:], dtype=dtype, device=device)[::2]\n self.assertFalse(out.is_contiguous())\n ans = torch.kron(a, b, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, result)\n\n shapes = [(2, 2), (2, 2, 3), (2, 2, 3, 3)]\n for a_shape, b_shape in itertools.product(shapes, reversed(shapes)):\n # run_test_transposed(a_shape, b_shape)\n run_test_skipped_elements(a_shape, b_shape)\n\n # Test that kron perserve memory format\n a = torch.randn(1, 2, 3, 4, dtype=dtype, device=device).contiguous(memory_format=torch.channels_last)\n b = torch.randn(1, 2, 3, 4, dtype=dtype, device=device).contiguous(memory_format=torch.channels_last)\n c = torch.kron(a, b)\n self.assertTrue(c.is_contiguous(memory_format=torch.channels_last))\n torch.kron(a, b, out=c)\n self.assertTrue(c.is_contiguous(memory_format=torch.channels_last))\n c = c.contiguous(memory_format=torch.contiguous_format)\n torch.kron(a, b, out=c)\n self.assertTrue(c.is_contiguous(memory_format=torch.contiguous_format))\n\n\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_kron_empty(self, device, dtype):\n\n def run_test_case(empty_shape):\n a = torch.eye(3, dtype=dtype, device=device)\n b = torch.empty(empty_shape, dtype=dtype, device=device)\n result = torch.kron(a, b)\n expected = np.kron(a.cpu().numpy(), b.cpu().numpy())\n self.assertEqual(result, expected)\n\n # NumPy doesn't work if the first argument is empty\n result = torch.kron(b, a)\n self.assertEqual(result.shape, expected.shape)\n\n empty_shapes = [(0,), (2, 0), (1, 0, 3)]\n for empty_shape in empty_shapes:\n run_test_case(empty_shape)\n\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_kron_errors_and_warnings(self, device, dtype):\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = torch.eye(3, dtype=dtype, device=device)\n b = torch.ones((2, 2), dtype=dtype, device=device)\n out = torch.empty_like(a)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.kron(a, b, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should match\n out = torch.empty_like(a).to(torch.int)\n with self.assertRaisesRegex(RuntimeError, \"can't be cast to the desired output type\"):\n torch.kron(a, b, out=out)\n\n # This test confirms that torch.linalg.norm's dtype argument works\n # as expected, according to the function's documentation\n @skipCUDAIfNoMagma\n def test_norm_dtype(self, device):\n def run_test_case(input_size, ord, keepdim, from_dtype, to_dtype):\n # Determine the best dtype to use for comparisons between tensors\n # of two different types\n def get_compare_dtype(type0, type1):\n types_32bit_based = [torch.float, torch.cfloat]\n is_complex = type0.is_complex or type1.is_complex\n\n if type0 in types_32bit_based or type1 in types_32bit_based:\n return torch.cfloat if is_complex else torch.float\n else:\n return torch.cdouble if is_complex else torch.double\n\n compare_dtype = get_compare_dtype(from_dtype, to_dtype)\n\n def get_value_type(dtype):\n if dtype == torch.cfloat:\n return torch.float\n elif dtype == torch.cdouble:\n return torch.double\n elif dtype == torch.complex32:\n return torch.float16\n else:\n return dtype\n\n msg = (\n f'input_size={input_size}, ord={ord}, keepdim={keepdim}, '\n f'from_dtype={from_dtype}, to_dtype={to_dtype}')\n input = torch.randn(*input_size, dtype=from_dtype, device=device)\n result = torch.linalg.norm(input, ord, keepdim=keepdim)\n if from_dtype.is_complex:\n # By default, norm downgrades a complex input to the corresponding real number type\n self.assertEqual(result.dtype, get_value_type(from_dtype), msg=msg)\n else:\n self.assertEqual(result.dtype, from_dtype, msg=msg)\n\n result_out = torch.empty((0), dtype=to_dtype, device=device)\n torch.linalg.norm(input, ord, keepdim=keepdim, out=result_out)\n self.assertEqual(result_out.dtype, to_dtype, msg=msg)\n self.assertEqual(result.to(compare_dtype), result_out.to(compare_dtype), msg=msg)\n\n result_with_dtype = torch.linalg.norm(input, ord, keepdim=keepdim, dtype=to_dtype)\n self.assertEqual(result_with_dtype.dtype, to_dtype, msg=msg)\n\n if from_dtype.is_complex:\n result_convert_first = torch.linalg.norm(input.to(to_dtype), ord, keepdim=keepdim)\n self.assertEqual(result_with_dtype.to(compare_dtype), result_convert_first.to(compare_dtype), msg=msg)\n else:\n self.assertEqual(result.to(compare_dtype), result_with_dtype.to(compare_dtype), msg=msg)\n\n result_out_with_dtype = torch.empty_like(result_with_dtype)\n torch.linalg.norm(input, ord, keepdim=keepdim, dtype=to_dtype, out=result_out_with_dtype)\n self.assertEqual(result_out_with_dtype.dtype, to_dtype, msg=msg)\n self.assertEqual(result_with_dtype, result_out_with_dtype, msg=msg)\n\n ord_vector = [0, 0.1, -0.1, 1, -1, 2, -2, 3, -3, 4.5, -4.5, inf, -inf, None]\n ord_matrix = ['fro', 'nuc', 1, -1, 2, -2, inf, -inf, None]\n S = 10\n test_cases = [\n ((S, ), ord_vector),\n ((S, S), ord_matrix),\n ]\n for keepdim in [True, False]:\n for input_size, ord_settings in test_cases:\n for ord in ord_settings:\n dtypes = [torch.float, torch.double, torch.cfloat, torch.cdouble]\n for from_dtype, to_dtype in itertools.product(dtypes, dtypes):\n if from_dtype.is_complex and not to_dtype.is_complex:\n continue\n run_test_case(input_size, ord, keepdim, from_dtype, to_dtype)\n\n # Make sure that setting dtype != out.dtype raises an error\n dtype_pairs = [\n (torch.float, torch.double),\n (torch.double, torch.float),\n (torch.cfloat, torch.cdouble),\n (torch.cdouble, torch.cfloat),\n ]\n for keepdim in [True, False]:\n for input_size, ord_settings in test_cases:\n for ord in ord_settings:\n for dtype, out_dtype in dtype_pairs:\n input = torch.rand(*input_size)\n result = torch.tensor([]).to(out_dtype)\n with self.assertRaisesRegex(RuntimeError, r'provided dtype must match dtype of result'):\n torch.linalg.norm(input, ord=ord, keepdim=keepdim, dtype=dtype, out=result)\n\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble, torch.bfloat16, torch.float16)\n def test_vector_norm(self, device, dtype):\n # This test compares torch.linalg.vector_norm's output with\n # torch.linalg.norm given a flattened tensor\n ord_vector = [0, 0.9, 1, 2, 3, inf, -0.5, -1, -2, -3, -inf]\n input_sizes = [\n (10, ),\n (4, 5),\n (3, 4, 5),\n (0, ),\n (0, 10),\n (0, 0),\n (10, 0, 10),\n ]\n\n def vector_norm_reference(input, ord, dim=None, keepdim=False, dtype=None):\n if dim is None:\n input_maybe_flat = input.flatten(0, -1)\n else:\n input_maybe_flat = input\n\n result = torch.linalg.norm(input_maybe_flat, ord, dim=dim, keepdim=keepdim, dtype=dtype)\n if keepdim and dim is None:\n result = result.reshape([1] * input.dim())\n return result\n\n def run_test_case(input, ord, dim, keepdim, norm_dtype):\n msg = f'input.size()={input.size()}, ord={ord}, dim={dim}, keepdim={keepdim}, dtype={dtype}, norm_dtype={norm_dtype}'\n error_msg = None\n if input.numel() == 0:\n if ord < 0:\n error_msg = r'linalg.vector_norm of negative order cannot be performed on an empty tensor'\n elif ord == inf and (dim is None or input.size(dim) == 0):\n error_msg = (\n r'linalg.vector_norm cannot compute the infinity norm on an empty '\n r'dimension because the operation does not have an identity')\n if error_msg is None:\n result_dtype_reference = vector_norm_reference(input, ord, dim=dim, keepdim=keepdim, dtype=norm_dtype)\n result_dtype = torch.linalg.vector_norm(input, ord, dim=dim, keepdim=keepdim, dtype=norm_dtype)\n self.assertEqual(result_dtype, result_dtype_reference, msg=msg)\n\n if norm_dtype is not None:\n result_convert_before = torch.linalg.vector_norm(input.to(norm_dtype), ord, dim=dim, keepdim=keepdim)\n if norm_dtype.is_complex:\n result_convert_before = result_convert_before.to(norm_dtype)\n\n result_out = torch.empty((0), dtype=norm_dtype, device=device)\n torch.linalg.vector_norm(input, ord, dtype=norm_dtype, dim=dim, keepdim=keepdim, out=result_out)\n self.assertEqual(result_convert_before, result_out, msg=msg)\n else:\n result_out = torch.empty((0), dtype=result_dtype.dtype, device=device)\n torch.linalg.vector_norm(input, ord, dim=dim, keepdim=keepdim, out=result_out)\n self.assertEqual(result_dtype, result_out, msg=msg)\n else:\n with self.assertRaises(RuntimeError):\n vector_norm_reference(input, ord, dim=dim, keepdim=keepdim)\n with self.assertRaisesRegex(RuntimeError, error_msg):\n torch.linalg.vector_norm(input, ord, dim=dim, keepdim=keepdim)\n\n if dtype.is_complex:\n norm_dtypes = [None, torch.cfloat, torch.cdouble]\n else:\n norm_dtypes = [None, torch.float, torch.double, torch.cfloat, torch.cdouble, torch.float16, torch.bfloat16]\n\n for input_size, ord, keepdim, norm_dtype in product(input_sizes, ord_vector, [True, False], norm_dtypes):\n input = make_tensor(input_size, device, dtype, low=-9, high=9)\n for dim in [None, random.randint(0, len(input_size) - 1)]:\n run_test_case(\n input,\n ord,\n dim,\n keepdim,\n norm_dtype)\n\n def test_vector_norm_dim_tuple_arg(self, device):\n test_cases = [\n # input size, dim, error, error message\n ((4, ), (0, ), None, None),\n ((4, ), (1, ), IndexError, r'Dimension out of range'),\n ((4, ), (-2, ), IndexError, r'Dimension out of range'),\n ((4, 3), (0, -1), None, None),\n ((4, 3), (0, 0), RuntimeError, r'dim 0 appears multiple times in the list of dims'),\n ((4, 3), (0, -2), RuntimeError, r'dim 0 appears multiple times in the list of dims'),\n ((4, 3), (0, 1.0), TypeError, r\"argument 'dim' must be tuple of ints\"),\n ((4, 3), (None, ), TypeError, r\"argument 'dim' must be tuple of ints\"),\n ]\n for input_size, dim_tuple, error, error_msg in test_cases:\n input = torch.randn(input_size, device=device)\n # vector_norm should accept a tuple or a list for dim arg\n for dim in [dim_tuple, list(dim_tuple)]:\n if error is None:\n torch.linalg.vector_norm(input, dim=dim)\n else:\n with self.assertRaises(error):\n torch.linalg.vector_norm(input, dim=dim)\n\n # Test that linalg.vector_norm throws an error if the out tensor's dtype\n # does not match the expected output dtype\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble, torch.bfloat16, torch.float16)\n def test_vector_norm_out_dtype_error(self, device, dtype):\n input = torch.randn(10, device=device, dtype=dtype)\n dtypes = [None, torch.float, torch.double, torch.cfloat, torch.cdouble, torch.float16, torch.bfloat16]\n\n for norm_dtype, out_dtype in product(dtypes, dtypes):\n if out_dtype is None:\n continue\n\n if norm_dtype is None:\n if dtype == torch.cfloat:\n expected_dtype = torch.float\n elif dtype == torch.cdouble:\n expected_dtype = torch.double\n else:\n expected_dtype = dtype\n else:\n expected_dtype = norm_dtype\n\n result = torch.empty((0), device=device, dtype=out_dtype)\n msg = f'norm_dtype: {norm_dtype}, out_dtype: {out_dtype}, expected_dtype: {expected_dtype}'\n\n if dtype.is_complex and norm_dtype is not None and not norm_dtype.is_complex:\n with self.assertRaisesRegex(RuntimeError, r\"linalg.vector_norm expected complex 'dtype'\", msg=msg):\n torch.linalg.vector_norm(input, dtype=norm_dtype, out=result)\n\n elif out_dtype != expected_dtype:\n with self.assertRaisesRegex(RuntimeError, r'linalg.vector_norm expected out tensor dtype', msg=msg):\n torch.linalg.vector_norm(input, dtype=norm_dtype, out=result)\n else:\n torch.linalg.vector_norm(input, dtype=norm_dtype, out=result)\n\n # This test compares torch.linalg.norm and numpy.linalg.norm to ensure that\n # their vector norm results match\n @dtypes(torch.float, torch.double)\n def test_norm_vector(self, device, dtype):\n def run_test_case(input, p, dim, keepdim):\n result = torch.linalg.norm(input, ord, dim, keepdim)\n input_numpy = input.cpu().numpy()\n result_numpy = np.linalg.norm(input_numpy, ord, dim, keepdim)\n\n msg = f'input.size()={input.size()}, ord={ord}, dim={dim}, keepdim={keepdim}, dtype={dtype}'\n self.assertEqual(result, result_numpy, msg=msg)\n\n result_out = torch.empty_like(result)\n torch.linalg.norm(input, ord, dim, keepdim, out=result_out)\n self.assertEqual(result, result_out, msg=msg)\n\n ord_vector = [0, 1, -1, 2, -2, 3, -3, 4.5, -4.5, inf, -inf]\n S = 10\n test_cases = [\n # input size, p settings, dim\n ((S, ), ord_vector, None),\n ((S, ), ord_vector, 0),\n ((S, S, S), ord_vector, 0),\n ((S, S, S), ord_vector, 1),\n ((S, S, S), ord_vector, 2),\n ((S, S, S), ord_vector, -1),\n ((S, S, S), ord_vector, -2),\n ]\n L = 1_000_000\n if dtype == torch.double:\n test_cases.append(((L, ), ord_vector, None))\n for keepdim in [True, False]:\n for input_size, ord_settings, dim in test_cases:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for ord in ord_settings:\n run_test_case(input, ord, dim, keepdim)\n\n # This test compares torch.linalg.norm, torch.linalg.matrix_norm and numpy.linalg.norm to\n # ensure that their matrix norm results match.\n @skipMeta # https://github.com/pytorch/pytorch/issues/54082\n @skipCUDAIfNoMagma\n @dtypes(torch.float, torch.double)\n @precisionOverride({torch.float32: 2e-5})\n def test_norm_matrix(self, device, dtype):\n def run_test_case(input, ord, dim, keepdim):\n msg = f'input.size()={input.size()}, ord={ord}, dim={dim}, keepdim={keepdim}, dtype={dtype}'\n result = torch.linalg.norm(input, ord, dim, keepdim)\n input_numpy = input.cpu().numpy()\n result_numpy = np.linalg.norm(input_numpy, ord, dim, keepdim)\n\n def check(op):\n result = op(input, ord, dim, keepdim)\n self.assertEqual(result, result_numpy, msg=msg)\n result_out = torch.empty_like(result)\n op(input, ord, dim, keepdim, out=result_out)\n self.assertEqual(result, result_out, msg=msg)\n\n check(torch.linalg.norm)\n if ord is not None and dim is not None:\n check(torch.linalg.matrix_norm)\n\n ord_matrix = [1, -1, 2, -2, inf, -inf, 'nuc', 'fro']\n S = 10\n test_cases = [\n # input size, p settings, dim\n ((S, S), ord_matrix, None),\n ((S, S), ord_matrix, (0, 1)),\n ((S, S), ord_matrix, (1, 0)),\n ((S, S, S, S), ord_matrix, (2, 0)),\n ((S, S, S, S), ord_matrix, (-1, -2)),\n ((S, S, S, S), ord_matrix, (-1, -3)),\n ((S, S, S, S), ord_matrix, (-3, 2)),\n ]\n L = 1_000\n\n if dtype == torch.double:\n test_cases.append(((L, L), ord_matrix, None))\n\n for keepdim in [True, False]:\n for input_size, ord_settings, dim in test_cases:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for ord in ord_settings:\n run_test_case(input, ord, dim, keepdim)\n\n\n @onlyCUDA\n @dtypes(torch.bfloat16, torch.float16)\n def test_norm_fused_type_promotion(self, device, dtype):\n x = torch.randn(10, device=device, dtype=dtype)\n\n def profile_and_check(fn, x, kwargs, fn_name):\n with torch.profiler.profile(activities=(torch.profiler.ProfilerActivity.CPU,)) as p:\n fn(x, **kwargs, dtype=torch.float)\n # smoke check that profiler returned some events\n self.assertTrue(fn_name in map(lambda e: e.name, p.events()))\n # test that there was no explicit copy\n self.assertFalse(\"aten::to\" in map(lambda e: e.name, p.events()))\n\n for f, kwargs, fn_name in zip((torch.norm, torch.linalg.vector_norm), ({\"p\" : 2}, {}),\n (\"aten::norm\", \"aten::linalg_vector_norm\")):\n profile_and_check(f, x, kwargs, fn_name)\n\n @skipMeta # https://github.com/pytorch/pytorch/issues/53739\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3})\n def test_cond(self, device, dtype):\n def run_test_case(input, p):\n result = torch.linalg.cond(input, p)\n result_numpy = np.linalg.cond(input.cpu().numpy(), p)\n self.assertEqual(result, result_numpy, rtol=1e-2, atol=self.precision, exact_dtype=False)\n self.assertEqual(result.shape, result_numpy.shape)\n\n # test out= variant\n out = torch.empty_like(result)\n ans = torch.linalg.cond(input, p, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, result)\n\n norm_types = [1, -1, 2, -2, inf, -inf, 'fro', 'nuc', None]\n input_sizes = [(32, 32), (2, 3, 3, 3)]\n for input_size in input_sizes:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for p in norm_types:\n run_test_case(input, p)\n\n # test empty batch sizes\n input_sizes = [(0, 3, 3), (0, 2, 5, 5)]\n for input_size in input_sizes:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for p in norm_types:\n run_test_case(input, p)\n\n # test non-square input\n input_sizes = [(16, 32), (32, 16), (2, 3, 5, 3), (2, 3, 3, 5)]\n for input_size in input_sizes:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for p in [2, -2, None]:\n run_test_case(input, p)\n\n # test for singular input\n a = torch.eye(3, dtype=dtype, device=device)\n a[-1, -1] = 0 # make 'a' singular\n for p in norm_types:\n run_test_case(a, p)\n\n # test for 0x0 matrices. NumPy doesn't work for such input, we return 0\n input_sizes = [(0, 0), (2, 5, 0, 0)]\n for input_size in input_sizes:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for p in ['fro', 2]:\n expected_dtype = a.real.dtype if dtype.is_complex else dtype\n expected = torch.zeros(input_size[:-2], dtype=expected_dtype, device=device)\n actual = torch.linalg.cond(input, p)\n self.assertEqual(actual, expected)\n\n @skipMeta # https://github.com/pytorch/pytorch/issues/53739\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3})\n def test_cond_errors_and_warnings(self, device, dtype):\n norm_types = [1, -1, 2, -2, inf, -inf, 'fro', 'nuc', None]\n\n # cond expects the input to be at least 2-dimensional\n a = torch.ones(3, dtype=dtype, device=device)\n for p in norm_types:\n with self.assertRaisesRegex(RuntimeError, r'supports matrices or batches of matrices'):\n torch.linalg.cond(a, p)\n\n # for some norm types cond expects the input to be square\n a = torch.ones(3, 2, dtype=dtype, device=device)\n norm_types = [1, -1, inf, -inf, 'fro', 'nuc']\n for p in norm_types:\n with self.assertRaisesRegex(RuntimeError, r'supports square matrices or batches of square matrices'):\n torch.linalg.cond(a, p)\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = torch.ones((2, 2), dtype=dtype, device=device)\n for p in ['fro', 2]:\n real_dtype = a.real.dtype if dtype.is_complex else dtype\n out = torch.empty(a.shape, dtype=real_dtype, device=device)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.cond(a, p, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out = torch.empty(0, dtype=torch.int, device=device)\n for p in ['fro', 2]:\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.linalg.cond(a, p, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n for p in ['fro', 2]:\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.cond(a, p, out=out)\n\n # for batched input if at least one matrix in the batch is not invertible,\n # we can't get the result for all other (possibly) invertible matrices in the batch without an explicit for loop.\n # this should change when at::inverse works with silent errors\n # NumPy works fine in this case because it's possible to silence the error and get the inverse matrix results\n # possibly filled with NANs\n batch_dim = 3\n a = torch.eye(3, 3, dtype=dtype, device=device)\n a = a.reshape((1, 3, 3))\n a = a.repeat(batch_dim, 1, 1)\n a[1, -1, -1] = 0 # now a[1] is singular\n for p in [1, -1, inf, -inf, 'fro', 'nuc']:\n result = torch.linalg.cond(a, p)\n self.assertEqual(result[1], float('inf'))\n\n # check invalid norm type\n a = torch.ones(3, 3, dtype=dtype, device=device)\n for p in ['wrong_norm', 5]:\n with self.assertRaisesRegex(RuntimeError, f\"linalg_cond got an invalid norm type: {p}\"):\n torch.linalg.cond(a, p)\n\n # This test calls torch.linalg.norm and numpy.linalg.norm with illegal arguments\n # to ensure that they both throw errors\n @dtypes(torch.float, torch.double)\n def test_norm_errors(self, device, dtype):\n def run_error_test_case(input, ord, dim, keepdim, error_type, error_regex):\n test_case_info = (\n f'test case input.size()={input.size()}, ord={ord}, dim={dim}, '\n f'keepdim={keepdim}, dtype={dtype}')\n\n with self.assertRaisesRegex(error_type, error_regex, msg=test_case_info):\n torch.linalg.norm(input, ord, dim, keepdim)\n\n input_numpy = input.cpu().numpy()\n\n msg = f'numpy does not raise error but pytorch does, for case \"{test_case_info}\"'\n with self.assertRaises(Exception, msg=test_case_info):\n np.linalg.norm(input_numpy, ord, dim, keepdim)\n\n S = 10\n error_test_cases = [\n # input size, p settings, dim, error type, error regex\n ((S, ), ['fro'], None, RuntimeError, r'order \"fro\" can only be used if either len\\(dim\\) == 2'),\n ((S, ), ['nuc'], None, RuntimeError, r'order \"nuc\" can only be used if either len\\(dim\\) == 2'),\n ((S, S), [3.5], None, RuntimeError, r'Order 3.5 not supported for matrix norm'),\n ((S, S), [0], None, RuntimeError, r'Order 0 not supported for matrix norm'),\n ((S, S), ['nuc'], 0, RuntimeError, r'order \"nuc\" can only be used if either len\\(dim\\) == 2'),\n ((S, S), ['fro'], 0, RuntimeError, r'order \"fro\" can only be used if either len\\(dim\\) == 2'),\n ((S, S), ['nuc'], (0, 0), RuntimeError, r'duplicate or invalid dimensions'),\n ((S, S), ['fro', 0], (0, 0), RuntimeError, r'Expected dims to be different'),\n ((S, S), ['fro', 'nuc', 0], (0, 4), IndexError, r'Dimension out of range'),\n ((S, ), [0], (4, ), IndexError, r'Dimension out of range'),\n ((S, ), [None], (0, 0), RuntimeError, r'dim 0 appears multiple times'),\n ((S, S, S), [1], (0, 1, 2), RuntimeError, r\"'dim' must specify 1 or 2 dimensions\"),\n ((S, S, S), [1], None, RuntimeError, r\"'dim' must specify 1 or 2 dimensions\"),\n ((S, S), ['garbage'], (0, 1), RuntimeError, r'Invalid norm order: garbage'),\n ]\n for keepdim in [True, False]:\n for input_size, ord_settings, dim, error_type, error_regex in error_test_cases:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for ord in ord_settings:\n run_error_test_case(input, ord, dim, keepdim, error_type, error_regex)\n\n # Test complex number inputs for linalg.norm\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.cfloat, torch.cdouble)\n @precisionOverride({torch.cfloat: 2e-4})\n def test_norm_complex(self, device, dtype):\n def gen_error_message(input_size, ord, keepdim, dim=None):\n return \"complex norm failed for input size %s, ord=%s, keepdim=%s, dim=%s\" % (\n input_size, ord, keepdim, dim)\n\n vector_ords = [None, 0, 1, 2, 3, inf, -1, -2, -3, -inf]\n matrix_ords = [None, 'fro', 'nuc', 1, 2, inf, -1, -2, -inf]\n\n # Test supported ords\n for keepdim in [False, True]:\n # vector norm\n x = torch.randn(25, device=device, dtype=dtype)\n xn = x.cpu().numpy()\n for ord in vector_ords:\n res = torch.linalg.norm(x, ord, keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, ord, keepdims=keepdim)\n msg = gen_error_message(x.size(), ord, keepdim)\n self.assertEqual(res.shape, expected.shape, msg=msg)\n self.assertEqual(res, expected, msg=msg, exact_dtype=False)\n\n res_out = torch.tensor([]).to(device)\n torch.linalg.norm(x, ord, keepdim=keepdim, out=res_out)\n self.assertEqual(res_out.shape, expected.shape, msg=msg)\n self.assertEqual(res_out.cpu(), expected, msg=msg, exact_dtype=False)\n\n # matrix norm\n x = torch.randn(25, 25, device=device, dtype=dtype)\n xn = x.cpu().numpy()\n for ord in matrix_ords:\n res = torch.linalg.norm(x, ord, keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, ord, keepdims=keepdim)\n msg = gen_error_message(x.size(), ord, keepdim)\n self.assertEqual(res.shape, expected.shape, msg=msg)\n self.assertEqual(res, expected, msg=msg, exact_dtype=False)\n\n res_out = torch.tensor([]).to(device)\n torch.linalg.norm(x, ord, keepdim=keepdim, out=res_out)\n self.assertEqual(res_out.shape, expected.shape, msg=msg)\n self.assertEqual(res_out.cpu(), expected, msg=msg, exact_dtype=False)\n\n # Test that linal.vector_norm gives the same result as numpy when inputs\n # contain extreme values (inf, -inf, nan)\n def test_vector_norm_extreme_values(self, device):\n vector_ords = [0, 1, 2, 3, inf, -1, -2, -3, -inf]\n vectors = []\n for pair in itertools.product([inf, -inf, 0.0, nan, 1.0], repeat=2):\n vectors.append(list(pair))\n for vector in vectors:\n x = torch.tensor(vector, device=device)\n x_n = x.cpu().numpy()\n for ord in vector_ords:\n msg = f'ord={ord}, vector={vector}'\n result = torch.linalg.vector_norm(x, ord=ord)\n result_n = np.linalg.norm(x_n, ord=ord)\n self.assertEqual(result, result_n, msg=msg)\n\n @skipMeta # https://github.com/pytorch/pytorch/issues/54082\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double)\n @precisionOverride({torch.float32: 2e-5})\n def test_matrix_norm(self, device, dtype):\n # Test only inputs for which torch.linalg.matrix_norm diverges from torch.linalg.norm\n A = make_tensor((2, 2, 2), device, dtype)\n\n with self.assertRaisesRegex(RuntimeError, r'linalg.matrix_norm\\(\\):.*must be a matrix.*'):\n torch.linalg.matrix_norm(make_tensor((2,), device, dtype))\n with self.assertRaisesRegex(RuntimeError, r'linalg.matrix_norm\\(\\):.*must be a 2-tuple.*'):\n torch.linalg.matrix_norm(A, dim=(0,))\n with self.assertRaisesRegex(RuntimeError, r'.*not supported.*'):\n torch.linalg.matrix_norm(A, ord=0)\n with self.assertRaisesRegex(RuntimeError, r'.*not supported.*'):\n torch.linalg.matrix_norm(A, ord=3.0)\n\n # Test dim=None behavior\n ref = torch.linalg.norm(A, dim=(-2, -1))\n res = torch.linalg.matrix_norm(A)\n self.assertEqual(ref, res)\n\n # Test that linal.norm gives the same result as numpy when inputs\n # contain extreme values (inf, -inf, nan)\n @unittest.skipIf(IS_WINDOWS, \"Skipped on Windows!\")\n @unittest.skipIf(IS_MACOS, \"Skipped on MacOS!\")\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n def test_norm_extreme_values(self, device):\n vector_ords = [0, 1, 2, 3, inf, -1, -2, -3, -inf]\n matrix_ords = ['fro', 'nuc', 1, 2, inf, -1, -2, -inf]\n vectors = []\n matrices = []\n for pair in itertools.product([inf, -inf, 0.0, nan, 1.0], repeat=2):\n vectors.append(list(pair))\n matrices.append([[pair[0], pair[1]]])\n matrices.append([[pair[0]], [pair[1]]])\n for vector in vectors:\n x = torch.tensor(vector).to(device)\n x_n = x.cpu().numpy()\n for ord in vector_ords:\n msg = f'ord={ord}, vector={vector}'\n result = torch.linalg.norm(x, ord=ord)\n result_n = np.linalg.norm(x_n, ord=ord)\n self.assertEqual(result, result_n, msg=msg)\n\n # TODO: Remove this function once the broken cases are fixed\n def is_broken_matrix_norm_case(ord, x):\n if self.device_type == 'cuda':\n if x.size() == torch.Size([1, 2]):\n if ord in ['nuc', 2, -2] and isnan(x[0][0]) and x[0][1] == 1:\n # These cases are broken because of an issue with svd\n # https://github.com/pytorch/pytorch/issues/43567\n return True\n if ord in ['nuc', 2, -2]:\n # These cases are broken because of another issue with svd\n # https://github.com/pytorch/pytorch/issues/52633\n return True\n return False\n\n for matrix in matrices:\n x = torch.tensor(matrix).to(device)\n x_n = x.cpu().numpy()\n for ord in matrix_ords:\n msg = f'ord={ord}, matrix={matrix}'\n if is_broken_matrix_norm_case(ord, x):\n continue\n else:\n result = torch.linalg.norm(x, ord=ord)\n result_n = np.linalg.norm(x_n, ord=ord)\n self.assertEqual(result, result_n, msg=msg)\n\n # Test degenerate shape results match numpy for linalg.norm vector norms\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @unittest.skipIf(TEST_WITH_ASAN, \"Skipped on ASAN since it checks for undefined behavior.\")\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_norm_vector_degenerate_shapes(self, device, dtype):\n def run_test_case(input, ord, dim, keepdim):\n msg = f'input.size()={input.size()}, ord={ord}, dim={dim}, keepdim={keepdim}, dtype={dtype}'\n should_error = False\n if ord is not None and ord < 0:\n should_error = True\n elif ord == inf:\n if dim is None or input.size(dim) == 0:\n should_error = True\n\n if should_error:\n with self.assertRaises(RuntimeError):\n torch.linalg.norm(input, ord, dim, keepdim)\n else:\n input_numpy = input.cpu().numpy()\n result_numpy = np.linalg.norm(input_numpy, ord, dim, keepdim)\n result = torch.linalg.norm(input, ord, dim, keepdim)\n self.assertEqual(result, result_numpy, msg=msg)\n\n ord_vector = [0, 0.5, 1, 2, 3, inf, -0.5, -1, -2, -3, -inf, None]\n S = 10\n test_cases = [\n # input size, dim\n ((0, ), None),\n ((0, S), 0),\n ((0, S), 1),\n ((S, 0), 0),\n ((S, 0), 1),\n ]\n for keepdim in [True, False]:\n for input_size, dim in test_cases:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for ord in ord_vector:\n run_test_case(input, ord, dim, keepdim)\n\n # Test degenerate shape results match numpy for linalg.norm matrix norms\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_norm_matrix_degenerate_shapes(self, device, dtype):\n def run_test_case(input, ord, dim, keepdim, should_error):\n msg = f'input.size()={input.size()}, ord={ord}, dim={dim}, keepdim={keepdim}, dtype={dtype}'\n input_numpy = input.cpu().numpy()\n ops = [torch.linalg.norm]\n\n if ord is not None and dim is not None:\n ops.append(torch.linalg.matrix_norm)\n\n if should_error:\n with self.assertRaises(ValueError):\n np.linalg.norm(input_numpy, ord, dim, keepdim)\n for op in ops:\n with self.assertRaises(IndexError):\n op(input, ord, dim, keepdim)\n else:\n result_numpy = np.linalg.norm(input_numpy, ord, dim, keepdim)\n for op in ops:\n result = op(input, ord, dim, keepdim)\n self.assertEqual(result, result_numpy, msg=msg)\n\n ord_matrix = ['fro', 'nuc', 1, 2, inf, -1, -2, -inf, None]\n S = 10\n test_cases = [\n # input size, p settings that cause error, dim\n ((0, 0), [1, 2, inf, -1, -2, -inf], None),\n ((0, S), [2, inf, -2, -inf], None),\n ((S, 0), [1, 2, -1, -2], None),\n ((S, S, 0), [], (0, 1)),\n ((1, S, 0), [], (0, 1)),\n ((0, 0, S), [1, 2, inf, -1, -2, -inf], (0, 1)),\n ((0, 0, S), [1, 2, inf, -1, -2, -inf], (1, 0)),\n ]\n\n for keepdim in [True, False]:\n for input_size, error_ords, dim in test_cases:\n input = torch.randn(*input_size, dtype=dtype, device=device)\n for ord in ord_matrix:\n run_test_case(input, ord, dim, keepdim, ord in error_ords)\n\n def test_norm_fastpaths(self, device):\n x = torch.randn(3, 5, device=device)\n\n # slow path\n result = torch.linalg.norm(x, 4.5, 1)\n expected = torch.pow(x.abs().pow(4.5).sum(1), 1.0 / 4.5)\n self.assertEqual(result, expected)\n\n # fast 0-norm\n result = torch.linalg.norm(x, 0, 1)\n expected = (x != 0).type_as(x).sum(1)\n self.assertEqual(result, expected)\n\n # fast 1-norm\n result = torch.linalg.norm(x, 1, 1)\n expected = x.abs().sum(1)\n self.assertEqual(result, expected)\n\n # fast 2-norm\n result = torch.linalg.norm(x, 2, 1)\n expected = torch.sqrt(x.pow(2).sum(1))\n self.assertEqual(result, expected)\n\n # fast 3-norm\n result = torch.linalg.norm(x, 3, 1)\n expected = torch.pow(x.pow(3).abs().sum(1), 1.0 / 3.0)\n self.assertEqual(result, expected)\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(*floating_and_complex_types())\n def test_old_eig_basic(self, device, dtype):\n a = torch.tensor([[1.96, 0.00, 0.00, 0.00, 0.00],\n [-6.49, 3.80, 0.00, 0.00, 0.00],\n [-0.47, -6.39, 4.17, 0.00, 0.00],\n [-7.20, 1.50, -1.51, 5.70, 0.00],\n [-0.65, -6.34, 2.67, 1.80, -7.10]],\n dtype=dtype, device=device).t()\n e = torch.eig(a)[0]\n ee, vv = torch.eig(a, True)\n te = torch.tensor((), dtype=dtype, device=device)\n tv = torch.tensor((), dtype=dtype, device=device)\n eee, vvv = torch.eig(a, True, out=(te, tv))\n self.assertEqual(e, ee, atol=1e-12, rtol=0)\n self.assertEqual(ee, eee, atol=1e-12, rtol=0)\n self.assertEqual(ee, te, atol=1e-12, rtol=0)\n self.assertEqual(vv, vvv, atol=1e-12, rtol=0)\n self.assertEqual(vv, tv, atol=1e-12, rtol=0)\n #\n # compare with numpy\n np_e, np_v = np.linalg.eig(a.cpu().numpy())\n if dtype.is_complex:\n self.assertEqual(ee, np_e)\n else:\n # np_e.shape == (n, 2), where each column contain the real and\n # imaginary parts of the result\n self.assertEqual(ee[:, 0], np_e) # real part\n self.assertEqual(ee[:, 1], torch.zeros(ee.shape[0], dtype=dtype)) # imaginary part\n self.assertEqual(vv, np_v)\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.double, torch.float)\n def test_old_eig_reuse(self, device, dtype):\n X = torch.randn(4, 4, dtype=dtype, device=device)\n X = torch.mm(X.t(), X)\n e = torch.zeros(4, 2, dtype=dtype, device=device)\n v = torch.zeros(4, 4, dtype=dtype, device=device)\n torch.eig(X, True, out=(e, v))\n Xhat = np.matmul(np.matmul(v.cpu(), torch.diag(e.select(1, 0)).cpu()), v.t().cpu())\n if dtype is torch.float:\n atol = 1e-7\n rtol = 1e-5\n else:\n atol = 1e-8\n rtol = 0\n self.assertEqual(X, Xhat, atol=atol, rtol=rtol, msg='VeV\\' wrong')\n self.assertTrue(v.is_contiguous(), 'V is not contiguous')\n\n torch.eig(X, True, out=(e, v))\n Xhat = np.matmul(v.cpu(), np.matmul(e.select(1, 0).diag().cpu(), v.t().cpu()))\n self.assertEqual(X, Xhat, atol=atol, rtol=rtol, msg='VeV\\' wrong')\n self.assertTrue(v.is_contiguous(), 'V is not contiguous')\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.double, torch.float)\n def test_old_eig_non_contiguous(self, device, dtype):\n X = torch.randn(4, 4, dtype=dtype, device=device)\n X = torch.mm(X.t(), X)\n e = torch.zeros(4, 2, 2, dtype=dtype, device=device)[:, 1]\n v = torch.zeros(4, 2, 4, dtype=dtype, device=device)[:, 1]\n self.assertFalse(v.is_contiguous(), 'V is contiguous')\n self.assertFalse(e.is_contiguous(), 'E is contiguous')\n torch.eig(X, True, out=(e, v))\n Xhat = np.matmul(np.matmul(v.cpu(), torch.diag(e.cpu().select(1, 0))), v.t().cpu())\n if dtype is torch.float:\n atol = 1e-7\n rtol = 1e-5\n else:\n atol = 1e-8\n rtol = 0\n self.assertEqual(X, Xhat, atol=atol, rtol=rtol, msg='VeV\\' wrong')\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.double, torch.float)\n def test_old_eig_invalid_input(self, device, dtype):\n # test invalid input\n self.assertRaisesRegex(\n RuntimeError,\n 'input should be 2 dimensional',\n lambda: torch.eig(torch.ones((2))))\n self.assertRaisesRegex(\n RuntimeError,\n 'input should be square',\n lambda: torch.eig(torch.ones((2, 3))))\n self.assertRaisesRegex(\n RuntimeError,\n 'input should not contain infs or NaNs',\n lambda: torch.eig(np.inf * torch.ones((2, 2))))\n self.assertRaisesRegex(\n RuntimeError,\n 'input should not contain infs or NaNs',\n lambda: torch.eig(np.nan * torch.ones((2, 2))))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double, torch.float)\n def test_old_eig_out(self, device, dtype):\n # the out version of torch.eig needs to be tested manually: we can't\n # use the \"test_out=True\" parameter to tensor_op_tests because the\n # signature is irregular (since we have *two* output vectors)\n t = torch.randn(10, 10, dtype=dtype, device=device)\n evals, evecs = torch.eig(t, eigenvectors=True)\n #\n # check that the out= version computes the same values as the normal one\n out_evals = torch.empty_like(evals)\n out_evecs = torch.empty_like(evecs)\n evals2, evecs2 = torch.eig(t, eigenvectors=True, out=(out_evals, out_evecs))\n # check that the out tensors were used in-place\n self.assertEqual(evals2.data_ptr(), out_evals.data_ptr())\n self.assertEqual(evecs2.data_ptr(), out_evecs.data_ptr())\n # check that the result is the same as the non-out version\n self.assertEqual(evals, out_evals)\n self.assertEqual(evecs, out_evecs)\n #\n # check what happens in the eigenvectors=False case\n out_evals = torch.empty_like(evals)\n out_evecs = torch.tensor([1, 2, 3], dtype=dtype, device=device)\n evals2, evecs2 = torch.eig(t, eigenvectors=False, out=(out_evals, out_evecs))\n # check that the out_evals was used in-place\n self.assertEqual(evals2.data_ptr(), out_evals.data_ptr())\n self.assertEqual(evals, out_evals)\n # check that out_evecs was NOT touched at all\n assert out_evecs.tolist() == [1, 2, 3]\n #\n # check that we complain if we pass an out vector of the wrong dtype\n wrong_out = torch.empty((0, 0), dtype=int)\n with self.assertRaisesRegex(RuntimeError, r\"Expected .* but got .*\"):\n torch.eig(t, eigenvectors=True, out=(wrong_out, out_evecs))\n with self.assertRaisesRegex(RuntimeError, r\"Expected .* but got .*\"):\n torch.eig(t, eigenvectors=True, out=(out_evals, wrong_out))\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n # NumPy computes only in float64 and complex128 precisions\n # for float32 or complex64 results might be very different from float64 or complex128\n @dtypes(torch.float64, torch.complex128)\n def test_eig_numpy(self, device, dtype):\n def run_test(shape, *, symmetric=False):\n from torch.testing._internal.common_utils import random_symmetric_matrix\n\n if not dtype.is_complex and symmetric:\n # for symmetric real-valued inputs eigenvalues and eigenvectors have imaginary part equal to zero\n # unlike NumPy the result is not cast to float32 or float64 dtype in this case\n a = random_symmetric_matrix(shape[-1], *shape[:-2], dtype=dtype, device=device)\n else:\n a = make_tensor(shape, dtype=dtype, device=device)\n\n actual = torch.linalg.eig(a)\n\n # compare with NumPy\n # the eigenvalues are not necessarily ordered\n # so order of NumPy and PyTorch can be different\n expected = np.linalg.eig(a.cpu().numpy())\n\n # sort NumPy output\n ind = np.argsort(expected[0], axis=-1)[::-1]\n expected = (np.take_along_axis(expected[0], ind, axis=-1), np.take_along_axis(expected[1], ind[:, None], axis=-1))\n\n # sort PyTorch output\n # torch.argsort doesn't work with complex inputs, NumPy sorting on CPU is used instead\n # RuntimeError: _th_sort not supported on CUDAType for ComplexDouble\n # RuntimeError: \"sorting_kernel_method_name\" not implemented for 'ComplexDouble'\n ind = np.argsort(actual[0].cpu().numpy(), axis=-1)[::-1]\n actual_np = [x.cpu().numpy() for x in actual]\n sorted_actual = (\n np.take_along_axis(actual_np[0], ind, axis=-1),\n np.take_along_axis(actual_np[1], ind[:, None], axis=-1))\n\n self.assertEqual(expected[0], sorted_actual[0], exact_dtype=False)\n self.assertEqual(abs(expected[1]), abs(sorted_actual[1]), exact_dtype=False)\n\n shapes = [(0, 0), # Empty matrix\n (5, 5), # Single matrix\n (0, 0, 0), (0, 5, 5), # Zero batch dimension tensors\n (2, 5, 5), # 3-dim tensors\n (2, 1, 5, 5)] # 4-dim tensors\n for shape in shapes:\n run_test(shape)\n run_test(shape, symmetric=True)\n\n @onlyCUDA\n @skipCUDAIfNoMagma\n @dtypes(*floating_and_complex_types())\n def test_eig_compare_backends(self, device, dtype):\n def run_test(shape, *, symmetric=False):\n from torch.testing._internal.common_utils import random_symmetric_matrix\n\n if not dtype.is_complex and symmetric:\n # for symmetric real-valued inputs eigenvalues and eigenvectors have imaginary part equal to zero\n a = random_symmetric_matrix(shape[-1], *shape[:-2], dtype=dtype, device=device)\n else:\n a = make_tensor(shape, dtype=dtype, device=device)\n\n actual = torch.linalg.eig(a)\n\n complementary_device = 'cpu'\n\n # compare with CPU\n expected = torch.linalg.eig(a.to(complementary_device))\n self.assertEqual(expected[0], actual[0])\n self.assertEqual(expected[1], actual[1])\n\n shapes = [(0, 0), # Empty matrix\n (5, 5), # Single matrix\n (0, 0, 0), (0, 5, 5), # Zero batch dimension tensors\n (2, 5, 5), # 3-dim tensors\n (2, 1, 5, 5)] # 4-dim tensors\n for shape in shapes:\n run_test(shape)\n run_test(shape, symmetric=True)\n\n @slowTest\n @onlyCUDA\n @skipCUDAIfNoMagma\n @dtypes(torch.float32)\n def test_eig_check_magma(self, device, dtype):\n # For CUDA inputs only matrices of size larger than 2048x2048 actually call MAGMA library\n shape = (2049, 2049)\n a = make_tensor(shape, dtype=dtype, device=device)\n w, v = torch.linalg.eig(a)\n # check correctness using eigendecomposition identity\n self.assertEqual(a.to(v.dtype) @ v, w * v, atol=1e-3, rtol=1e-3)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(*floating_and_complex_types())\n def test_eig_errors_and_warnings(self, device, dtype):\n # eig requires the input to be at least 2 dimensional tensor\n a = make_tensor(2, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"must have at least 2 dimensions\"):\n torch.linalg.eig(a)\n\n # eig requires a square matrix\n a = make_tensor((2, 3), dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"must be batches of square matrices\"):\n torch.linalg.eig(a)\n\n # if out tensor with floating dtype is passed for complex output an error is thrown\n if not dtype.is_complex:\n # The characteristic equation is p(λ) = λ^2 − 2λ + 5 = 0, with roots λ = 1±2i\n a = torch.tensor([[3., -2.], [4., -1.]], dtype=dtype, device=device)\n out0 = torch.empty(0, device=device, dtype=dtype)\n out1 = torch.empty(0, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"Expected eigenvalues to be safely castable\"):\n torch.linalg.eig(a, out=(out0, out1))\n\n out0 = torch.empty(0, device=device, dtype=torch.complex128)\n with self.assertRaisesRegex(RuntimeError, \"Expected eigenvectors to be safely castable\"):\n torch.linalg.eig(a, out=(out0, out1))\n\n # dtypes should be safely castable\n a = make_tensor((3, 3), dtype=dtype, device=device)\n out0 = torch.empty(0, dtype=torch.int, device=device)\n out1 = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got eigenvalues with dtype Int\"):\n torch.linalg.eig(a, out=(out0, out1))\n\n out0 = torch.empty(0, dtype=torch.complex128, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got eigenvectors with dtype Int\"):\n torch.linalg.eig(a, out=(out0, out1))\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = make_tensor((3, 3), dtype=dtype, device=device)\n out0 = torch.empty(1, device=device, dtype=torch.complex128)\n out1 = torch.empty(1, device=device, dtype=torch.complex128)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.eig(a, out=(out0, out1))\n # Check warning occurs\n self.assertEqual(len(w), 2)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-2].message))\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out_w = torch.empty(0, device=wrong_device, dtype=torch.complex128)\n out_v = torch.empty(0, device=device, dtype=torch.complex128)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.eig(a, out=(out_w, out_v))\n out_w = torch.empty(0, device=device, dtype=torch.complex128)\n out_v = torch.empty(0, device=wrong_device, dtype=torch.complex128)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.eig(a, out=(out_w, out_v))\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n # NumPy computes only in float64 and complex128 precisions\n # for float32 or complex64 results might be very different from float64 or complex128\n @dtypes(torch.float64, torch.complex128)\n def test_eigvals_numpy(self, device, dtype):\n def run_test(shape, *, symmetric=False):\n from torch.testing._internal.common_utils import random_symmetric_matrix\n\n if not dtype.is_complex and symmetric:\n # for symmetric real-valued inputs eigenvalues and eigenvectors have imaginary part equal to zero\n # unlike NumPy the result is not cast to float32 or float64 dtype in this case\n a = random_symmetric_matrix(shape[-1], *shape[:-2], dtype=dtype, device=device)\n else:\n a = make_tensor(shape, dtype=dtype, device=device)\n\n actual = torch.linalg.eigvals(a)\n\n # compare with NumPy\n # the eigenvalues are not necessarily ordered\n # so order of NumPy and PyTorch can be different\n expected = np.linalg.eigvals(a.cpu().numpy())\n\n # sort NumPy output\n ind = np.argsort(expected, axis=-1)[::-1]\n expected = np.take_along_axis(expected, ind, axis=-1)\n\n # sort PyTorch output\n # torch.argsort doesn't work with complex inputs, NumPy sorting on CPU is used instead\n # RuntimeError: _th_sort not supported on CUDAType for ComplexDouble\n # RuntimeError: \"sorting_kernel_method_name\" not implemented for 'ComplexDouble'\n ind = np.argsort(actual.cpu().numpy(), axis=-1)[::-1]\n actual_np = actual.cpu().numpy()\n sorted_actual = np.take_along_axis(actual_np, ind, axis=-1)\n\n self.assertEqual(expected, sorted_actual, exact_dtype=False)\n\n shapes = [(0, 0), # Empty matrix\n (5, 5), # Single matrix\n (0, 0, 0), (0, 5, 5), # Zero batch dimension tensors\n (2, 5, 5), # 3-dim tensors\n (2, 1, 5, 5)] # 4-dim tensors\n for shape in shapes:\n run_test(shape)\n run_test(shape, symmetric=True)\n\n @onlyCUDA\n @skipCUDAIfNoMagma\n @dtypes(*floating_and_complex_types())\n def test_eigvals_compare_backends(self, device, dtype):\n def run_test(shape, *, symmetric=False):\n from torch.testing._internal.common_utils import random_symmetric_matrix\n\n if not dtype.is_complex and symmetric:\n # for symmetric real-valued inputs eigenvalues and eigenvectors have imaginary part equal to zero\n a = random_symmetric_matrix(shape[-1], *shape[:-2], dtype=dtype, device=device)\n else:\n a = make_tensor(shape, dtype=dtype, device=device)\n\n actual = torch.linalg.eigvals(a)\n\n complementary_device = 'cpu'\n\n # compare with CPU\n expected = torch.linalg.eigvals(a.to(complementary_device))\n self.assertEqual(expected, actual)\n\n # check out= variant\n complex_dtype = dtype\n if not dtype.is_complex:\n complex_dtype = torch.complex128 if dtype == torch.float64 else torch.complex64\n out = torch.empty(0, dtype=complex_dtype, device=device)\n ans = torch.linalg.eigvals(a, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(expected.to(complex_dtype), out)\n\n # check non-contiguous out\n if a.numel() > 0:\n out = torch.empty(2 * shape[0], *shape[1:-1], dtype=complex_dtype, device=device)[::2]\n self.assertFalse(out.is_contiguous())\n ans = torch.linalg.eigvals(a, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(expected.to(complex_dtype), out)\n\n shapes = [(0, 0), # Empty matrix\n (5, 5), # Single matrix\n (0, 0, 0), (0, 5, 5), # Zero batch dimension tensors\n (2, 5, 5), # 3-dim tensors\n (2, 1, 5, 5)] # 4-dim tensors\n for shape in shapes:\n run_test(shape)\n run_test(shape, symmetric=True)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(*floating_and_complex_types())\n def test_eigvals_errors_and_warnings(self, device, dtype):\n # eig requires the input to be at least 2 dimensional tensor\n a = make_tensor(2, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"must have at least 2 dimensions\"):\n torch.linalg.eigvals(a)\n\n # eig requires a square matrix\n a = make_tensor((2, 3), dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"must be batches of square matrices\"):\n torch.linalg.eigvals(a)\n\n # if out tensor with floating dtype is passed for complex output an error is thrown\n if not dtype.is_complex:\n # The characteristic equation is p(λ) = λ^2 − 2λ + 5 = 0, with roots λ = 1±2i\n a = torch.tensor([[3., -2.], [4., -1.]], dtype=dtype, device=device)\n out = torch.empty(0, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"Expected eigenvalues to be safely castable\"):\n torch.linalg.eigvals(a, out=out)\n\n # dtypes should be safely castable\n a = make_tensor((3, 3), dtype=dtype, device=device)\n out = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got eigenvalues with dtype Int\"):\n torch.linalg.eigvals(a, out=out)\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n out = torch.empty(1, device=device, dtype=torch.complex128)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.eigvals(a, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out_w = torch.empty(0, device=wrong_device, dtype=torch.complex128)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.eigvals(a, out=out_w)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n def test_norm_old(self, device):\n def gen_error_message(input_size, p, keepdim, dim=None):\n return \"norm failed for input size %s, p=%s, keepdim=%s, dim=%s\" % (\n input_size, p, keepdim, dim)\n\n for keepdim in [False, True]:\n # full reduction\n x = torch.randn(25, device=device)\n xn = x.cpu().numpy()\n for p in [0, 1, 2, 3, 4, inf, -inf, -1, -2, -3, 1.5]:\n res = x.norm(p, keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, p, keepdims=keepdim)\n self.assertEqual(res, expected, atol=1e-5, rtol=0, msg=gen_error_message(x.size(), p, keepdim))\n\n # one dimension\n x = torch.randn(25, 25, device=device)\n xn = x.cpu().numpy()\n for p in [0, 1, 2, 3, 4, inf, -inf, -1, -2, -3]:\n dim = 1\n res = x.norm(p, dim, keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, p, dim, keepdims=keepdim)\n msg = gen_error_message(x.size(), p, keepdim, dim)\n self.assertEqual(res.shape, expected.shape, msg=msg)\n self.assertEqual(res, expected, msg=msg)\n\n # matrix norm\n for p in ['fro', 'nuc']:\n res = x.norm(p, keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, p, keepdims=keepdim)\n msg = gen_error_message(x.size(), p, keepdim)\n self.assertEqual(res.shape, expected.shape, msg=msg)\n self.assertEqual(res, expected, msg=msg)\n\n # zero dimensions\n x = torch.randn((), device=device)\n xn = x.cpu().numpy()\n res = x.norm(keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, keepdims=keepdim)\n msg = gen_error_message(x.size(), None, keepdim)\n self.assertEqual(res.shape, expected.shape, msg=msg)\n self.assertEqual(res, expected, msg=msg)\n\n # larger tensor sanity check\n self.assertEqual(\n 2 * torch.norm(torch.ones(10000), keepdim=keepdim),\n torch.norm(torch.ones(40000), keepdim=keepdim))\n\n # matrix norm with non-square >2-D tensors, all combinations of reduction dims\n x = torch.randn(5, 6, 7, 8, device=device)\n xn = x.cpu().numpy()\n for p in ['fro', 'nuc']:\n for dim in itertools.product(*[list(range(4))] * 2):\n if dim[0] == dim[1]:\n continue\n res = x.norm(p=p, dim=dim, keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, ord=p, axis=dim, keepdims=keepdim)\n msg = gen_error_message(x.size(), p, keepdim, dim)\n self.assertEqual(res.shape, expected.shape, msg=msg)\n self.assertEqual(res, expected, msg=msg)\n\n # Test that torch.norm with p=+/-inf propagates NaN\n def test_norm_old_nan_propagation(self, device):\n ords = [inf, -inf]\n for pair in itertools.product([0.0, nan, 1.0], repeat=2):\n x = torch.tensor(list(pair), device=device)\n for ord in ords:\n result = torch.norm(x, p=ord)\n result_check = torch.linalg.norm(x, ord=ord)\n self.assertEqual(result, result_check)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n def test_norm_complex_old(self, device):\n def gen_error_message(input_size, p, keepdim, dim=None):\n return \"complex norm failed for input size %s, p=%s, keepdim=%s, dim=%s\" % (\n input_size, p, keepdim, dim)\n\n for keepdim in [False, True]:\n # vector norm\n x = torch.randn(25, device=device) + 1j * torch.randn(25, device=device)\n xn = x.cpu().numpy()\n for p in [0, 1, 2, 3, inf, -1, -2, -3, -inf]:\n res = x.norm(p, keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, p, keepdims=keepdim)\n msg = gen_error_message(x.size(), p, keepdim)\n self.assertEqual(res.shape, expected.shape, msg=msg)\n self.assertEqual(res, expected, msg=msg)\n\n # matrix norm\n x = torch.randn(25, 25, device=device) + 1j * torch.randn(25, 25, device=device)\n xn = x.cpu().numpy()\n for p in ['nuc', 'fro']:\n res = x.norm(p, keepdim=keepdim).cpu()\n expected = np.linalg.norm(xn, p, keepdims=keepdim)\n msg = gen_error_message(x.size(), p, keepdim)\n self.assertEqual(res.shape, expected.shape, msg=msg)\n self.assertEqual(res, expected, msg=msg, rtol=1.3e-6, atol=3e-4)\n\n # Ensure torch.norm with p='fro' and p=2 give the same results for mutually supported input combinations\n @dtypes(torch.float)\n def test_norm_fro_2_equivalence_old(self, device, dtype):\n input_sizes = [\n (0,),\n (10,),\n (0, 0),\n (4, 30),\n (0, 45),\n (100, 0),\n (45, 10, 23),\n (0, 23, 59),\n (23, 0, 37),\n (34, 58, 0),\n (0, 0, 348),\n (0, 3434, 0),\n (0, 0, 0),\n (5, 3, 8, 1, 3, 5)]\n\n for input_size in input_sizes:\n a = make_tensor(input_size, device, dtype, low=-9, high=9)\n\n # Try full reduction\n dim_settings = [None]\n\n # Try all possible 1-D reductions\n dim_settings += list(range(-a.dim(), a.dim()))\n\n def wrap_dim(dim, ndims):\n assert (dim < ndims) and (dim >= -ndims)\n if dim >= 0:\n return dim\n else:\n return dim + ndims\n\n # Try all possible 2-D reductions\n dim_settings += [\n (d0, d1) for d0, d1 in itertools.combinations(range(-a.dim(), a.dim()), 2)\n if wrap_dim(d0, a.dim()) != wrap_dim(d1, a.dim())]\n\n for dim in dim_settings:\n for keepdim in [True, False]:\n a_norm_2 = torch.norm(a, p=2, dim=dim, keepdim=keepdim)\n a_norm_fro = torch.norm(a, p='fro', dim=dim, keepdim=keepdim)\n self.assertEqual(a_norm_fro, a_norm_2)\n\n @skipCUDAIfNoMagma\n def test_nuclear_norm_axes_small_brute_force_old(self, device):\n def check_single_nuclear_norm(x, axes):\n if self.device_type != 'cpu' and randrange(100) < 95:\n return # too many cpu <==> device copies\n\n a = np.array(x.cpu(), copy=False)\n expected = np.linalg.norm(a, \"nuc\", axis=axes)\n\n ans = torch.norm(x, \"nuc\", dim=axes)\n self.assertTrue(ans.is_contiguous())\n self.assertEqual(ans.shape, expected.shape)\n self.assertEqual(ans.cpu(), expected, rtol=1e-02, atol=1e-03, equal_nan=True)\n\n out = torch.zeros(expected.shape, dtype=x.dtype, device=x.device)\n ans = torch.norm(x, \"nuc\", dim=axes, out=out)\n self.assertIs(ans, out)\n self.assertTrue(ans.is_contiguous())\n self.assertEqual(ans.shape, expected.shape)\n self.assertEqual(ans.cpu(), expected, rtol=1e-02, atol=1e-03, equal_nan=True)\n\n for n in range(1, 3):\n for m in range(1, 3):\n for axes in itertools.permutations([0, 1], 2):\n # 2d, inner dimensions C\n x = torch.randn(n, m, device=device)\n check_single_nuclear_norm(x, axes)\n\n # 2d, inner dimensions Fortran\n x = torch.randn(m, n, device=device).transpose(-1, -2)\n check_single_nuclear_norm(x, axes)\n\n # 2d, inner dimensions non-contiguous\n x = torch.randn(n, 2 * m, device=device)[:, ::2]\n check_single_nuclear_norm(x, axes)\n\n # 2d, all dimensions non-contiguous\n x = torch.randn(7 * n, 2 * m, device=device)[::7, ::2]\n check_single_nuclear_norm(x, axes)\n\n for o in range(1, 3):\n for axes in itertools.permutations([0, 1, 2], 2):\n # 3d, inner dimensions C\n x = torch.randn(o, n, m, device=device)\n check_single_nuclear_norm(x, axes)\n\n # 3d, inner dimensions Fortran\n x = torch.randn(o, m, n, device=device).transpose(-1, -2)\n check_single_nuclear_norm(x, axes)\n\n # 3d, inner dimensions non-contiguous\n x = torch.randn(o, n, 2 * m, device=device)[:, :, ::2]\n check_single_nuclear_norm(x, axes)\n\n # 3d, all dimensions non-contiguous\n x = torch.randn(7 * o, 5 * n, 2 * m, device=device)[::7, ::5, ::2]\n check_single_nuclear_norm(x, axes)\n\n for r in range(1, 3):\n for axes in itertools.permutations([0, 1, 2, 3], 2):\n # 4d, inner dimensions C\n x = torch.randn(r, o, n, m, device=device)\n check_single_nuclear_norm(x, axes)\n\n # 4d, inner dimensions Fortran\n x = torch.randn(r, o, n, m, device=device).transpose(-1, -2)\n check_single_nuclear_norm(x, axes)\n\n # 4d, inner dimensions non-contiguous\n x = torch.randn(r, o, n, 2 * m, device=device)[:, :, :, ::2]\n check_single_nuclear_norm(x, axes)\n\n # 4d, all dimensions non-contiguous\n x = torch.randn(7 * r, 5 * o, 11 * n, 2 * m, device=device)[::7, ::5, ::11, ::2]\n check_single_nuclear_norm(x, axes)\n\n @skipCUDAIfNoMagma\n def test_nuclear_norm_exceptions_old(self, device):\n for lst in [], [1], [1, 2]:\n x = torch.tensor(lst, dtype=torch.double, device=device)\n for axes in (), (0,):\n self.assertRaises(RuntimeError, torch.norm, x, \"nuc\", axes)\n self.assertRaises(IndexError, torch.norm, x, \"nuc\", (0, 1))\n\n x = torch.tensor([[0, 1, 2], [3, 4, 5]], dtype=torch.double, device=device)\n self.assertRaisesRegex(RuntimeError, \"duplicate or invalid\", torch.norm, x, \"nuc\", (0, 0))\n self.assertRaisesRegex(IndexError, \"Dimension out of range\", torch.norm, x, \"nuc\", (0, 2))\n\n # ~~~ tests for torch.svd ~~~\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.double)\n def test_svd(self, device, dtype):\n def run_test(dims, some, compute_uv):\n x = torch.randn(*dims, dtype=dtype, device=device)\n outu = torch.empty(0, dtype=dtype, device=device)\n outs = torch.empty(0, dtype=dtype, device=device)\n outv = torch.empty(0, dtype=dtype, device=device)\n torch.svd(x, some=some, compute_uv=compute_uv, out=(outu, outs, outv))\n\n if compute_uv:\n if some:\n x_recon = torch.matmul(outu, torch.matmul(outs.diag_embed(), outv.transpose(-2, -1)))\n self.assertEqual(x, x_recon, atol=1e-8, rtol=0, msg='Incorrect reconstruction using U @ diag(S) @ V.T')\n else:\n narrow_u = outu[..., :min(*dims[-2:])]\n narrow_v = outv[..., :min(*dims[-2:])]\n x_recon = torch.matmul(narrow_u, torch.matmul(outs.diag_embed(), narrow_v.transpose(-2, -1)))\n self.assertEqual(x, x_recon, atol=1e-8, rtol=0, msg='Incorrect reconstruction using U @ diag(S) @ V.T')\n else:\n _, singvals, _ = torch.svd(x, compute_uv=True)\n self.assertEqual(singvals, outs, msg='Singular values mismatch')\n self.assertEqual(outu, torch.zeros_like(outu), msg='U not zero')\n self.assertEqual(outv, torch.zeros_like(outv), msg='V not zero')\n\n resu, ress, resv = torch.svd(x, some=some, compute_uv=compute_uv)\n self.assertEqual(resu, outu, msg='outputs of svd and svd with out differ')\n self.assertEqual(ress, outs, msg='outputs of svd and svd with out differ')\n self.assertEqual(resv, outv, msg='outputs of svd and svd with out differ')\n\n # test non-contiguous\n x = torch.randn(*dims, dtype=dtype, device=device)\n if x.numel() > 0:\n n_dim = len(dims)\n # Reverse the batch dimensions and the matrix dimensions and then concat them\n x = x.permute(tuple(range(n_dim - 3, -1, -1)) + (n_dim - 1, n_dim - 2))\n assert not x.is_contiguous(), \"x is intentionally non-contiguous\"\n resu, ress, resv = torch.svd(x, some=some, compute_uv=compute_uv)\n if compute_uv:\n if some:\n x_recon = torch.matmul(resu, torch.matmul(ress.diag_embed(), resv.transpose(-2, -1)))\n self.assertEqual(x, x_recon, atol=1e-8, rtol=0, msg='Incorrect reconstruction using U @ diag(S) @ V.T')\n else:\n narrow_u = resu[..., :min(*dims[-2:])]\n narrow_v = resv[..., :min(*dims[-2:])]\n x_recon = torch.matmul(narrow_u, torch.matmul(ress.diag_embed(), narrow_v.transpose(-2, -1)))\n self.assertEqual(x, x_recon, atol=1e-8, rtol=0, msg='Incorrect reconstruction using U @ diag(S) @ V.T')\n else:\n _, singvals, _ = torch.svd(x, compute_uv=True)\n self.assertEqual(singvals, ress, msg='Singular values mismatch')\n self.assertEqual(resu, torch.zeros_like(resu), msg='U not zero')\n self.assertEqual(resv, torch.zeros_like(resv), msg='V not zero')\n\n shapes = [(0, 0), (5, 0), (0, 5), # empty matrices\n (0, 0, 0), (0, 5, 5), (0, 5, 3), # zero batch dimension\n (3, 3), (5, 3, 3), (7, 5, 3, 3), # square matrices\n (7, 3), (5, 7, 3), (7, 5, 7, 3), # fat matrices\n (3, 7), (5, 3, 7), (7, 5, 3, 7)] # thin matrices\n for dims, some, compute_uv in product(shapes, [True, False], [True, False]):\n run_test(dims, some, compute_uv)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float)\n def test_svd_no_singularvectors(self, device, dtype):\n for size in [(5, 5), (5, 20), (20, 5)]:\n a = torch.randn(*size, device=device, dtype=dtype)\n u, s_expect, v = torch.svd(a)\n u, s_actual, v = torch.svd(a, compute_uv=False)\n self.assertEqual(s_expect, s_actual, msg=\"Singular values don't match\")\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.double)\n def test_svd_lowrank(self, device, dtype):\n from torch.testing._internal.common_utils import random_lowrank_matrix, random_sparse_matrix\n\n def run_subtest(actual_rank, matrix_size, batches, device, svd_lowrank, **options):\n density = options.pop('density', 1)\n if isinstance(matrix_size, int):\n rows = columns = matrix_size\n else:\n rows, columns = matrix_size\n if density == 1:\n a_input = random_lowrank_matrix(actual_rank, rows, columns, *batches, device=device, dtype=dtype)\n a = a_input\n else:\n assert batches == ()\n a_input = random_sparse_matrix(rows, columns, density, device=device, dtype=dtype)\n a = a_input.to_dense()\n\n q = min(*size)\n u, s, v = svd_lowrank(a_input, q=q, **options)\n\n # check if u, s, v is a SVD\n u, s, v = u[..., :q], s[..., :q], v[..., :q]\n A = u.matmul(s.diag_embed()).matmul(v.transpose(-2, -1))\n self.assertEqual(A, a, rtol=1e-7, atol=2e-7)\n\n # check if svd_lowrank produces same singular values as torch.svd\n U, S, V = torch.svd(a)\n self.assertEqual(s.shape, S.shape)\n self.assertEqual(u.shape, U.shape)\n self.assertEqual(v.shape, V.shape)\n self.assertEqual(s, S)\n\n if density == 1:\n # actual_rank is known only for dense inputs\n #\n # check if pairs (u, U) and (v, V) span the same\n # subspaces, respectively\n u, s, v = u[..., :actual_rank], s[..., :actual_rank], v[..., :actual_rank]\n U, S, V = U[..., :actual_rank], S[..., :actual_rank], V[..., :actual_rank]\n self.assertEqual(u.transpose(-2, -1).matmul(U).det().abs(), torch.ones(batches, device=device, dtype=dtype))\n self.assertEqual(v.transpose(-2, -1).matmul(V).det().abs(), torch.ones(batches, device=device, dtype=dtype))\n\n all_batches = [(), (1,), (3,), (2, 3)]\n for actual_rank, size, all_batches in [\n (2, (17, 4), all_batches),\n (4, (17, 4), all_batches),\n (4, (17, 17), all_batches),\n (10, (100, 40), all_batches),\n (7, (1000, 1000), [()]),\n ]:\n # dense input\n for batches in all_batches:\n run_subtest(actual_rank, size, batches, device, torch.svd_lowrank)\n if size != size[::-1]:\n run_subtest(actual_rank, size[::-1], batches, device, torch.svd_lowrank)\n\n # sparse input\n for size in [(17, 4), (4, 17), (17, 17), (100, 40), (40, 100), (1000, 1000)]:\n for density in [0.005, 0.1]:\n run_subtest(None, size, (), device, torch.svd_lowrank, density=density)\n\n # jitting support\n jitted = torch.jit.script(torch.svd_lowrank)\n actual_rank, size, batches = 2, (17, 4), ()\n run_subtest(actual_rank, size, batches, device, jitted)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.cfloat)\n def test_svd_complex(self, device, dtype):\n # this test verifies that torch.svd really returns V and not V.conj()\n # see: https://github.com/pytorch/pytorch/issues/45821\n t = torch.randn((10, 10), dtype=dtype, device=device)\n U, S, V = torch.svd(t, some=False)\n # verify that t ≈ t2\n # t2 = U @ diag(S) @ Vᴴ\n # Vᴴ is the conjugate transpose of V\n t2 = U @ torch.diag(S).type(dtype) @ V.conj().T\n self.assertEqual(t, t2)\n\n def _test_svd_helper(self, shape, some, col_maj, device, dtype):\n # To have accurate tests and less false positives on different CPUs and GPUs,\n # we use double or complex double accuracy for CPU reference.\n cpu_dtype = torch.complex128 if dtype.is_complex else torch.float64\n cpu_tensor = torch.randn(shape, device='cpu', dtype=cpu_dtype)\n device_tensor = cpu_tensor.to(device=device, dtype=dtype)\n if col_maj:\n cpu_tensor = cpu_tensor.t()\n device_tensor = device_tensor.t()\n cpu_result = torch.svd(cpu_tensor, some=some)\n device_result = torch.svd(device_tensor, some=some)\n m = min(cpu_tensor.shape[-2:])\n # torch.svd returns torch.return_types.svd which is a tuple of (U, V, S).\n # - When some==False, U[..., m:] can be arbitrary.\n # - When some==True, U shape: [..., m], V shape: [m, m]\n # - Signs are not deterministic. If the sign of a column of U is changed\n # then the corresponding column of the V has to be changed.\n # Thus here we only compare result[..., :m].abs() from CPU and device.\n for x, y in zip(cpu_result, device_result):\n self.assertEqual(x[..., :m].abs(), y[..., :m].abs(), exact_dtype=False)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_svd_errors_and_warnings(self, device, dtype):\n for svd in [torch.svd, torch.linalg.svd]:\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = torch.randn(3, 3, dtype=dtype, device=device)\n real_dtype = a.real.dtype if dtype.is_complex else dtype\n out_u = torch.empty(2, 2, dtype=dtype, device=device)\n out_s = torch.empty(4, 4, dtype=real_dtype, device=device)\n out_v = torch.empty(6, 6, dtype=dtype, device=device)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n svd(a, out=(out_u, out_s, out_v))\n # Check warning occurs\n self.assertEqual(len(w), 3)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-3].message))\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-2].message))\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out_u = torch.empty(0, dtype=torch.int, device=device)\n out_s = torch.empty(0, dtype=torch.int, device=device)\n out_v = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got U with dtype Int\"):\n svd(a, out=(out_u, out_s, out_v))\n\n out_u = torch.empty(0, dtype=dtype, device=device)\n if svd == torch.linalg.svd:\n msg = \"but got Vh with dtype Int\"\n else:\n msg = \"but got V with dtype Int\"\n with self.assertRaisesRegex(RuntimeError, msg):\n svd(a, out=(out_u, out_s, out_v))\n\n out_v = torch.empty(0, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got S with dtype Int\"):\n svd(a, out=(out_u, out_s, out_v))\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out_u = torch.empty(0, device=wrong_device, dtype=dtype)\n out_s = torch.empty(0, device=wrong_device, dtype=real_dtype)\n out_v = torch.empty(0, device=wrong_device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n # error from out_u\n svd(a, out=(out_u, out_s, out_v))\n\n out_u = torch.empty(0, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n # error from out_s\n svd(a, out=(out_u, out_s, out_v))\n\n out_s = torch.empty(0, device=device, dtype=real_dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n # error from out_v\n svd(a, out=(out_u, out_s, out_v))\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(*floating_and_complex_types())\n def test_svd_square(self, device, dtype):\n self._test_svd_helper((10, 10), True, False, device, dtype)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(*floating_types())\n def test_svd_square_col_maj(self, device, dtype):\n self._test_svd_helper((10, 10), True, True, device, dtype)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(*floating_types())\n def test_svd_tall_some(self, device, dtype):\n self._test_svd_helper((20, 5), True, False, device, dtype)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(*floating_types())\n def test_svd_tall_all(self, device, dtype):\n self._test_svd_helper((20, 5), False, False, device, dtype)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(*floating_types())\n def test_svd_tall_some_col_maj(self, device, dtype):\n self._test_svd_helper((5, 20), True, True, device, dtype)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(*floating_types())\n def test_svd_tall_all_col_maj(self, device, dtype):\n self._test_svd_helper((5, 20), False, True, device, dtype)\n\n # ~~~ tests for torch.linalg.svd ~~~\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_linalg_svd_compute_uv(self, device, dtype):\n \"\"\"\n Test the default case. Here we have the very same behavior as\n NumPy with compute_uv=True.\n \"\"\"\n t = torch.randn((10, 11), device=device, dtype=dtype)\n np_t = t.cpu().numpy()\n for full_matrices in (True, False):\n # check linalg.svd vs numpy\n expected = np.linalg.svd(np_t, full_matrices, compute_uv=True)\n actual = torch.linalg.svd(t, full_matrices)\n # sign/phase of the singular vectors is not unique and therefore absolute values are compared\n self.assertEqual(abs(actual[0]), abs(expected[0]))\n self.assertEqual(actual[1], expected[1])\n self.assertEqual(abs(actual[2]), abs(expected[2]))\n # check linalg.svd vs linalg.svd(out=...)\n out = (torch.empty_like(actual[0]),\n torch.empty_like(actual[1]),\n torch.empty_like(actual[2]))\n out2 = torch.linalg.svd(t, full_matrices, out=out)\n self.assertEqual(actual, out)\n self.assertEqual(actual, out2)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_svdvals(self, device, dtype):\n\n def run_test(shape):\n # NumPy doesn't have separate svdvals function, it is included in\n # svd with compute_uv=False\n # so we test our implementation against numpy.linalg.svd(*, compute_uv=False)\n A = make_tensor(shape, dtype=dtype, device=device)\n expected = np.linalg.svd(A.cpu(), compute_uv=False)\n actual = torch.linalg.svdvals(A)\n self.assertEqual(actual, expected)\n\n batches = [(), (0, ), (2, ), (2, 1)]\n ns = [5, 2, 0]\n for batch, (m, n) in itertools.product(batches, product(ns, ns)):\n run_test((*batch, m, n))\n\n @skipCUDAIfNoCusolver # MAGMA backend doesn't work in this case\n @skipCUDAIfRocm\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_svd_memory_allocation(self, device, dtype):\n # test for https://github.com/pytorch/pytorch/issues/61949\n # the problem was that tensors of incorrect size were allocated and then narrowed\n m = 3\n n = 2**20\n a = make_tensor((m, n), dtype=dtype, device=device)\n # the following should run without errors\n result = torch.linalg.svdvals(a)\n result = torch.linalg.svd(a, full_matrices=False)\n\n out0 = torch.empty_like(result[0])\n out1 = torch.empty_like(result[1])\n out2 = torch.empty_like(result[2])\n torch.linalg.svdvals(a, out=out0)\n torch.linalg.svd(a, full_matrices=False, out=(out0, out1, out2))\n\n def cholesky_solve_test_helper(self, A_dims, b_dims, upper, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n b = torch.randn(*b_dims, dtype=dtype, device=device)\n A = random_hermitian_pd_matrix(*A_dims, dtype=dtype, device=device)\n L = torch.cholesky(A, upper=upper)\n return b, A, L\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_cholesky_solve(self, device, dtype):\n for (k, n), upper in itertools.product(zip([2, 3, 5], [3, 5, 7]), [True, False]):\n b, A, L = self.cholesky_solve_test_helper((n,), (n, k), upper, device, dtype)\n x = torch.cholesky_solve(b, L, upper=upper)\n self.assertEqual(b, np.matmul(A.cpu(), x.cpu()))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_cholesky_solve_batched(self, device, dtype):\n def cholesky_solve_batch_helper(A_dims, b_dims, upper):\n b, A, L = self.cholesky_solve_test_helper(A_dims, b_dims, upper, device, dtype)\n x_exp_list = []\n for i in range(b_dims[0]):\n x_exp_list.append(torch.cholesky_solve(b[i], L[i], upper=upper))\n x_exp = torch.stack(x_exp_list) # Stacked output\n x_act = torch.cholesky_solve(b, L, upper=upper) # Actual output\n self.assertEqual(x_act, x_exp) # Equality check\n Ax = np.matmul(A.cpu(), x_act.cpu())\n self.assertEqual(b, Ax) # Correctness check\n\n for upper, batchsize in itertools.product([True, False], [1, 3, 4]):\n cholesky_solve_batch_helper((5, batchsize), (batchsize, 5, 10), upper)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky_solve_batched_non_contiguous(self, device, dtype):\n from numpy.linalg import solve\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n for upper in [True, False]:\n A = random_hermitian_pd_matrix(2, 2, dtype=dtype, device='cpu')\n b = torch.randn(2, 2, 2, dtype=dtype, device='cpu')\n x_exp = solve(A.permute(0, 2, 1).numpy(), b.permute(2, 1, 0).numpy())\n A = A.to(device).permute(0, 2, 1)\n b = b.to(device).permute(2, 1, 0)\n assert not A.is_contiguous() and not b.is_contiguous(), \"contiguous inputs\"\n L = torch.cholesky(A, upper)\n x = torch.cholesky_solve(b, L, upper=upper)\n self.assertEqual(x, x_exp)\n\n @slowTest\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_cholesky_solve_batched_many_batches(self, device, dtype):\n for A_dims, b_dims in zip([(5, 256, 256), (5,)], [(5, 10), (512, 512, 5, 10)]):\n for upper in [True, False]:\n b, A, L = self.cholesky_solve_test_helper(A_dims, b_dims, upper, device, dtype)\n x = torch.cholesky_solve(b, L, upper)\n Ax = torch.matmul(A, x)\n self.assertEqual(Ax, b.expand_as(Ax))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_cholesky_solve_batched_broadcasting(self, device, dtype):\n from numpy.linalg import solve\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n def run_test(A_dims, b_dims, upper):\n A_matrix_size = A_dims[-1]\n A_batch_dims = A_dims[:-2]\n A = random_hermitian_pd_matrix(A_matrix_size, *A_batch_dims,\n dtype=dtype, device='cpu')\n b = torch.randn(*b_dims, dtype=dtype, device='cpu')\n x_exp = torch.tensor(solve(A.numpy(), b.numpy()), dtype=dtype, device=device)\n A, b = A.to(dtype=dtype, device=device), b.to(dtype=dtype, device=device)\n L = torch.cholesky(A, upper)\n x = torch.cholesky_solve(b, L, upper=upper)\n self.assertEqual(x, x_exp)\n # https://github.com/pytorch/pytorch/issues/42695\n x = torch.cholesky_solve(b, L, upper=upper, out=x)\n self.assertEqual(x, x_exp)\n\n # test against numpy.linalg.solve\n for upper in [True, False]:\n run_test((2, 1, 3, 4, 4), (2, 1, 3, 4, 6), upper) # no broadcasting\n run_test((2, 1, 3, 4, 4), (4, 6), upper) # broadcasting b\n run_test((4, 4), (2, 1, 3, 4, 2), upper) # broadcasting A\n run_test((1, 3, 1, 4, 4), (2, 1, 3, 4, 5), upper) # broadcasting A & b\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float64, torch.complex128)\n def test_cholesky_solve_autograd(self, device, dtype):\n def run_test(A_dims, B_dims, upper):\n root = torch.randn(*A_dims, device=device, dtype=dtype).requires_grad_()\n b = torch.randn(*B_dims, device=device, dtype=dtype).requires_grad_()\n\n def func(root, b, upper):\n if upper:\n A = root.triu()\n else:\n A = root.tril()\n return torch.cholesky_solve(b, A, upper)\n\n gradcheck(func, [root, b, upper])\n # TODO(#50743): the following fails with batched grad testing\n # TODO(#56235): disabling temporarily\n # gradgradcheck(func, [root, b, upper], atol=1e-3, check_batched_grad=False)\n\n for (a_size, b_size), upper in itertools.product([((3, 3), (3, 4)), ((3, 3), (3, 2)),\n ((2, 3, 3), (2, 3, 4)), ((2, 3, 3), (2, 3, 2))],\n [True, False]):\n run_test(a_size, b_size, upper)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky_solve_out_errors_and_warnings(self, device, dtype):\n # dtypes should be safely castable\n a = torch.eye(2, dtype=dtype, device=device)\n b = torch.randn(2, 1, dtype=dtype, device=device)\n out = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.cholesky_solve(b, a, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.cholesky_solve(b, a, out=out)\n\n # if out tensor with wrong shape is passed a warning is given\n with warnings.catch_warnings(record=True) as w:\n out = torch.empty(1, dtype=dtype, device=device)\n # Trigger warning\n torch.cholesky_solve(b, a, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 2e-3, torch.complex64: 2e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_inverse(self, device, dtype):\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n def run_test(torch_inverse, matrix, batches, n):\n matrix_inverse = torch_inverse(matrix)\n\n # Compare against NumPy output\n # NumPy uses 'gesv' LAPACK routine solving the equation A A_inv = I\n # But in PyTorch 'gertf' + 'getri' is used causing element-wise differences\n expected = np.linalg.inv(matrix.cpu().numpy())\n self.assertEqual(matrix_inverse, expected, atol=self.precision, rtol=self.precision)\n\n # Additional correctness tests, check matrix*matrix_inverse == identity\n identity = torch.eye(n, dtype=dtype, device=device)\n self.assertEqual(identity.expand_as(matrix), np.matmul(matrix.cpu(), matrix_inverse.cpu()))\n self.assertEqual(identity.expand_as(matrix), np.matmul(matrix_inverse.cpu(), matrix.cpu()))\n\n # check the out= variant\n # prepare the expected out tensor\n matrix_inverse_out = torch.empty(*batches, n, n, dtype=dtype, device=device)\n matrix_inverse_out_t = matrix_inverse_out.transpose(-2, -1).clone(memory_format=torch.contiguous_format)\n matrix_inverse_out = matrix_inverse_out_t.transpose(-2, -1)\n ans = torch_inverse(matrix, out=matrix_inverse_out)\n self.assertEqual(matrix_inverse_out, ans, atol=0, rtol=0)\n self.assertEqual(matrix_inverse_out, matrix_inverse, atol=0, rtol=0)\n\n # batched matrices: 3+ dimensional tensors, check matrix_inverse same as single-inverse for each matrix\n if matrix.ndim > 2 and batches[0] != 0:\n expected_inv_list = []\n p = int(np.prod(batches)) # use `p` instead of -1, so that the test works for empty input as well\n for mat in matrix.contiguous().view(p, n, n):\n expected_inv_list.append(torch_inverse(mat))\n expected_inv = torch.stack(expected_inv_list).view(*batches, n, n)\n if self.device_type == 'cuda' and dtype in [torch.float32, torch.complex64]:\n # single-inverse is done using cuSOLVER, while batched inverse is done using MAGMA\n # individual values can be significantly different for fp32, hence rather high rtol is used\n # the important thing is that torch_inverse passes above checks with identity\n self.assertEqual(matrix_inverse, expected_inv, atol=1e-1, rtol=1e-2)\n else:\n self.assertEqual(matrix_inverse, expected_inv)\n\n # helper function for testing torch.linalg.inv_ex\n def test_inv_ex(input, out=None):\n if out is not None:\n info = torch.empty(0, dtype=torch.int32, device=device)\n return torch.linalg.inv_ex(input, out=(out, info)).inverse\n return torch.linalg.inv_ex(input).inverse\n\n for torch_inverse in [torch.inverse, torch.linalg.inv, test_inv_ex]:\n for batches, n in itertools.product(\n [[], [0], [2], [2, 1]],\n [0, 5]\n ):\n matrices = random_fullrank_matrix_distinct_singular_value(n, *batches, dtype=dtype).to(device)\n run_test(torch_inverse, matrices, batches, n)\n\n # test non-contiguous input\n run_test(torch_inverse, matrices.transpose(-2, -1), batches, n)\n if n > 0:\n run_test(\n torch_inverse,\n random_fullrank_matrix_distinct_singular_value(n * 2, *batches, dtype=dtype).to(device)\n .view(-1, n * 2, n * 2)[:, ::2, ::2].view(*batches, n, n),\n batches, n\n )\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_inv_ex_info_device(self, device, dtype):\n A = torch.eye(3, 3, dtype=dtype, device=device)\n info = torch.linalg.inv_ex(A).info\n self.assertTrue(info.device == A.device)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @skipCUDAIfRocm\n def test_inv_ex_singular(self, device, dtype):\n # if the input matrix is not invertible, info with positive integer is returned\n A = torch.eye(3, 3, dtype=dtype, device=device)\n A[-1, -1] = 0 # Now A is singular\n info = torch.linalg.inv_ex(A).info\n self.assertEqual(info, 3)\n with self.assertRaisesRegex(RuntimeError, r'U\\(3,3\\) is zero, singular U\\.'):\n torch.linalg.inv_ex(A, check_errors=True)\n\n # if at least one matrix in the batch is not positive definite,\n # batched info with positive integer for the corresponding matrix is returned\n A = torch.eye(3, 3, dtype=dtype, device=device)\n A = A.reshape((1, 3, 3))\n A = A.repeat(5, 1, 1)\n A[3, -2, -2] = 0 # Now A[3] is singular\n info = torch.linalg.inv_ex(A).info\n\n expected_info = torch.zeros(A.shape[:-2], dtype=torch.int32, device=device)\n expected_info[3] = 2\n self.assertEqual(info, expected_info)\n with self.assertRaisesRegex(RuntimeError, r'For batch 3: U\\(2,2\\) is zero, singular U\\.'):\n torch.linalg.inv_ex(A, check_errors=True)\n\n @slowTest\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 2e-3, torch.complex64: 2e-3,\n torch.float64: 1e-5, torch.complex128: 1e-5})\n def test_inverse_many_batches(self, device, dtype):\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n def test_inverse_many_batches_helper(torch_inverse, b, n):\n matrices = random_fullrank_matrix_distinct_singular_value(b, n, n, dtype=dtype).to(device)\n matrices_inverse = torch_inverse(matrices)\n\n # Compare against NumPy output\n expected = np.linalg.inv(matrices.cpu().numpy())\n self.assertEqual(matrices_inverse, expected, atol=self.precision, rtol=1e-3)\n\n for torch_inverse in [torch.inverse, torch.linalg.inv]:\n test_inverse_many_batches_helper(torch_inverse, 5, 256)\n test_inverse_many_batches_helper(torch_inverse, 3, 512)\n test_inverse_many_batches_helper(torch_inverse, 64, 64)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @onlyOnCPUAndCUDA # TODO: XLA doesn't raise exception\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_inverse_errors(self, device, dtype):\n # inverse expects batches of square matrices as input\n with self.assertRaisesRegex(RuntimeError, \"must be batches of square matrices\"):\n torch.inverse(torch.randn(2, 3, 4, 3))\n\n # if input is not invertible, RuntimeError is raised mentioning the first non-invertible batch\n def run_test_singular_input(batch_dim, n):\n x = torch.eye(3, 3, dtype=dtype, device=device).reshape((1, 3, 3)).repeat(batch_dim, 1, 1)\n x[n, -1, -1] = 0\n with self.assertRaisesRegex(RuntimeError, rf'For batch {n}: U\\(3,3\\) is zero'):\n torch.inverse(x)\n\n for params in [(1, 0), (2, 0), (2, 1), (4, 0), (4, 2), (10, 2)]:\n run_test_singular_input(*params)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @onlyOnCPUAndCUDA # TODO: XLA doesn't raise exception\n @skipCUDAIfRocm\n @skipCUDAVersionIn([(11, 3)]) # https://github.com/pytorch/pytorch/issues/57482\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_inverse_errors_large(self, device, dtype):\n # Test batched inverse of singular matrices reports errors without crashing (gh-51930)\n x = torch.empty((8, 10, 616, 616), dtype=dtype, device=device)\n x[:] = torch.eye(616, dtype=dtype, device=device)\n x[..., 10, 10] = 0\n with self.assertRaisesRegex(RuntimeError, r'For batch 0: U\\(11,11\\) is zero'):\n torch.inverse(x)\n\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3, torch.float64: 1e-7, torch.complex128: 1e-7})\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_pinv(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n def run_test_main(A, hermitian):\n # Testing against definition for pseudo-inverses\n A_pinv = torch.linalg.pinv(A, hermitian=hermitian)\n np_A = A.cpu().numpy()\n np_A_pinv = A_pinv.cpu().numpy()\n if A.numel() > 0:\n self.assertEqual(A, np_A @ np_A_pinv @ np_A, atol=self.precision, rtol=self.precision)\n self.assertEqual(A_pinv, np_A_pinv @ np_A @ np_A_pinv, atol=self.precision, rtol=self.precision)\n self.assertEqual(np_A @ np_A_pinv, (np_A @ np_A_pinv).conj().swapaxes(-2, -1))\n self.assertEqual(np_A_pinv @ np_A, (np_A_pinv @ np_A).conj().swapaxes(-2, -1))\n else:\n self.assertEqual(A.shape, A_pinv.shape[:-2] + (A_pinv.shape[-1], A_pinv.shape[-2]))\n\n # Check out= variant\n out = torch.empty_like(A_pinv)\n ans = torch.linalg.pinv(A, hermitian=hermitian, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, A_pinv)\n\n def run_test_numpy(A, hermitian):\n # Check against NumPy output\n # Test float rcond, and specific value for each matrix\n rconds = [float(torch.rand(1)), ]\n # Test different types of rcond tensor\n for rcond_type in all_types():\n rconds.append(torch.rand(A.shape[:-2], dtype=torch.double, device=device).to(rcond_type))\n # Test broadcasting of rcond\n if A.ndim > 2:\n rconds.append(torch.rand(A.shape[-3], device=device))\n for rcond in rconds:\n actual = torch.linalg.pinv(A, rcond=rcond, hermitian=hermitian)\n numpy_rcond = rcond if isinstance(rcond, float) else rcond.cpu().numpy()\n expected = np.linalg.pinv(A.cpu().numpy(), rcond=numpy_rcond, hermitian=hermitian)\n self.assertEqual(actual, expected, atol=self.precision, rtol=1e-5)\n\n for sizes in [(5, 5), (3, 5, 5), (3, 2, 5, 5), # square matrices\n (3, 2), (5, 3, 2), (2, 5, 3, 2), # fat matrices\n (2, 3), (5, 2, 3), (2, 5, 2, 3), # thin matrices\n (0, 0), (0, 2), (2, 0), (3, 0, 0), (0, 3, 0), (0, 0, 3)]: # zero numel matrices\n A = torch.randn(*sizes, dtype=dtype, device=device)\n hermitian = False\n run_test_main(A, hermitian)\n run_test_numpy(A, hermitian)\n\n # Check hermitian = True\n for sizes in [(5, 5), (3, 5, 5), (3, 2, 5, 5), # square matrices\n (0, 0), (3, 0, 0), ]: # zero numel square matrices\n A = random_hermitian_pd_matrix(sizes[-1], *sizes[:-2], dtype=dtype, device=device)\n hermitian = True\n run_test_main(A, hermitian)\n run_test_numpy(A, hermitian)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_pinv_errors_and_warnings(self, device, dtype):\n # pinv requires at least 2D tensor\n a = torch.randn(1, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"expected a tensor with 2 or more dimensions\"):\n torch.linalg.pinv(a)\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = torch.randn(3, 3, dtype=dtype, device=device)\n out = torch.empty(7, 7, dtype=dtype, device=device)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.pinv(a, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes of out and input should be safely castable\n out = torch.empty_like(a).to(torch.int)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.linalg.pinv(a, out=out)\n\n if torch.cuda.is_available():\n # device of out and input should match\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty_like(a).to(wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"Expected result and input tensors to be on the same device\"):\n torch.linalg.pinv(a, out=out)\n\n # device of rcond and input should match\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n rcond = torch.full((), 1e-2, device=wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"Expected rcond and input to be on the same device\"):\n torch.linalg.pinv(a, rcond=rcond)\n\n # rcond can't be complex\n rcond = torch.full((), 1j, device=device)\n with self.assertRaisesRegex(RuntimeError, \"rcond tensor of complex type is not supported\"):\n torch.linalg.pinv(a, rcond=rcond)\n\n @skipCUDAIfNoMagmaAndNoCusolver\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_inv_errors_and_warnings(self, device, dtype):\n # inv expects batches of square matrices as input\n a = torch.randn(2, 3, 4, 3, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"must be batches of square matrices\"):\n torch.linalg.inv(a)\n\n # inv requires the input to be at least 2 dimensional tensor\n a = torch.randn(2, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"must have at least 2 dimensions\"):\n torch.linalg.inv(a)\n\n # if input is not invertible, RuntimeError is raised mentioning the first non-invertible batch\n def run_test_singular_input(batch_dim, n):\n a = torch.eye(3, 3, dtype=dtype, device=device).reshape((1, 3, 3)).repeat(batch_dim, 1, 1)\n a[n, -1, -1] = 0\n with self.assertRaisesRegex(RuntimeError, rf\"For batch {n}: U\\(3,3\\) is zero\"):\n torch.linalg.inv(a)\n\n for params in [(1, 0), (2, 0), (2, 1), (4, 0), (4, 2), (10, 2)]:\n run_test_singular_input(*params)\n\n # dtypes should match\n a = torch.eye(2, dtype=dtype, device=device)\n out = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"got result with dtype Int\"):\n torch.linalg.inv(a, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, device=wrong_device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.inv(a, out=out)\n\n # if out tensor with wrong shape is passed a warning is given\n with warnings.catch_warnings(record=True) as w:\n a = torch.eye(2, dtype=dtype, device=device)\n out = torch.empty(1, dtype=dtype, device=device)\n # Trigger warning\n torch.linalg.inv(a, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # if out tensor in batched column major format but with wrong a warning is given\n with warnings.catch_warnings(record=True) as w:\n a = torch.eye(2, dtype=dtype, device=device)\n out = torch.empty(3, 3, dtype=dtype, device=device)\n out = out.transpose(-2, -1).clone(memory_format=torch.contiguous_format)\n out = out.transpose(-2, -1)\n self.assertTrue(out.transpose(-2, -1).is_contiguous())\n # Trigger warning\n torch.linalg.inv(a, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n def solve_test_helper(self, A_dims, b_dims, device, dtype):\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n b = torch.randn(*b_dims, dtype=dtype, device=device)\n A = random_fullrank_matrix_distinct_singular_value(*A_dims, dtype=dtype).to(device)\n return b, A\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3})\n def test_solve(self, device, dtype):\n def run_test(n, batch, rhs):\n A_dims = (n, *batch)\n b_dims = (*batch, n, *rhs)\n b, A = self.solve_test_helper(A_dims, b_dims, device, dtype)\n\n # Correctness test\n x = torch.linalg.solve(A, b)\n if rhs == ():\n Ax = np.matmul(A.cpu(), x.unsqueeze(-1).cpu())\n Ax.squeeze_(-1)\n else:\n Ax = np.matmul(A.cpu(), x.cpu())\n self.assertEqual(b.expand_as(Ax), Ax)\n\n # Check against NumPy\n expected = np.linalg.solve(A.cpu().numpy(), b.expand_as(x).cpu().numpy())\n self.assertEqual(x, expected)\n\n # Check out= variant\n out = torch.empty_like(x)\n ans = torch.linalg.solve(A, b, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(x, out)\n\n # Check out= variant with complex128 out tensor\n out = torch.empty_like(x).to(torch.complex128)\n ans = torch.linalg.solve(A, b, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(x.to(torch.complex128), out)\n\n # Check empty out\n out = torch.empty(0, dtype=dtype, device=device)\n ans = torch.linalg.solve(A, b, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(x, out)\n\n batches = [(), (0, ), (3, ), (2, 3)]\n ns = [0, 5, 32]\n nrhs = [(), (1, ), (5, )]\n for n, batch, rhs in itertools.product(ns, batches, nrhs):\n run_test(n, batch, rhs)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3})\n def test_solve_batched_non_contiguous(self, device, dtype):\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n A = random_fullrank_matrix_distinct_singular_value(2, 2, dtype=dtype).to(device).permute(1, 0, 2)\n b = torch.randn(2, 2, 2, dtype=dtype, device=device).permute(2, 1, 0)\n self.assertFalse(A.is_contiguous())\n self.assertFalse(b.is_contiguous())\n actual = torch.linalg.solve(A, b)\n expected = np.linalg.solve(A.cpu().numpy(), b.cpu().numpy())\n self.assertEqual(actual, expected)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_solve_errors_and_warnings(self, device, dtype):\n # solve expects batches of square matrices as input\n with self.assertRaisesRegex(RuntimeError, \"must be batches of square matrices\"):\n a = torch.randn(2, 3, 4, 3, dtype=dtype, device=device)\n b = torch.randn(2, 3, 4, 1, dtype=dtype, device=device)\n torch.linalg.solve(a, b)\n\n # solve expects compatible shapes for A x = b\n with self.assertRaisesRegex(RuntimeError, \"Incompatible matrix sizes\"):\n a = torch.randn(2, 3, 3, 3, dtype=dtype, device=device)\n b = torch.randn(2, 3, 2, 1, dtype=dtype, device=device)\n torch.linalg.solve(a, b)\n\n # if input is not solvable, RuntimeError is raised mentioning the first non-solvable batch\n def run_test_singular_input(batch_dim, n):\n a = torch.eye(3, 3, dtype=dtype, device=device).reshape((1, 3, 3)).repeat(batch_dim, 1, 1)\n a[n, -1, -1] = 0\n b = torch.randn(batch_dim, 3, 1, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, rf'For batch {n}: U\\(3,3\\) is zero'):\n torch.linalg.solve(a, b)\n\n for params in [(1, 0), (2, 0), (2, 1), (4, 0), (4, 2), (10, 2)]:\n run_test_singular_input(*params)\n\n # if out tensor with wrong shape is passed a warning is given\n # matrix 'b' case\n with warnings.catch_warnings(record=True) as w:\n A = torch.eye(2, dtype=dtype, device=device).reshape((1, 2, 2)).repeat(2, 1, 1)\n b = torch.randn(2, 2, 2, dtype=dtype, device=device)\n out = torch.zeros(1, dtype=dtype, device=device)\n # Trigger warning\n torch.linalg.solve(A, b, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # if out tensor with wrong shape is passed a warning is given\n # vector 'b' case\n with warnings.catch_warnings(record=True) as w:\n A = torch.eye(2, dtype=dtype, device=device)\n b = torch.randn(2, dtype=dtype, device=device)\n out = torch.zeros(1, dtype=dtype, device=device)\n # Trigger warning\n torch.linalg.solve(A, b, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n a = torch.eye(2, dtype=dtype, device=device)\n b = torch.randn(2, 1, dtype=dtype, device=device)\n out = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.linalg.solve(a, b, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n clone_a = torch.empty_like(a)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.solve(a, b, out=out)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_solve(self, device, dtype):\n for (k, n) in zip([2, 3, 5], [3, 5, 7]):\n b, A = self.solve_test_helper((n,), (n, k), device, dtype)\n x = torch.solve(b, A)[0]\n self.assertEqual(b, np.matmul(A.cpu(), x.cpu()))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_solve_batched(self, device, dtype):\n def solve_batch_helper(A_dims, b_dims):\n b, A = self.solve_test_helper(A_dims, b_dims, device, dtype)\n x_exp_list = []\n for i in range(b_dims[0]):\n x_exp_list.append(torch.solve(b[i], A[i])[0])\n x_exp = torch.stack(x_exp_list) # Stacked output\n x_act = torch.solve(b, A)[0] # Actual output\n self.assertEqual(x_exp, x_act) # Equality check\n Ax = np.matmul(A.cpu(), x_act.cpu())\n self.assertEqual(b, Ax)\n\n for batchsize in [1, 3, 4]:\n solve_batch_helper((5, batchsize), (batchsize, 5, 10))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_solve_batched_non_contiguous(self, device, dtype):\n from numpy.linalg import solve\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n A = random_fullrank_matrix_distinct_singular_value(2, 2, dtype=dtype).to(device).permute(1, 0, 2)\n b = torch.randn(2, 2, 2, dtype=dtype, device=device).permute(2, 1, 0)\n x, _ = torch.solve(b, A)\n x_exp = solve(A.cpu().numpy(), b.cpu().numpy())\n self.assertEqual(x, x_exp)\n\n @slowTest\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_solve_batched_many_batches(self, device, dtype):\n for A_dims, b_dims in zip([(5, 256, 256), (3, )], [(5, 1), (512, 512, 3, 1)]):\n b, A = self.solve_test_helper(A_dims, b_dims, device, dtype)\n x, _ = torch.solve(b, A)\n Ax = torch.matmul(A, x)\n self.assertEqual(Ax, b.expand_as(x))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_solve_batched_broadcasting(self, device, dtype):\n from numpy.linalg import solve\n\n def run_test(A_dims, b_dims):\n A_matrix_size = A_dims[-1]\n A_batch_dims = A_dims[:-2]\n b, A = self.solve_test_helper((A_matrix_size,) + A_batch_dims, b_dims, device, dtype)\n x, _ = torch.solve(b, A)\n x_exp = solve(A.cpu().numpy(), b.cpu().numpy())\n self.assertEqual(x, x_exp)\n\n # test against numpy.linalg.solve\n run_test((2, 1, 3, 4, 4), (2, 1, 3, 4, 6)) # no broadcasting\n run_test((2, 1, 3, 4, 4), (4, 6)) # broadcasting b\n run_test((4, 4), (2, 1, 3, 4, 2)) # broadcasting A\n run_test((1, 3, 1, 4, 4), (2, 1, 3, 4, 5)) # broadcasting A & b\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_solve_errors_and_warnings(self, device, dtype):\n # dtypes should be safely castable\n a = torch.eye(2, dtype=dtype, device=device)\n b = torch.randn(2, 1, dtype=dtype, device=device)\n out = torch.empty(0, dtype=torch.int, device=device)\n lu = torch.empty(0, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got solution with dtype Int\"):\n torch.solve(b, a, out=(out, lu))\n\n out = torch.empty(0, dtype=dtype, device=device)\n lu = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got lu with dtype Int\"):\n torch.solve(b, a, out=(out, lu))\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n lu = torch.empty_like(a)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.solve(b, a, out=(out, lu))\n out = torch.empty(0, dtype=dtype, device=device)\n lu = torch.empty_like(a).to(wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.solve(b, a, out=(out, lu))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n @precisionOverride({torch.float: 1e-4, torch.cfloat: 1e-4})\n def test_tensorsolve(self, device, dtype):\n def run_test(a_shape, dims):\n a = torch.randn(a_shape, dtype=dtype, device=device)\n b = torch.randn(a_shape[:2], dtype=dtype, device=device)\n result = torch.linalg.tensorsolve(a, b, dims=dims)\n expected = np.linalg.tensorsolve(a.cpu().numpy(), b.cpu().numpy(), axes=dims)\n self.assertEqual(result, expected)\n\n # check the out= variant\n out = torch.empty_like(result)\n ans = torch.linalg.tensorsolve(a, b, dims=dims, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, result)\n\n a_shapes = [(2, 3, 6), (3, 4, 4, 3)]\n dims = [None, (0, 2)]\n for a_shape, d in itertools.product(a_shapes, dims):\n run_test(a_shape, d)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_tensorsolve_empty(self, device, dtype):\n # Check for empty inputs. NumPy does not work for these cases.\n a = torch.empty(0, 0, 1, 2, 3, 0, dtype=dtype, device=device)\n b = torch.empty(a.shape[:2], dtype=dtype, device=device)\n x = torch.linalg.tensorsolve(a, b)\n self.assertEqual(torch.tensordot(a, x, dims=len(x.shape)), b)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n @precisionOverride({torch.float: 1e-4, torch.cfloat: 1e-4})\n def test_tensorsolve_non_contiguous(self, device, dtype):\n def run_test_permuted(a_shape, dims):\n # check for permuted / transposed inputs\n a = torch.randn(a_shape, dtype=dtype, device=device)\n a = a.movedim((0, 2), (-2, -1))\n self.assertFalse(a.is_contiguous())\n b = torch.randn(a.shape[:2], dtype=dtype, device=device)\n b = b.t()\n self.assertFalse(b.is_contiguous())\n result = torch.linalg.tensorsolve(a, b, dims=dims)\n expected = np.linalg.tensorsolve(a.cpu().numpy(), b.cpu().numpy(), axes=dims)\n self.assertEqual(result, expected)\n\n def run_test_skipped_elements(a_shape, dims):\n # check for inputs with skipped elements\n a = torch.randn(a_shape, dtype=dtype, device=device)\n a = a[::2]\n self.assertFalse(a.is_contiguous())\n b = torch.randn(a_shape[:2], dtype=dtype, device=device)\n b = b[::2]\n self.assertFalse(b.is_contiguous())\n result = torch.linalg.tensorsolve(a, b, dims=dims)\n expected = np.linalg.tensorsolve(a.cpu().numpy(), b.cpu().numpy(), axes=dims)\n self.assertEqual(result, expected)\n\n # check non-contiguous out\n out = torch.empty(2 * result.shape[0], *result.shape[1:], dtype=dtype, device=device)[::2]\n self.assertFalse(out.is_contiguous())\n ans = torch.linalg.tensorsolve(a, b, dims=dims, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, result)\n\n a_shapes = [(2, 3, 6), (3, 4, 4, 3)]\n dims = [None, (0, 2)]\n for a_shape, d in itertools.product(a_shapes, dims):\n run_test_permuted(a_shape, d)\n\n a_shapes = [(4, 3, 6), (6, 4, 4, 3)]\n dims = [None, (0, 2)]\n for a_shape, d in itertools.product(a_shapes, dims):\n run_test_skipped_elements(a_shape, d)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32)\n def test_tensorsolve_errors_and_warnings(self, device, dtype):\n # tensorsolve expects the input that can be reshaped to a square matrix\n a = torch.eye(2 * 3 * 4, dtype=dtype, device=device).reshape((2 * 3, 4, 2, 3, 4))\n b = torch.randn(8, 4, dtype=dtype, device=device)\n self.assertTrue(np.prod(a.shape[2:]) != np.prod(b.shape))\n with self.assertRaisesRegex(RuntimeError, r'Expected self to satisfy the requirement'):\n torch.linalg.tensorsolve(a, b)\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n out = torch.empty_like(a)\n b = torch.randn(6, 4, dtype=dtype, device=device)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.tensorsolve(a, b, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out = torch.empty_like(a).to(torch.int)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.linalg.tensorsolve(a, b, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.tensorsolve(a, b, out=out)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float: 1e-3, torch.cfloat: 1e-3})\n def test_tensorinv(self, device, dtype):\n\n def run_test(a_shape, ind):\n a = torch.randn(a_shape, dtype=dtype, device=device)\n a_numpy = a.cpu().numpy()\n result = torch.linalg.tensorinv(a, ind=ind)\n expected = np.linalg.tensorinv(a_numpy, ind=ind)\n self.assertEqual(result, expected)\n\n # check the out= variant\n out = torch.empty_like(result)\n ans = torch.linalg.tensorinv(a, ind=ind, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, result)\n\n # compare to NumPy output\n run_test((12, 3, 4), ind=1)\n run_test((3, 8, 24), ind=2)\n run_test((18, 3, 3, 2), ind=1)\n run_test((1, 4, 2, 2), ind=2)\n run_test((2, 3, 5, 30), ind=3)\n run_test((24, 2, 2, 3, 2), ind=1)\n run_test((3, 4, 2, 3, 2), ind=2)\n run_test((1, 2, 3, 2, 3), ind=3)\n run_test((3, 2, 1, 2, 12), ind=4)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float: 1e-3, torch.cfloat: 1e-3})\n def test_tensorinv_non_contiguous(self, device, dtype):\n\n def run_test(a_shape, ind):\n # check for permuted (transposed) case\n a = torch.randn(a_shape, dtype=dtype, device=device)\n permutation = list(range(0, a.ndim))\n a = a.permute(permutation[ind:] + permutation[:ind])\n self.assertFalse(a.is_contiguous())\n a_numpy = a.cpu().numpy()\n result = torch.linalg.tensorinv(a, ind=a.ndim - ind)\n expected = np.linalg.tensorinv(a_numpy, ind=a.ndim - ind)\n self.assertEqual(result, expected)\n\n def run_test_skipped_elements(a_shape, ind):\n # check for input with skipped elements\n a = torch.randn(a_shape, dtype=dtype, device=device)\n a = a[::2]\n self.assertFalse(a.is_contiguous())\n a_numpy = a.cpu().numpy()\n result = torch.linalg.tensorinv(a, ind=ind)\n expected = np.linalg.tensorinv(a_numpy, ind=ind)\n self.assertEqual(result, expected)\n\n # check non-contiguous out\n out = torch.empty(2 * result.shape[0], *result.shape[1:], dtype=dtype, device=device)[::2]\n self.assertFalse(out.is_contiguous())\n ans = torch.linalg.tensorinv(a, ind=ind, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, result)\n\n run_test((12, 3, 4), ind=1)\n run_test((3, 8, 24), ind=2)\n run_test((18, 3, 3, 2), ind=1)\n run_test((1, 4, 2, 2), ind=2)\n run_test((2, 3, 5, 30), ind=3)\n run_test((24, 2, 2, 3, 2), ind=1)\n run_test((3, 4, 2, 3, 2), ind=2)\n run_test((1, 2, 3, 2, 3), ind=3)\n run_test((3, 2, 1, 2, 12), ind=4)\n\n run_test_skipped_elements((12, 3, 2), ind=1)\n run_test_skipped_elements((18, 3, 3, 1), ind=1)\n\n @skipMeta # See https://github.com/pytorch/pytorch/issues/53739\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_tensorinv_empty(self, device, dtype):\n for ind in range(1, 4):\n # Check for empty inputs. NumPy does not work for these cases.\n a = torch.empty(0, 0, 1, 2, 3, 0, dtype=dtype, device=device)\n a_inv = torch.linalg.tensorinv(a, ind=ind)\n self.assertEqual(a_inv.shape, a.shape[ind:] + a.shape[:ind])\n\n @skipMeta # See https://github.com/pytorch/pytorch/issues/53739\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_tensorinv_errors_and_warnings(self, device, dtype):\n\n def check_shape(a_shape, ind):\n # tensorinv requires the input to satisfy\n # prod(a.shape[ind:]) == prod(a.shape[:ind])\n a = torch.randn(a_shape, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"Expected self to satisfy the requirement\"):\n torch.linalg.tensorinv(a, ind=ind)\n\n def check_ind(a_shape, ind):\n a = torch.randn(a_shape, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"Expected a strictly positive integer\"):\n torch.linalg.tensorinv(a, ind=ind)\n\n def check_out(a_shape, ind):\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = torch.randn(a_shape, dtype=dtype, device=device)\n out = torch.empty_like(a)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.tensorinv(a, ind=ind, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.linalg.tensorinv(a, ind=ind, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.tensorinv(a, ind=ind, out=out)\n\n # test for invalid shape\n check_shape((2, 3, 4), ind=1)\n check_shape((1, 2, 3, 4), ind=3)\n\n # test for invalid ind\n check_ind((12, 3, 4), ind=-1)\n check_ind((18, 3, 3, 2), ind=0)\n\n # test for invalid out tensor\n check_out((12, 3, 4), ind=1)\n check_out((3, 8, 24), ind=2)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_tensorinv_singular_input(self, device, dtype):\n\n def check_singular_input(a_shape, ind):\n prod_ind_end = np.prod(a_shape[ind:])\n a = torch.eye(prod_ind_end, dtype=dtype, device=device)\n a[-1, -1] = 0 # Now `a` is singular\n a = a.reshape(a_shape)\n with self.assertRaisesRegex(RuntimeError, \"Failed to invert the input tensor, because it is singular\"):\n torch.linalg.tensorinv(a, ind=ind)\n\n # test for non-invertible input\n check_singular_input((12, 3, 4), ind=1)\n check_singular_input((3, 6, 18), ind=2)\n\n def _test_dot_vdot_vs_numpy(self, device, dtype, torch_fn, np_fn):\n def check(x, y):\n # Compare with numpy\n res = torch_fn(x, y)\n ref = torch.from_numpy(np.array(np_fn(x.cpu().numpy(), y.cpu().numpy())))\n self.assertEqual(res.cpu(), ref)\n\n # Test out variant\n out = torch.empty_like(res)\n torch_fn(x, y, out=out)\n self.assertEqual(out, res)\n\n # Empty\n x = torch.tensor([], dtype=dtype, device=device)\n y = torch.tensor([], dtype=dtype, device=device)\n check(x, y)\n\n # Contiguous\n x = torch.randn(10, dtype=dtype, device=device)\n y = torch.randn(10, dtype=dtype, device=device)\n check(x, y)\n\n # 0 strided\n y = torch.randn(1, dtype=dtype, device=device).expand(10)\n check(x, y)\n\n # 2 strided\n check(x[::2], y[::2])\n\n @dtypes(torch.float, torch.cfloat)\n @precisionOverride({torch.cfloat: 1e-4, torch.float32: 5e-5})\n def test_dot_vs_numpy(self, device, dtype):\n self._test_dot_vdot_vs_numpy(device, dtype, torch.dot, np.dot)\n\n @dtypes(torch.float, torch.cfloat)\n @precisionOverride({torch.cfloat: 1e-4, torch.float32: 5e-5})\n def test_vdot_vs_numpy(self, device, dtype):\n self._test_dot_vdot_vs_numpy(device, dtype, torch.vdot, np.vdot)\n\n def _test_dot_vdot_invalid_args(self, device, torch_fn, complex_dtypes=False):\n def check(x, y, regex):\n with self.assertRaisesRegex(RuntimeError, regex):\n torch_fn(x, y)\n\n if complex_dtypes:\n x = torch.randn(1, dtype=torch.cfloat, device=device)\n y = torch.randn(3, dtype=torch.cdouble, device=device)\n else:\n x = torch.randn(1, dtype=torch.float, device=device)\n y = torch.randn(3, dtype=torch.double, device=device)\n\n check(x, y, 'dot : expected both vectors to have same dtype')\n check(x.reshape(1, 1), y, '1D tensors expected')\n check(x.expand(9), y.to(x.dtype), 'inconsistent tensor size')\n\n if self.device_type != 'cpu':\n x_cpu = x.expand(3).cpu()\n check(x_cpu, y.to(x.dtype), 'Expected all tensors to be on the same device')\n\n @onlyOnCPUAndCUDA\n def test_vdot_invalid_args(self, device):\n self._test_dot_vdot_invalid_args(device, torch.vdot)\n self._test_dot_vdot_invalid_args(device, torch.vdot, complex_dtypes=True)\n\n @onlyOnCPUAndCUDA\n def test_dot_invalid_args(self, device):\n self._test_dot_vdot_invalid_args(device, torch.dot)\n self._test_dot_vdot_invalid_args(device, torch.dot, complex_dtypes=True)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_matrix_rank(self, device, dtype):\n matrix_rank = torch.linalg.matrix_rank\n\n def run_test(shape0, shape1, batch):\n a = torch.randn(*batch, shape0, shape1, dtype=dtype, device=device)\n rank_a = matrix_rank(a)\n\n self.assertEqual(rank_a, matrix_rank(a.conj().transpose(-2, -1)))\n aaH = torch.matmul(a, a.conj().transpose(-2, -1))\n rank_aaH = matrix_rank(aaH)\n rank_aaH_hermitian = matrix_rank(aaH, hermitian=True)\n self.assertEqual(rank_aaH, rank_aaH_hermitian)\n aHa = torch.matmul(a.conj().transpose(-2, -1), a)\n self.assertEqual(matrix_rank(aHa), matrix_rank(aHa, hermitian=True))\n\n # check against NumPy\n self.assertEqual(rank_a, np.linalg.matrix_rank(a.cpu().numpy()))\n self.assertEqual(matrix_rank(a, 0.01), np.linalg.matrix_rank(a.cpu().numpy(), 0.01))\n\n self.assertEqual(rank_aaH, np.linalg.matrix_rank(aaH.cpu().numpy()))\n self.assertEqual(matrix_rank(aaH, 0.01), np.linalg.matrix_rank(aaH.cpu().numpy(), 0.01))\n\n # hermitian flag for NumPy was added in 1.14.0\n if np.lib.NumpyVersion(np.__version__) >= '1.14.0':\n self.assertEqual(rank_aaH_hermitian,\n np.linalg.matrix_rank(aaH.cpu().numpy(), hermitian=True))\n self.assertEqual(matrix_rank(aaH, 0.01, True),\n np.linalg.matrix_rank(aaH.cpu().numpy(), 0.01, True))\n\n # check out= variant\n out = torch.empty(a.shape[:-2], dtype=torch.int64, device=device)\n ans = matrix_rank(a, out=out)\n self.assertEqual(ans, out)\n self.assertEqual(ans, rank_a)\n\n shapes = (3, 13)\n batches = ((), (0, ), (4, ), (3, 5, ))\n for (shape0, shape1), batch in zip(itertools.product(shapes, reversed(shapes)), batches):\n run_test(shape0, shape1, batch)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_matrix_rank_tol(self, device, dtype):\n\n def run_test_tol(shape0, shape1, batch):\n a = make_tensor((*batch, shape0, shape1), dtype=dtype, device=device)\n # Check against NumPy output\n # Test float tol, and specific value for each matrix\n tolerances = [float(torch.rand(1)), ]\n # Test different types of tol tensor\n for tol_type in all_types():\n tolerances.append(make_tensor(a.shape[:-2], dtype=tol_type, device=device, low=0))\n # Test broadcasting of tol\n if a.ndim > 2:\n tolerances.append(make_tensor(a.shape[-3], dtype=torch.float32, device=device, low=0))\n for tol in tolerances:\n actual = torch.linalg.matrix_rank(a, tol=tol)\n numpy_tol = tol if isinstance(tol, float) else tol.cpu().numpy()\n expected = np.linalg.matrix_rank(a.cpu().numpy(), tol=numpy_tol)\n self.assertEqual(actual, expected)\n\n shapes = (3, 13)\n batches = ((), (0, ), (4, ), (3, 5, ))\n for (shape0, shape1), batch in zip(itertools.product(shapes, reversed(shapes)), batches):\n run_test_tol(shape0, shape1, batch)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_matrix_rank_empty(self, device, dtype):\n matrix_rank = torch.linalg.matrix_rank\n\n # NumPy doesn't work for input with no elements\n def run_test(shape0, shape1, batch):\n a = torch.randn(*batch, shape0, shape1, dtype=dtype, device=device)\n rank_a = matrix_rank(a)\n expected = torch.zeros(batch, dtype=torch.int64, device=device)\n\n self.assertEqual(rank_a, matrix_rank(a.conj().transpose(-2, -1)))\n\n aaH = torch.matmul(a, a.conj().transpose(-2, -1))\n rank_aaH = matrix_rank(aaH)\n rank_aaH_hermitian = matrix_rank(aaH, hermitian=True)\n self.assertEqual(rank_aaH, rank_aaH_hermitian)\n\n aHa = torch.matmul(a.conj().transpose(-2, -1), a)\n self.assertEqual(matrix_rank(aHa), matrix_rank(aHa, hermitian=True))\n\n self.assertEqual(rank_a, expected)\n self.assertEqual(matrix_rank(a, 0.01), expected)\n\n self.assertEqual(rank_aaH, expected)\n self.assertEqual(matrix_rank(aaH, 0.01), expected)\n\n self.assertEqual(rank_aaH_hermitian, expected)\n self.assertEqual(matrix_rank(aaH, 0.01, True), expected)\n\n batches = ((), (4, ), (3, 5, ))\n for batch in batches:\n run_test(0, 0, batch)\n run_test(0, 3, batch)\n run_test(3, 0, batch)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_matrix_rank_out_errors_and_warnings(self, device, dtype):\n # dtypes should be safely castable\n a = torch.eye(2, dtype=dtype, device=device)\n out = torch.empty(0, dtype=torch.bool, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Bool\"):\n torch.linalg.matrix_rank(a, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.matrix_rank(a, out=out)\n\n # if out tensor with wrong shape is passed a warning is given\n with warnings.catch_warnings(record=True) as w:\n out = torch.empty(3, dtype=dtype, device=device)\n # Trigger warning\n torch.linalg.matrix_rank(a, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_matrix_rank_basic(self, device, dtype):\n matrix_rank = torch.linalg.matrix_rank\n\n a = torch.eye(10, dtype=dtype, device=device)\n self.assertEqual(matrix_rank(a).item(), 10)\n self.assertEqual(matrix_rank(a, hermitian=True).item(), 10)\n\n a[5, 5] = 0\n self.assertEqual(matrix_rank(a).item(), 9)\n self.assertEqual(matrix_rank(a, hermitian=True).item(), 9)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_old_matrix_rank(self, device, dtype):\n a = torch.eye(10, dtype=dtype, device=device)\n self.assertEqual(torch.matrix_rank(a).item(), 10)\n self.assertEqual(torch.matrix_rank(a, True).item(), 10)\n\n a[5, 5] = 0\n self.assertEqual(torch.matrix_rank(a).item(), 9)\n self.assertEqual(torch.matrix_rank(a, True).item(), 9)\n\n a = torch.randn(24, 42, dtype=dtype, device=device)\n self.assertEqual(torch.matrix_rank(a), torch.matrix_rank(a.t()))\n aaT = torch.mm(a, a.conj().t())\n self.assertEqual(torch.matrix_rank(aaT), torch.matrix_rank(aaT, True))\n aTa = torch.mm(a.conj().t(), a)\n self.assertEqual(torch.matrix_rank(aTa), torch.matrix_rank(aTa, True))\n\n a = torch.randn(35, 75, dtype=dtype, device=device)\n self.assertEqual(torch.matrix_rank(a), np.linalg.matrix_rank(a.cpu().numpy()))\n self.assertEqual(torch.matrix_rank(a, 0.01), np.linalg.matrix_rank(a.cpu().numpy(), 0.01))\n\n aaT = torch.mm(a, a.conj().t())\n self.assertEqual(torch.matrix_rank(aaT), np.linalg.matrix_rank(aaT.cpu().numpy()))\n self.assertEqual(torch.matrix_rank(aaT, 0.01), np.linalg.matrix_rank(aaT.cpu().numpy(), 0.01))\n\n if np.lib.NumpyVersion(np.__version__) >= '1.14.0':\n self.assertEqual(torch.matrix_rank(aaT, True), np.linalg.matrix_rank(aaT.cpu().numpy(), True))\n self.assertEqual(torch.matrix_rank(aaT, 0.01, True), np.linalg.matrix_rank(aaT.cpu().numpy(), 0.01, True))\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.double)\n # This tests only the cases where torch.chain_matmul differs from torch.linalg.multi_dot which this is an \"alias\" for.\n def test_chain_matmul(self, device, dtype):\n # chain_matmul accepts a single input tensor while multi_dot does not\n t = make_tensor((2, 2), device, dtype)\n self.assertEqual(t, torch.chain_matmul(t))\n with self.assertRaisesRegex(RuntimeError, r\"chain_matmul\\(\\): Expected one or more matrices\"):\n torch.chain_matmul()\n\n # chain_matmul expects all tensors to be 2D whereas multi_dot allows the first and last tensors to\n # be either 1D or 2D\n with self.assertRaisesRegex(RuntimeError, r\"Tensor dimension is 1, expected 2 instead\"):\n torch.chain_matmul(make_tensor(1, device, dtype), make_tensor(1, device, dtype))\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.double, torch.cdouble)\n def test_multi_dot(self, device, dtype):\n def check(*shapes, noncontiguous=False):\n tensors = [make_tensor(shape, device, dtype, noncontiguous=noncontiguous) for shape in shapes]\n np_arrays = [tensor.cpu().numpy() for tensor in tensors]\n res = torch.linalg.multi_dot(tensors).cpu()\n ref = torch.from_numpy(np.array(np.linalg.multi_dot(np_arrays)))\n self.assertEqual(res, ref)\n\n # test for inputs with empty dimensions\n check([0], [0])\n check([2], [2, 0])\n check([1, 0], [0])\n check([0, 2], [2, 1])\n check([2, 2], [2, 0])\n check([2, 0], [0, 3])\n check([0, 0], [0, 1])\n check([4, 2], [2, 0], [0, 3], [3, 2])\n\n # test variable output shapes\n check([2], [2])\n check([1, 2], [2])\n check([2], [2, 1])\n check([1, 2], [2, 1])\n check([3, 2], [2, 4])\n\n # test multiple input tensors\n check([3], [3, 4], [4, 2], [2, 5], [5])\n check([1, 2], [2, 2], [2, 3], [3, 1])\n\n # test large tensors\n check([10, 100], [100, 5], [5, 50])\n check([10, 20], [20, 30], [30, 5])\n\n # test noncontiguous input\n check([3, 2], [2, 2], [2, 3], [3, 4], noncontiguous=True)\n check([15, 5], [5, 10], [10, 20], [20, 25], noncontiguous=True)\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.float)\n def test_multi_dot_errors(self, device, dtype):\n def check(tensors, out, msg):\n with self.assertRaisesRegex(RuntimeError, msg):\n torch.linalg.multi_dot(tensors, out=out)\n\n a = make_tensor(2, device, dtype)\n\n check([], None, \"expected at least 2 tensors\")\n check([a], None, \"expected at least 2 tensors\")\n\n check([torch.tensor(1, device=device, dtype=dtype), a], None, \"the first tensor must be 1D or 2D\")\n check([a, torch.tensor(1, device=device, dtype=dtype)], None, \"the last tensor must be 1D or 2D\")\n\n check([a, a, a], None, \"tensor 1 must be 2D\")\n check([a, make_tensor((2, 2, 2), device, dtype), a], None, \"tensor 1 must be 2D\")\n\n check([a, make_tensor(2, device, torch.double)], None, \"all tensors must have be the same dtype\")\n check([a, a], torch.empty(0, device=device, dtype=torch.double), \"expected out tensor to have dtype\")\n\n if self.device_type == 'cuda':\n check([a, make_tensor(2, 'cpu', dtype)], None, \"all tensors must be on the same device\")\n check([a, a], torch.empty(0, dtype=dtype), \"expected out tensor to be on device\")\n\n check([a, make_tensor(3, device, dtype)], None, \"cannot be multiplied\")\n check([a, make_tensor((3, 2), device, dtype), a], None, \"cannot be multiplied\")\n\n @precisionOverride({torch.float32: 5e-6, torch.complex64: 5e-6})\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_qr(self, device, dtype):\n def run_test(tensor_dims, some):\n A = torch.randn(*tensor_dims, dtype=dtype, device=device)\n Q, R = torch.qr(A, some=some)\n\n # Check0: Q[-2:] = (m, n_columns), R[-2:] = (n_columns, n)\n m, n = tensor_dims[-2:]\n n_columns = m if (not some) and m > n else min(m, n)\n self.assertEqual(Q.size(-2), m)\n self.assertEqual(R.size(-1), n)\n self.assertEqual(Q.size(-1), n_columns)\n\n A_ = A.cpu().numpy()\n Q_ = Q.cpu().numpy()\n R_ = R.cpu().numpy()\n\n # Check1: A = QR\n self.assertEqual(A_, np.matmul(Q_, R_))\n\n # Check2: A = QR (with out)\n Q_out, R_out = torch.full_like(Q, math.nan), torch.full_like(R, math.nan)\n torch.qr(A, some=some, out=(Q_out, R_out))\n Q_out_ = Q_out.cpu().numpy()\n R_out_ = R_out.cpu().numpy()\n self.assertEqual(A_, np.matmul(Q_out_, R_out_))\n\n # Check3: Q == Q_out, R == R_out\n self.assertEqual(Q_, Q_out_)\n self.assertEqual(R_, R_out_)\n\n # Check4: Q^{T}Q = I, triu(R) = R\n eye = torch.eye(n_columns, device=device, dtype=dtype).expand(Q.shape[:-2] + (n_columns, n_columns)).cpu().numpy()\n self.assertEqual(np.matmul(Q_.swapaxes(-1, -2).conj(), Q_), eye)\n self.assertEqual(R.triu(), R)\n\n tensor_dims_list = [(0, 5), (0, 0), (5, 0), # Empty Tensors\n (2, 1, 0, 5), (2, 1, 0, 0), (2, 1, 5, 0), (2, 0, 5, 5), # Batched empty Tensors\n (3, 5), (5, 5), (5, 3), # Single matrix\n (7, 3, 5), (7, 5, 5), (7, 5, 3), # 3-dim Tensors\n (7, 5, 3, 5), (7, 5, 5, 5), (7, 5, 5, 3)] # 4-dim Tensors\n for tensor_dims, some in itertools.product(tensor_dims_list, [True, False]):\n run_test(tensor_dims, some)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_qr_vs_numpy(self, device, dtype):\n \"\"\"\n test torch.linalg.qr vs numpy.linalg.qr\n \"\"\"\n sizes_to_test = [\n (7, 5),\n (5, 7),\n (5, 0), # empty\n (0, 5), # empty\n ]\n for size in sizes_to_test:\n t = torch.randn(size, device=device, dtype=dtype)\n np_t = t.cpu().numpy()\n for mode in ['reduced', 'complete']:\n exp_q, exp_r = np.linalg.qr(np_t, mode=mode)\n q, r = torch.linalg.qr(t, mode=mode)\n self.assertEqual(q, exp_q)\n self.assertEqual(r, exp_r)\n #\n # for mode='r' we need a special logic because numpy returns only r\n exp_r = np.linalg.qr(np_t, mode='r')\n q, r = torch.linalg.qr(t, mode='r')\n # check that q is empty\n self.assertEqual(q.shape, (0,))\n self.assertEqual(q.dtype, t.dtype)\n self.assertEqual(q.device, t.device)\n # check r\n self.assertEqual(r, exp_r)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float)\n def test_linalg_qr_autograd_errors(self, device, dtype):\n # torch.linalg.qr(mode='r') returns only 'r' and discards 'q', but\n # without 'q' you cannot compute the backward pass. Check that\n # linalg_qr_backward complains cleanly in that case.\n inp = torch.randn((5, 7), device=device, dtype=dtype, requires_grad=True)\n q, r = torch.linalg.qr(inp, mode='r')\n self.assertEqual(q.shape, (0,)) # empty tensor\n b = torch.sum(r)\n with self.assertRaisesRegex(RuntimeError,\n \"The derivative of qr is not implemented when mode='r'\"):\n b.backward()\n #\n inp = torch.randn((7, 5), device=device, dtype=dtype, requires_grad=True)\n q, r = torch.linalg.qr(inp, mode='complete')\n b = torch.sum(r)\n with self.assertRaisesRegex(RuntimeError,\n \"The derivative of qr is not implemented when mode='complete' and nrows > ncols\"):\n b.backward()\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_qr_batched(self, device, dtype):\n \"\"\"\n test torch.linalg.qr vs numpy.linalg.qr. We need some special logic\n because numpy does not support batched qr\n \"\"\"\n def np_qr_batched(a, mode):\n \"\"\"poor's man batched version of np.linalg.qr\"\"\"\n all_q = []\n all_r = []\n for matrix in a:\n result = np.linalg.qr(matrix, mode=mode)\n if mode == 'r':\n all_r.append(result)\n else:\n q, r = result\n all_q.append(q)\n all_r.append(r)\n if mode == 'r':\n return np.array(all_r)\n else:\n return np.array(all_q), np.array(all_r)\n\n t = torch.randn((3, 7, 5), device=device, dtype=dtype)\n np_t = t.cpu().numpy()\n for mode in ['reduced', 'complete']:\n exp_q, exp_r = np_qr_batched(np_t, mode=mode)\n q, r = torch.linalg.qr(t, mode=mode)\n self.assertEqual(q, exp_q)\n self.assertEqual(r, exp_r)\n # for mode='r' we need a special logic because numpy returns only r\n exp_r = np_qr_batched(np_t, mode='r')\n q, r = torch.linalg.qr(t, mode='r')\n # check that q is empty\n self.assertEqual(q.shape, (0,))\n self.assertEqual(q.dtype, t.dtype)\n self.assertEqual(q.device, t.device)\n # check r\n self.assertEqual(r, exp_r)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_qr_out(self, device, dtype):\n \"\"\"\n test torch.linalg.qr(out=...) vs torch.lingalg.qr\n \"\"\"\n sizes_to_test = [\n (7, 5),\n (5, 7),\n (5, 0), # empty\n (0, 5), # empty\n ]\n for size in sizes_to_test:\n t = torch.randn(size, device=device, dtype=dtype)\n np_t = t.cpu().numpy()\n for mode in ['reduced', 'complete', 'r']:\n q, r = torch.linalg.qr(t, mode=mode)\n out = (torch.empty((0), dtype=dtype, device=device),\n torch.empty((0), dtype=dtype, device=device))\n q2, r2 = torch.linalg.qr(t, mode=mode, out=out)\n self.assertIs(q2, out[0])\n self.assertIs(r2, out[1])\n self.assertEqual(q2, q)\n self.assertEqual(r2, r)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float)\n def test_qr_error_cases(self, device, dtype):\n t1 = torch.randn(5, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, 'qr input should have at least 2 dimensions, but has 1 dimensions instead'):\n torch.linalg.qr(t1)\n t2 = torch.randn((5, 7), device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"qr received unrecognized mode 'hello'\"):\n torch.linalg.qr(t2, mode='hello')\n\n def _check_einsum(self, *args, np_args=None):\n if np_args is None:\n np_args = [arg.cpu().numpy() if isinstance(arg, torch.Tensor) else arg for arg in args]\n res = torch.einsum(*args)\n ref = np.einsum(*np_args)\n self.assertEqual(torch.from_numpy(np.array(ref)), res)\n\n @dtypes(torch.double, torch.cdouble)\n def test_einsum(self, device, dtype):\n # Test cases from https://gist.github.com/rockt/15ee013889d65342088e9260a377dc8f\n x = make_tensor((5,), device, dtype)\n y = make_tensor((7,), device, dtype)\n A = make_tensor((3, 5), device, dtype)\n B = make_tensor((2, 5), device, dtype)\n C = make_tensor((2, 3, 5), device, dtype)\n D = make_tensor((2, 5, 7), device, dtype)\n E = make_tensor((7, 9), device, dtype)\n F = make_tensor((2, 3, 3, 5), device, dtype)\n G = make_tensor((5, 4, 6), device, dtype)\n H = make_tensor((4, 4), device, dtype)\n I = make_tensor((2, 3, 2), device, dtype)\n\n # Vector operations\n self._check_einsum('i->', x) # sum\n self._check_einsum('i,i->', x, x) # dot\n self._check_einsum('i,i->i', x, x) # vector element-wisem mul\n self._check_einsum('i,j->ij', x, y) # outer\n\n # Matrix operations\n self._check_einsum(\"ij->ji\", A) # transpose\n self._check_einsum(\"ij->j\", A) # row sum\n self._check_einsum(\"ij->i\", A) # col sum\n self._check_einsum(\"ij,ij->ij\", A, A) # matrix element-wise mul\n self._check_einsum(\"ij,j->i\", A, x) # matrix vector multiplication\n self._check_einsum(\"ij,kj->ik\", A, B) # matmul\n self._check_einsum(\"ij,ab->ijab\", A, E) # matrix outer product\n\n # Tensor operations\n self._check_einsum(\"Aij,Ajk->Aik\", C, D) # batch matmul\n self._check_einsum(\"ijk,jk->i\", C, A) # tensor matrix contraction\n self._check_einsum(\"aij,jk->aik\", D, E) # tensor matrix contraction\n self._check_einsum(\"abCd,dFg->abCFg\", F, G) # tensor tensor contraction\n self._check_einsum(\"ijk,jk->ik\", C, A) # tensor matrix contraction with double indices\n self._check_einsum(\"ijk,jk->ij\", C, A) # tensor matrix contraction with double indices\n self._check_einsum(\"ijk,ik->j\", C, B) # non contiguous\n self._check_einsum(\"ijk,ik->jk\", C, B) # non contiguous with double indices\n\n # Test diagonals\n self._check_einsum(\"ii\", H) # trace\n self._check_einsum(\"ii->i\", H) # diagonal\n self._check_einsum('iji->j', I) # non-contiguous trace\n self._check_einsum('ngrg...->nrg...', make_tensor((2, 1, 3, 1, 4), device, dtype))\n\n # Test ellipsis\n self._check_einsum(\"i...->...\", H)\n self._check_einsum(\"ki,...k->i...\", A.t(), B)\n self._check_einsum(\"k...,jk->...\", A.t(), B)\n self._check_einsum('...ik, ...j -> ...ij', C, x)\n self._check_einsum('Bik,k...j->i...j', C, make_tensor((5, 3), device, dtype))\n self._check_einsum('i...j, ij... -> ...ij', C, make_tensor((2, 5, 2, 3), device, dtype))\n\n # torch.bilinear with noncontiguous tensors\n l = make_tensor((5, 10), device, dtype, noncontiguous=True)\n r = make_tensor((5, 20), device, dtype, noncontiguous=True)\n w = make_tensor((15, 10, 20), device, dtype)\n self._check_einsum(\"bn,anm,bm->ba\", l, w, r)\n\n # with strided tensors\n self._check_einsum(\"bn,Anm,bm->bA\", l[:, ::2], w[:, ::2, ::2], r[:, ::2])\n\n @dtypes(torch.double, torch.cdouble)\n def test_einsum_sublist_format(self, device, dtype):\n x = make_tensor((5,), device, dtype)\n y = make_tensor((7,), device, dtype)\n A = make_tensor((3, 5), device, dtype)\n B = make_tensor((2, 5), device, dtype)\n C = make_tensor((2, 1, 3, 1, 4), device, dtype)\n\n self._check_einsum(x, [0])\n self._check_einsum(x, [0], [])\n self._check_einsum(x, [0], y, [1], [0, 1])\n self._check_einsum(A, [0, 1], [1, 0])\n self._check_einsum(A, [0, 1], x, [1], [0])\n self._check_einsum(A, [0, 1], B, [2, 1])\n self._check_einsum(A, [0, 1], B, [2, 1], [0, 2])\n self._check_einsum(C, [0, 1, 2, 1, Ellipsis], [0, 2, 1, Ellipsis])\n self._check_einsum(A.t(), [0, 1], B, [Ellipsis, 0])\n self._check_einsum(A.t(), [0, 1], B, [Ellipsis, 0], [1, Ellipsis])\n self._check_einsum(A.t(), [0, Ellipsis], B, [1, 0], [Ellipsis])\n\n # torch.bilinear with noncontiguous tensors\n l = make_tensor((5, 10), device, dtype, noncontiguous=True)\n r = make_tensor((5, 20), device, dtype, noncontiguous=True)\n w = make_tensor((15, 10, 20), device, dtype)\n self._check_einsum(l, [40, 41], w, [2, 41, 50], r, [40, 50], [40, 2])\n\n @dtypes(torch.double, torch.cdouble)\n def test_einsum_random(self, device, dtype):\n def convert_label(label):\n if label == ...:\n return '...'\n elif label < 26:\n return chr(ord('A') + label)\n else:\n return chr(ord('a') + label - 26)\n\n def convert_sublist(sublist):\n return ''.join(convert_label(label) for label in sublist)\n\n def test(n=10, # how many tests to generate\n n_labels=5, # how many labels available\n min_ops=1, max_ops=3, # min and max number of operands per test\n min_dims=1, max_dims=3, # min and max number of dimensions per operand\n min_size=1, max_size=8, # min and max size of each dimension\n max_out_dim=3, # max number of dimensions for the output\n enable_diagonals=True, # controls if labels can be repeated for diagonals\n ellipsis_prob=0.5, # probability of including ellipsis in operand\n broadcasting_prob=0.1): # probability of turning some dim sizes 1 for broadcasting\n\n all_labels = torch.arange(52)\n\n assert 0 <= n\n assert 0 <= n_labels < len(all_labels)\n assert 0 < min_ops <= max_ops\n assert 0 <= min_dims <= max_dims\n assert 0 <= min_size <= max_size\n assert 0 <= max_out_dim\n assert enable_diagonals or max_dims <= n_labels\n\n for _ in range(n):\n\n # Select a subset of labels for this test and give them random sizes\n possible_labels = all_labels[torch.randperm(len(all_labels))[:n_labels]]\n labels_size = torch.randint_like(all_labels, min_size, max_size + 1)\n ellipsis_shape = torch.randint(min_size, max_size + 1, (max_dims - min_dims,))\n\n operands = []\n sublists = []\n\n ell_size = 0\n valid_labels = set()\n\n # create random input operands\n for _ in range(random.randint(min_ops, max_ops)):\n n_dim = random.randint(min_dims, max_dims)\n labels_idx = torch.ones(len(possible_labels)).multinomial(n_dim, enable_diagonals)\n labels = possible_labels[labels_idx]\n valid_labels.update(labels.tolist())\n shape = labels_size[labels]\n\n # turn some dimensions to size 1 for testing broadcasting\n mask = Binomial(probs=broadcasting_prob).sample((n_dim,))\n broadcast_labels = torch.unique(labels[mask == 1])\n shape[(labels[..., None] == broadcast_labels).any(-1)] = 1\n\n labels = labels.tolist()\n shape = shape.tolist()\n\n # include ellipsis if not all dimensions were assigned a label already\n if n_dim < max_dims and torch.rand(1) < ellipsis_prob:\n ell_num_dim = random.randint(1, max_dims - n_dim)\n ell_size = max(ell_size, ell_num_dim)\n ell_shape = ellipsis_shape[-ell_num_dim:]\n # again, turn some dimensions to size 1 for broadcasting\n mask = Binomial(probs=broadcasting_prob).sample((ell_num_dim,))\n ell_shape[mask == 1] = 1\n ell_index = random.randint(0, n_dim)\n shape[ell_index:ell_index] = ell_shape\n labels.insert(ell_index, ...)\n\n operands.append(make_tensor(shape, device, dtype))\n sublists.append(labels)\n\n # NumPy has a bug with the sublist format so for now we compare PyTorch sublist\n # implementation against the equation format implementation of NumPy\n # see https://github.com/numpy/numpy/issues/10926\n np_operands = [op.cpu().numpy() for op in operands]\n\n # test equation format\n equation = ','.join(convert_sublist(l) for l in sublists)\n self._check_einsum(equation, *operands, np_args=(equation, *np_operands))\n\n # test sublist format\n args = [*itertools.chain(*zip(operands, sublists))]\n self._check_einsum(*args, np_args=(equation, *np_operands))\n\n # generate an explicit output\n out_sublist = []\n num_out_labels = max(0, random.randint(0, min(max_out_dim, len(valid_labels))) - ell_size)\n if num_out_labels > 0:\n out_labels_idx = torch.ones(len(valid_labels)).multinomial(num_out_labels)\n out_sublist = torch.tensor(list(valid_labels))[out_labels_idx].tolist()\n out_sublist.insert(random.randint(0, num_out_labels), ...)\n\n # test equation format with explicit output\n equation += '->' + convert_sublist(out_sublist)\n self._check_einsum(equation, *operands, np_args=(equation, *np_operands))\n\n # test sublist format with explicit output\n args.append(out_sublist)\n self._check_einsum(*args, np_args=(equation, *np_operands))\n\n test(100)\n\n def test_einsum_corner_cases(self, device):\n def check(equation, *operands, expected_output):\n tensors = [torch.tensor(operand, device=device, dtype=torch.float32) if not isinstance(operand, tuple)\n else make_tensor(operand, device, torch.float32) for operand in operands]\n output = torch.einsum(equation, tensors)\n self.assertEqual(output, torch.tensor(expected_output, dtype=torch.float32, device=device))\n\n # Test equation variantions\n check(' ', 1, expected_output=1)\n check(' -> ', 1, expected_output=1)\n check(' , ', 2, 2, expected_output=4)\n check(' , , ', 2, 2, 2, expected_output=8)\n check(' , -> ', 2, 2, expected_output=4)\n check(' i ', [1], expected_output=[1])\n check(' i -> ', [1], expected_output=1)\n check(' i -> i ', [1], expected_output=[1])\n check(' i , i ', [2], [2], expected_output=4)\n check(' i , i -> i ', [2], [2], expected_output=[4])\n\n # Test tensors with 0 size dimensions\n check('i', [], expected_output=[])\n check(' i j -> j', [[], []], expected_output=[])\n check('ij->i', [[], []], expected_output=[0., 0.])\n check(' i j k , k -> i j ', (3, 0, 6), (6,), expected_output=[[], [], []])\n\n # Test broadcasting\n check('i,j', [2], [1, 2], expected_output=[[2, 4]])\n check('i,ij->ij', [1, 2], [[1, 2, 3], [2, 3, 4]], expected_output=[[1, 2, 3], [4, 6, 8]])\n\n # Test ellipsis broadcasting\n check('...', 1, expected_output=1)\n check('...->', 1, expected_output=1)\n check('...->...', 1, expected_output=1)\n check('...', [1], expected_output=[1])\n check('...->', [1], expected_output=1)\n check('z...->z', [1], expected_output=[1])\n check('Z...->...Z', [1], expected_output=[1])\n check('...a->', [[2], [4]], expected_output=6)\n check('a...b->ab', [[[1], [2]], [[3], [4]]], expected_output=[[3], [7]])\n\n def test_einsum_error_cases(self, device):\n def check(*args, regex, exception=RuntimeError):\n with self.assertRaisesRegex(exception, r'einsum\\(\\):.*' + regex):\n torch.einsum(*args)\n\n x = make_tensor((2,), device, torch.float32)\n y = make_tensor((2, 3), device, torch.float32)\n\n check('', [], regex=r'at least one operand', exception=ValueError)\n check('. ..', [x], regex=r'found \\'.\\' for operand 0 that is not part of any ellipsis')\n check('... ...', [x], regex=r'found \\'.\\' for operand 0 for which an ellipsis was already found')\n check('1', [x], regex=r'invalid subscript given at index 0')\n check(',', [x], regex=r'fewer operands were provided than specified in the equation')\n check('', [x, x], regex=r'more operands were provided than specified in the equation')\n check('', [x], regex=r'the number of subscripts in the equation \\(0\\) does not match the number '\n r'of dimensions \\(1\\) for operand 0 and no ellipsis was given')\n check('ai', [x], regex=r'the number of subscripts in the equation \\(2\\) does not match the number '\n r'of dimensions \\(1\\) for operand 0 and no ellipsis was given')\n check('ai...', [x], regex=r'the number of subscripts in the equation \\(2\\) is more than the number '\n r'of dimensions \\(1\\) for operand 0')\n check('a->... .', [x], regex=r'found \\'.\\' for output but an ellipsis \\(...\\) was already found')\n check('a->..', [x], regex=r'found \\'.\\' for output that is not part of any ellipsis \\(...\\)')\n check('a->1', [x], regex=r'invalid subscript given at index 3')\n check('a->aa', [x], regex=r'output subscript a appears more than once in the output')\n check('a->i', [x], regex=r'output subscript i does not appear in the equation for any input operand')\n check('aa', [y], regex=r'subscript a is repeated for operand 0 but the sizes don\\'t match, 3 != 2')\n check('a, ba', [x, y], regex=r'operands do not broadcast with remapped shapes \\[original->remapped\\]: '\n r'\\[2\\]->\\[1, 2\\] \\[2, 3\\]->\\[2, 3\\]')\n\n check(x, [-1], regex=r'not within the valid range \\[0, 52\\)', exception=ValueError)\n check(x, [52], regex=r'not within the valid range \\[0, 52\\)', exception=ValueError)\n\n def triangular_solve_test_helper(self, A_dims, b_dims, upper, unitriangular,\n device, dtype):\n triangle_function = torch.triu if upper else torch.tril\n b = torch.randn(*b_dims, dtype=dtype, device=device)\n A = torch.randn(*A_dims, dtype=dtype, device=device)\n # create positive definite matrix\n A = torch.matmul(A, A.transpose(-2, -1))\n A_triangular = triangle_function(A)\n if unitriangular:\n A_triangular.diagonal(dim1=-2, dim2=-1).fill_(1.)\n return b, A_triangular\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_triangular_solve(self, device, dtype):\n ks = [0, 1, 3]\n ns = [0, 5]\n for (k, n), (upper, unitriangular, transpose) in itertools.product(zip(ks, ns),\n itertools.product([True, False], repeat=3)):\n b, A = self.triangular_solve_test_helper((n, n), (n, k), upper,\n unitriangular, device, dtype)\n x = torch.triangular_solve(b, A, upper=upper, unitriangular=unitriangular, transpose=transpose)[0]\n if transpose:\n self.assertEqual(b, np.matmul(A.t().cpu(), x.cpu()))\n else:\n self.assertEqual(b, np.matmul(A.cpu(), x.cpu()))\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_triangular_solve_batched(self, device, dtype):\n def triangular_solve_batch_helper(A_dims, b_dims, upper, unitriangular, transpose):\n b, A = self.triangular_solve_test_helper(A_dims, b_dims, upper,\n unitriangular, device, dtype)\n x_exp_list = []\n for i in range(b_dims[0]):\n x_exp_list.append(torch.triangular_solve(b[i], A[i], upper=upper,\n unitriangular=unitriangular,\n transpose=transpose)[0])\n x_exp = torch.stack(x_exp_list) # Stacked output\n x_act = torch.triangular_solve(b, A, upper=upper,\n unitriangular=unitriangular,\n transpose=transpose)[0] # Actual output\n self.assertEqual(x_act, x_exp) # Equality check\n if transpose:\n A = A.transpose(-2, -1)\n\n Ax = np.matmul(A.cpu(), x_act.cpu())\n self.assertEqual(b, Ax)\n\n def triangular_solve_zero_batch_helper(A_dims, b_dims, upper, unitriangular, transpose):\n b, A = self.triangular_solve_test_helper(A_dims, b_dims, upper,\n unitriangular, device, dtype)\n x = torch.triangular_solve(b, A, upper=upper,\n unitriangular=unitriangular,\n transpose=transpose)[0]\n self.assertTrue(x.shape == b.shape)\n\n for upper, unitriangular, transpose in itertools.product([True, False], repeat=3):\n batchsize = 3\n triangular_solve_batch_helper((batchsize, 5, 5), (batchsize, 5, 10),\n upper, unitriangular, transpose)\n\n # test empty input\n triangular_solve_batch_helper((batchsize, 0, 0), (batchsize, 0, 10),\n upper, unitriangular, transpose)\n triangular_solve_batch_helper((batchsize, 0, 0), (batchsize, 0, 0),\n upper, unitriangular, transpose)\n\n # test zero batch case\n batchsize = 0\n triangular_solve_zero_batch_helper((batchsize, 5, 5), (batchsize, 5, 10),\n upper, unitriangular, transpose)\n\n\n @slowTest\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_triangular_solve_batched_many_batches(self, device, dtype):\n for upper, transpose, unitriangular in itertools.product([True, False], repeat=3):\n # test batched A case\n b, A = self.triangular_solve_test_helper((256, 256, 5, 5), (5, 1),\n upper, unitriangular, device, dtype)\n x, _ = torch.triangular_solve(b, A,\n upper=upper, transpose=transpose, unitriangular=unitriangular)\n if transpose:\n A = A.transpose(-2, -1)\n\n Ax = torch.matmul(A, x)\n\n rtol = 1e-2 if dtype in [torch.float32, torch.complex64] else self.precision\n self.assertEqual(Ax, b.expand_as(Ax), atol=self.precision, rtol=rtol)\n\n # test batched b case\n b, A = self.triangular_solve_test_helper((3, 3), (512, 512, 3, 1),\n upper, unitriangular, device, dtype)\n x, _ = torch.triangular_solve(b, A, upper=upper, transpose=transpose,\n unitriangular=unitriangular)\n if transpose:\n A = A.transpose(-2, -1)\n\n self.assertEqual(torch.matmul(A, x), b)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @unittest.skipIf(not TEST_SCIPY, \"SciPy not found\")\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_triangular_solve_batched_broadcasting(self, device, dtype):\n from scipy.linalg import solve_triangular as tri_solve\n\n def scipy_tri_solve_batched(A, B, upper, trans, diag):\n batch_dims_A, batch_dims_B = A.shape[:-2], B.shape[:-2]\n single_dim_A, single_dim_B = A.shape[-2:], B.shape[-2:]\n expand_dims = tuple(torch._C._infer_size(torch.Size(batch_dims_A),\n torch.Size(batch_dims_B)))\n expand_A = np.broadcast_to(A, expand_dims + single_dim_A)\n expand_B = np.broadcast_to(B, expand_dims + single_dim_B)\n flat_A = expand_A.reshape((-1,) + single_dim_A)\n flat_B = expand_B.reshape((-1,) + single_dim_B)\n flat_X = np.vstack([tri_solve(a, b, lower=(not upper), trans=int(trans), unit_diagonal=diag)\n for a, b in zip(flat_A, flat_B)])\n return flat_X.reshape(expand_B.shape)\n\n def run_test(A_dims, b_dims, device, upper, transpose, unitriangular):\n b, A = self.triangular_solve_test_helper(A_dims, b_dims, upper,\n unitriangular, device, dtype)\n x_exp = torch.as_tensor(scipy_tri_solve_batched(A.cpu().numpy(), b.cpu().numpy(),\n upper, transpose, unitriangular))\n x = torch.triangular_solve(b, A, upper=upper, transpose=transpose, unitriangular=unitriangular)[0]\n\n self.assertEqual(x, x_exp.to(device))\n\n for upper, transpose, unitriangular in itertools.product([True, False], repeat=3):\n # test against scipy.linalg.solve_triangular\n run_test((2, 1, 3, 4, 4), (2, 1, 3, 4, 6), device, upper, transpose, unitriangular) # no broadcasting\n run_test((2, 1, 3, 4, 4), (4, 6), device, upper, transpose, unitriangular) # broadcasting b\n run_test((4, 4), (2, 1, 3, 4, 2), device, upper, transpose, unitriangular) # broadcasting A\n run_test((1, 3, 1, 4, 4), (2, 1, 3, 4, 5), device, upper, transpose, unitriangular) # broadcasting A & b\n\n @onlyCPU\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_triangular_solve_singular(self, device, dtype):\n b = torch.rand(3, 1, dtype=dtype, device=device)\n A = torch.eye(3, 3, dtype=dtype, device=device)\n A[-1, -1] = 0 # Now A is singular\n err_str = r\"triangular_solve: U\\(3,3\\) is zero, singular U\\.\"\n with self.assertRaisesRegex(RuntimeError, err_str):\n torch.triangular_solve(b, A)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_triangular_solve_out_errors_and_warnings(self, device, dtype):\n # dtypes should be safely castable\n a = torch.eye(2, dtype=dtype, device=device)\n b = torch.randn(2, 1, dtype=dtype, device=device)\n out = torch.empty_like(b).to(torch.int)\n clone_a = torch.empty_like(a)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.triangular_solve(b, a, out=(out, clone_a))\n\n out = torch.empty_like(b)\n clone_a = clone_a.to(torch.int)\n with self.assertRaisesRegex(RuntimeError, \"but got clone_A with dtype Int\"):\n torch.triangular_solve(b, a, out=(out, clone_a))\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n clone_a = torch.empty_like(a)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.triangular_solve(b, a, out=(out, clone_a))\n out = torch.empty(0, dtype=dtype, device=device)\n clone_a = torch.empty_like(a).to(wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.triangular_solve(b, a, out=(out, clone_a))\n\n # if out tensor with wrong shape is passed a warning is given\n with warnings.catch_warnings(record=True) as w:\n out = torch.empty(1, dtype=dtype, device=device)\n clone_a = torch.empty(1, dtype=dtype, device=device)\n # Trigger warning\n torch.triangular_solve(b, a, out=(out, clone_a))\n # Check warning occurs\n self.assertEqual(len(w), 2)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-2].message))\n\n def check_single_matmul(self, x, y, shape):\n a = np.array(x, copy=False)\n b = np.array(y, copy=False)\n expected = np.matmul(a, b)\n\n ans = torch.matmul(x, y)\n self.assertTrue(ans.is_contiguous())\n self.assertTrue(np.array_equal(ans, expected))\n\n out = torch.zeros(*shape, dtype=torch.int64).to(x.device)\n ans = torch.matmul(x, y, out=out)\n self.assertIs(ans, out)\n self.assertTrue(ans.is_contiguous())\n self.assertTrue(np.array_equal(ans, expected))\n\n # TODO: update to run on CUDA, too\n @onlyCPU\n def test_matmul_small_brute_force_1d_Nd(self, device):\n # Issue #20452: range(0, 10) does not work.\n n = 1\n for m in range(1, 8):\n for p in range(1, 8):\n for o in range(1, 5):\n # 1d, 3d, inner dimensions C\n x = torch.arange(m, device=device)\n y = torch.arange(o * m * p, device=device).reshape(o, m, p)\n self.check_single_matmul(x, y, (o, n, p))\n\n # 1d, 3d, inner dimensions Fortran\n x = torch.arange(m, device=device)\n y = torch.arange(o * p * m, device=device).reshape(o, p, m).transpose(-1, -2)\n self.check_single_matmul(x, y, (o, n, p))\n\n # 1d, 3d, inner dimensions non-contiguous\n x = torch.arange(2 * m, device=device)[::2]\n y = torch.arange(o * m * 2 * p, device=device).reshape(o, m, 2 * p)[:, :, ::2]\n self.check_single_matmul(x, y, (o, n, p))\n\n for r in range(1, 5):\n # 1d, 4d, inner dimensions C\n x = torch.arange(m)\n y = torch.arange(r * o * m * p, device=device).reshape(r, o, m, p)\n self.check_single_matmul(x, y, (r, o, n, p))\n\n # 1d, 4d, inner dimensions Fortran\n x = torch.arange(m)\n y = torch.arange(r * o * p * m, device=device).reshape(r, o, p, m).transpose(-1, -2)\n self.check_single_matmul(x, y, (r, o, n, p))\n\n # 1d, 4d, inner dimensions non-contiguous\n x = torch.arange(2 * m, device=device)[::2]\n y = torch.arange(r * o * m * 2 * p, device=device).reshape(r, o, m, 2 * p)[:, :, :, ::2]\n self.check_single_matmul(x, y, (r, o, n, p))\n\n # TODO: update to run on CUDA, too\n @onlyCPU\n def test_matmul_small_brute_force_2d_Nd(self, device):\n # Issue #20452: range(0, 10) does not work.\n for n in range(1, 5):\n for m in range(1, 5):\n for p in range(1, 5):\n for o in range(1, 3):\n # 2d, 3d, inner dimensions C\n x = torch.arange(n * m, device=device).reshape(n, m)\n y = torch.arange(o * m * p, device=device).reshape(o, m, p)\n self.check_single_matmul(x, y, (o, n, p))\n\n # 2d, 3d, inner dimensions Fortran\n x = torch.arange(m * n, device=device).reshape(m, n).transpose(-1, -2)\n y = torch.arange(o * p * m, device=device).reshape(o, p, m).transpose(-1, -2)\n self.check_single_matmul(x, y, (o, n, p))\n\n # 2d, 3d, inner dimensions non-contiguous\n x = torch.arange(n * 2 * m, device=device).reshape(n, 2 * m)[:, ::2]\n y = torch.arange(o * m * 2 * p, device=device).reshape(o, m, 2 * p)[:, :, ::2]\n self.check_single_matmul(x, y, (o, n, p))\n\n for r in range(1, 2):\n # 2d, 4d, inner dimensions C\n x = torch.arange(n * m, device=device).reshape(n, m)\n y = torch.arange(r * o * m * p, device=device).reshape(r, o, m, p)\n self.check_single_matmul(x, y, (r, o, n, p))\n\n # 2d, 4d, inner dimensions Fortran\n x = torch.arange(m * n, device=device).reshape(m, n).transpose(-1, -2)\n y = torch.arange(r * o * p * m, device=device).reshape(r, o, p, m).transpose(-1, -2)\n self.check_single_matmul(x, y, (r, o, n, p))\n\n # 2d, 4d, inner dimensions non-contiguous\n x = torch.arange(n * 2 * m, device=device).reshape(n, 2 * m)[:, ::2]\n y = torch.arange(r * o * m * 2 * p, device=device).reshape(r, o, m, 2 * p)[:, :, :, ::2]\n self.check_single_matmul(x, y, (r, o, n, p))\n\n def test_linear_algebra_scalar_raises(self, device) -> None:\n m = torch.randn(5, 5, device=device)\n v = torch.randn(5, device=device)\n s = torch.tensor(7, device=device)\n self.assertRaises(RuntimeError, lambda: torch.mv(m, s))\n self.assertRaises(RuntimeError, lambda: torch.addmv(v, m, s))\n\n @onlyCPU\n @dtypes(torch.float)\n def test_cross(self, device, dtype):\n x = torch.rand(100, 3, 100, dtype=dtype, device=device)\n y = torch.rand(100, 3, 100, dtype=dtype, device=device)\n res1 = torch.cross(x, y)\n res2 = torch.tensor((), dtype=dtype, device=device)\n torch.cross(x, y, out=res2)\n self.assertEqual(res1, res2)\n\n @onlyCPU\n @dtypes(torch.float)\n def test_cross_with_and_without_dim(self, device, dtype):\n x = torch.rand(100, 3, dtype=dtype, device=device)\n y = torch.rand(100, 3, dtype=dtype, device=device)\n res1 = torch.cross(x, y, dim=1)\n res2 = torch.cross(x, y, dim=-1)\n res3 = torch.cross(x, y)\n self.assertEqual(res1, res2)\n self.assertEqual(res1, res3)\n\n def test_cross_errors(self, device):\n self.assertRaisesRegex(\n RuntimeError, \"inconsistent tensors dimensions\",\n lambda: torch.cross(torch.rand(100, 3, device=device), torch.rand(100, 3, 10, device=device)))\n self.assertRaisesRegex(\n RuntimeError, \"inconsistent tensors sizes\",\n lambda: torch.cross(torch.rand(5, 3, device=device), torch.rand(3, 5, device=device)))\n self.assertRaisesRegex(\n RuntimeError, \"no dimension of size 3 in input\",\n lambda: torch.cross(torch.rand(5, 4, device=device), torch.rand(5, 4, device=device)))\n self.assertRaisesRegex(\n RuntimeError, \"dimension 0 does not have size 3\",\n lambda: torch.cross(torch.rand(5, 4, 3, device=device), torch.rand(5, 4, 3, device=device), dim=0))\n self.assertRaisesRegex(\n RuntimeError, \"dimension -1 does not have size 3\",\n lambda: torch.cross(torch.rand(5, 3, 4, device=device), torch.rand(5, 3, 4, device=device), dim=-1))\n self.assertRaisesRegex(\n IndexError, \"Dimension out of range\",\n lambda: torch.cross(torch.rand(5, 3, 4, device=device), torch.rand(5, 3, 4, device=device), dim=-5))\n\n def test_renorm(self, device):\n m1 = torch.randn(20, 20, device=device) # big enough to exercise vectorized path\n res1 = torch.tensor((), device=device)\n\n def renorm(matrix, value, dim, max_norm):\n m1 = matrix.transpose(dim, 0).contiguous()\n # collapse non-dim dimensions.\n m2 = m1.clone().resize_(m1.size(0), int(math.floor(m1.nelement() / m1.size(0))))\n norms = m2.norm(value, 1, True)\n # clip\n new_norms = norms.clone()\n new_norms[torch.gt(norms, max_norm)] = max_norm\n new_norms.div_(norms.add_(1e-7))\n # renormalize\n m1.mul_(new_norms.expand_as(m1))\n return m1.transpose(dim, 0)\n\n # note that the axis fed to torch.renorm is different (2~=1)\n maxnorm = m1.norm(2, 1).mean()\n m2 = renorm(m1, 2, 1, maxnorm)\n m1.renorm_(2, 1, maxnorm)\n self.assertEqual(m1, m2, atol=1e-5, rtol=0)\n self.assertEqual(m1.norm(2, 0), m2.norm(2, 0), atol=1e-5, rtol=0)\n\n m1 = torch.randn(3, 4, 5, device=device)\n m2 = m1.transpose(1, 2).contiguous().clone().resize_(15, 4)\n maxnorm = m2.norm(2, 0).mean()\n m2 = renorm(m2, 2, 1, maxnorm)\n m1.renorm_(2, 1, maxnorm)\n m3 = m1.transpose(1, 2).contiguous().clone().resize_(15, 4)\n self.assertEqual(m3, m2)\n self.assertEqual(m3.norm(2, 0), m2.norm(2, 0))\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoCusolver\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_ormqr(self, device, dtype):\n\n def run_test(batch, m, n, fortran_contiguous):\n A = make_tensor((*batch, m, n), dtype=dtype, device=device)\n reflectors, tau = torch.geqrf(A)\n if not fortran_contiguous:\n self.assertTrue(reflectors.transpose(-2, -1).is_contiguous())\n reflectors = reflectors.contiguous()\n\n # Q is of size m x m\n Q, _ = torch.linalg.qr(A, mode='complete')\n C_right = make_tensor((*batch, m, n), dtype=dtype, device=device)\n C_left = make_tensor((*batch, n, m), dtype=dtype, device=device)\n\n expected = Q @ C_right\n actual = torch.ormqr(reflectors, tau, C_right, left=True, transpose=False)\n self.assertEqual(expected, actual)\n\n expected = C_left @ Q\n actual = torch.ormqr(reflectors, tau, C_left, left=False, transpose=False)\n self.assertEqual(expected, actual)\n\n expected = Q.transpose(-2, -1).conj() @ C_right\n actual = torch.ormqr(reflectors, tau, C_right, left=True, transpose=True)\n self.assertEqual(expected, actual)\n\n expected = C_left @ Q.transpose(-2, -1).conj()\n actual = torch.ormqr(reflectors, tau, C_left, left=False, transpose=True)\n self.assertEqual(expected, actual)\n\n # if tau is all zeros then the implicit matrix Q is the identity matrix\n # so the actual result should be C_right in this case\n zero_tau = torch.zeros_like(tau)\n actual = torch.ormqr(reflectors, zero_tau, C_right, left=True, transpose=False)\n self.assertEqual(C_right, actual)\n\n batches = [(), (0, ), (2, ), (2, 1)]\n ns = [5, 2, 0]\n for batch, (m, n), fortran_contiguous in product(batches, product(ns, ns), [True, False]):\n run_test(batch, m, n, fortran_contiguous)\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoCusolver\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_ormqr_errors_and_warnings(self, device, dtype):\n test_cases = [\n # input1 size, input2 size, input3 size, error regex\n ((10,), (2,), (2,), r\"input must have at least 2 dimensions\"),\n ((2, 2), (2,), (2,), r\"other must have at least 2 dimensions\"),\n ((10, 6), (20,), (10, 6), r\"other.shape\\[-2\\] must be greater than or equal to tau.shape\\[-1\\]\"),\n ((6, 6), (5,), (5, 5), r\"other.shape\\[-2\\] must be equal to input.shape\\[-2\\]\"),\n ((1, 2, 2), (2, 2), (1, 2, 2), r\"batch dimensions of tau to be equal to input.shape\\[:-2\\]\"),\n ((1, 2, 2), (1, 2), (2, 2, 2), r\"batch dimensions of other to be equal to input.shape\\[:-2\\]\"),\n ]\n for a_size, tau_size, c_size, error_regex in test_cases:\n a = make_tensor(a_size, dtype=dtype, device=device)\n tau = make_tensor(tau_size, dtype=dtype, device=device)\n c = make_tensor(c_size, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, error_regex):\n torch.ormqr(a, tau, c)\n\n def test_blas_empty(self, device):\n def fn(torchfn, *args, test_out=False, **kwargs):\n def call_torch_fn(*args, **kwargs):\n return torchfn(*tuple(torch.randn(shape, device=device) if isinstance(shape, tuple) else shape\n for shape in args), **kwargs)\n result = call_torch_fn(*args, **kwargs)\n if not test_out:\n return result\n else:\n out = torch.full_like(result, math.nan)\n out1 = call_torch_fn(*args, **kwargs, out=out)\n return out\n\n # mm, addmm\n self.assertEqual((0, 0), fn(torch.mm, (0, 0), (0, 0)).shape)\n self.assertEqual((0, 5), fn(torch.mm, (0, 0), (0, 5)).shape)\n self.assertEqual((5, 0), fn(torch.mm, (5, 0), (0, 0)).shape)\n self.assertEqual((3, 0), fn(torch.mm, (3, 2), (2, 0)).shape)\n self.assertEqual(torch.zeros((5, 6), device=device), fn(torch.mm, (5, 0), (0, 6)))\n self.assertEqual(torch.zeros((5, 6), device=device), fn(torch.mm, (5, 0), (0, 6), test_out=True))\n\n self.assertEqual((0, 0), fn(torch.addmm, (0, 0), (0, 0), (0, 0)).shape)\n self.assertEqual((0, 1), fn(torch.addmm, (1, ), (0, 17), (17, 1)).shape)\n t = torch.randn((5, 6), device=device)\n self.assertEqual(t, fn(torch.addmm, t, (5, 0), (0, 6)))\n self.assertEqual(t, fn(torch.addmm, t, (5, 0), (0, 6), test_out=True))\n\n # mv, addmv\n self.assertEqual((0,), fn(torch.mv, (0, 0), (0,)).shape)\n self.assertEqual((0,), fn(torch.mv, (0, 2), (2,)).shape)\n self.assertEqual(torch.zeros((3,), device=device), fn(torch.mv, (3, 0), (0,)))\n self.assertEqual(torch.zeros((3,), device=device), fn(torch.mv, (3, 0), (0,), test_out=True))\n\n self.assertEqual((0,), fn(torch.addmv, (0,), (0, 0), (0,)).shape)\n t = torch.randn((3,), device=device)\n self.assertEqual(t, fn(torch.addmv, t, (3, 0), (0,)))\n self.assertEqual(t, fn(torch.addmv, t, (3, 0), (0,), test_out=True))\n\n # bmm, baddbmm\n self.assertEqual((0, 0, 0), fn(torch.bmm, (0, 0, 0), (0, 0, 0)).shape)\n self.assertEqual((3, 0, 5), fn(torch.bmm, (3, 0, 0), (3, 0, 5)).shape)\n self.assertEqual((0, 5, 6), fn(torch.bmm, (0, 5, 0), (0, 0, 6)).shape)\n self.assertEqual(torch.zeros((3, 5, 6), device=device), fn(torch.bmm, (3, 5, 0), (3, 0, 6)))\n self.assertEqual(torch.zeros((3, 5, 6), device=device), fn(torch.bmm, (3, 5, 0), (3, 0, 6), test_out=True))\n\n self.assertEqual((0, 0, 0), fn(torch.baddbmm, (0, 0, 0), (0, 0, 0), (0, 0, 0)).shape)\n self.assertEqual((3, 0, 5), fn(torch.baddbmm, (3, 0, 5), (3, 0, 0), (3, 0, 5)).shape)\n self.assertEqual((0, 5, 6), fn(torch.baddbmm, (0, 5, 6), (0, 5, 0), (0, 0, 6)).shape)\n self.assertEqual((3, 5, 6), fn(torch.baddbmm, (3, 5, 6), (3, 5, 0), (3, 0, 6)).shape)\n c = torch.arange(30, dtype=torch.float32, device=device).reshape(3, 2, 5)\n self.assertEqual(-2 * c, fn(torch.baddbmm, c, (3, 2, 0), (3, 0, 5), beta=-2)) # Issue #33467\n self.assertEqual(-2 * c, fn(torch.baddbmm, c, (3, 2, 0), (3, 0, 5), beta=-2, test_out=True)) # Issue #33467\n\n # addbmm\n self.assertEqual((0, 0), fn(torch.addbmm, (0, 0), (0, 0, 0), (0, 0, 0)).shape)\n self.assertEqual((0, 5), fn(torch.addbmm, (0, 5), (3, 0, 0), (3, 0, 5)).shape)\n t = torch.randn((5, 6), device=device)\n self.assertEqual(t, fn(torch.addbmm, t, (0, 5, 0), (0, 0, 6)))\n self.assertEqual(t, fn(torch.addbmm, t, (0, 5, 0), (0, 0, 6), test_out=True))\n\n # matmul\n self.assertEqual(torch.tensor(0., device=device), fn(torch.matmul, (0,), (0,)))\n self.assertEqual(torch.tensor(0., device=device), fn(torch.matmul, (0,), (0,), test_out=True))\n self.assertEqual((0, 0), fn(torch.matmul, (0, 0), (0, 0)).shape)\n self.assertEqual((0, 0, 0), fn(torch.matmul, (0, 0, 0), (0, 0, 0)).shape)\n self.assertEqual((5, 0, 0), fn(torch.matmul, (5, 0, 0), (5, 0, 0)).shape)\n self.assertEqual(torch.zeros((5, 3, 4), device=device), fn(torch.matmul, (5, 3, 0), (5, 0, 4)))\n self.assertEqual(torch.zeros((5, 3, 4), device=device), fn(torch.matmul, (5, 3, 0), (5, 0, 4), test_out=True))\n\n # dot\n self.assertEqual(torch.tensor(0., device=device), fn(torch.dot, (0,), (0,)))\n self.assertEqual(torch.tensor(0., device=device), fn(torch.dot, (0,), (0,), test_out=True))\n\n if torch._C.has_lapack:\n # lu\n A_LU, pivots = fn(torch.lu, (0, 5, 5))\n self.assertEqual([(0, 5, 5), (0, 5)], [A_LU.shape, pivots.shape])\n A_LU, pivots = fn(torch.lu, (0, 0, 0))\n self.assertEqual([(0, 0, 0), (0, 0)], [A_LU.shape, pivots.shape])\n A_LU, pivots = fn(torch.lu, (2, 0, 0))\n self.assertEqual([(2, 0, 0), (2, 0)], [A_LU.shape, pivots.shape])\n\n @dtypesIfCUDA(torch.cfloat, torch.cdouble,\n *torch.testing.get_all_fp_dtypes(include_half=not CUDA9, include_bfloat16=(CUDA11OrLater and SM53OrLater)))\n @dtypes(*(set(torch.testing.get_all_dtypes()) - {torch.half, torch.bool}))\n def test_blas_alpha_beta_empty(self, device, dtype):\n # This test is disabled on CUDA 9 due to:\n # See: https://github.com/pytorch/pytorch/issues/31006\n if dtype is torch.bfloat16 and self.device_type == 'xla':\n # TODO (@zasdfgbnm): this causes the following error on test\n # TestTorchDeviceTypeXLA.test_blas_alpha_beta_empty_xla_bfloat16:\n #\n # RuntimeError: _th_equal not supported on CPUType for BFloat16\n return\n # ensure beta is respected\n value = 11\n input = torch.full((2,), value, dtype=dtype, device=device)\n mat = torch.ones((2, 0), dtype=dtype, device=device)\n vec = torch.ones((0,), dtype=dtype, device=device)\n out = torch.empty((2,), dtype=dtype, device=device)\n if dtype.is_complex:\n alpha = 6 + 7j\n beta = 3 + 4j\n else:\n alpha = 6\n beta = 3\n self.assertEqual(torch.full((2,), beta * value, dtype=dtype, device=device),\n torch.addmv(input=input, mat=mat, vec=vec, alpha=alpha, beta=beta))\n self.assertEqual(torch.full((2,), beta * value, dtype=dtype, device=device),\n torch.addmv(input=input, mat=mat, vec=vec, alpha=alpha, beta=beta, out=out))\n\n # torch.addmm\n input = torch.full((2, 3), value, dtype=dtype, device=device)\n mat2 = torch.ones((0, 3), dtype=dtype, device=device)\n out = torch.empty((2, 3), dtype=dtype, device=device)\n self.assertEqual(torch.full((2, 3), beta * value, dtype=dtype, device=device),\n torch.addmm(input=input, mat1=mat, mat2=mat2, alpha=alpha, beta=beta))\n self.assertEqual(torch.full((2, 3), beta * value, dtype=dtype, device=device),\n torch.addmm(input=input, mat1=mat, mat2=mat2, alpha=alpha, beta=beta, out=out))\n\n @dtypes(*(torch.testing.get_all_complex_dtypes() + torch.testing.get_all_fp_dtypes()))\n def test_blas_nan_out(self, device, dtype):\n # These functions should work correctly with NaN filled outputs,\n # but need special handling, see [NOTE: cpu_zero]\n b = 3\n n = 5\n m = 7\n p = 11\n\n # torch.mv\n nm = torch.randn((m, n), device=device).t()\n _m = torch.randn((), device=device).expand(m)\n _m_out = torch.full((m,), float('nan'), device=device)\n self.assertEqual(torch.mv(nm, _m), torch.mv(nm, _m, out=_m_out))\n self.assertEqual(0, torch.isnan(torch.mv(nm, _m)).sum())\n\n # torch.mm\n mp = torch.randn((p, m), device=device).t()\n np_out = torch.full((n, p), float('nan'), device=device)\n self.assertEqual(torch.mm(nm, mp), torch.mm(nm, mp, out=np_out))\n\n # torch.bmm\n bnm = torch.randn((b, m, n), device=device).transpose(1, 2)\n bmp = torch.randn((b, p, m), device=device).transpose(1, 2)\n bnp_out = torch.full((b, n, p), float('nan'), device=device)\n self.assertEqual(torch.bmm(bnm, bmp), torch.bmm(bnm, bmp, out=bnp_out))\n\n @onlyCPU # not supported by CUBLAS\n def test_blas_mv_large_input(self, device):\n # This would previously fail if the allocated output had NaNs, see:\n # https://github.com/pytorch/pytorch/issues/31663 and [NOTE: cpu_zero]\n n = 3000\n m = 200\n\n nm = torch.randn((m, n), device=device).t()\n _m = torch.randn((), device=device).expand(m)\n _m_out = torch.full((m,), 0., device=device)\n\n self.assertEqual(torch.mv(nm, _m), torch.mv(nm, _m, out=_m_out))\n\n @onlyCPU\n def test_renorm_ps(self, device):\n # full reduction\n x = torch.randn(5, 5)\n xn = x.numpy()\n for p in [1, 2, 3, 4, inf]:\n res = x.renorm(p, 1, 1)\n expected = x / x.norm(p, 0, keepdim=True).clamp(min=1)\n self.assertEqual(res, expected, msg=\"renorm failed for {}-norm\".format(p))\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoCusolver\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_householder_product(self, device, dtype):\n def generate_reflectors_and_tau(A):\n \"\"\"\n This function uses numpy.linalg.qr with mode \"raw\" to extract output of LAPACK's geqrf.\n There is torch.geqrf function but it doesn't work with complex-valued input.\n \"\"\"\n if A.numel() > 0:\n A_cpu = A.cpu()\n flattened_batch_shape = [-1, *A_cpu.shape[-2:]]\n reflectors = torch.empty_like(A_cpu).view(*flattened_batch_shape)\n tau_shape = [*A_cpu.shape[:-2], A_cpu.shape[-1]]\n tau = torch.empty(tau_shape, dtype=dtype).view(-1, A_cpu.shape[-1])\n for A_i, reflectors_i, tau_i in zip(A_cpu.contiguous().view(*flattened_batch_shape), reflectors, tau):\n reflectors_tmp, tau_i[:] = map(torch.from_numpy, np.linalg.qr(A_i, mode='raw'))\n reflectors_i[:] = reflectors_tmp.T\n reflectors = reflectors.view(*A_cpu.shape)\n tau = tau.view(tau_shape)\n return reflectors.to(A.device), tau.to(A.device)\n\n reflectors = torch.empty_like(A)\n tau = torch.empty(*A.shape[:-2], A.shape[-1], dtype=dtype, device=device)\n return reflectors, tau\n\n def run_test(shape):\n A = torch.randn(*shape, dtype=dtype, device=device)\n reflectors, tau = generate_reflectors_and_tau(A)\n expected, _ = torch.linalg.qr(A)\n actual = torch.linalg.householder_product(reflectors, tau)\n # torch.linalg.qr does not work correctly for zero batch dimension tensors\n # see https://github.com/pytorch/pytorch/issues/50576\n if (A.numel() > 0):\n self.assertEqual(expected, actual)\n else:\n self.assertTrue(actual.shape == shape)\n\n # if tau is empty and A is not the result should be a matrix with ones on the diagonal\n if (A.numel() > 0):\n tau_empty = torch.empty(*shape[:-2], 0, dtype=dtype, device=device)\n identity_mat = torch.zeros_like(reflectors)\n identity_mat.diagonal(dim1=-1, dim2=-2)[:] = 1\n actual = torch.linalg.householder_product(reflectors, tau_empty)\n self.assertEqual(actual, identity_mat)\n\n out = torch.empty_like(A)\n ans = torch.linalg.householder_product(reflectors, tau, out=out)\n self.assertEqual(ans, out)\n if (A.numel() > 0):\n self.assertEqual(expected, out)\n\n shapes = [(0, 0), (5, 0), # Empty matrix\n (5, 5), (5, 3), # Single matrix\n (0, 0, 0), (0, 5, 5), (0, 5, 3), # Zero batch dimension tensors\n (2, 5, 5), (2, 5, 3), # 3-dim tensors\n (2, 1, 5, 5), (2, 1, 5, 3)] # 4-dim tensors\n for shape in shapes:\n run_test(shape)\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoCusolver\n def test_householder_product_errors_and_warnings(self, device):\n test_cases = [\n # input1 size, input2 size, error regex\n ((10,), (2,), r\"input must have at least 2 dimensions\"),\n ((10, 6), (20,), r\"input.shape\\[-1\\] must be greater than or equal to tau.shape\\[-1\\]\"),\n ((6, 10), (5,), r\"input.shape\\[-2\\] must be greater than or equal to input.shape\\[-1\\]\"),\n ]\n for a_size, tau_size, error_regex in test_cases:\n a = torch.rand(*a_size, device=device)\n tau = torch.rand(*tau_size, device=device)\n with self.assertRaisesRegex(RuntimeError, error_regex):\n torch.linalg.householder_product(a, tau)\n\n # if out tensor with wrong shape is passed a warning is given\n reflectors = torch.randn(3, 3, device=device)\n tau = torch.randn(3, device=device)\n out = torch.empty(2, 3, device=device)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.householder_product(reflectors, tau, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out = torch.empty_like(reflectors).to(torch.int)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.linalg.householder_product(reflectors, tau, out=out)\n\n with self.assertRaisesRegex(RuntimeError, \"tau dtype Int does not match input dtype\"):\n torch.linalg.householder_product(reflectors, tau.to(torch.int))\n\n if torch.cuda.is_available():\n # device of out and input should match\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty_like(reflectors).to(wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"Expected all tensors to be on the same device\"):\n torch.linalg.householder_product(reflectors, tau, out=out)\n\n # device of tau and input should match\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n tau = tau.to(wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"Expected all tensors to be on the same device\"):\n torch.linalg.householder_product(reflectors, tau)\n\n @precisionOverride({torch.complex64: 5e-6})\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double, torch.cfloat, torch.cdouble)\n def test_lu(self, device, dtype):\n from torch.testing._internal.common_utils import random_matrix\n\n def run_test(device, pivot):\n def run_subtest(matrix_size, batches, device, pivot, singular=False, a=None):\n if isinstance(matrix_size, int):\n rows = columns = matrix_size\n else:\n rows, columns = matrix_size\n if a is None:\n a = random_matrix(rows, columns, *batches, **dict(singular=singular, dtype=dtype)).to(device)\n a_LU_info, pivots_info, info_ = a.lu(pivot=pivot, get_infos=True)\n self.assertEqual(a_LU_info.size(), torch.Size(batches + (rows, columns)))\n self.assertEqual(pivots_info.size(), torch.Size(batches + (min(rows, columns),)))\n self.assertEqual(info_.size(), torch.Size(batches))\n # If a randomly generated input matrix is singular,\n # then info_ contains indices i such that U[i, i] ==\n # 0. This however conveys that the factorization was\n # successful albeit with a singular input. Therefore,\n # we require info.min() >= 0\n self.assertGreaterEqual(info_.min(), 0)\n a_LU, pivots = a.lu(pivot=pivot)\n self.assertEqual(a_LU, a_LU_info)\n self.assertEqual(pivots_info, pivots)\n\n\n P, L, U = torch.lu_unpack(a_LU, pivots)\n P_ = P.cpu().numpy()\n L_ = L.cpu().numpy()\n U_ = U.cpu().numpy()\n\n self.assertEqual(np.matmul(P_, np.matmul(L_, U_)), a)\n\n if self.device_type == 'cuda':\n # lu without pivoting is implemented only for cuda device\n a_LU_info_nopiv, nopiv, info_nopiv = a.lu(pivot=False, get_infos=True)\n P_nopiv, L_nopiv, U_nopiv = torch.lu_unpack(a_LU_info_nopiv, nopiv)\n P_nopiv_ = P_nopiv.cpu().numpy()\n L_nopiv_ = L_nopiv.cpu().numpy()\n U_nopiv_ = U_nopiv.cpu().numpy()\n\n self.assertEqual(np.matmul(P_nopiv_, np.matmul(L_nopiv_, U_nopiv_)), a)\n\n k = min(rows, columns)\n self.assertEqual(nopiv, torch.arange(1, 1 + k, device=device, dtype=torch.int32).expand(a.shape[:-2] + (k, )))\n if not singular:\n # It is not guaranteed that LU factorization\n # without pivoting is able to determine if a\n # matrix is singular while LU factorization\n # with pivoting is. Therefore, we require the\n # equality of info-s only for non-singular\n # matrices.\n # NOTE: infor_ is reshaped because info_nopiv might have\n # squashed batch dimensions for complex types on CUDA,\n # see the TODOs above.\n self.assertEqual(info_.reshape(info_nopiv.shape), info_nopiv)\n\n for ms, batch in itertools.product([3, 5, 7, (4, 2), (3, 4)], [(), (2,), (3,), (3, 5)]):\n run_subtest(ms, batch, device, pivot)\n run_subtest(ms, batch, device, pivot, singular=True)\n\n # Reproducer of a magma bug, see https://bitbucket.org/icl/magma/issues/13/getrf_batched-kernel-produces-nans-on\n a = torch.ones(batch + (ms if isinstance(ms, tuple) else (ms, ms)), dtype=torch.double, device=device)\n run_subtest(ms, batch, device, pivot, singular=True, a=a)\n\n # Info should be positive for rank deficient matrices\n a = torch.ones(5, 3, 3, device=device)\n self.assertGreater(a.lu(pivot=pivot, get_infos=True)[2][0], 0)\n\n run_test(device, True)\n\n if self.device_type == 'cpu':\n # Error checking, no pivoting variant on CPU\n with self.assertRaisesRegex(RuntimeError, 'lu without pivoting is not implemented on the CPU'):\n torch.lu(torch.empty(1, 2, 2), pivot=False)\n else:\n run_test(device, False)\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n @skipCUDAIfRocm\n @precisionOverride({torch.float: 1e-3})\n def test_lu_unpack(self, device, dtype):\n def run_test(pivot):\n for shape in ((3, 3), (5, 3, 3), (7, 3, 5, 5), (7, 5, 3, 3, 3)):\n a = torch.randn(*shape, dtype=dtype, device=device)\n a_lu, p = torch.lu(a, pivot=pivot)\n p_ref, l_ref, u_ref = torch.lu_unpack(a_lu, p)\n self.assertEqual(p_ref.matmul(l_ref.matmul(u_ref)), a)\n for shape in ((3, 3), (5, 3, 3), (7, 3, 5, 5), (7, 5, 3, 3, 3),\n (3, 5), (5, 3), (3, 3, 5), (3, 5, 3),\n (7, 5, 3, 5, 3), (7, 5, 3, 3, 5),\n # empty tensors\n (0, 0), (0, 0, 0), (0, 3, 3)\n ):\n a = make_tensor(shape, dtype=dtype, device=device, low=-0.1, high=+0.1)\n a_lu, p = torch.lu(a, pivot=pivot)\n p_ref, l_ref, u_ref = torch.lu_unpack(a_lu, p)\n self.assertEqual(p_ref.matmul(l_ref.matmul(u_ref)), a)\n\n run_test(True)\n\n if self.device_type == 'cuda':\n run_test(False)\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.double)\n def test_lu_unpack_check_input(self, device, dtype):\n x = torch.rand(5, 5, 5, device=device, dtype=dtype)\n lu_data, lu_pivots = torch.lu(x, pivot=True)\n\n with self.assertRaisesRegex(RuntimeError, \"torch.int32 dtype\"):\n torch.lu_unpack(lu_data, lu_pivots.long())\n with self.assertRaisesRegex(RuntimeError, \"contiguous tensor\"):\n torch.lu_unpack(lu_data, lu_pivots.transpose(-1, -2))\n\n # check that onces flags are unset, Nones are returned\n p, l, u = torch.lu_unpack(lu_data, lu_pivots, unpack_data=False)\n self.assertTrue((l == u) and l is None)\n p, l, u = torch.lu_unpack(lu_data, lu_pivots, unpack_pivots=False)\n self.assertTrue(p is None)\n p, l, u = torch.lu_unpack(lu_data, lu_pivots, unpack_data=False, unpack_pivots=False)\n self.assertTrue((p == l == u) and p is None)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double)\n @skipCUDAIfRocm\n def test_lobpcg_basic(self, device, dtype):\n self._test_lobpcg_method(device, dtype, 'basic')\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double)\n @skipCUDAIfRocm\n def test_lobpcg_ortho(self, device, dtype):\n self._test_lobpcg_method(device, dtype, 'ortho')\n\n def _test_lobpcg_method(self, device, dtype, method):\n from torch.testing._internal.common_utils import random_symmetric_pd_matrix, random_sparse_pd_matrix\n from torch._linalg_utils import matmul, qform\n from torch._lobpcg import lobpcg\n\n def test_tracker(worker):\n k = worker.iparams['k']\n nc = worker.ivars['converged_count']\n if k <= nc:\n tol = worker.fparams['tol']\n rerr = worker.tvars['rerr']\n X = worker.X\n E = worker.E\n B = worker.B\n A = worker.A\n dtype = X.dtype\n device = X.device\n\n # Check convergence\n self.assertLessEqual(rerr[:k].max(), tol)\n\n # Check B-orthogonality\n I = torch.eye(k, k, dtype=dtype, device=device)\n self.assertEqual(qform(B, X[:, :k]), I)\n\n # Check block equation\n self.assertEqual(qform(A, X[:, :k]) / E[:k], I, atol=0.2, rtol=0)\n\n orig_lobpcg = lobpcg\n\n def lobpcg(*args, **kwargs):\n kwargs['tracker'] = test_tracker\n kwargs['niter'] = 1000\n kwargs['method'] = method\n kwargs['tol'] = 1e-8\n return orig_lobpcg(*args, **kwargs)\n prec = 5e-4\n\n # check dense input\n mm = torch.matmul\n for batches in [(), (2,), (2, 3)]:\n for m, n, k in [\n (9, 3, 1),\n (9, 3, 2),\n (9, 2, 2),\n (100, 15, 5),\n ]:\n # skip tests that are known to fail with the basic\n # LOBPCG method due to calling cholesky on singular\n # input\n if method == 'basic' and (m, n, k) in [(9, 2, 2), (100, 15, 5)]:\n continue\n A = random_symmetric_pd_matrix(m, *batches, device=device, dtype=dtype)\n B = random_symmetric_pd_matrix(m, *batches, device=device, dtype=dtype)\n\n # classical eigenvalue problem, smallest eigenvalues\n E, V = lobpcg(A, k=k, n=n, largest=False)\n self.assertEqual(E.shape, batches + (k,))\n self.assertEqual(V.shape, batches + (m, k))\n self.assertEqual(matmul(A, V), mm(V, E.diag_embed()), atol=prec, rtol=0)\n e = torch.symeig(A)[0]\n e_smallest = e[..., :k]\n self.assertEqual(E, e_smallest)\n\n # classical eigenvalue problem, largest eigenvalues\n E, V = lobpcg(A, k=k, n=n, largest=True)\n e_largest, _ = torch.sort(e[..., -k:], descending=True)\n self.assertEqual(E, e_largest, atol=prec, rtol=0)\n self.assertEqual(matmul(A, V), mm(V, E.diag_embed()), atol=prec, rtol=0)\n\n # generalized eigenvalue problem, smallest eigenvalues\n E, V = lobpcg(A, B=B, k=k, n=n, largest=False)\n self.assertEqual(matmul(A, V), mm(matmul(B, V), E.diag_embed()), atol=prec, rtol=0)\n\n # generalized eigenvalue problem, largest eigenvalues\n E, V = lobpcg(A, B=B, k=k, n=n, largest=True)\n self.assertEqual(matmul(A, V) / E.max(), mm(matmul(B, V), (E / E.max()).diag_embed()),\n atol=prec, rtol=0)\n\n # check sparse input\n for m, n, k, density in [\n (5, 1, 1, 0.8),\n (9, 3, 2, 0.5),\n (100, 1, 1, 0.1),\n (1000, 7, 3, 0.01),\n ]:\n # skip tests that are known to fail with the basic LOBCG\n # method due to insufficient accuracy\n if method == 'basic' and (m, n, k, density) in [(1000, 7, 3, 0.01)]:\n continue\n A = random_sparse_pd_matrix(m, density=density, device=device, dtype=dtype)\n B = random_sparse_pd_matrix(m, density=density, device=device, dtype=dtype)\n A_eigenvalues = torch.arange(1, m + 1, dtype=dtype) / m\n e_smallest = A_eigenvalues[..., :k]\n e_largest, _ = torch.sort(A_eigenvalues[..., -k:], descending=True)\n\n # classical eigenvalue problem, smallest eigenvalues\n E, V = lobpcg(A, k=k, n=n, largest=False)\n self.assertEqual(E, e_smallest)\n self.assertEqual(matmul(A, V), mm(V, E.diag_embed()), atol=prec, rtol=0)\n\n # classical eigenvalue problem, largest eigenvalues\n E, V = lobpcg(A, k=k, n=n, largest=True)\n self.assertEqual(matmul(A, V), mm(V, E.diag_embed()), atol=prec, rtol=0)\n self.assertEqual(E, e_largest)\n\n # generalized eigenvalue problem, smallest eigenvalues\n E, V = lobpcg(A, B=B, k=k, n=n, largest=False)\n self.assertEqual(matmul(A, V), matmul(B, mm(V, E.diag_embed())), atol=prec, rtol=0)\n\n # generalized eigenvalue problem, largest eigenvalues\n E, V = lobpcg(A, B=B, k=k, n=n, largest=True)\n self.assertEqual(matmul(A, V) / E.max(), mm(matmul(B, V), (E / E.max()).diag_embed()),\n atol=prec, rtol=0)\n\n @skipCPUIfNoLapack\n @onlyCPU\n @dtypes(torch.double)\n def test_lobpcg_torchscript(self, device, dtype):\n from torch.testing._internal.common_utils import random_sparse_pd_matrix\n from torch._linalg_utils import matmul as mm\n\n lobpcg = torch.jit.script(torch.lobpcg)\n\n m = 500\n k = 5\n A1 = random_sparse_pd_matrix(m, density=2.0 / m, device=device, dtype=dtype)\n X1 = torch.randn((m, k), dtype=dtype, device=device)\n E1, V1 = lobpcg(A1, X=X1)\n eq_err = torch.norm((mm(A1, V1) - V1 * E1), 2) / E1.max()\n self.assertLess(eq_err, 1e-6)\n\n @unittest.skipIf(not TEST_SCIPY or (TEST_SCIPY and scipy.__version__ < '1.4.1'), \"Scipy not found or older than 1.4.1\")\n @skipCPUIfNoLapack\n @onlyCPU\n @dtypes(torch.double)\n def test_lobpcg_scipy(self, device, dtype):\n \"\"\"Compare torch and scipy.sparse.linalg implementations of lobpcg\n \"\"\"\n import time\n from torch.testing._internal.common_utils import random_sparse_pd_matrix\n from torch._linalg_utils import matmul as mm\n from scipy.sparse.linalg import lobpcg as scipy_lobpcg\n import scipy.sparse\n\n def toscipy(A):\n if A.layout == torch.sparse_coo:\n values = A.coalesce().values().cpu().numpy().copy()\n indices = A.coalesce().indices().cpu().numpy().copy()\n return scipy.sparse.coo_matrix((values, (indices[0], indices[1])), A.shape)\n return A.cpu().numpy().copy()\n\n niter = 1000\n repeat = 10\n m = 500 # size of the square matrix\n k = 7 # the number of requested eigenpairs\n A1 = random_sparse_pd_matrix(m, density=2.0 / m, device=device, dtype=dtype)\n B1 = random_sparse_pd_matrix(m, density=2.0 / m, device=device, dtype=dtype)\n X1 = torch.randn((m, k), dtype=dtype, device=device)\n\n A2 = toscipy(A1)\n B2 = toscipy(B1)\n X2 = toscipy(X1)\n\n lambdas1 = []\n\n def tracker(worker):\n lambdas1.append(worker.E[:])\n\n tol = 1e-8\n # tol for scipy lobpcg will be choosed so that the number of\n # iterations will be equal or very close to pytorch lobpcg\n # (that is around 170-180)\n\n # Standard eigenvalue problem\n E1, V1 = torch.lobpcg(A1, X=X1, niter=niter, largest=True, tracker=tracker, tol=tol)\n E2, V2, lambdas2 = scipy_lobpcg(A2, X2, maxiter=niter, largest=True, retLambdaHistory=True, tol=1.1 * tol)\n iters1 = len(lambdas1)\n iters2 = len(lambdas2)\n self.assertLess(abs(iters1 - iters2), 0.05 * max(iters1, iters2))\n\n E2a, V2a = scipy_lobpcg(A2, X2, maxiter=niter, largest=False)\n\n eq_err = torch.norm((mm(A1, V1) - V1 * E1), 2) / E1.max()\n eq_err_scipy = (abs(A2.dot(V2) - V2 * E2)**2).sum() ** 0.5 / E2.max()\n self.assertLess(eq_err, 1e-6) # std\n self.assertLess(eq_err_scipy, 1e-6) # std\n\n self.assertEqual(E1, torch.from_numpy(E2.copy()))\n\n # Generalized eigenvalue problem\n lambdas1 = []\n\n def tracker(worker):\n lambdas1.append(worker.E[:])\n\n E1, V1 = torch.lobpcg(A1, B=B1, X=X1, niter=niter, largest=True, tracker=tracker, tol=tol)\n E2, V2, lambdas2 = scipy_lobpcg(A2, X2, B=B2, maxiter=niter, largest=True, retLambdaHistory=True, tol=39 * tol)\n E2a, V2a = scipy_lobpcg(A2, X2, B=B2, maxiter=niter, largest=False)\n iters1 = len(lambdas1)\n iters2 = len(lambdas2)\n self.assertLess(abs(iters1 - iters2), 0.05 * max(iters1, iters2))\n\n eq_err = torch.norm((mm(A1, V1) - mm(B1, V1) * E1), 2) / E1.max()\n eq_err_scipy = (abs(A2.dot(V2) - B2.dot(V2) * E2)**2).sum() ** 0.5 / E2.max()\n self.assertLess(eq_err, 1e-6) # general\n self.assertLess(eq_err_scipy, 1e-6) # general\n\n self.assertEqual(E1, torch.from_numpy(E2.copy()))\n\n # Timings\n elapsed_ortho = 0\n elapsed_ortho_general = 0\n elapsed_scipy = 0\n elapsed_general_scipy = 0\n for i in range(repeat):\n start = time.time()\n torch.lobpcg(A1, X=X1, niter=niter, method='ortho', tol=tol)\n end = time.time()\n elapsed_ortho += end - start\n\n start = time.time()\n torch.lobpcg(A1, X=X1, B=B1, niter=niter, method='ortho', tol=tol)\n end = time.time()\n elapsed_ortho_general += end - start\n\n start = time.time()\n scipy_lobpcg(A2, X2, maxiter=niter, tol=1.1 * tol)\n end = time.time()\n elapsed_scipy += end - start\n\n start = time.time()\n scipy_lobpcg(A2, X2, B=B2, maxiter=niter, tol=39 * tol)\n end = time.time()\n elapsed_general_scipy += end - start\n\n elapsed_ortho_ms = 1000.0 * elapsed_ortho / repeat\n elapsed_ortho_general_ms = 1000.0 * elapsed_ortho_general / repeat\n elapsed_scipy_ms = 1000.0 * elapsed_scipy / repeat\n elapsed_general_scipy_ms = 1000.0 * elapsed_general_scipy / repeat\n\n print('''\nCPU timings: torch.lobpcg vs scipy.sparse.linalg.lobpcg\n-------------------------------------------------------\n | standard | generalized | method\ntorch.lobpcg | {:10.2f} | {:10.2f} | ortho\nscipy_lobpcg | {:10.2f} | {:10.2f} | N/A\n-(input size: {:4}, eigenpairs:{:2}, units: ms per call)-\n '''.format(elapsed_ortho_ms, elapsed_ortho_general_ms,\n elapsed_scipy_ms, elapsed_general_scipy_ms,\n m, k))\n\n # Handling of very small tolerence\n tol = 1e-100\n\n lambdas1 = []\n\n def tracker(worker):\n lambdas1.append(worker.E[:])\n\n E1, V1 = torch.lobpcg(A1, X=X1, niter=niter, largest=True, tracker=tracker, tol=tol)\n iters1 = len(lambdas1)\n eq_err = torch.norm((mm(A1, V1) - V1 * E1), 2) / E1.max()\n\n try:\n E2, V2, lambdas2 = scipy_lobpcg(A2, X2, maxiter=niter, largest=True, retLambdaHistory=True, tol=tol)\n iters2 = len(lambdas2)\n eq_err_scipy = (abs(A2.dot(V2) - V2 * E2)**2).sum() ** 0.5 / E2.max()\n except Exception as msg:\n print('Calling scipy_lobpcg failed [standard]:', msg)\n iters2 = -1\n eq_err_scipy = -1\n\n lambdas1 = []\n\n def tracker(worker):\n lambdas1.append(worker.E[:])\n\n E1, V1 = torch.lobpcg(A1, X=X1, B=B1, niter=niter, largest=True, tracker=tracker, tol=tol)\n iters1_general = len(lambdas1)\n eq_err_general = torch.norm((mm(A1, V1) - mm(B1, V1) * E1), 2) / E1.max()\n\n try:\n E2, V2, lambdas2 = scipy_lobpcg(A2, X2, B=B2, maxiter=niter, largest=True, retLambdaHistory=True, tol=tol)\n iters2_general = len(lambdas2)\n eq_err_general_scipy = (abs(A2.dot(V2) - B2.dot(V2) * E2)**2).sum() ** 0.5 / E2.max()\n except Exception as msg:\n print('Calling scipy_lobpcg failed [generalized]:', msg)\n iters2_general = -1\n eq_err_general_scipy = -1\n\n print('''\\\nHandling of small tol={:6.0e}: torch.lobpcg vs scipy.sparse.linalg.lobpcg\n----------------------------------------------------------------------------\n | standard | generalized | niter | method\ntorch.lobpcg | {:10.2e} | {:10.2e} | {:6} | ortho\nscipy_lobpcg | {:10.2e} | {:10.2e} | {:6} | N/A\n---(input size: {:4}, eigenpairs:{:2}, units: relative error, maxiter={:4})---\n'''.format(tol, eq_err, eq_err_general, iters1, eq_err_scipy, eq_err_general_scipy, iters2, m, k, niter))\n\n def _test_addmm_addmv(self, f, t, m, v, *, alpha=None, beta=None, transpose_out=False):\n dtype = t.dtype\n numpy_dtype = dtype\n if dtype in {torch.bfloat16}:\n numpy_dtype = torch.float\n if dtype.is_complex:\n alpha = 0.9 + 0.3j if alpha is None else alpha\n beta = 0.5 + 0.6j if beta is None else beta\n else:\n alpha = 1.2 if alpha is None else alpha\n beta = 0.8 if beta is None else beta\n res1 = f(t, m, v, alpha=alpha, beta=beta)\n res2 = torch.full_like(res1, math.nan)\n if transpose_out:\n res2 = res2.t().clone(memory_format=torch.contiguous_format).t()\n f(t, m, v, alpha=alpha, beta=beta, out=res2)\n res3 = alpha * (m.to(numpy_dtype).cpu().numpy() @ v.to(numpy_dtype).cpu().numpy())\n if beta != 0:\n res3 += (beta * t).to(numpy_dtype).cpu().numpy()\n res3 = torch.from_numpy(res3).to(dtype)\n self.assertEqual(res1, res2)\n self.assertEqual(res1, res3)\n\n @precisionOverride({torch.bfloat16: 1e-0, torch.half: 5e-4, torch.float: 1e-4, torch.double: 1e-8,\n torch.cfloat: 1e-4, torch.cdouble: 1e-8})\n @dtypesIfCUDA(*torch.testing.get_all_complex_dtypes(),\n *torch.testing.get_all_fp_dtypes(include_bfloat16=(TEST_WITH_ROCM or (CUDA11OrLater and SM53OrLater)),\n include_half=(not TEST_WITH_ROCM)))\n @dtypes(torch.bfloat16, torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_addmv(self, device, dtype):\n # have to use torch.randn(...).to(bfloat16) instead of\n # torch.randn(..., dtype=bfloat16). randn does not support\n # bfloat16 yet.\n ts = [\n torch.randn(10, device=device).to(dtype),\n torch.randn(1, device=device).to(dtype).expand(10),\n ]\n vs = [\n torch.randn(100, device=device).to(dtype),\n torch.ones(1, device=device).to(dtype).expand(100), # to reduce errors for low precision\n ]\n ms = [\n # 0d\n torch.ones((), device=device).to(dtype).expand(10, 100), # to reduce errors for low precision\n # 1d\n torch.randn((1, 100), device=device).to(dtype).expand(10, 100),\n # this initialization reduces errors for low precision for broadcasted matrices\n # by making sure that intermediate and result values are exactly representable\n # in low precision type\n torch.randint(3, (10, 1), dtype=torch.float, device=device).to(dtype).expand(10, 100),\n # 2d\n torch.randn((10, 100), device=device).to(dtype),\n torch.randn((100, 10), device=device).to(dtype).t(),\n ]\n for m, v, t in itertools.product(ms, vs, ts):\n self._test_addmm_addmv(torch.addmv, t, m, v)\n # Test beta=0, t=nan\n t = torch.full((10,), math.nan, device=device).to(dtype)\n for m, v in itertools.product(ms, vs):\n self._test_addmm_addmv(torch.addmv, t, m, v, beta=0)\n\n @dtypesIfCUDA(*torch.testing.get_all_fp_dtypes(include_bfloat16=(TEST_WITH_ROCM or (CUDA11OrLater and SM53OrLater))))\n @dtypes(torch.float, torch.double)\n def test_addmv_rowmajor_colmajor_incx_incy_lda(self, device, dtype):\n # tests (o, s)*(s). o is output size, s is summed size.\n o = 5\n s = 3\n a_data = torch.arange(1, o * s + 1, device=device, dtype=dtype).view(o, s)\n x_data = torch.arange(1, s + 1, 1, device=device, dtype=dtype)\n y_data = torch.ones(o, device=device, dtype=dtype)\n control = torch.tensor([15., 33., 51., 69., 87.], device=device, dtype=dtype)\n\n def _test(row_major, incx, incy, lda_tail):\n if row_major:\n a_storage = torch.full((o, s + lda_tail), float('nan'), device=device, dtype=dtype)\n else:\n a_storage = torch.full((s, o + lda_tail), float('nan'), device=device, dtype=dtype).permute(1, 0)\n a = a_storage[:o, :s].copy_(a_data)\n\n x_storage = torch.full((s, incx), float('nan'), device=device, dtype=dtype)\n x = x_storage[:, 0].copy_(x_data)\n\n y_storage = torch.full((o, incy), float('nan'), device=device, dtype=dtype)\n y = y_storage[:, 0].copy_(y_data)\n\n self._test_addmm_addmv(torch.addmv, y, a, x)\n\n for row_major, incx, incy, lda_tail in itertools.product((False, True), (1, 2), (1, 2), (0, 1)):\n _test(row_major, incx, incy, lda_tail)\n\n @precisionOverride({torch.double: 1e-8, torch.float: 1e-4, torch.bfloat16: 0.6,\n torch.half: 1e-1, torch.cfloat: 1e-4, torch.cdouble: 1e-8})\n @dtypesIfCUDA(*torch.testing.get_all_complex_dtypes(),\n *torch.testing.get_all_fp_dtypes(include_bfloat16=(TEST_WITH_ROCM or (CUDA11OrLater and SM53OrLater))))\n @dtypes(*torch.testing.get_all_complex_dtypes(), *torch.testing.get_all_fp_dtypes())\n @tf32_on_and_off(0.05)\n def test_addmm(self, device, dtype):\n M = torch.randn(10, 25, device=device).to(dtype)\n m1 = torch.randn(10, 50, device=device).to(dtype)\n m2 = torch.randn(50, 25, device=device).to(dtype)\n self._test_addmm_addmv(torch.addmm, M, m1, m2)\n\n # Test 0-strided\n M = torch.randn(10, 1, device=device).to(dtype).expand(10, 25)\n m1 = torch.randn(10, 1, device=device).to(dtype).expand(10, 50)\n m2 = torch.randn(50, 25, device=device).to(dtype)\n self._test_addmm_addmv(torch.addmm, M, m1, m2)\n\n # Test beta=0, M=nan\n M = torch.full((10, 25), math.nan, device=device).to(dtype)\n m1 = torch.randn(10, 50, device=device).to(dtype)\n m2 = torch.randn(50, 25, device=device).to(dtype)\n self._test_addmm_addmv(torch.addmm, M, m1, m2, beta=0)\n\n # Test transpose\n for t1, t2, t3, t4 in itertools.product([True, False], repeat=4):\n def maybe_transpose(cond, m):\n if not cond:\n return m\n return m.t().clone(memory_format=torch.contiguous_format).t()\n\n M = maybe_transpose(t1, torch.randn(10, 25, device=device).to(dtype))\n m1 = maybe_transpose(t2, torch.randn(10, 50, device=device).to(dtype))\n m2 = maybe_transpose(t3, torch.randn(50, 25, device=device).to(dtype))\n self._test_addmm_addmv(torch.addmm, M, m1, m2, transpose_out=t4)\n\n @dtypes(torch.float, torch.double)\n @dtypesIfCUDA(*([torch.float, torch.double] + torch.testing.get_all_complex_dtypes()))\n @tf32_on_and_off(0.005)\n def test_addmm_sizes(self, device, dtype):\n for m in [0, 1, 25]:\n for n in [0, 1, 10]:\n for k in [0, 1, 8]:\n M = torch.randn(n, m, device=device).to(dtype)\n m1 = torch.randn(n, k, device=device).to(dtype)\n m2 = torch.randn(k, m, device=device).to(dtype)\n self._test_addmm_addmv(torch.addmm, M, m1, m2)\n\n m1 = torch.randn(n, k + 1, device=device).to(dtype)\n m2 = torch.randn(k, m, device=device).to(dtype)\n self.assertRaisesRegex(RuntimeError, f\"{n}x{k + 1}.*{k}x{m}\", lambda: torch.addmm(M, m1, m2))\n self.assertRaisesRegex(RuntimeError, f\"{n}x{k + 1}.*{k}x{m}\", lambda: torch.mm(m1, m2))\n\n @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, \"cublas runtime error\")\n @onlyCUDA\n def test_matmul_45724(self, device):\n # https://github.com/pytorch/pytorch/issues/45724\n a = torch.rand(65537, 22, 64, device=device, dtype=torch.half)\n b = torch.rand(65537, 64, 22, device=device, dtype=torch.half)\n c = torch.full((65537, 22, 22), math.nan, dtype=torch.half, device=device)\n cpu_result = torch.matmul(a.cpu().float(), b.cpu().float()).cuda().half()\n torch.matmul(a, b, out=c)\n self.assertEqual(c, cpu_result)\n\n @slowTest\n @onlyOnCPUAndCUDA\n @dtypes(torch.float32, torch.float64, torch.bfloat16, torch.int32, torch.int64, torch.cfloat, torch.cdouble)\n @dtypesIfCUDA(torch.float32, torch.float64, torch.cfloat, torch.cdouble)\n @tf32_on_and_off(0.01)\n def test_mm(self, device, dtype):\n def _test_mm(n, m, p, dtype, genf):\n # helper function\n def matrixmultiply(mat1, mat2):\n n = mat1.size(0)\n m = mat1.size(1)\n p = mat2.size(1)\n res = torch.zeros(n, p, dtype=dtype, device=device)\n for i, j in iter_indices(res):\n res[i, j] = sum(mat1[i, k] * mat2[k, j] for k in range(m))\n return res\n\n # contiguous case\n mat1 = genf(n, m)\n mat2 = genf(m, p)\n res = torch.mm(mat1, mat2)\n\n res2 = matrixmultiply(mat1, mat2)\n self.assertEqual(res, res2)\n\n # non contiguous case 1\n mat1 = genf(n, m)\n mat2 = genf(p, m).t()\n res = torch.mm(mat1, mat2)\n\n res2 = matrixmultiply(mat1, mat2)\n self.assertEqual(res, res2)\n\n # non contiguous case 2\n mat1 = genf(m, n).t()\n mat2 = genf(m, p)\n res = torch.mm(mat1, mat2)\n\n res2 = matrixmultiply(mat1, mat2)\n self.assertEqual(res, res2)\n\n # non contiguous case 3\n mat1 = genf(m, n).t()\n mat2 = genf(p, m).t()\n res = torch.mm(mat1, mat2)\n\n res2 = matrixmultiply(mat1, mat2)\n self.assertEqual(res, res2)\n\n # test with zero stride\n mat1 = genf(n, m)\n mat2 = genf(m, 1).expand(m, p)\n res = torch.mm(mat1, mat2)\n\n res2 = matrixmultiply(mat1, mat2)\n self.assertEqual(res, res2)\n\n # explicitly exercise the _out variant in torch.mm().\n # contiguous case\n mat1 = genf(n, m)\n mat2 = genf(m, p)\n res = genf(n, p)\n torch.mm(mat1, mat2, out=res)\n\n res2 = matrixmultiply(mat1, mat2)\n self.assertEqual(res, res2)\n\n # explicitly exercise the _out variant in torch.mm().\n # non contiguous case 3\n mat1 = genf(m, n).t()\n mat2 = genf(p, m).t()\n res = genf(n, p)\n torch.mm(mat1, mat2, out=res)\n\n res2 = matrixmultiply(mat1, mat2)\n self.assertEqual(res, res2)\n\n def genf_int(x, y):\n return torch.randint(0, 100, (x, y), dtype=dtype, device=device)\n\n def genf_bfloat(x, y):\n return torch.randn(x, y, dtype=torch.float32, device=device).to(dtype)\n\n def genf_float(x, y):\n return torch.randn(x, y, dtype=dtype, device=device)\n\n for (n, m, p) in [(20, 10, 5), (15, 5, 10), (5, 18, 10)]:\n if (dtype == torch.int32) or (dtype == torch.int64):\n genf = genf_int\n elif (dtype == torch.bfloat16):\n genf = genf_bfloat\n else:\n genf = genf_float\n\n _test_mm(n, m, p, dtype, genf)\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.float32, torch.float64)\n def test_strided_mm_bmm(self, device, dtype):\n # Tests strided view case with stride smaller than corresponding dimension size\n x = torch.tensor([[1., 2., 3.], [4., 5., 6.]], dtype=dtype, device=device)\n new_shape = [2, 2, 2]\n new_stride = [3, 1, 1]\n sx = torch.as_strided(x, size=new_shape, stride=new_stride)\n\n torch_fn = lambda x: torch.bmm(x, x) # noqa: E731\n np_fn = lambda x: np.matmul(x, x) # noqa: E731\n self.compare_with_numpy(torch_fn, np_fn, sx)\n\n torch_fn = lambda x: torch.mm(x, x) # noqa: E731\n self.compare_with_numpy(torch_fn, np_fn, sx[0])\n\n @precisionOverride({torch.half: 0.05, torch.bfloat16: 0.05})\n @skipCUDAIf(torch.version.cuda == \"10.1\", \"flaky on CUDA 10.1\")\n @onlyOnCPUAndCUDA\n @dtypes(*torch.testing.get_all_fp_dtypes(), *torch.testing.get_all_complex_dtypes())\n @tf32_on_and_off(0.05)\n def test_bmm(self, device, dtype):\n if self.device_type == 'cuda' and dtype is torch.bfloat16 and CUDA11OrLater and not SM53OrLater:\n # cuBLAS does not guarantee BFloat16 support on SM < 53.\n # So on PyTorch, we consider BFloat16 support on SM < 53 as\n # undefined bahavior\n return\n\n batch_sizes = [1, 10]\n M, N, O = 23, 8, 12\n numpy_dtype = dtype if dtype != torch.bfloat16 else torch.float32\n\n is_supported = True\n if dtype == torch.bfloat16 and self.device_type == 'cuda':\n is_supported = TEST_WITH_ROCM or (CUDA11OrLater and SM53OrLater)\n\n if not is_supported:\n for num_batches in batch_sizes:\n b1 = torch.randn(num_batches, M, N, device=device).to(dtype)\n b2 = torch.randn(num_batches, N, O, device=device).to(dtype)\n self.assertRaisesRegex(RuntimeError, \"type|Type|not implemented|CUBLAS_STATUS_NOT_SUPPORTED\",\n lambda: torch.bmm(b1, b2))\n return\n\n def invert_perm(p):\n d = {x: i for i, x in enumerate(p)}\n return (d[0], d[1], d[2])\n\n def generate_inputs(num_batches):\n # transposed tensors\n for perm1, perm2 in itertools.product(itertools.permutations((0, 1, 2)), repeat=2):\n b1 = make_tensor((num_batches, M, N), device, dtype, low=-1, high=1)\n b2 = make_tensor((num_batches, N, O), device, dtype, low=-1, high=1)\n b1 = b1.permute(perm1).contiguous().permute(invert_perm(perm1))\n b2 = b2.permute(perm2).contiguous().permute(invert_perm(perm2))\n yield b1, b2\n # broadcasting tensors\n for b1, b2, b3, b4, b5, b6 in itertools.product((True, False), repeat=6):\n shape1 = (num_batches if b1 else 1, M if b2 else 1, N if b3 else 1)\n shape2 = (num_batches if b4 else 1, N if b5 else 1, O if b6 else 1)\n b1 = make_tensor(shape1, device, dtype, low=-1, high=1).expand(num_batches, M, N)\n b2 = make_tensor(shape2, device, dtype, low=-1, high=1).expand(num_batches, N, O)\n yield b1, b2\n # zero-sized tensors\n for z1, z2, z3, z4 in itertools.product((True, False), repeat=4):\n shape1 = (num_batches if z1 else 0, M if z2 else 0, N if z3 else 0)\n shape2 = (num_batches if z1 else 0, N if z3 else 0, O if z4 else 0)\n b1 = torch.randn(shape1, dtype=dtype, device=device)\n b2 = torch.randn(shape2, dtype=dtype, device=device)\n yield b1, b2\n\n for num_batches in batch_sizes:\n for (b1, b2), perm3 in itertools.product(generate_inputs(num_batches), itertools.permutations((0, 1, 2))):\n res1 = torch.bmm(b1, b2)\n res2 = torch.full((num_batches, M, O), math.nan, dtype=dtype, device=device) \\\n .permute(perm3).contiguous().permute(invert_perm(perm3))\n torch.bmm(b1, b2, out=res2)\n expect = torch.from_numpy(\n b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype)\n self.assertEqual(expect, res1)\n self.assertEqual(expect, res2)\n\n if self.device_type == 'cuda':\n # check that mixed arguments are rejected\n self.assertRaises(RuntimeError, lambda: torch.bmm(b1, b2.cpu()))\n self.assertRaises(RuntimeError, lambda: torch.bmm(b1.cpu(), b2))\n self.assertRaises(RuntimeError, lambda: torch.bmm(b1, b2, out=res2.cpu()))\n\n def _test_addbmm_baddbmm(self, func, b1, b2, ref, out_tensor):\n getattr(out_tensor, func + \"_\")(b1, b2)\n self.assertEqual(out_tensor, ref)\n res3 = out_tensor.clone()\n\n with self.assertWarnsOnceRegex(\n UserWarning, f\"This overload of {func}_ is deprecated\"):\n getattr(out_tensor, func + \"_\")(1, b1, b2)\n self.assertEqual(out_tensor, ref * 2),\n getattr(res3, func + \"_\")(b1, b2, beta=1)\n self.assertEqual(out_tensor, res3)\n\n with self.assertWarnsOnceRegex(\n UserWarning, f\"This overload of {func}_ is deprecated\"):\n getattr(out_tensor, func + \"_\")(1., .5, b1, b2)\n self.assertEqual(out_tensor, ref * 2.5)\n getattr(res3, func + \"_\")(b1, b2, beta=1., alpha=.5)\n self.assertEqual(out_tensor, res3)\n\n with self.assertWarnsOnceRegex(\n UserWarning, f\"This overload of {func} is deprecated\"):\n self.assertEqual(out_tensor, getattr(torch, func)(1, out_tensor, 0, b1, b2))\n\n res4 = getattr(torch, func)(out_tensor, b1, b2, beta=1, alpha=.5)\n self.assertEqual(res4, ref * 3),\n\n nan = torch.full_like(out_tensor, math.nan)\n res5 = getattr(torch, func)(nan, b1, b2, beta=0, alpha=1)\n self.assertEqual(res5, ref)\n\n if b1.is_complex():\n res6 = getattr(torch, func)(out_tensor, b1, b2, beta=.1j, alpha=.5j)\n self.assertEqual(res6, out_tensor * .1j + .5j * ref)\n else:\n res6 = getattr(torch, func)(out_tensor, b1, b2, beta=.1, alpha=.5)\n self.assertEqual(res6, out_tensor * .1 + .5 * ref)\n\n res7 = torch.full_like(out_tensor, math.nan)\n getattr(torch, func)(nan, b1, b2, beta=0, out=res7)\n self.assertEqual(res7, ref)\n\n @precisionOverride({torch.half: 0.05, torch.bfloat16: 0.05})\n @onlyOnCPUAndCUDA\n @dtypes(*torch.testing.get_all_fp_dtypes(), *torch.testing.get_all_complex_dtypes())\n @tf32_on_and_off(0.05)\n def test_addbmm(self, device, dtype):\n if self.device_type == 'cuda' and dtype is torch.bfloat16 and CUDA11OrLater and not SM53OrLater:\n # cuBLAS does not guarantee BFloat16 support on SM < 53.\n # So on PyTorch, we consider BFloat16 support on SM < 53 as\n # undefined bahavior\n return\n\n num_batches = 2\n M, N, O = 2, 3, 4\n\n is_supported = True\n if dtype == torch.bfloat16:\n if self.device_type == 'cpu':\n self.precision = 1 # 43 vs 43.75\n else:\n is_supported = TEST_WITH_ROCM or (CUDA11OrLater and SM53OrLater)\n\n if not is_supported:\n b1 = make_tensor((num_batches, M, N), device, dtype, low=-1, high=1)\n b2 = make_tensor((num_batches, N, O), device, dtype, low=-1, high=1)\n t = make_tensor((M, O), device, dtype, low=-1, high=1)\n self.assertRaisesRegex(RuntimeError, \"type|Type|not implemented|CUBLAS_STATUS_NOT_SUPPORTED\",\n lambda: torch.addbmm(t, b1, b2))\n return\n\n def invert_perm(p):\n d = {x: i for i, x in enumerate(p)}\n return (d[0], d[1], d[2])\n\n def generate_tensor():\n numpy_dtype = dtype if dtype != torch.bfloat16 else torch.float32\n # transposed tensors\n for perm1, perm2 in itertools.product(itertools.permutations((0, 1, 2)), repeat=2):\n for perm3 in itertools.permutations((0, 1)):\n b1 = make_tensor((num_batches, M, N), device, dtype, low=-1, high=1)\n b2 = make_tensor((num_batches, N, O), device, dtype, low=-1, high=1)\n b1 = b1.permute(perm1).contiguous().permute(invert_perm(perm1))\n b2 = b2.permute(perm2).contiguous().permute(invert_perm(perm2))\n ref = torch.from_numpy(\n b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()\n ).to(device=device, dtype=dtype).sum(0)\n out_tensor = torch.zeros_like(ref).permute(perm3).contiguous().permute(perm3)\n yield b1, b2, ref, out_tensor\n # broadcasting tensors\n for s1, s2, s3, s4, s5, s6 in itertools.product((True, False), repeat=6):\n shape1 = (num_batches if s1 else 1, M if s2 else 1, N if s3 else 1)\n shape2 = (num_batches if s4 else 1, N if s5 else 1, O if s6 else 1)\n b1 = make_tensor(shape1, device, dtype, low=-1, high=1).expand(num_batches, M, N)\n b2 = make_tensor(shape2, device, dtype, low=-1, high=1).expand(num_batches, N, O)\n ref = torch.from_numpy(\n b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()\n ).to(device=device, dtype=dtype).sum(0)\n out_tensor = torch.zeros_like(ref)\n yield b1, b2, ref, out_tensor\n # zero-sized tensors\n for z1, z2, z3, z4 in itertools.product((True, False), repeat=4):\n shape1 = (num_batches if z1 else 0, M if z2 else 0, N if z3 else 0)\n shape2 = (num_batches if z1 else 0, N if z3 else 0, O if z4 else 0)\n b1 = make_tensor(shape1, device, dtype, low=-1, high=1)\n b2 = make_tensor(shape2, device, dtype, low=-1, high=1)\n ref = torch.from_numpy(\n b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()\n ).to(device=device, dtype=dtype).sum(0)\n out_tensor = torch.zeros_like(ref)\n yield b1, b2, ref, out_tensor\n\n for b1, b2, ref, out_tensor in generate_tensor():\n self._test_addbmm_baddbmm(\"addbmm\", b1, b2, ref, out_tensor)\n\n @precisionOverride({torch.half: 0.1, torch.bfloat16: 0.5})\n @onlyOnCPUAndCUDA\n @dtypes(*torch.testing.get_all_fp_dtypes(), *torch.testing.get_all_complex_dtypes())\n @tf32_on_and_off(0.05)\n def test_baddbmm(self, device, dtype):\n if self.device_type == 'cuda' and dtype is torch.bfloat16 and CUDA11OrLater and not SM53OrLater:\n # cuBLAS does not guarantee BFloat16 support on SM < 53.\n # So on PyTorch, we consider BFloat16 support on SM < 53 as\n # undefined bahavior\n return\n\n num_batches = 10\n M, N, O = 12, 8, 5\n\n is_supported = True\n if dtype == torch.bfloat16 and self.device_type == 'cuda':\n is_supported = TEST_WITH_ROCM or (CUDA11OrLater and SM53OrLater)\n\n if not is_supported:\n b1 = make_tensor((num_batches, M, N), device, dtype, low=-1, high=1)\n b2 = make_tensor((num_batches, N, O), device, dtype, low=-1, high=1)\n t = make_tensor((num_batches, M, O), device, dtype, low=-1, high=1)\n self.assertRaisesRegex(RuntimeError, \"type|Type|not implemented|CUBLAS_STATUS_NOT_SUPPORTED\",\n lambda: torch.baddbmm(t, b1, b2))\n return\n\n def invert_perm(p):\n d = {x: i for i, x in enumerate(p)}\n return (d[0], d[1], d[2])\n\n def generate_tensor():\n numpy_dtype = dtype if dtype != torch.bfloat16 else torch.float32\n # transposed tensors\n for perm1, perm2, perm3 in itertools.product(itertools.permutations((0, 1, 2)), repeat=3):\n b1 = make_tensor((num_batches, M, N), device, dtype, low=-1, high=1)\n b2 = make_tensor((num_batches, N, O), device, dtype, low=-1, high=1)\n b1 = b1.permute(perm1).contiguous().permute(invert_perm(perm1))\n b2 = b2.permute(perm2).contiguous().permute(invert_perm(perm2))\n ref = torch.from_numpy(\n b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype)\n out_tensor = torch.zeros_like(ref)\n out_tensor = out_tensor.permute(perm3).contiguous().permute(invert_perm(perm3))\n yield b1, b2, ref, out_tensor\n # broadcasting tensors\n for s1, s2, s3, s4, s5, s6 in itertools.product((True, False), repeat=6):\n shape1 = (num_batches if s1 else 1, M if s2 else 1, N if s3 else 1)\n shape2 = (num_batches if s4 else 1, N if s5 else 1, O if s6 else 1)\n b1 = make_tensor(shape1, device, dtype, low=-1, high=1).expand(num_batches, M, N)\n b2 = make_tensor(shape2, device, dtype, low=-1, high=1).expand(num_batches, N, O)\n ref = torch.from_numpy(\n b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype)\n out_tensor = torch.zeros_like(ref)\n yield b1, b2, ref, out_tensor\n # zero-sized tensors\n for z1, z2, z3, z4 in itertools.product((True, False), repeat=4):\n shape1 = (num_batches if z1 else 0, M if z2 else 0, N if z3 else 0)\n shape2 = (num_batches if z1 else 0, N if z3 else 0, O if z4 else 0)\n b1 = make_tensor(shape1, device, dtype, low=-2, high=2)\n b2 = make_tensor(shape2, device, dtype, low=-2, high=2)\n ref = torch.from_numpy(\n b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype)\n out_tensor = torch.zeros_like(ref)\n yield b1, b2, ref, out_tensor\n\n for b1, b2, ref, out_tensor in generate_tensor():\n self._test_addbmm_baddbmm(\"baddbmm\", b1, b2, ref, out_tensor)\n\n # TODO: update to compare against NumPy\n @onlyCUDA\n def test_solve_methods_arg_device(self, device):\n for b_device, A_device in itertools.product(['cpu', device], repeat=2):\n if b_device == A_device:\n continue\n\n b = torch.randn(3, 1, device=b_device)\n A = torch.randn(3, 3, device=A_device)\n\n # solve and cholesky_solve goes through generic backend dispatch and hit kernel specific device check first\n # triangular_solve goes through specific backend dispatch (CPU/CUDA) and hit auto-generated device check first\n generic_backend_dispatch_err_str = \"Expected b and A to be on the same device\"\n specific_backend_dispatch_err_str = \"Expected all tensors to be on the same device\"\n with self.assertRaisesRegex(RuntimeError, generic_backend_dispatch_err_str):\n torch.solve(b, A)\n\n with self.assertRaisesRegex(RuntimeError, generic_backend_dispatch_err_str):\n torch.cholesky_solve(b, A)\n\n with self.assertRaisesRegex(RuntimeError, specific_backend_dispatch_err_str):\n torch.triangular_solve(b, A)\n\n # b and A have to be modified to match accepted inputs sizes for lu_solve\n b = b.unsqueeze(0)\n A = A.unsqueeze(0)\n with self.assertRaisesRegex(RuntimeError, specific_backend_dispatch_err_str):\n torch.lu_solve(b, A, torch.rand(A.shape[:-1], device=A_device).int())\n\n # This checks if a suitable error message is thrown\n # when LU output and pivots are not on the same device\n with self.assertRaisesRegex(RuntimeError, specific_backend_dispatch_err_str):\n torch.lu_solve(b, A, torch.rand(A.shape[:-1], device=b_device).int())\n\n @precisionOverride({torch.float32: 5e-3, torch.complex64: 1e-3})\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_pinverse(self, device, dtype):\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value as fullrank\n\n def run_test(M):\n # Testing against definition for pseudo-inverses\n MPI = torch.pinverse(M)\n MPI_ = MPI.cpu().numpy()\n M_ = M.cpu().numpy()\n if M.numel() > 0:\n self.assertEqual(M_, np.matmul(np.matmul(M_, MPI_), M_))\n self.assertEqual(MPI_, np.matmul(np.matmul(MPI_, M_), MPI_))\n self.assertEqual(np.matmul(M_, MPI_), np.matmul(M_, MPI_).swapaxes(-2, -1).conj())\n self.assertEqual(np.matmul(MPI_, M_), np.matmul(MPI_, M_).swapaxes(-2, -1).conj())\n else:\n self.assertEqual(M.shape, MPI.shape[:-2] + (MPI.shape[-1], MPI.shape[-2]))\n for sizes in [(5, 5), (3, 5, 5), (3, 7, 5, 5), # square matrices\n (3, 2), (5, 3, 2), (7, 5, 3, 2), # fat matrices\n (2, 3), (5, 2, 3), (7, 5, 2, 3), # thin matrices\n (0, 0), (0, 2), (2, 0), (3, 0, 0), (0, 3, 0), (0, 0, 3)]: # zero numel matrices\n M = torch.randn(*sizes, dtype=dtype, device=device)\n run_test(M)\n\n # Test inverse and pseudo-inverse for invertible matrix\n for sizes in [(5, 5), (3, 5, 5), (3, 7, 5, 5)]:\n matsize = sizes[-1]\n batchdims = sizes[:-2]\n M = fullrank(matsize, *batchdims, dtype=dtype, device=device)\n self.assertEqual(torch.eye(matsize, dtype=dtype, device=device).expand(sizes), M.pinverse().matmul(M),\n atol=1e-7, rtol=0, msg='pseudo-inverse for invertible matrix')\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagmaAndNoCusolver\n @dtypes(torch.double, torch.cdouble)\n def test_matrix_power_non_negative(self, device, dtype):\n def check(*size, noncontiguous=False):\n t = make_tensor(size, device, dtype, noncontiguous=noncontiguous)\n for n in range(8):\n res = torch.linalg.matrix_power(t, n)\n ref = np.linalg.matrix_power(t.cpu().numpy(), n)\n self.assertEqual(res.cpu(), torch.from_numpy(ref))\n\n check(0, 0)\n check(1, 1)\n check(5, 5)\n check(5, 5, noncontiguous=True)\n check(0, 3, 3)\n check(2, 3, 3)\n check(2, 3, 4, 4, noncontiguous=True)\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagmaAndNoCusolver\n @dtypes(torch.double, torch.cdouble)\n def test_matrix_power_negative(self, device, dtype):\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n def check(*size):\n t = random_fullrank_matrix_distinct_singular_value(*size, dtype=dtype, device=device)\n for n in range(-7, 0):\n res = torch.linalg.matrix_power(t, n)\n ref = np.linalg.matrix_power(t.cpu().numpy(), n)\n self.assertEqual(res.cpu(), torch.from_numpy(ref))\n\n check(0)\n check(5)\n check(0, 2)\n check(3, 0)\n check(3, 2)\n check(5, 2, 3)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.complex64)\n def test_matrix_exp_utils(self, device, dtype):\n # test linear combination\n def run_test(coeff_shape, data_shape):\n coeffs = torch.rand(*coeff_shape, device=device, dtype=torch.float)\n x = torch.rand(coeff_shape[1], *data_shape, device=device, dtype=dtype)\n\n res1 = torch._compute_linear_combination(x, coeffs)\n res2 = (x.unsqueeze(0) * coeffs.view(*coeff_shape, *([1] * len(data_shape)))).sum(1)\n self.assertEqual(res1, res2, atol=1e-5, rtol=0.0)\n\n # check `out=` version\n res3 = torch.zeros(coeff_shape[0], *data_shape, device=device, dtype=dtype)\n torch._compute_linear_combination(x, coeffs, out=res3)\n self.assertEqual(res1, res3, atol=1e-5, rtol=0.0)\n\n res4 = torch.ones(coeff_shape[0], *data_shape, device=device, dtype=dtype)\n torch._compute_linear_combination(x, coeffs, out=res4)\n self.assertEqual(res1, res4 - 1.0, atol=1e-5, rtol=0.0)\n\n res5 = torch.ones(coeff_shape[0], *data_shape, device=device, dtype=dtype)\n res5_clone = res5.clone()\n torch._compute_linear_combination(x, coeffs, out=res5)\n self.assertEqual(res1, res5 - res5_clone, atol=1e-5, rtol=0.0)\n\n run_test([1, 3], [2, 2])\n run_test([3, 1], [2, 2])\n run_test([1, 10], [10, 10])\n run_test([10, 1], [10, 10])\n run_test([5, 3], [2, 2])\n run_test([5, 3], [100, 100])\n run_test([3, 4], [3, 3, 3])\n run_test([3, 4], [3, 3, 3, 3])\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.complex64, torch.complex128)\n def test_matrix_exp_boundary_cases(self, device, dtype):\n\n with self.assertRaisesRegex(RuntimeError, \"expected a tensor of floating or complex types\"):\n torch.randn(3, 3).type(torch.int).matrix_exp()\n\n with self.assertRaisesRegex(RuntimeError, \"with dim at least 2\"):\n torch.randn(3).matrix_exp()\n\n with self.assertRaisesRegex(RuntimeError, \"expected a tensor of squared matrices\"):\n torch.randn(3, 2, 1).matrix_exp()\n\n # check 1x1 matrices\n x = torch.randn(3, 3, 1, 1)\n mexp = x.matrix_exp()\n self.assertEqual(mexp, x.exp())\n\n @slowTest\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_matrix_exp_analytic(self, device, dtype):\n # check zero matrix\n x = torch.zeros(20, 20, dtype=dtype, device=device)\n self.assertTrue((x.matrix_exp() == torch.eye(20, 20, dtype=dtype, device=device)).all().item())\n\n def normalize_to_1_operator_norm(sample, desired_norm):\n sample_norm, _ = sample.abs().sum(-2).max(-1)\n sample_to_1_norm = sample / sample_norm.unsqueeze(-1).unsqueeze(-1)\n return sample_to_1_norm * desired_norm\n\n def gen_good_cond_number_matrices(*n):\n \"\"\"\n Generates a diagonally-domimant matrix\n with the eigenvalues centered at 1\n and the radii at most (n[-1] - 1) / (n[-2] ** 2)\n \"\"\"\n identity = torch.eye(n[-2], n[-1], dtype=dtype, device=device).expand(*n)\n x = torch.rand(*n, dtype=dtype, device=device) / (n[-1] ** 2)\n x = (x - x * identity) + identity\n return x\n\n def run_test(*n):\n if dtype == torch.float:\n thetas = [\n 1.192092800768788e-07, # deg 1\n 5.978858893805233e-04, # deg 2\n 5.116619363445086e-02, # deg 4\n 5.800524627688768e-01, # deg 8\n 1.461661507209034e+00, # deg 12\n 3.010066362817634e+00 # deg 18\n ]\n else: # if torch.double\n thetas = [\n 2.220446049250313e-16, # deg 1\n 2.580956802971767e-08, # deg 2\n 3.397168839976962e-04, # deg 4\n 4.991228871115323e-02, # deg 8\n 2.996158913811580e-01, # deg 12\n 1.090863719290036e+00 # deg 18\n ]\n\n # generate input\n q = gen_good_cond_number_matrices(*n)\n q_ = q.cpu().numpy()\n qinv = torch.inverse(q)\n qinv_ = qinv.cpu().numpy()\n d = torch.randn(n[:-1], dtype=dtype, device=device)\n x = torch.from_numpy(\n np.matmul(q_, np.matmul(torch.diag_embed(d).cpu().numpy(), qinv_))).to(device)\n x_norm, _ = x.abs().sum(-2).max(-1)\n\n # test simple analytic whatever norm generated\n mexp = x.matrix_exp()\n mexp_analytic = np.matmul(\n q_,\n np.matmul(\n torch.diag_embed(d.exp()).cpu().numpy(),\n qinv_\n )\n )\n self.assertEqual(mexp, mexp_analytic, atol=1e-3, rtol=0.0)\n\n # generate norms to test different degree expansions\n sample_norms = []\n for i in range(len(thetas) - 1):\n sample_norms.append(0.5 * (thetas[i] + thetas[i + 1]))\n sample_norms = [thetas[0] / 2] + sample_norms + [thetas[-1] * 2]\n\n # matrices to equal norm\n for sample_norm in sample_norms:\n x_normalized = normalize_to_1_operator_norm(x, sample_norm)\n\n mexp = x_normalized.matrix_exp()\n mexp_analytic = np.matmul(\n q_,\n np.matmul(\n torch.diag_embed((d / x_norm.unsqueeze(-1) * sample_norm).exp()).cpu().numpy(),\n qinv_\n )\n )\n self.assertEqual(mexp, mexp_analytic, atol=1e-3, rtol=0.0)\n\n # single matrix\n run_test(2, 2)\n run_test(3, 3)\n run_test(4, 4)\n run_test(5, 5)\n run_test(100, 100)\n run_test(200, 200)\n\n # small batch of matrices\n run_test(3, 2, 2)\n run_test(3, 3, 3)\n run_test(3, 4, 4)\n run_test(3, 5, 5)\n run_test(3, 100, 100)\n run_test(3, 200, 200)\n\n # large batch of matrices\n run_test(3, 3, 2, 2)\n run_test(3, 3, 3, 3)\n run_test(3, 3, 4, 4)\n run_test(3, 3, 5, 5)\n run_test(3, 3, 100, 100)\n run_test(3, 3, 200, 200)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double)\n def test_matrix_exp_batch(self, device, dtype):\n\n def run_test(*n):\n tensors_batch = torch.zeros(n, dtype=dtype, device=device)\n tensors_batch = tensors_batch.view(-1, n[-2], n[-1])\n\n num_matrices = tensors_batch.size(0)\n tensors_list = []\n for i in range(num_matrices):\n tensors_list.append(torch.randn(n[-2], n[-1], dtype=dtype, device=device))\n\n for i in range(num_matrices):\n tensors_batch[i, ...] = tensors_list[i]\n\n tensors_exp_map = (x.matrix_exp() for x in tensors_list)\n tensors_exp_batch = tensors_batch.matrix_exp()\n\n for i, tensor_exp in enumerate(tensors_exp_map):\n self.assertEqual(tensors_exp_batch[i, ...], tensor_exp)\n\n # small batch of matrices\n run_test(3, 2, 2)\n run_test(3, 3, 3)\n run_test(3, 4, 4)\n run_test(3, 5, 5)\n\n # large batch of matrices\n run_test(3, 3, 2, 2)\n run_test(3, 3, 3, 3)\n run_test(3, 3, 4, 4)\n run_test(3, 3, 5, 5)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_matrix_exp_compare_with_taylor(self, device, dtype):\n\n def normalize_to_1_operator_norm(sample, desired_norm):\n sample_norm, _ = sample.abs().sum(-2).max(-1)\n sample_to_1_norm = sample / sample_norm.unsqueeze(-1).unsqueeze(-1)\n return sample_to_1_norm * desired_norm\n\n def gen_good_cond_number_matrices(*n):\n \"\"\"\n Generates a diagonally-domimant matrix\n with the eigenvalues centered at 1\n and the radii at most (n[-1] - 1) / (n[-2] ** 2)\n \"\"\"\n identity = torch.eye(n[-2], n[-1], dtype=dtype, device=device).expand(*n)\n x = torch.rand(*n, dtype=dtype, device=device) / (n[-1] ** 2)\n x = (x - x * identity) + identity\n return x\n\n def get_taylor_approximation(a, deg):\n a_ = a.cpu().numpy()\n identity = torch.eye(a.size(-2), a.size(-1), dtype=dtype, device=device).expand_as(a)\n res = identity.cpu().numpy()\n taylor_term = identity.cpu().numpy()\n\n for i in range(1, deg + 1):\n taylor_term = np.matmul(a_, taylor_term) / i\n res = res + taylor_term\n\n return res\n\n def scale_square(a, deg):\n if a.abs().pow(2).sum().sqrt() < 1.0:\n return get_taylor_approximation(a, 12)\n else:\n s = int(torch.log2(a.abs().pow(2).sum().sqrt()).ceil().item())\n b = a / (2 ** s)\n b = get_taylor_approximation(b, 18)\n for _ in range(s):\n b = np.matmul(b, b)\n return torch.from_numpy(b).to(a.device)\n\n def run_test(*n):\n degs = [1, 2, 4, 8, 12, 18]\n if dtype == torch.float:\n thetas = [\n 1.192092800768788e-07, # deg 1\n 5.978858893805233e-04, # deg 2\n 5.116619363445086e-02, # deg 4\n 5.800524627688768e-01, # deg 8\n 1.461661507209034e+00, # deg 12\n 3.010066362817634e+00 # deg 18\n ]\n else: # if torch.double\n thetas = [\n 2.220446049250313e-16, # deg 1\n 2.580956802971767e-08, # deg 2\n 3.397168839976962e-04, # deg 4\n 4.991228871115323e-02, # deg 8\n 2.996158913811580e-01, # deg 12\n 1.090863719290036e+00 # deg 18\n ]\n\n # generate norms to test different degree expansions\n sample_norms = []\n for i in range(len(thetas) - 1):\n sample_norms.append(0.5 * (thetas[i] + thetas[i + 1]))\n sample_norms = [thetas[0] / 2] + sample_norms + [thetas[-1] * 2]\n degs = [degs[0]] + degs\n\n for sample_norm, deg in zip(sample_norms, degs):\n x = gen_good_cond_number_matrices(*n)\n x = normalize_to_1_operator_norm(x, sample_norm)\n\n mexp = x.matrix_exp()\n mexp_taylor = scale_square(x, deg)\n\n self.assertEqual(mexp, mexp_taylor, atol=1e-2, rtol=0.0)\n\n # single matrix\n run_test(2, 2)\n run_test(3, 3)\n run_test(4, 4)\n run_test(5, 5)\n\n # small batch of matrices\n run_test(3, 2, 2)\n run_test(3, 3, 3)\n run_test(3, 4, 4)\n run_test(3, 5, 5)\n\n # large batch of matrices\n run_test(3, 3, 2, 2)\n run_test(3, 3, 3, 3)\n run_test(3, 3, 4, 4)\n run_test(3, 3, 5, 5)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_slogdet(self, device, dtype):\n from torch.testing._internal.common_utils import (random_hermitian_matrix, random_hermitian_psd_matrix,\n random_hermitian_pd_matrix, random_square_matrix_of_rank)\n\n # mat_chars denotes matrix characteristics\n # possible values are: hermitian, hermitian_psd, hermitian_pd, singular, non_singular\n def run_test(matsize, batchdims, mat_chars):\n num_matrices = np.prod(batchdims)\n list_of_matrices = []\n if num_matrices != 0:\n for idx in range(num_matrices):\n mat_type = idx % len(mat_chars)\n if mat_chars[mat_type] == 'hermitian':\n list_of_matrices.append(random_hermitian_matrix(matsize, dtype=dtype, device=device))\n elif mat_chars[mat_type] == 'hermitian_psd':\n list_of_matrices.append(random_hermitian_psd_matrix(matsize, dtype=dtype, device=device))\n elif mat_chars[mat_type] == 'hermitian_pd':\n list_of_matrices.append(random_hermitian_pd_matrix(matsize, dtype=dtype, device=device))\n elif mat_chars[mat_type] == 'singular':\n list_of_matrices.append(torch.ones(matsize, matsize, dtype=dtype, device=device))\n elif mat_chars[mat_type] == 'non_singular':\n list_of_matrices.append(random_square_matrix_of_rank(matsize, matsize, dtype=dtype, device=device))\n full_tensor = torch.stack(list_of_matrices, dim=0).reshape(batchdims + (matsize, matsize))\n else:\n full_tensor = torch.randn(*batchdims, matsize, matsize, dtype=dtype, device=device)\n\n actual_value = torch.linalg.slogdet(full_tensor)\n expected_value = np.linalg.slogdet(full_tensor.cpu().numpy())\n self.assertEqual(expected_value[0], actual_value[0], atol=self.precision, rtol=self.precision)\n self.assertEqual(expected_value[1], actual_value[1], atol=self.precision, rtol=self.precision)\n\n # test out=variant\n sign_out = torch.empty_like(actual_value[0])\n logabsdet_out = torch.empty_like(actual_value[1])\n ans = torch.linalg.slogdet(full_tensor, out=(sign_out, logabsdet_out))\n self.assertEqual(ans[0], sign_out)\n self.assertEqual(ans[1], logabsdet_out)\n self.assertEqual(sign_out, actual_value[0])\n self.assertEqual(logabsdet_out, actual_value[1])\n\n for matsize, batchdims in itertools.product([0, 3, 5], [(0,), (3,), (5, 3)]):\n run_test(matsize, batchdims, mat_chars=['hermitian_pd'])\n run_test(matsize, batchdims, mat_chars=['singular'])\n run_test(matsize, batchdims, mat_chars=['non_singular'])\n run_test(matsize, batchdims, mat_chars=['hermitian', 'hermitian_pd', 'hermitian_psd'])\n run_test(matsize, batchdims, mat_chars=['singular', 'non_singular'])\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_slogdet_errors_and_warnings(self, device, dtype):\n # slogdet requires the input to be a square matrix or batch of square matrices\n a = torch.randn(2, 3, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, r'must be batches of square matrices'):\n torch.linalg.slogdet(a)\n\n # slogdet requires the input to be at least 2 dimensional tensor\n a = torch.randn(2, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, r'must have at least 2 dimensions'):\n torch.linalg.slogdet(a)\n\n # slogdet requires the input to be of float, double, cfloat or cdouble types\n a = torch.randn(2, 2, device=device, dtype=torch.bfloat16)\n with self.assertRaisesRegex(RuntimeError, r'of float, double, cfloat or cdouble types'):\n torch.linalg.slogdet(a)\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = torch.randn(2, 3, 3, device=device, dtype=dtype)\n sign_out = torch.empty(1, device=device, dtype=dtype)\n real_dtype = a.real.dtype if dtype.is_complex else dtype\n logabsdet_out = torch.empty(1, device=device, dtype=real_dtype)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.linalg.slogdet(a, out=(sign_out, logabsdet_out))\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n sign_out = torch.empty_like(a).to(torch.int)\n logabsdet_out = torch.empty_like(a).to(torch.int)\n with self.assertRaisesRegex(RuntimeError, \"but got sign with dtype Int\"):\n torch.linalg.slogdet(a, out=(sign_out, logabsdet_out))\n\n sign_out = torch.empty(0, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"but got logabsdet with dtype Int\"):\n torch.linalg.slogdet(a, out=(sign_out, logabsdet_out))\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n sign_out = torch.empty(0, device=wrong_device, dtype=dtype)\n logabsdet_out = torch.empty(0, device=wrong_device, dtype=real_dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.linalg.slogdet(a, out=(sign_out, logabsdet_out))\n\n @slowTest\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double)\n def test_det_logdet_slogdet(self, device, dtype):\n def reference_slogdet(M):\n sdet, logabsdet = np.linalg.slogdet(M.detach().cpu().numpy())\n return M.new_tensor(sdet), M.new_tensor(logabsdet)\n\n def test_single_det(M, target, desc):\n target_sdet, target_logabsdet = target\n\n det = M.det()\n logdet = M.logdet()\n sdet, logabsdet = M.slogdet()\n linalg_sdet, linalg_logabsdet = torch.linalg.slogdet(M)\n\n # Test det\n self.assertEqual(det, target_sdet * target_logabsdet.exp(),\n atol=1e-7, rtol=0, msg='{} (det)'.format(desc))\n\n # Test slogdet\n # Compare the overall value rather than individual parts because of\n # precision issues when det is near zero.\n self.assertEqual(sdet * logabsdet.exp(), target_sdet * target_logabsdet.exp(),\n atol=1e-7, rtol=0, msg='{} (slogdet)'.format(desc))\n self.assertEqual(linalg_sdet * linalg_logabsdet.exp(), target_sdet * target_logabsdet.exp(),\n atol=1e-7, rtol=0, msg='{} (linalg_slogdet)'.format(desc))\n\n # Test logdet\n # Compare logdet against our own pytorch slogdet because they should\n # be consistent, while it may behave slightly differently with other\n # slogdet implementations when det is near zero due to precision\n # issues.\n if sdet.item() < 0:\n self.assertTrue(logdet.item() != logdet.item(), '{} (logdet negative case)'.format(desc))\n else:\n self.assertEqual(logdet.exp(), target_logabsdet.exp(),\n atol=1e-7, rtol=0, msg='{} (logdet non-negative case)'.format(desc))\n\n eye = torch.eye(5, dtype=dtype, device=device)\n test_single_det(eye, (torch.ones((), dtype=dtype, device=device), torch.zeros((), dtype=dtype, device=device)), 'identity')\n # Testing bug in #34061 (https://github.com/pytorch/pytorch/issues/34061)\n for n in range(250, 551, 100):\n mat = torch.randn(n, n, dtype=dtype, device=device)\n q, _ = torch.qr(mat)\n ref_det, ref_logabsdet = reference_slogdet(q)\n test_single_det(q, (ref_det, ref_logabsdet), 'orthogonal')\n\n def test(M):\n assert M.size(0) >= 5, 'this helper fn assumes M to be at least 5x5'\n M = M.to(device)\n\n ref_M_sdet, ref_M_logabsdet = reference_slogdet(M)\n\n test_single_det(M, (ref_M_sdet, ref_M_logabsdet), 'basic')\n if ref_M_logabsdet.exp().item() >= 1e-6: # skip singular\n M_inv = M.inverse()\n test_single_det(M_inv, reference_slogdet(M_inv), 'inverse')\n\n test_single_det(M, (ref_M_sdet, ref_M_logabsdet), 'transpose')\n\n for x in [0, 2, 4]:\n for scale in [-2, -0.1, 0, 10]:\n if scale > 0:\n target = ref_M_sdet, ref_M_logabsdet + math.log(scale)\n elif scale == 0:\n target = torch.zeros_like(ref_M_sdet), torch.full_like(ref_M_logabsdet, -inf)\n else:\n target = ref_M_sdet.neg(), ref_M_logabsdet + math.log(-scale)\n\n # dim 0\n M_clone = M.clone()\n M_clone[:, x] *= scale\n test_single_det(M_clone, target, 'scale a row')\n # dim 1\n M_clone = M.clone()\n M_clone[x, :] *= scale\n test_single_det(M_clone, target, 'scale a column')\n\n for x1, x2 in [(0, 3), (4, 1), (3, 2)]:\n assert x1 != x2, 'x1 and x2 needs to be different for this test'\n target = torch.zeros_like(ref_M_sdet), torch.full_like(ref_M_logabsdet, -inf)\n # dim 0\n M_clone = M.clone()\n M_clone[:, x2] = M_clone[:, x1]\n test_single_det(M_clone, target, 'two rows are same')\n # dim 1\n M_clone = M.clone()\n M_clone[x2, :] = M_clone[x1, :]\n test_single_det(M_clone, target, 'two columns are same')\n\n for scale1, scale2 in [(0.3, -1), (0, 2), (10, 0.1)]:\n det_scale = scale1 * scale2 * -1\n if det_scale > 0:\n target = ref_M_sdet, ref_M_logabsdet + math.log(det_scale)\n elif det_scale == 0:\n target = torch.zeros_like(ref_M_sdet), torch.full_like(ref_M_logabsdet, -inf)\n else:\n target = ref_M_sdet.neg(), ref_M_logabsdet + math.log(-det_scale)\n\n # dim 0\n M_clone = M.clone()\n t = M_clone[:, x1] * scale1\n M_clone[:, x1] += M_clone[:, x2] * scale2\n M_clone[:, x2] = t\n test_single_det(M_clone, target, 'exchanging rows')\n # dim 1\n M_clone = M.clone()\n t = M_clone[x1, :] * scale1\n M_clone[x1, :] += M_clone[x2, :] * scale2\n M_clone[x2, :] = t\n test_single_det(M_clone, target, 'exchanging columns')\n\n def get_random_mat_scale(n):\n # For matrices with values i.i.d. with 0 mean, unit variance, and\n # subexponential tail, we have:\n # E[log det(A^2)] \\approx log((n-1)!)\n #\n # Notice:\n # log Var[det(A)] = log E[det(A^2)] >= E[log det(A^2)]\n #\n # So:\n # stddev[det(A)] >= sqrt( (n-1)! )\n #\n # We use this as an intuitive guideline to scale random generated\n # matrices so our closeness tests can work more robustly:\n # scale by sqrt( (n-1)! )^(-1/n) = ( (n-1)! )^(-1/(2n))\n #\n # source: https://arxiv.org/pdf/1112.0752.pdf\n\n # TODO: technically we need subexponential distn for this to hold,\n # but we mostly use gaussian entries below. Consider switching\n # to Chi-sq if this turns out not stable enough, since Chi-sq\n # is easy enough to sample from.\n return math.factorial(n - 1) ** (-1.0 / (2 * n))\n\n for n in [5, 10, 25]:\n scale = get_random_mat_scale(n)\n test(torch.randn(n, n, dtype=dtype, device=device) * scale)\n r = torch.randn(n, n, dtype=dtype, device=device) * scale\n # symmetric psd\n test(r.mm(r.t()))\n # symmetric pd\n r = torch.randn(n, n, dtype=dtype, device=device) * scale\n test(r.mm(r.t()) + torch.eye(n, dtype=dtype, device=device) * 1e-6)\n # symmetric\n r = torch.randn(n, n, dtype=dtype, device=device) * scale\n for i in range(n):\n for j in range(i):\n r[i, j] = r[j, i]\n test(r)\n # non-contiguous\n test((torch.randn(n, n, n + 1, dtype=dtype, device=device) * scale)[:, 2, 1:])\n # det = 0\n r = torch.randn(n, n, dtype=dtype, device=device) * scale\n u, s, v = r.svd()\n if reference_slogdet(u)[0] < 0:\n u = -u\n if reference_slogdet(v)[0] < 0:\n v = -v\n s[0] *= -1\n s[-1] = 0\n test(u.mm(s.diag()).mm(v))\n\n # Small values to test numerical stability. Note that we don't scale\n # this matrix.\n r = torch.randn(512, 512, dtype=dtype, device=device)\n u, s, v = r.svd()\n s.fill_(1. / (100 * s.numel()))\n test(u.mm(s.diag()).mm(v))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double)\n def test_det_logdet_slogdet_batched(self, device, dtype):\n from torch.testing._internal.common_utils import (random_symmetric_matrix, random_symmetric_psd_matrix,\n random_symmetric_pd_matrix, random_square_matrix_of_rank)\n\n # mat_chars denotes matrix characteristics\n # possible values are: sym, sym_psd, sym_pd, sing, non_sym\n def run_test(matsize, batchdims, mat_chars):\n num_matrices = reduce(lambda x, y: x * y, batchdims, 1)\n list_of_matrices = []\n\n for idx in range(num_matrices):\n mat_type = idx % len(mat_chars)\n if mat_chars[mat_type] == 'sym':\n list_of_matrices.append(random_symmetric_matrix(matsize, dtype=dtype, device=device))\n elif mat_chars[mat_type] == 'sym_psd':\n list_of_matrices.append(random_symmetric_psd_matrix(matsize, dtype=dtype, device=device))\n elif mat_chars[mat_type] == 'sym_pd':\n list_of_matrices.append(random_symmetric_pd_matrix(matsize, dtype=dtype, device=device))\n elif mat_chars[mat_type] == 'sing':\n list_of_matrices.append(torch.ones(matsize, matsize, dtype=dtype, device=device))\n elif mat_chars[mat_type] == 'non_sing':\n list_of_matrices.append(random_square_matrix_of_rank(matsize, matsize, dtype=dtype, device=device))\n full_tensor = torch.stack(list_of_matrices, dim=0).reshape(batchdims + (matsize, matsize))\n # Scaling adapted from `get_random_mat_scale` in _test_det_logdet_slogdet\n full_tensor *= (math.factorial(matsize - 1) ** (-1.0 / (2 * matsize)))\n\n for fn in [torch.det, torch.logdet, torch.slogdet, torch.linalg.slogdet]:\n expected_value = []\n actual_value = fn(full_tensor)\n for full_idx in itertools.product(*map(lambda x: list(range(x)), batchdims)):\n expected_value.append(fn(full_tensor[full_idx]))\n\n if fn == torch.slogdet or fn == torch.linalg.slogdet:\n sign_value = torch.stack([tup[0] for tup in expected_value], dim=0).reshape(batchdims)\n expected_value = torch.stack([tup[1] for tup in expected_value], dim=0).reshape(batchdims)\n self.assertEqual(sign_value, actual_value[0])\n self.assertEqual(expected_value, actual_value[1])\n else:\n expected_value = torch.stack(expected_value, dim=0).reshape(batchdims)\n self.assertEqual(actual_value, expected_value)\n\n for matsize, batchdims in itertools.product([3, 5], [(3,), (5, 3)]):\n run_test(matsize, batchdims, mat_chars=['sym_pd'])\n run_test(matsize, batchdims, mat_chars=['sing'])\n run_test(matsize, batchdims, mat_chars=['non_sing'])\n run_test(matsize, batchdims, mat_chars=['sym', 'sym_pd', 'sym_psd'])\n run_test(matsize, batchdims, mat_chars=['sing', 'non_sing'])\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky_inverse(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n def run_test(shape, batch, upper, contiguous):\n A = random_hermitian_pd_matrix(shape, *batch, dtype=dtype, device=device)\n if A.numel() > 0 and not contiguous:\n A = A.transpose(-2, -1)\n self.assertFalse(A.is_contiguous())\n L = torch.linalg.cholesky(A)\n expected_inverse = torch.inverse(A)\n L = L.conj().transpose(-2, -1) if upper else L\n actual_inverse = torch.cholesky_inverse(L, upper)\n self.assertEqual(actual_inverse, expected_inverse)\n\n shapes = (0, 3, 5)\n batches = ((), (0,), (3, ), (2, 2))\n for shape, batch, upper, contiguous in list(itertools.product(shapes, batches, (True, False), (True, False))):\n run_test(shape, batch, upper, contiguous)\n\n # check the out= variant\n A = random_hermitian_pd_matrix(3, 2, dtype=dtype, device=device)\n L = torch.linalg.cholesky(A)\n\n # There are two code paths currently for the out= variant\n # 1. When 'out' tensor is in Fortran (column-major) memory format\n # then the fast route is taken and the storage is reused directly in the computations\n # 2. When 'out' tensor is not in Fortran format then a temporary tensor is allocated internally\n # and the result is copied from the temporary tensor to 'out' tensor\n\n # This test checks the first code path\n out = torch.empty_like(A)\n out_t = out.transpose(-2, -1).clone(memory_format=torch.contiguous_format)\n out = out_t.transpose(-2, -1)\n ans = torch.cholesky_inverse(L, out=out)\n self.assertEqual(ans, out)\n expected = torch.inverse(A)\n self.assertEqual(expected, out)\n\n # This test checks the second code path\n out = torch.empty_like(A)\n ans = torch.cholesky_inverse(L, out=out)\n self.assertEqual(ans, out)\n expected = torch.inverse(A)\n self.assertEqual(expected, out)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_cholesky_inverse_errors_and_warnings(self, device, dtype):\n # cholesky_inverse requires the input to be at least 2 dimensional tensor\n a = torch.randn(2, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"must have at least 2 dimensions\"):\n torch.cholesky_inverse(a)\n\n # cholesky_inverse requires a square matrix\n a = torch.randn(2, 3, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"must be batches of square matrices\"):\n torch.cholesky_inverse(a)\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = torch.randn(3, 3, device=device, dtype=dtype)\n out = torch.empty(2, 3, device=device, dtype=dtype)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.cholesky_inverse(a, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out = torch.empty(*a.shape, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.cholesky_inverse(a, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, device=wrong_device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"Expected all tensors to be on the same device\"):\n torch.cholesky_inverse(a, out=out)\n\n # cholesky_inverse raises an error for invalid inputs on CPU\n # for example if at least one diagonal element is zero\n a = torch.randn(3, 3, device=device, dtype=dtype)\n a[1, 1] = 0\n if self.device_type == 'cpu':\n with self.assertRaisesRegex(RuntimeError, r\"cholesky_inverse: U\\(2,2\\) is zero, singular U\\.\"):\n torch.cholesky_inverse(a)\n # cholesky_inverse on GPU does not raise an error for this case\n elif self.device_type == 'cuda':\n out = torch.cholesky_inverse(a)\n self.assertTrue(out.isinf().any() or out.isnan().any())\n\n def _select_broadcastable_dims(self, dims_full=None):\n # select full dimensionality\n if dims_full is None:\n dims_full = []\n ndims = random.randint(1, 4)\n dims_full = [random.randint(1, 8) for _ in range(ndims)]\n else:\n ndims = len(dims_full)\n\n # select actual dimensions for ops:\n # larger: full ndims, individual sizes may be reduced\n # smaller: possibly reduced ndims, sizes may be reduced\n smaller_ndims = random.randint(1, ndims)\n dims_small = []\n dims_large = []\n for i in range(ndims - 1, -1, -1):\n j = random.randint(1, 3)\n if j == 1: # no reduced singleton dimension\n ds = dims_full[i]\n dl = dims_full[i]\n elif j == 2: # larger may have reduced singleton dimension\n ds = dims_full[i]\n dl = 1 if len(dims_small) < smaller_ndims else dims_full[i]\n elif j == 3: # smaller may have reduced singleton dimension\n ds = 1\n dl = dims_full[i]\n dims_large = [dl] + dims_large\n if len(dims_small) < smaller_ndims:\n dims_small = [ds] + dims_small\n return (dims_small, dims_large, dims_full)\n\n def test_broadcast_fused_matmul(self, device):\n fns = [\"baddbmm\", \"addbmm\", \"addmm\", \"addmv\", \"addr\"]\n\n for fn in fns:\n batch_dim = random.randint(1, 8)\n n_dim = random.randint(1, 8)\n m_dim = random.randint(1, 8)\n p_dim = random.randint(1, 8)\n\n def dims_full_for_fn():\n if fn == \"baddbmm\":\n return ([batch_dim, n_dim, p_dim], [batch_dim, n_dim, m_dim], [batch_dim, m_dim, p_dim])\n elif fn == \"addbmm\":\n return ([n_dim, p_dim], [batch_dim, n_dim, m_dim], [batch_dim, m_dim, p_dim])\n elif fn == \"addmm\":\n return ([n_dim, p_dim], [n_dim, m_dim], [m_dim, p_dim])\n elif fn == \"addmv\":\n return ([n_dim], [n_dim, m_dim], [m_dim])\n elif fn == \"addr\":\n return ([n_dim, m_dim], [n_dim], [m_dim])\n else:\n raise AssertionError(\"unknown function\")\n\n (t0_dims_full, t1_dims, t2_dims) = dims_full_for_fn()\n (t0_dims_small, _, _) = self._select_broadcastable_dims(t0_dims_full)\n\n t0_small = torch.randn(*t0_dims_small, device=device).float()\n t1 = torch.randn(*t1_dims, device=device).float()\n t2 = torch.randn(*t2_dims, device=device).float()\n\n t0_full = t0_small.expand(*t0_dims_full).to(device)\n\n fntorch = getattr(torch, fn)\n r0 = fntorch(t0_small, t1, t2)\n r1 = fntorch(t0_full, t1, t2)\n self.assertEqual(r0, r1)\n\n @tf32_on_and_off(0.001)\n def test_broadcast_batched_matmul(self, device):\n n_dim = random.randint(1, 8)\n m_dim = random.randint(1, 8)\n p_dim = random.randint(1, 8)\n full_batch_dims = [random.randint(1, 3) for i in range(random.randint(1, 3))]\n (batch_dims_small, _, _) = self._select_broadcastable_dims(full_batch_dims)\n\n def verify_batched_matmul(full_lhs, one_dimensional):\n if not one_dimensional:\n lhs_dims = [n_dim, m_dim]\n rhs_dims = [m_dim, p_dim]\n result_dims = [n_dim, p_dim]\n else:\n lhs_dims = [n_dim, m_dim] if full_lhs else [m_dim]\n rhs_dims = [m_dim, p_dim] if not full_lhs else [m_dim]\n result_dims = [n_dim] if full_lhs else [p_dim]\n\n lhs_mat_dims = lhs_dims if len(lhs_dims) != 1 else [1, m_dim]\n rhs_mat_dims = rhs_dims if len(rhs_dims) != 1 else [m_dim, 1]\n full_mat_dims = lhs_mat_dims if full_lhs else rhs_mat_dims\n dim0_dims = rhs_dims if full_lhs else lhs_dims\n small_dims = batch_dims_small + (rhs_mat_dims if full_lhs else lhs_mat_dims)\n\n small = torch.randn(*(small_dims), device=device).float()\n dim0 = torch.randn(*(dim0_dims), device=device).float()\n full = torch.randn(*(full_batch_dims + full_mat_dims), device=device).float()\n if not one_dimensional:\n (lhsTensors, rhsTensors) = ((full,), (small, dim0)) if full_lhs else ((small, dim0), (full,))\n else:\n (lhsTensors, rhsTensors) = ((full,), (dim0,)) if full_lhs else ((dim0,), (full,))\n\n def maybe_squeeze_result(l, r, result):\n if len(lhs_dims) == 1 and l.dim() != 1:\n return result.squeeze(-2)\n elif len(rhs_dims) == 1 and r.dim() != 1:\n return result.squeeze(-1)\n else:\n return result\n\n for lhs in lhsTensors:\n lhs_expanded = lhs.expand(*(torch.Size(full_batch_dims) + torch.Size(lhs_mat_dims)))\n lhs_expanded_matmul_fn = lhs_expanded.matmul\n for rhs in rhsTensors:\n rhs_expanded = ((rhs if len(rhs_dims) != 1 else rhs.unsqueeze(-1)).\n expand(*(torch.Size(full_batch_dims) + torch.Size(rhs_mat_dims))))\n truth = maybe_squeeze_result(lhs_expanded, rhs_expanded, lhs_expanded_matmul_fn(rhs_expanded))\n for l in (lhs, lhs_expanded):\n for r in (rhs, rhs_expanded):\n l_matmul_fn = l.matmul\n result = maybe_squeeze_result(l, r, l_matmul_fn(r))\n self.assertEqual(truth, result)\n # test torch.matmul function as well\n torch_result = maybe_squeeze_result(l, r, torch.matmul(l, r))\n self.assertEqual(truth, torch_result)\n # test torch.matmul with out\n out = torch.zeros_like(torch_result)\n torch.matmul(l, r, out=out)\n self.assertEqual(truth, maybe_squeeze_result(l, r, out))\n\n # compare to bmm\n bmm_result = (torch.bmm(lhs_expanded.contiguous().view(-1, *lhs_mat_dims),\n rhs_expanded.contiguous().view(-1, *rhs_mat_dims)))\n self.assertEqual(truth.view(-1, *result_dims), bmm_result.view(-1, *result_dims))\n\n for indices in itertools.product((True, False), repeat=2):\n verify_batched_matmul(*indices)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_lu_solve_batched_non_contiguous(self, device, dtype):\n from numpy.linalg import solve\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n A = random_fullrank_matrix_distinct_singular_value(2, 2, dtype=dtype, device='cpu')\n b = torch.randn(2, 2, 2, dtype=dtype, device='cpu')\n x_exp = torch.as_tensor(solve(A.permute(0, 2, 1).numpy(), b.permute(2, 1, 0).numpy())).to(device)\n A = A.to(device).permute(0, 2, 1)\n b = b.to(device).permute(2, 1, 0)\n assert not A.is_contiguous() and not b.is_contiguous(), \"contiguous inputs\"\n LU_data, LU_pivots = torch.lu(A)\n x = torch.lu_solve(b, LU_data, LU_pivots)\n self.assertEqual(x, x_exp)\n\n def lu_solve_test_helper(self, A_dims, b_dims, pivot, device, dtype):\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n b = torch.randn(*b_dims, dtype=dtype, device=device)\n A = random_fullrank_matrix_distinct_singular_value(*A_dims, dtype=dtype).to(device)\n LU_data, LU_pivots, info = torch.lu(A, get_infos=True, pivot=pivot)\n self.assertEqual(info, torch.zeros_like(info))\n return b, A, LU_data, LU_pivots\n\n @skipCPUIfNoLapack\n @skipCUDAIfNoMagma\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_lu_solve(self, device, dtype):\n def sub_test(pivot):\n for k, n in zip([2, 3, 5], [3, 5, 7]):\n b, A, LU_data, LU_pivots = self.lu_solve_test_helper((n,), (n, k), pivot, device, dtype)\n x = torch.lu_solve(b, LU_data, LU_pivots)\n self.assertEqual(b, np.matmul(A.cpu(), x.cpu()))\n\n sub_test(True)\n if self.device_type == 'cuda':\n sub_test(False)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n @precisionOverride({torch.float32: 1e-3, torch.complex64: 1e-3,\n torch.float64: 1e-8, torch.complex128: 1e-8})\n def test_lu_solve_batched(self, device, dtype):\n def sub_test(pivot):\n def lu_solve_batch_test_helper(A_dims, b_dims, pivot):\n b, A, LU_data, LU_pivots = self.lu_solve_test_helper(A_dims, b_dims, pivot, device, dtype)\n x_exp_list = []\n for i in range(b_dims[0]):\n x_exp_list.append(torch.lu_solve(b[i], LU_data[i], LU_pivots[i]))\n x_exp = torch.stack(x_exp_list) # Stacked output\n x_act = torch.lu_solve(b, LU_data, LU_pivots) # Actual output\n self.assertEqual(x_exp, x_act) # Equality check\n Ax = np.matmul(A.cpu(), x_act.cpu())\n self.assertEqual(b, Ax)\n\n for batchsize in [1, 3, 4]:\n lu_solve_batch_test_helper((5, batchsize), (batchsize, 5, 10), pivot)\n\n # Tests tensors with 0 elements\n b = torch.randn(3, 0, 3, dtype=dtype, device=device)\n A = torch.randn(3, 0, 0, dtype=dtype, device=device)\n LU_data, LU_pivots = torch.lu(A)\n self.assertEqual(torch.empty_like(b), b.lu_solve(LU_data, LU_pivots))\n\n sub_test(True)\n if self.device_type == 'cuda':\n sub_test(False)\n\n @slowTest\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_lu_solve_batched_many_batches(self, device, dtype):\n def run_test(A_dims, b_dims):\n b, A, LU_data, LU_pivots = self.lu_solve_test_helper(A_dims, b_dims, True, device, dtype)\n x = torch.lu_solve(b, LU_data, LU_pivots)\n Ax = torch.matmul(A, x)\n self.assertEqual(Ax, b.expand_as(Ax))\n\n run_test((5, 65536), (65536, 5, 10))\n run_test((5, 262144), (262144, 5, 10))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_lu_solve_batched_broadcasting(self, device, dtype):\n from numpy.linalg import solve\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n def run_test(A_dims, b_dims, pivot=True):\n A_matrix_size = A_dims[-1]\n A_batch_dims = A_dims[:-2]\n A = random_fullrank_matrix_distinct_singular_value(A_matrix_size, *A_batch_dims, dtype=dtype)\n b = torch.randn(*b_dims, dtype=dtype)\n x_exp = torch.as_tensor(solve(A.numpy(), b.numpy())).to(dtype=dtype, device=device)\n A, b = A.to(device), b.to(device)\n LU_data, LU_pivots = torch.lu(A, pivot=pivot)\n x = torch.lu_solve(b, LU_data, LU_pivots)\n self.assertEqual(x, x_exp)\n\n # test against numpy.linalg.solve\n run_test((2, 1, 3, 4, 4), (2, 1, 3, 4, 6)) # no broadcasting\n run_test((2, 1, 3, 4, 4), (4, 6)) # broadcasting b\n run_test((4, 4), (2, 1, 3, 4, 2)) # broadcasting A\n run_test((1, 3, 1, 4, 4), (2, 1, 3, 4, 5)) # broadcasting A & b\n\n @onlyCUDA\n @skipCUDAIfNoMagma\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n # this tests https://github.com/pytorch/pytorch/issues/36921\n def test_lu_solve_large_matrices(self, device, dtype):\n def run_test(A_dims, b_dims):\n b, A, LU_data, LU_pivots = self.lu_solve_test_helper(A_dims, b_dims, True, device, dtype)\n x = torch.lu_solve(b, LU_data, LU_pivots)\n Ax = torch.matmul(A, x)\n self.assertEqual(Ax, b.expand_as(Ax))\n\n run_test((1, 1), (1, 1, 1025))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_lu_solve_out_errors_and_warnings(self, device, dtype):\n # dtypes should be safely castable\n a = torch.eye(2, dtype=dtype, device=device)\n LU_data, LU_pivots = torch.lu(a, pivot=True)\n b = torch.randn(2, 1, dtype=dtype, device=device)\n out = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got result with dtype Int\"):\n torch.lu_solve(b, LU_data, LU_pivots, out=out)\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out = torch.empty(0, dtype=dtype, device=wrong_device)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.lu_solve(b, LU_data, LU_pivots, out=out)\n\n # if out tensor with wrong shape is passed a warning is given\n with warnings.catch_warnings(record=True) as w:\n out = torch.empty(1, dtype=dtype, device=device)\n # Trigger warning\n torch.lu_solve(b, LU_data, LU_pivots, out=out)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n @precisionOverride({torch.float32: 1e-5, torch.complex64: 1e-5})\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_symeig(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_matrix\n\n def run_test(dims, eigenvectors, upper):\n x = random_hermitian_matrix(*dims, dtype=dtype, device=device)\n if dtype.is_complex:\n real_dtype = torch.float32 if dtype is torch.complex64 else torch.float64\n else:\n real_dtype = dtype\n oute = torch.empty(dims[1:] + dims[:1], dtype=real_dtype, device=device)\n outv = torch.empty(dims[1:] + dims[:1] * 2, dtype=dtype, device=device)\n torch.symeig(x, eigenvectors=eigenvectors, upper=upper, out=(oute, outv))\n\n if eigenvectors:\n outv_ = outv.cpu().numpy()\n x_recon = np.matmul(np.matmul(outv_, torch.diag_embed(oute.to(dtype)).cpu().numpy()),\n outv_.swapaxes(-2, -1).conj())\n self.assertEqual(x, x_recon, atol=1e-8, rtol=0, msg='Incorrect reconstruction using V @ diag(e) @ V.T')\n else:\n eigvals, _ = torch.symeig(x, eigenvectors=True, upper=upper)\n self.assertEqual(eigvals, oute, msg='Eigenvalues mismatch')\n self.assertEqual(torch.empty(0, device=device, dtype=dtype), outv, msg='Eigenvector matrix not empty')\n\n rese, resv = x.symeig(eigenvectors=eigenvectors, upper=upper)\n self.assertEqual(rese, oute, msg=\"outputs of symeig and symeig with out don't match\")\n self.assertEqual(resv, outv, msg=\"outputs of symeig and symeig with out don't match\")\n\n # test non-contiguous\n x = random_hermitian_matrix(*dims, dtype=dtype, device=device)\n n_dim = len(dims) + 1\n # Reverse the batch dimensions and the matrix dimensions and then concat them\n x = x.permute(tuple(range(n_dim - 3, -1, -1)) + (n_dim - 1, n_dim - 2))\n assert not x.is_contiguous(), \"x is intentionally non-contiguous\"\n rese, resv = torch.symeig(x, eigenvectors=eigenvectors, upper=upper)\n if eigenvectors:\n resv_ = resv.cpu().numpy()\n x_recon = np.matmul(np.matmul(resv_, torch.diag_embed(rese.to(dtype)).cpu().numpy()),\n resv_.swapaxes(-2, -1).conj())\n self.assertEqual(x, x_recon, atol=1e-8, rtol=0, msg='Incorrect reconstruction using V @ diag(e) @ V.T')\n else:\n eigvals, _ = torch.symeig(x, eigenvectors=True, upper=upper)\n self.assertEqual(eigvals, rese, msg='Eigenvalues mismatch')\n self.assertEqual(torch.empty(0, device=device, dtype=dtype), resv, msg='Eigenvector matrix not empty')\n\n batch_dims_set = [(), (3,), (3, 5), (5, 3, 5)]\n for batch_dims, eigenvectors, upper in itertools.product(batch_dims_set, (True, False), (True, False)):\n run_test((5,) + batch_dims, eigenvectors, upper)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_symeig_out_errors_and_warnings(self, device, dtype):\n from torch.testing._internal.common_utils import random_hermitian_matrix\n\n # if non-empty out tensor with wrong shape is passed a warning is given\n a = random_hermitian_matrix(3, dtype=dtype, device=device)\n real_dtype = a.real.dtype if dtype.is_complex else dtype\n out_w = torch.empty(7, 7, dtype=real_dtype, device=device)\n out_v = torch.empty(7, 7, dtype=dtype, device=device)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n torch.symeig(a, out=(out_w, out_v))\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-2].message))\n self.assertTrue(\"An output with one or more elements was resized\" in str(w[-1].message))\n\n # dtypes should be safely castable\n out_w = torch.empty(0, dtype=real_dtype, device=device)\n out_v = torch.empty(0, dtype=torch.int, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got eigenvectors with dtype Int\"):\n torch.symeig(a, out=(out_w, out_v))\n\n out_w = torch.empty(0, dtype=torch.int, device=device)\n out_v = torch.empty(0, dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, \"but got eigenvalues with dtype Int\"):\n torch.symeig(a, out=(out_w, out_v))\n\n # device should match\n if torch.cuda.is_available():\n wrong_device = 'cpu' if self.device_type != 'cpu' else 'cuda'\n out_w = torch.empty(0, device=wrong_device, dtype=dtype)\n out_v = torch.empty(0, device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.symeig(a, out=(out_w, out_v))\n out_w = torch.empty(0, device=device, dtype=dtype)\n out_v = torch.empty(0, device=wrong_device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, \"tensors to be on the same device\"):\n torch.symeig(a, out=(out_w, out_v))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n def test_pca_lowrank(self, device):\n from torch.testing._internal.common_utils import random_lowrank_matrix, random_sparse_matrix\n\n dtype = torch.double\n\n def run_subtest(guess_rank, actual_rank, matrix_size, batches, device, pca, **options):\n density = options.pop('density', 1)\n if isinstance(matrix_size, int):\n rows = columns = matrix_size\n else:\n rows, columns = matrix_size\n if density == 1:\n a_input = random_lowrank_matrix(actual_rank, rows, columns, *batches, device=device, dtype=dtype)\n a = a_input\n else:\n a_input = random_sparse_matrix(rows, columns, density, device=device, dtype=dtype)\n a = a_input.to_dense()\n\n u, s, v = pca(a_input, q=guess_rank, **options)\n\n self.assertEqual(s.shape[-1], guess_rank)\n self.assertEqual(u.shape[-2], rows)\n self.assertEqual(u.shape[-1], guess_rank)\n self.assertEqual(v.shape[-1], guess_rank)\n self.assertEqual(v.shape[-2], columns)\n\n A1 = u.matmul(s.diag_embed()).matmul(v.transpose(-2, -1))\n ones_m1 = torch.ones(batches + (rows, 1), dtype=a.dtype, device=device)\n c = a.sum(axis=-2) / rows\n c = c.reshape(batches + (1, columns))\n A2 = a - ones_m1.matmul(c)\n self.assertEqual(A1, A2)\n\n if density == 1:\n # actual rank is known only for dense input\n detect_rank = (s.abs() > 1e-5).sum(axis=-1)\n self.assertEqual(actual_rank * torch.ones(batches, device=device, dtype=torch.int64), detect_rank)\n S = torch.linalg.svdvals(A2)\n self.assertEqual(s[..., :actual_rank], S[..., :actual_rank])\n\n all_batches = [(), (1,), (3,), (2, 3)]\n for actual_rank, size, all_batches in [\n (2, (17, 4), all_batches),\n (2, (100, 4), all_batches),\n (6, (100, 40), all_batches),\n (12, (1000, 1000), [()]),\n ]:\n for batches in all_batches:\n for guess_rank in [\n actual_rank,\n actual_rank + 2,\n actual_rank + 6,\n ]:\n if guess_rank <= min(*size):\n run_subtest(guess_rank, actual_rank, size, batches, device, torch.pca_lowrank)\n run_subtest(guess_rank, actual_rank, size[::-1], batches, device, torch.pca_lowrank)\n\n # sparse input\n for guess_rank, size in [\n (4, (17, 4)), (4, (4, 17)), (16, (17, 17)),\n (21, (100, 40)), (20, (40, 100)), (600, (1000, 1000))]:\n for density in [0.005, 0.1]:\n run_subtest(guess_rank, None, size, (), device, torch.pca_lowrank, density=density)\n\n # jitting support\n jitted = torch.jit.script(torch.pca_lowrank)\n guess_rank, actual_rank, size, batches = 2, 2, (17, 4), ()\n run_subtest(guess_rank, actual_rank, size, batches, device, jitted)\n\n # Ensure that nuclear_norm's out variant gives the same result as the non-out\n @onlyOnCPUAndCUDA\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64)\n def test_nuclear_norm_out(self, device, dtype):\n test_cases = [\n # input size, dim\n ((25, 25), None),\n ((25, 25), (0, 1)),\n ((25, 25), (1, 0)),\n ((25, 25, 25), (2, 0)),\n ((25, 25, 25), (0, 1)),\n ]\n for keepdim in [False, True]:\n for input_size, dim in test_cases:\n msg = f'input_size: {input_size}, dim: {dim}, keepdim: {keepdim}'\n x = torch.randn(*input_size, device=device, dtype=dtype)\n result_out = torch.empty(0, device=device, dtype=dtype)\n if dim is None:\n result = torch.nuclear_norm(x, keepdim=keepdim)\n torch.nuclear_norm(x, keepdim=keepdim, out=result_out)\n else:\n result = torch.nuclear_norm(x, keepdim=keepdim, dim=dim)\n torch.nuclear_norm(x, keepdim=keepdim, dim=dim, out=result_out)\n self.assertEqual(result, result_out, msg=msg)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128)\n def test_geqrf(self, device, dtype):\n\n def run_test(shape):\n # numpy.linalg.qr with mode = 'raw' computes the same operation as torch.geqrf\n # so this test compares against that function\n A = make_tensor(shape, dtype=dtype, device=device)\n\n # numpy.linalg.qr doesn't work with batched input\n m, n = A.shape[-2:]\n tau_size = \"n\" if m > n else \"m\"\n np_dtype = A.cpu().numpy().dtype\n ot = [np_dtype, np_dtype]\n numpy_geqrf_batched = np.vectorize(\n lambda x: np.linalg.qr(x, mode='raw'),\n otypes=ot,\n signature=f'(m,n)->(n,m),({tau_size})')\n\n expected = numpy_geqrf_batched(A.cpu())\n actual = torch.geqrf(A)\n\n # numpy.linalg.qr returns transposed result\n self.assertEqual(expected[0].swapaxes(-2, -1), actual[0])\n self.assertEqual(expected[1], actual[1])\n\n batches = [(), (0, ), (2, ), (2, 1)]\n ns = [5, 2, 0]\n for batch, (m, n) in product(batches, product(ns, ns)):\n run_test((*batch, m, n))\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n @dtypes(torch.double)\n def test_lstsq(self, device, dtype):\n def _test_underdetermined(a, b, expectedNorm):\n # underdetermined systems are only supported on CPU\n if self.device_type != 'cpu':\n return\n\n m = a.size()[0]\n n = a.size()[1]\n assert(m <= n)\n\n a_copy = a.clone()\n b_copy = b.clone()\n res1 = torch.lstsq(b, a)[0]\n self.assertEqual(a, a_copy, atol=0, rtol=0)\n self.assertEqual(b, b_copy, atol=0, rtol=0)\n self.assertEqual((torch.mm(a, res1) - b).norm(), expectedNorm, atol=1e-8, rtol=0)\n\n ta = torch.tensor((), dtype=dtype, device=device)\n tb = torch.tensor((), dtype=dtype, device=device)\n res2 = torch.lstsq(b, a, out=(tb, ta))[0]\n self.assertEqual(a, a_copy, atol=0, rtol=0)\n self.assertEqual(b, b_copy, atol=0, rtol=0)\n self.assertEqual((torch.mm(a, res1) - b).norm(), expectedNorm, atol=1e-8, rtol=0)\n\n res3 = torch.lstsq(b, a, out=(b, a))[0]\n self.assertEqual((torch.mm(a_copy, b) - b_copy).norm(), expectedNorm, atol=1e-8, rtol=0)\n self.assertEqual(res1, tb, atol=0, rtol=0)\n self.assertEqual(res1, b, atol=0, rtol=0)\n self.assertEqual(res1, res2, atol=0, rtol=0)\n self.assertEqual(res1, res3, atol=0, rtol=0)\n\n def _test_overdetermined(a, b, expectedNorm):\n m = a.size()[0]\n n = a.size()[1]\n assert(m > n)\n\n def check_norm(a, b, expected_norm, gels_result):\n # Checks |ax - b| and the residual info from the result\n\n # The first n rows is the least square solution.\n # Rows n to m-1 contain residual information.\n x = gels_result[:n]\n resid_info = gels_result[n:]\n\n resid_norm = (torch.mm(a, x) - b).norm()\n self.assertEqual(resid_norm, expectedNorm, atol=1e-8, rtol=0)\n self.assertEqual(resid_info.norm(), resid_norm, atol=1e-8, rtol=0)\n\n a_copy = a.clone()\n b_copy = b.clone()\n res1 = torch.lstsq(b, a)[0]\n self.assertEqual(a, a_copy, atol=0, rtol=0)\n self.assertEqual(b, b_copy, atol=0, rtol=0)\n check_norm(a, b, expectedNorm, res1)\n\n ta = torch.tensor((), dtype=dtype, device=device)\n tb = torch.tensor((), dtype=dtype, device=device)\n res2 = torch.lstsq(b, a, out=(tb, ta))[0]\n self.assertEqual(a, a_copy, atol=0, rtol=0)\n self.assertEqual(b, b_copy, atol=0, rtol=0)\n check_norm(a, b, expectedNorm, res2)\n\n res3 = torch.lstsq(b, a, out=(b, a))[0]\n check_norm(a_copy, b_copy, expectedNorm, res3)\n\n self.assertEqual(res1, tb, atol=0, rtol=0)\n self.assertEqual(res1, b, atol=0, rtol=0)\n self.assertEqual(res1, res2, atol=0, rtol=0)\n self.assertEqual(res1, res3, atol=0, rtol=0)\n\n # basic test\n expectedNorm = 0\n a = torch.tensor(((1.44, -9.96, -7.55, 8.34),\n (-7.84, -0.28, 3.24, 8.09),\n (-4.39, -3.24, 6.27, 5.28),\n (4.53, 3.83, -6.64, 2.06)), dtype=dtype, device=device).t()\n b = torch.tensor(((8.58, 8.26, 8.48, -5.28),\n (9.35, -4.43, -0.70, -0.26)), dtype=dtype, device=device).t()\n _test_underdetermined(a, b, expectedNorm)\n\n # test overdetermined\n expectedNorm = 17.390200628863\n a = torch.tensor(((1.44, -9.96, -7.55, 8.34, 7.08, -5.45),\n (-7.84, -0.28, 3.24, 8.09, 2.52, -5.70),\n (-4.39, -3.24, 6.27, 5.28, 0.74, -1.19),\n (4.53, 3.83, -6.64, 2.06, -2.47, 4.70)), dtype=dtype, device=device).t()\n b = torch.tensor(((8.58, 8.26, 8.48, -5.28, 5.72, 8.93),\n (9.35, -4.43, -0.70, -0.26, -7.36, -2.52)), dtype=dtype, device=device).t()\n _test_overdetermined(a, b, expectedNorm)\n\n # test underdetermined\n expectedNorm = 0\n a = torch.tensor(((1.44, -9.96, -7.55),\n (-7.84, -0.28, 3.24),\n (-4.39, -3.24, 6.27),\n (4.53, 3.83, -6.64)), dtype=dtype, device=device).t()\n b = torch.tensor(((8.58, 8.26, 8.48),\n (9.35, -4.43, -0.70)), dtype=dtype, device=device).t()\n _test_underdetermined(a, b, expectedNorm)\n\n # test reuse\n expectedNorm = 0\n a = torch.tensor(((1.44, -9.96, -7.55, 8.34),\n (-7.84, -0.28, 3.24, 8.09),\n (-4.39, -3.24, 6.27, 5.28),\n (4.53, 3.83, -6.64, 2.06)), dtype=dtype, device=device).t()\n b = torch.tensor(((8.58, 8.26, 8.48, -5.28),\n (9.35, -4.43, -0.70, -0.26)), dtype=dtype, device=device).t()\n ta = torch.tensor((), dtype=dtype, device=device)\n tb = torch.tensor((), dtype=dtype, device=device)\n torch.lstsq(b, a, out=(tb, ta))\n self.assertEqual((torch.mm(a, tb) - b).norm(), expectedNorm, atol=1e-8, rtol=0)\n torch.lstsq(b, a, out=(tb, ta))\n self.assertEqual((torch.mm(a, tb) - b).norm(), expectedNorm, atol=1e-8, rtol=0)\n torch.lstsq(b, a, out=(tb, ta))\n self.assertEqual((torch.mm(a, tb) - b).norm(), expectedNorm, atol=1e-8, rtol=0)\n\n @skipCUDAIfNoMagma\n @skipCPUIfNoLapack\n def test_lapack_empty(self, device):\n # FIXME: these are just a selection of LAPACK functions -- we need a general strategy here.\n # The LAPACK functions themselves generally do NOT work with zero sized dimensions, although\n # numpy/sci often has a direct wrapper (e.g. lu_factor) and a wrapper that \"does the right thing\"\n # (e.g. lu). We often name our functions identically to the lapack function, so it will take work\n # to name / migrate-to better wrappers.\n def fn(torchfn, *args):\n return torchfn(*tuple(torch.randn(shape, device=device) if isinstance(shape, tuple) else shape\n for shape in args))\n\n # inverse, pinverse\n self.assertEqual((0, 0), fn(torch.inverse, (0, 0)).shape)\n self.assertEqual((5, 0), fn(torch.pinverse, (0, 5)).shape)\n self.assertEqual((0, 5), fn(torch.pinverse, (5, 0)).shape)\n self.assertEqual((0, 0), fn(torch.pinverse, (0, 0)).shape)\n\n # det, logdet, slogdet\n self.assertEqual(torch.tensor(1., device=device), fn(torch.det, (0, 0)))\n self.assertEqual(torch.tensor(0., device=device), fn(torch.logdet, (0, 0)))\n self.assertEqual((torch.tensor(1., device=device), torch.tensor(0., device=device)),\n fn(torch.slogdet, (0, 0)))\n\n # eig, symeig\n evalues, evectors = fn(torch.eig, (0, 0), True)\n self.assertEqual([(0, 2), (0, 0)], [evalues.shape, evectors.shape])\n evalues, evectors = fn(torch.symeig, (0, 0), True)\n self.assertEqual([(0,), (0, 0)], [evalues.shape, evectors.shape])\n\n # qr\n q, r = fn(torch.qr, (3, 0), True)\n self.assertEqual([(3, 0), (0, 0)], [q.shape, r.shape])\n q, r = fn(torch.qr, (0, 3), True)\n self.assertEqual([(0, 0), (0, 3)], [q.shape, r.shape])\n q, r = fn(torch.qr, (3, 0), False)\n self.assertEqual([(3, 3), (3, 0)], [q.shape, r.shape])\n\n # lstsq\n self.assertRaises(RuntimeError, lambda: torch.lstsq(torch.randn(0, 0), torch.randn(0, 0)))\n self.assertRaises(RuntimeError, lambda: torch.lstsq(torch.randn(0,), torch.randn(0, 0)))\n\n @tf32_on_and_off(0.005)\n def test_tensordot(self, device):\n a = torch.arange(60., device=device).reshape(3, 4, 5)\n b = torch.arange(24., device=device).reshape(4, 3, 2)\n c = torch.tensordot(a, b, dims=([1, 0], [0, 1])).cpu()\n cn = torch.from_numpy(np.tensordot(a.cpu().numpy(), b.cpu().numpy(),\n axes=([1, 0], [0, 1])))\n self.assertEqual(c, cn)\n\n cout = torch.zeros((5, 2), device=device)\n torch.tensordot(a, b, dims=([1, 0], [0, 1]), out=cout).cpu()\n self.assertEqual(c, cout)\n\n a = torch.randn(2, 3, 4, 5, device=device)\n b = torch.randn(4, 5, 6, 7, device=device)\n c = torch.tensordot(a, b, dims=2).cpu()\n cn = torch.from_numpy(np.tensordot(a.cpu().numpy(), b.cpu().numpy(),\n axes=2))\n\n with self.assertRaisesRegex(RuntimeError, \"expects dims >= 0\"):\n torch.tensordot(a, b, dims=-1)\n\n self.assertEqual(c, cn)\n c = torch.tensordot(a, b).cpu()\n cn = torch.from_numpy(np.tensordot(a.cpu().numpy(), b.cpu().numpy()))\n self.assertEqual(c, cn)\n\n a = torch.tensordot(torch.tensor(0.), torch.tensor(0.), 0)\n an = torch.from_numpy(np.tensordot(np.zeros((), dtype=np.float32), np.zeros((), dtype=np.float32), 0))\n self.assertEqual(a, an)\n\n\ninstantiate_device_type_tests(TestLinalg, globals())\n\nif __name__ == '__main__':\n run_tests()\n"
] |
[
[
"torch.cholesky_solve",
"numpy.array_equal",
"torch.promote_types",
"torch.linalg.matrix_power",
"torch.testing.get_all_complex_dtypes",
"torch.lobpcg",
"torch.bmm",
"torch.transpose",
"torch.linalg.cholesky",
"torch.testing._internal.common_device_type.skipCUDAIf",
"torch.testing.get_all_dtypes",
"torch.lu_unpack",
"torch._linalg_utils.qform",
"numpy.prod",
"torch.tensor",
"torch.linalg.matrix_rank",
"torch.cholesky",
"torch.as_strided",
"numpy.linalg.multi_dot",
"torch.full_like",
"numpy.linalg.svd",
"torch.testing._internal.common_device_type.precisionOverride",
"torch.testing._internal.common_device_type.skipCUDAVersionIn",
"torch.testing.all_types",
"torch.symeig",
"torch.linalg.qr",
"torch.from_numpy",
"torch.linalg.cond",
"torch.qr",
"torch.testing._internal.common_utils.run_tests",
"torch.testing._internal.common_utils.random_lowrank_matrix",
"torch.testing._internal.common_utils.random_well_conditioned_matrix",
"torch.svd",
"numpy.lib.NumpyVersion",
"torch.geqrf",
"torch.einsum",
"torch.Tensor.outer",
"torch.inverse",
"torch.linalg.inv_ex",
"torch._linalg_utils.matmul",
"numpy.linalg.qr",
"numpy.linalg.lstsq",
"torch.linalg.inv",
"torch.set_default_dtype",
"torch.sum",
"torch.ger",
"torch.Size",
"numpy.linalg.norm",
"torch.testing._internal.common_utils.random_symmetric_pd_matrix",
"torch.addr",
"torch.testing._internal.common_cuda.tf32_on_and_off",
"torch.randint",
"torch.testing._internal.common_utils.random_hermitian_matrix",
"scipy.sparse.linalg.lobpcg",
"torch.zeros_like",
"torch.zeros",
"torch.lstsq",
"numpy.array",
"torch.device",
"numpy.matmul",
"numpy.zeros",
"torch.eig",
"torch.testing._internal.common_utils.gradgradcheck",
"torch.linalg.householder_product",
"torch.testing._internal.common_utils.random_hermitian_pd_matrix",
"torch.addmv",
"torch.linalg.svdvals",
"torch.cross",
"torch.ormqr",
"numpy.argsort",
"torch.linalg.eig",
"torch.testing._internal.common_utils.random_sparse_pd_matrix",
"torch.matmul",
"torch.lu_solve",
"torch.rand",
"torch.unique",
"torch.linalg.slogdet",
"torch.mv",
"torch.all",
"torch.chain_matmul",
"torch.linalg.norm",
"torch.linalg.eigvalsh",
"torch.diag_embed",
"torch.stack",
"torch.gt",
"torch.testing._internal.common_utils.random_hermitian_psd_matrix",
"torch.testing.make_tensor",
"torch.cholesky_inverse",
"torch.nuclear_norm",
"numpy.outer",
"torch.randint_like",
"torch.pinverse",
"torch.testing._internal.common_device_type.dtypes",
"torch.norm",
"torch.linalg.multi_dot",
"torch.testing._internal.common_utils.random_symmetric_matrix",
"torch.jit.script",
"torch.linalg.tensorsolve",
"torch.testing.floating_types",
"torch.testing._internal.common_utils.random_square_matrix_of_rank",
"torch.linalg.cholesky_ex",
"torch.testing._internal.common_utils.random_fullrank_matrix_distinct_singular_value",
"torch.linalg.pinv",
"numpy.einsum",
"torch.outer",
"torch.linalg.tensorinv",
"torch.tensordot",
"torch.get_default_dtype",
"numpy.linalg.tensorinv",
"torch.testing._internal.common_cuda._get_torch_cuda_version",
"torch.kron",
"torch.addbmm",
"torch.profiler.profile",
"torch.linalg.solve",
"torch.triangular_solve",
"torch.Tensor.ger",
"torch.linalg.eigvals",
"torch.linalg.svd",
"torch.matrix_rank",
"torch.ones",
"torch.cuda.is_available",
"torch.eye",
"torch.result_type",
"numpy.broadcast_to",
"torch.linalg.matrix_norm",
"torch.testing._internal.common_utils.random_symmetric_psd_matrix",
"scipy.linalg.lstsq",
"torch.testing._internal.common_utils.gradcheck",
"torch.testing.get_all_int_dtypes",
"torch.testing._internal.common_utils.random_sparse_matrix",
"torch.inner",
"torch.empty",
"torch.linalg.eigh",
"scipy.sparse.coo_matrix",
"torch._compute_linear_combination",
"torch.testing._internal.common_device_type.dtypesIfCUDA",
"torch.testing._internal.common_utils.iter_indices",
"torch.mm",
"torch.testing.floating_and_complex_types",
"torch.full",
"numpy.take_along_axis",
"torch.testing.get_all_fp_dtypes",
"torch.addmm",
"torch.sort",
"torch.arange",
"torch.linalg.vector_norm",
"torch.distributions.binomial.Binomial",
"torch.lu",
"torch.linalg.lstsq",
"torch.baddbmm",
"torch.solve",
"torch.diag",
"torch.randn",
"torch.empty_like"
]
] |
MahdadJafarzadeh/Zzzscoring
|
[
"f5d22cb7a457412fcc575c5cc6d331286f117dbf"
] |
[
"Zzzscoring_v0.1.6.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 24 00:23:30 2020\n\n@author: mahda\n\n# =============================================================================\n# \n# Copyright (c) 2020 Mahdad Jafarzadeh\n# \n# Zzzscoring: A GUI-based package for sleep scoring!\n# =============================================================================\n\"\"\"\n\nfrom tkinter import LabelFrame, Label, Button, filedialog, messagebox,OptionMenu, StringVar,DoubleVar\nfrom tkinter import *\nimport mne\nimport numpy as np\nfrom numpy import loadtxt\nimport time\nfrom ssccoorriinngg import ssccoorriinngg\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\n\n\nclass Zzzscoring():\n \n def __init__(self, master):\n \n self.master = master\n \n master.title(\"Zzzscoring: Automatic sleep scoring package\")\n \n #### !!~~~~~~~~~~~~~~~~~ DEFINE INPUT DATAFRAME ~~~~~~~~~~~~~~~~~!!####\n \n self.frame_import = LabelFrame(self.master, text = \"Import files section\", padx = 150, pady = 100,\n font = 'Calibri 18 bold')\n self.frame_import.grid(row = 0 , column = 0, padx = 200, pady = 50, columnspan = 8)\n \n \n #### ==================== Help pop-up button ======================####\n \n self.popup_button = Button(self.master, text = \"Help\", command = self.help_pop_up_func,\n font = 'Calibri 13 bold', fg = 'white', bg = 'black')\n self.popup_button.grid(row = 1, column = 8)\n \n #### ==================== Import data EDFs ========================####\n # Label: Import EDF\n self.label_import = Label(self.frame_import, text = \"Import EDF files here:\",\n font = 'Calibri 12 bold')\n self.label_import.grid(row = 0 , column = 0, padx = 15, pady = 10)\n \n # Button: Import EDF (Browse)\n self.button_import_browse = Button(self.frame_import, text = \"Browse data\",\n padx = 100, pady = 20,font = 'Calibri 10 bold',\n command = self.load_data_file_dialog, fg = 'blue',\n relief = RIDGE)\n self.button_import_browse.grid(row = 1, column = 0, padx = 15, pady = 10)\n \n #### ================== Import hypnogram files ====================####\n # Show a message about hypnograms\n self.label_hypnos = Label(self.frame_import, text = \"Import hypnogram file (.txt) here:\",\n font = 'Calibri 12 bold')\n self.label_hypnos.grid(row = 0 , column = 1, padx = 15, pady = 10)\n \n # Define browse button to import hypnos\n self.button_hypnos_browse = Button(self.frame_import, text = \"Browse labels\", \n padx = 100, pady = 20, font = 'Calibri 10 bold',\n command = self.load_hypno_file_dialog,fg = 'blue',\n relief = RIDGE)\n self.button_hypnos_browse.grid(row = 1, column = 1, padx = 15, pady = 10)\n \n #### ===================== Define train size ======================####\n # Define train size section\n self.label_train_size = Label(self.frame_import, text = \"Train size portion (between 0 - 1):\",\n font = 'Calibri 12 bold')\n self.label_train_size.grid(row = 0 , column = 3, padx = 15, pady = 10)\n \n # Bar to ask for user's entry\n self.train_size = DoubleVar()\n self.train_size.set(0.7)\n self.entry_train_size = OptionMenu(self.frame_import, self.train_size, 0.6, 0.7, 0.8, 0.9)\n self.entry_train_size.grid(row = 1, column = 3, padx = 15, pady = 10)\n self.entry_train_size.config(font= 'Calibri 10 bold', fg='black') \n \n #### =================== Push apply to load data ==================####\n #Label to read data and extract features\n self.label_apply = Label(self.frame_import, text = \"Press to Load, pre-process, and extract features!\",\n font = 'Calibri 12 bold')\n self.label_apply.grid(row = 0 , column = 4)\n # Apply button\n self.button_apply = Button(self.frame_import, text = \"Apply\", padx = 100, pady=20,\n font = 'Calibri 10 bold', relief = RIDGE, fg = 'blue',\n command = self.Apply_button)\n self.button_apply.grid(row = 1 , column =4, padx = 15, pady = 10)\n\n #### !!~~~~~~~~~~~~~~ DEFINE ML SECTION FRAME ~~~~~~~~~~~~~~~~~~~!!####\n \n self.frame_ML = LabelFrame(self.master, text = \"Machine Learning Section\",\n padx = 150, pady = 100, font = 'Calibri 18 bold')\n self.frame_ML.grid(row = 1 , column = 0, padx = 200, pady = 50, columnspan = 8)\n \n #### ================ Pick ML Algorithm of interest ===============####\n # Label\n self.label_ML_algorithm = Label(self.frame_ML, text = \"Choose the machine learning algorithm:\",\n font = 'Calibri 12 bold')\n self.label_ML_algorithm.grid(row = 0, column = 0, padx = 15, pady = 10)\n \n # Dropdown menu\n self.selected_ML = StringVar()\n self.selected_ML.set(\"Random forest\")\n self.drop = OptionMenu(self.frame_ML, self.selected_ML, \"SVM\", \"Random forest\",\"XGBoost\",\"Logistic regression\", \"Naive bayes\", \"Randomized trees\",\"GradientBoosting\", \"ADABoost\")\n self.drop.grid(row = 1, column = 0)\n self.drop.config(font= 'Calibri 10 bold', fg='blue') \n \n # label_selec\n self.label_select = Label(self.frame_ML, text = \"Press after choosing ML algorithm:\",\n font = 'Calibri 12 bold')\n self.label_select.grid(row = 0 , column =1)\n \n # select button\n self.button_select = Button(self.frame_ML, text = \"Select!\", padx = 100, pady=20,\n font = 'Calibri 12 bold', relief = RIDGE, fg = 'blue',\n command = self.Select_ML_button)\n self.button_select.grid(row = 1 , column =1, padx = 15, pady = 10) \n \n # Chekbox for time-dependency\n \n self.td_var = IntVar()\n self.checkbox_td = Checkbutton(self.frame_ML, text = \"Multi-to-one classifcation\",\n font = 'Calibri 12 bold', variable = self.td_var)\n \n self.checkbox_td.grid(row = 2, column = 0)\n \n # Chekbox for feature selection\n \n self.feat_select_var = IntVar()\n self.checkbox_feat_select = Checkbutton(self.frame_ML, text = \"Feature Selection\",\n font = 'Calibri 12 bold', variable = self.feat_select_var)\n \n self.checkbox_feat_select.grid(row = 3, column = 0)\n \n\n #%% ################### DEFINE FUNCTIONS OF BUTTONS #######################\n #%% Function: Import EDF (Browse)\n def load_data_file_dialog(self):\n \n global data_files_list\n \n self.filenames = filedialog.askopenfilenames(initialdir= \"C:/\",title = 'select data files', \n filetype = ((\"edf\", \"*.edf\"), (\"All Files\", \"*.*\")))\n \n # Make a list of imported file names (full path)\n data_files_list = self.frame_import.tk.splitlist(self.filenames)\n self.n_data_files = len(data_files_list)\n \n # check if the user chose somthing\n if not data_files_list:\n \n self.label_data = Label(self.frame_import, text = \"No file has been selected!\",\n fg = 'red', font = 'Helvetica 9 bold').grid(row = 2, column = 0)\n \n else:\n self.label_data = Label(self.frame_import, text = str(self.n_data_files) + \" EDF files has been loaded!\",\n fg = 'green', font = 'Helvetica 9 bold').grid(row = 2, column = 0)\n \n #%% Function: Import Hypnogram (Browse)\n def load_hypno_file_dialog(self):\n \n global hypno_files_list\n \n self.filenames = filedialog.askopenfilenames(initialdir= \"C:/\",title = 'select label files', \n filetype = ((\"txt\", \"*.txt\"),(\"csv\", \"*.csv\"), (\"All Files\", \"*.*\")))\n hypno_files_list = self.frame_import.tk.splitlist(self.filenames)\n self.n_label_files = len(hypno_files_list)\n \n # check if the user chose somthing\n if not hypno_files_list:\n \n self.label_labels = Label(self.frame_import, text = \"No hypnogram has been selected!\",\n fg = 'red', font = 'Helvetica 9 bold').grid(row = 2, column = 1)\n \n else:\n \n self.label_labels = Label(self.frame_import, text = str(self.n_label_files) + \" hypnogram files has been loaded!\",\n fg = 'green', font = 'Helvetica 9 bold').grid(row = 2, column = 1)\n\n \n #%% Read EDF and hypnograms and apply feature extraction\n def Read_Preproc_FeatExtract(self):\n global subjects_dic, hyp_dic, dic_pciked_chans\n subjects_dic = {}\n hyp_dic = {}\n dic_pciked_chans = {}\n \n #### ======================= Create log window ====================####\n self.log_win = Toplevel()\n self.log_win.title(\"Log file of current processes\")\n \n # Label\n self.label = Label(self.log_win, text= \"Process log file:\",font = 'Helvetica 12 bold')\n \n self.label.pack()\n\n self.close_log_win = Button(self.log_win, text=\"Dismiss\", command=self.log_win.destroy)\n self.close_log_win.pack()\n \n #### ======================= Read data files ======================####\n\n for idx, c_subj in enumerate(data_files_list):\n self.log1_ = Label(self.log_win, text = \"Analyzing data: \" + str(c_subj[-11:-4]) + \"\\tPlease wait ...\").pack()\n print (f'Analyzing data: {c_subj[-11:-4]}')\n ## Read in data\n file = data_files_list[idx]\n tic = time.time()\n data = mne.io.read_raw_edf(file)\n # Data raw EEG --> Deactive\n # data.plot(duration = 30, highpass = .3 , lowpass = 25 )\n raw_data = data.get_data()\n print('Time to read EDF: {}'.format(time.time()-tic))\n self.log2_ = Label(self.log_win, text = \"Time to read EDF data (s): \" +str(np.round(time.time()-tic))).pack()\n\n #####=================Retrieving information from data====================#####\n \n# =============================================================================\n# DataInfo = data.info\n# AvailableChannels = DataInfo['ch_names']\n# self.fs = int(DataInfo['sfreq'])\n# =============================================================================\n \n\n #####================= Find index of required channels ===================#####\n \n# =============================================================================\n# for indx, c in enumerate(AvailableChannels):\n# if c in RequiredChannels:\n# Idx.append(indx)\n# elif c in Mastoids:\n# Idx_Mastoids.append(indx)\n# =============================================================================\n \n #####===== Sampling rate is 200hz; thus 1 epoch(30s) is 6000 samples =====#####\n self.fs = 256\n T = 30 #secs\n len_epoch = self.fs * T\n start_epoch = 0\n n_channels = 1\n \n #####============ Cut tail; use modulo to find full epochs ===============#####\n \n raw_data = raw_data[:, 0:raw_data.shape[1] - raw_data.shape[1]%len_epoch]\n \n #####========== Reshape data [n_channel, len_epoch, n_epochs] ============#####\n data_epoched = np.reshape(raw_data,\n (n_channels, len_epoch,\n int(raw_data.shape[1]/len_epoch)), order='F' )\n \n #####===================== Reading hypnogram data ========================#####\n \n hyp = loadtxt(hypno_files_list[idx])\n\n ### Create sepereate data subfiles based on hypnogram (N1, N2, N3, NREM, REM) \n tic = time.time()\n \n #####================= Concatenation of selected channels ================##### \n \n # Calculate referenced channels: \n \n #data_epoched_selected = data_epoched[Idx] - data_epoched[Idx_Mastoids]\n \n #####================= Find order of the selected channels ===============##### \n# =============================================================================\n# #Init\n# picked_channels = []\n# picked_refs = []\n# List_Channels = []\n# \n# # Find main channels\n# for jj,kk in enumerate(Idx):\n# picked_channels = np.append(picked_channels, AvailableChannels[kk])\n# # Find references\n# for jj,kk in enumerate(Idx_Mastoids):\n# picked_refs = np.append(picked_refs, AvailableChannels[kk])\n# print(f'subject LK {c_subj} --> detected channels: {str(picked_channels)} - {str(picked_refs)}')\n# self.log3_ = Label(self.log_win, text = \"Dectected channels:\"+str(picked_channels) +\"-\" +str(picked_refs)).pack()\n# \n# # Create lis of channels\n# for kk in np.arange(0, len(Idx)):\n# List_Channels = np.append(List_Channels, picked_channels[kk] + '-' + picked_refs[kk])\n# =============================================================================\n \n #%% Analysis section\n #####================= remove chanbnels without scroing ==================##### \n \n # assign the proper data and labels\n #x_tmp_init = data_epoched_selected\n x_tmp_init = data_epoched\n\n y_tmp_init = hyp\n \n #Define ssccoorriinngg object:\n self.Object = ssccoorriinngg(filename='', channel='', fs = self.fs, T = 30)\n # Ensure equalituy of length for arrays:\n self.Object.Ensure_data_label_length(x_tmp_init, y_tmp_init)\n \n # Remove non-scored epochs\n x_tmp, y_tmp = self.Object.remove_channels_without_scoring(hypno_labels = y_tmp_init,\n input_feats = x_tmp_init)\n \n # Remove disconnections\n x_tmp, y_tmp = self.Object.remove_disconnection(hypno_labels= y_tmp, \n input_feats=x_tmp)\n \n #####============= Create a one hot encoding form of labels ==============##### \n \n # Create binary labels array\n self.yy = self.Object.One_hot_encoding(y_tmp) \n \n # Ensure all the input labels have a class\n self.Object.Unlabaled_rows_detector(self.yy)\n \n #%% Function: Feature_Extraction\n # Initialize feature array:\n self.Feat_all_channels = np.empty((np.shape(x_tmp)[-1],0))\n \n #####================== Extract the relevant features ====================##### \n \n for k in np.arange(np.shape(data_epoched)[0]):\n \n feat_temp = self.Object.FeatureExtraction_per_subject(Input_data = x_tmp[k,:,:])\n self.Feat_all_channels = np.column_stack((self.Feat_all_channels,feat_temp))\n \n toc = time.time()\n print(f'Features of subject { c_subj[-11:-4]} were successfully extracted in: {toc-tic} secs')\n self.log4_ = Label(self.log_win, text = \"Features of subject\"+ str(c_subj[-11:-4])+\" were successfully extracted in (secs):\"+str(np.round(toc-tic))).pack()\n\n # Double check the equality of size of arrays\n self.Object.Ensure_feature_label_length(self.Feat_all_channels, self.yy)\n \n # Defining dictionary to save features PER SUBJECT\n subjects_dic[\"subject{}\".format( c_subj)] = self.Feat_all_channels\n \n # Defining dictionary to save hypnogram PER SUBJECT\n hyp_dic[\"hyp{}\".format( c_subj)] = self.yy\n \n# =============================================================================\n# # Show picked channels per subject\n# dic_pciked_chans[\"subj{}\".format(c_subj[-11:-4])] = List_Channels\n# \n# =============================================================================\n \n #####=============== Removing variables for next iteration ===============##### \n del x_tmp, y_tmp\n \n toc = time.time()\n \n print(f'Feature extraction of subject { c_subj[-11:-4]} has been finished.') \n self.log5_ = Label(self.log_win, text = \"Feature extraction of subject \"+str(c_subj[-11:-4])+\" has been finished.\").pack()\n\n #print(f'Total feature extraction of subjects took {tic_tot - time.time()} secs.')\n \n\n #%% Function: Import Hypnogram (Browse)\n def Apply_button(self):\n \n print(f'Train size --> {str(self.train_size.get() * 100)}%')\n #### ======================= Get the train size ===================####\n self.train_size = self.train_size.get()\n \n # Has the user loaded hypnos?!\n if not hypno_files_list: \n self.label_apply1 = Label(self.frame_import, text = \"You haven't added any hypnogram!\",\n fg = 'red', font = 'Helvetica 9 bold').grid(row = 2, column = 4)\n # Has the user loaded EDF files?! \n elif not data_files_list: \n self.label_apply2 = Label(self.frame_import, text = \"You haven't added any EDF files!\",\n fg = 'red', font = 'Helvetica 9 bold').grid(row = 2, column = 4) \n \n # Check if train size is a valid value\n elif not self.train_size :\n self.label_apply1 = Label(self.frame_import, text = \"No train size is entered!\",\n fg = 'red', font = 'Helvetica 9 bold').grid(row = 2, column = 4)\n \n elif float(self.train_size) > 0.99 or float(self.train_size) < 0.01 :\n self.label_apply1 = Label(self.frame_import, text = \"Invalid train size! (acceptable range:0-1)\",\n fg = 'red', font = 'Helvetica 9 bold').grid(row = 2, column = 4)\n \n # Do the imported data an hypnos have the same amount of inputs? \n elif len(data_files_list) != len(hypno_files_list):\n self.label_apply3 = Label(self.frame_import, text = \"Size of the loaded hypons and EDF files do not match! Please recheck ...\",\n fg = 'red', font = 'Helvetica 9 bold').grid(row = 2, column = 4)\n # Else --> Go next\n if len(data_files_list) == len(hypno_files_list) and float(self.train_size)<.99 and float(self.train_size)>0.01:\n self.label_apply4 = Label(self.frame_import, text = \"Train size: \"+str(self.train_size)+\"\\nData and hypnogram have received in a good order!\\n Go to next section to proceed ...\",\n fg = 'green', font = 'Helvetica 9 bold').grid(row = 2, column = 4)\n \n self.Read_Preproc_FeatExtract()\n \n #%% Function: Import Hypnogram (Browse)\n def Select_ML_button(self): \n # Check the current ML flag\n self.selected_ML = self.selected_ML.get()\n # Define label\n self.label_select1 = Label(self.frame_ML, text = str(self.selected_ML) + \" has been selected.\\n Please adjust the folloiwng hypermarameters.\",\n fg = 'green', font = 'Helvetica 9 bold').grid(row = 2, column = 1) \n \n # Report current td val\n print(f'Time dependence (0: deactive, 1: active) = {self.td_var.get()}')\n \n #### ============== Train the model and predict test ==============####\n self.label_train = Label(self.frame_ML, text = \"Start Taining!\",\n font = 'Calibri 12 bold')\n self.label_train.grid(row = 0 , column =3)\n # Activate train Button\n self.button_train = Button(self.frame_ML, text = \"Train model!\", padx = 100, pady=20,\n font = 'Calibri 12 bold', relief = RIDGE, fg = 'blue',\n command = self.Training_function)\n self.button_train.grid(row = 1 , column =3)\n \n #### ============== multi-to-one classification flag ============ ####\n \n if int(self.td_var.get()) == 1:\n \n # Label\n self.label_checkbox = Label(self.frame_ML, text = \"Time-dependence (#epochs):\",\n font = 'Calibri 12 bold')\n self.label_checkbox.grid(row = 2 , column = 2)\n \n # Dropdown menu for td\n \n self.entry_td = IntVar()\n self.entry_td.set(5)\n self.drop_td = OptionMenu(self.frame_ML, self.entry_td, 1,2,3,4,5,6)\n self.drop_td.grid(row = 3, column = 2)\n self.drop_td.config(font= 'Calibri 10 bold', fg='blue') \n # SVM Hyperparameters\n \n if self.selected_ML == \"SVM\":\n self.kernel_ = StringVar()\n #init\n self.kernel_.set('rbf')\n # Differnt Kernel functions of SVM:\n Kernel_rbf = Radiobutton(self.frame_ML, text = 'rbf', variable = self.kernel_, value = 'rbf',\n font = 'Helvetica 12 bold')\n Kernel_sig = Radiobutton(self.frame_ML, text = 'sigmoid', variable = self.kernel_, value = 'sigmoid',\n font = 'Helvetica 12 bold')\n Kernel_pol = Radiobutton(self.frame_ML, text = 'poly', variable = self.kernel_, value = 'poly',\n font = 'Helvetica 12 bold')\n # Get the chosen Kernel \n #self.kernel = self.kernel.get()\n \n # Shoving the radio buttons to the frame\n Kernel_rbf.grid(row = 0, column = 2)\n Kernel_sig.grid(row = 1, column = 2)\n Kernel_pol.grid(row = 2, column = 2)\n \n # Random forest hyperparameters\n elif self.selected_ML == \"Random forest\":\n self.n_estimator_RF = IntVar()\n self.n_estimator_RF.set(10)\n # Create n_estimators label\n self.label_n_estimators = Label(self.frame_ML,text = \"Number of trees:\",\n font = 'Calibri 12 bold')\n self.label_n_estimators.grid(row = 0, column = 2, padx = 15, pady = 10)\n # Create entry for user\n self.entry_n_estimator_RF = Entry(self.frame_ML,text = \" Enter the value here \", borderwidth = 8, width = 10)\n self.entry_n_estimator_RF.grid(row = 1, column = 2, padx = 15, pady = 10)\n # Assign the value to send to classifier\n #self.n_estimator_RF = self.entry_n_estimator_RF.get()\n \n # XGBoost\n elif self.selected_ML == \"XGBoost\":\n self.n_estimator_xgb = IntVar()\n # Create n_estimators label\n self.label_n_estimators = Label(self.frame_ML,text = \"Number of trees:\",\n font = 'Calibri 12 bold')\n self.label_n_estimators.grid(row = 0, column = 2, padx = 15, pady = 10)\n # Create entry for user\n self.entry_n_estimator_xgb = Entry(self.frame_ML,text = \" Enter the value here \", borderwidth = 8, width = 10)\n self.entry_n_estimator_xgb.grid(row = 1, column = 2, padx = 15, pady = 10)\n # Assign the value to send to classifier\n #self.n_estimator_xgb = self.entry_n_estimator_xgb.get()\n \n # ADABoost\n elif self.selected_ML == \"ADABoost\":\n self.n_estimator_ada = IntVar()\n # Create n_estimators label\n self.label_n_estimators = Label(self.frame_ML,text = \"Number of trees:\",\n font = 'Calibri 12 bold')\n self.label_n_estimators.grid(row = 0, column = 2, padx = 15, pady = 10)\n # Create entry for user\n self.entry_n_estimator_ada = Entry(self.frame_ML,text = \" Enter the value here \", borderwidth = 8, width = 10)\n self.entry_n_estimator_ada.grid(row = 1, column = 2, padx = 15, pady = 10)\n # Assign the value to send to classifier\n #self.n_estimator_ada = self.entry_n_estimator_ada.get()\n \n # GradientBoosting\n elif self.selected_ML == \"GradientBoosting\":\n self.n_estimator_gb = IntVar()\n # Create n_estimators label\n self.label_n_estimators = Label(self.frame_ML,text = \"Number of trees:\",\n font = 'Calibri 12 bold')\n self.label_n_estimators.grid(row = 0, column = 2, padx = 15, pady = 10)\n # Create entry for user\n self.entry_n_estimator_gb = Entry(self.frame_ML,text = \" Enter the value here \", borderwidth = 8, width = 10)\n self.entry_n_estimator_gb.grid(row = 1, column = 2, padx = 15, pady = 10)\n # Assign the value to send to classifier\n #self.n_estimator_gb = self.entry_n_estimator_gb.get()\n \n # Randomized trees\n \n elif self.selected_ML == \"Randomized trees\":\n self.n_estimator_rt = IntVar()\n # Create n_estimators label\n self.label_n_estimators = Label(self.frame_ML,text = \"Number of trees:\",\n font = 'Calibri 12 bold')\n self.label_n_estimators.grid(row = 0, column = 2, padx = 15, pady = 10)\n # Create entry for user\n self.entry_n_estimator_rt = Entry(self.frame_ML,text = \" Enter the value here \", borderwidth = 8, width = 10)\n self.entry_n_estimator_rt.grid(row = 1, column = 2, padx = 15, pady = 10)\n # Assign the value to send to classifier\n #self.n_estimator_rt = self.entry_n_estimator_rt.get()\n \n # Naive Bayes \n elif self.selected_ML == \"Naive Bayes\":\n pass\n \n # Logistic regression\n elif self.selected_ML == \"Logistic regression\":\n pass\n \n print(f'Time dependence : {self.entry_td.get()} epochs')\n #%% Function: Help pop-up\n def help_pop_up_func(self):\n \n line1 = \"Welcome to Zzzscoring!\\n\"\n line2 = \"Pick the EDF files of interest and their corresponding hypnograms!\\n\"\n line3 = \"** Notes:\\n- hypnograms should be in .txt or .csv format.\\n\"\n line4 = \"- The first and second column of hypnos are labels and artefact annotations, respecively.\\n\"\n line5 = \"- Default labels should be as below:\\n\"\n line6 = \"- Wake:0, N1: 1, N2: 2, SWS: 3, REM: 4.\\n\"\n line7 = \"- Once pushing a button e,.g. 'Apply' or 'Train' the process is time-taking. One can follow the status of process in the console (e.g. command prompt).\\n\"\n line8 = \"- After choosing a ML algorithm you should press 'Select' and then specify hyperparameters. After this, one is allowed to press 'Train' button.\\n\" \n line9 = \"- Activating feature selection extend the process time. Don't forget to follow the status from console. \"\n lines = line1 + line2 + line3 + line4 + line5 + line6 + line7 + line8 + line9\n \n messagebox.showinfo(title = \"Help\", message = lines)\n \n #%% Training function\n def Training_function(self):\n # Training perentage\n \n self.n_train = round(float(self.train_size) * len(data_files_list))\n \n # ========================== Show reuslt ============================ #\n # Label\n self.label_results = Label(self.frame_ML, text = \"Train and prediction finished!\",\n font = 'Calibri 12 bold')\n self.label_results.grid(row = 0 , column =4)\n # Activate results Button\n self.button_show_results = Button(self.frame_ML, text = \"Show results\", padx = 80, pady=15,\n font = 'Calibri 12 bold', relief = RIDGE, fg = 'blue',\n command = self.show_results_function)\n self.button_show_results.grid(row = 1 , column =4)\n \n # ========================== Plot conf mat ========================== #\n # Activate plot confusion Button\n self.button_plot_conf = Button(self.frame_ML, text = \"Plot confusion mat\", padx = 80, pady=15,\n font = 'Calibri 12 bold', relief = RIDGE, fg = 'blue',\n command = self.plot_conf_mat)\n self.button_plot_conf.grid(row = 1 , column =5)\n \n # ========================== Activate plot hypnogram ================ #\n self.button_plot_hyp = Button(self.frame_ML, text = \"Plot hypnograms\", padx = 80, pady=15,\n font = 'Calibri 12 bold', relief = RIDGE, fg = 'blue',\n command = self.plot_hyp_function)\n self.button_plot_hyp.grid(row = 2 , column =4)\n \n #######=== Randomly shuffle subjects to choose train and test splits ===######\n \n# =============================================================================\n# subj_c = np.random.RandomState(seed=42).permutation(subj_c)\n# \n# =============================================================================\n #######=============== Initialize train and test arrays ================#######\n global X_train, X_test, y_train\n X_train = np.empty((0, np.shape(self.Feat_all_channels)[1]))\n X_test = np.empty((0, np.shape(self.Feat_all_channels)[1]))\n y_train = np.empty((0, np.shape(self.yy)[1]))\n self.y_test = np.empty((0, np.shape(self.yy)[1]))\n \n ########======= Picking the train subjetcs and concatenate them =======########\n \n for c_subj in data_files_list[0:self.n_train]:\n \n self.tmp_name = c_subj\n \n # train hypnogram\n self.str_train_hyp = 'hyp' + str(self.tmp_name)\n \n # train featureset\n self.str_train_feat = 'subject' + str(self.tmp_name)\n \n # create template arrays for featurs and label\n self.tmp_x = subjects_dic[self.str_train_feat]\n self.tmp_y = hyp_dic[self.str_train_hyp]\n \n # Concatenate features and labels\n X_train = np.row_stack((X_train, self.tmp_x))\n y_train = np.row_stack((y_train, self.tmp_y))\n \n #del self.tmp_x, self.tmp_y, self.tmp_name, self.str_train_hyp, self.str_train_feat\n \n ########======== Picking the test subjetcs and concatenate them =======########\n \n self.test_subjects_list = []\n \n for c_subj in data_files_list[self.n_train:]:\n \n self.tmp_name = c_subj\n # test hypnogram\n str_test_hyp = 'hyp' + str(self.tmp_name)\n \n # test featureset\n str_test_feat = 'subject' + str(self.tmp_name)\n \n # create template arrays for featurs and label\n self.tmp_x = subjects_dic[str_test_feat]\n self.tmp_y = hyp_dic[str_test_hyp]\n \n # Concatenate features and labels\n X_test = np.row_stack((X_test, self.tmp_x))\n self.y_test = np.row_stack((self.y_test, self.tmp_y))\n \n # keep the subject id\n self.test_subjects_list.append(str_test_feat)\n \n # remove for next iteration\n #del self.tmp_x, self.tmp_y,self.tmp_name, self.str_test_feat, self.str_test_hyp\n ################# FOR NOW WE IGNOR MOVEMENT AROUSAL ###################\n y_train = y_train[:,:5]\n self.y_test = self.y_test[:,:5]\n \n # ========================= Time-dependency ========================= #\n #global X_train_td, X_test_td\n if int(self.td_var.get()) == 1:\n print(f'Adding time-dependency ... n_td : {self.entry_td.get()} ')\n X_train_td = self.Object.add_time_dependence_backward(X_train, n_time_dependence=int(self.entry_td.get()),padding_type = 'sequential')\n \n X_test_td = self.Object.add_time_dependence_backward(X_test, n_time_dependence=int(self.entry_td.get()),padding_type = 'sequential')\n \n X_train = X_train_td\n X_test = X_test_td\n # ======================== Feature selection ======================== #\n\n self.y_train_td = self.Object.binary_to_single_column_label(y_train)\n \n # Check activation of flag\n if int(self.feat_select_var.get()) == 1:\n \n tmp1,tmp2,self.selected_feats_ind = self.Object.FeatSelect_Boruta(X_train, self.y_train_td[:,0], max_iter = 50)\n X_train = X_train[:, self.selected_feats_ind]\n X_test = X_test[:, self.selected_feats_ind] \n \n ######## ================= Apply chosen ML ================= ##########\n global y_pred \n # SVM\n if self.selected_ML == \"SVM\":\n \n y_pred = self.Object.KernelSVM_Modelling(X_train, y_train, X_test, self.y_test, kernel=self.kernel_.get())\n y_pred = np.expand_dims(y_pred, axis=1)\n # One hot encoding\n \n \n # Random forest \n elif self.selected_ML == \"Random forest\":\n \n y_pred = self.Object.RandomForest_Modelling(X_train, y_train, X_test, self.y_test, n_estimators = int(self.entry_n_estimator_RF.get()))\n self.Object.multi_label_confusion_matrix(self.y_test, y_pred, print_results = 'on')\n \n # XGB\n elif self.selected_ML == \"XGBoost\":\n y_pred = self.Object.XGB_Modelling(X_train, y_train,X_test, self.y_test, n_estimators = int(self.entry_n_estimator_xgb.get()), \n max_depth=3, learning_rate=.1)\n \n # ADABoost\n elif self.selected_ML == \"ADABoost\":\n y_pred = self.Object.ADAboost_Modelling(X_train, y_train,X_test, self.y_test, n_estimators = int(self.entry_n_estimator_ada.get()))\n \n # GRadient Boosting \n elif self.selected_ML == \"GradientBoosting\":\n y_pred = self.Object.gradient_boosting_classifier(X_train, y_train,X_test, self.y_test, \n n_estimators = int(self.entry_n_estimator_gb.get()), learning_rate= 1.0, max_depth=1)\n # Randomized trees\n elif self.selected_ML == \"Randomized trees\":\n y_pred = self.Object.Extra_randomized_trees(X_train, y_train, X_test,self.y_test, \n n_estimators= int(self.entry_n_estimator_rt.get()), \n max_depth = None, min_samples_split =2,\n max_features=\"sqrt\")\n\n \n #%% Def show_results function\n def show_results_function(self):\n \n from sklearn.metrics import multilabel_confusion_matrix, cohen_kappa_score\n\n #### =================== Create results window ================####\n self.results_win = Toplevel()\n self.results_win.title(\"Results of classification\")\n \n # Label\n self.label_results_win = Label(self.results_win, text= \"Results were found as below:\\n\", font = 'Calibri 16 bold')\n \n self.label_results_win.pack()\n \n self.close_res_win = Button(self.results_win, text=\"Dismiss\", command=self.results_win.destroy)\n self.close_res_win.pack()\n \n # If the size of y_test & y_pred differ --> change them accordingly\n \n try: \n if np.shape(self.y_test)[1] != np.shape(y_pred)[1]:\n self.y_test = self.Object.binary_to_single_column_label(self.y_test)\n\n \n except IndexError:\n self.y_test = self.Object.binary_to_single_column_label(self.y_test)\n \n self.mcm = multilabel_confusion_matrix(self.y_test, y_pred)\n self.tn = self.mcm[:, 0, 0]\n self.tp = self.mcm[:, 1, 1]\n self.fn = self.mcm[:, 1, 0]\n self.fp = self.mcm[:, 0, 1]\n self.Recall = self.tp / (self.tp + self.fn)\n self.prec = self.tp / (self.tp + self.fp)\n self.f1_sc = 2 * self.Recall * self.prec / (self.Recall + self.prec)\n self.Acc = (self.tp + self.tn) / (self.tp + self.fp + self.fn+ self.tn)\n #kappa = cohen_kappa_score(y_true, y_pred)\n self.label_res1= Label(self.results_win, text = \"Accuracy for Wake,N1,N2,N3,REM were respectively:\" + str(self.Acc), font = 'Calibri 12 bold').pack()\n self.label_res2= Label(self.results_win, text = \"Precision for Wake,N1,N2,N3,REM were respectively:\" + str(self.prec), font = 'Calibri 12 bold').pack()\n self.label_res3= Label(self.results_win, text = \"Recall for Wake,N1,N2,N3,REM were respectively:\" + str(self.Recall),font = 'Calibri 12 bold').pack()\n self.label_res4= Label(self.results_win, text = \"F1-score for Wake,N1,N2,N3,REM were respectively:\" + str(self.f1_sc),font = 'Calibri 12 bold').pack() \n \n #%% Plot confusion matrix\n def plot_conf_mat(self):\n \n self.Object.plot_confusion_matrix(self.y_test,y_pred, target_names = ['Wake','N1','N2','SWS','REM'],\n title='Confusion matrix of ssccoorriinngg algorithm',\n cmap=None,\n normalize=True)\n \n #%% Plot hypnograms\n def plot_hyp_function(self):\n \n# =============================================================================\n# # If the size of y_test & y_pred differ --> change them accordingly\n# \n# try: \n# if np.shape(self.y_test)[1] != np.shape(y_pred)[1]:\n# self.y_test = self.Object.binary_to_single_column_label(self.y_test)\n# \n# \n# except IndexError:\n# self.y_test = self.Object.binary_to_single_column_label(self.y_test)\n# \n# self.hyp_true = self.Object.binary_to_single_column_label(self.y_test)\n# \n# if np.shape(y_pred)[1] == 1:\n# self.hyp_pred = self.Object.binary_to_single_column_label(y_pred)\n# else:\n# =============================================================================\n self.hyp_true = self.y_test\n self.hyp_pred = y_pred\n self.Object.plot_comparative_hyp(self.hyp_true, self.hyp_pred, mark_REM = 'active',\n Title = 'True Hypnogram')\n#%% Test section\nroot = Tk()\nmy_gui = Zzzscoring(root)\nroot.mainloop()\n"
] |
[
[
"numpy.round",
"numpy.shape",
"numpy.loadtxt",
"sklearn.metrics.multilabel_confusion_matrix",
"numpy.column_stack",
"numpy.expand_dims",
"numpy.row_stack"
]
] |
inzva/emotion-recognition-drawings
|
[
"56435f42d76c10c10fa58149ccbcc8d05efccdc0"
] |
[
"src/models/modules/visual_bert_classifier.py"
] |
[
"import torch\nfrom torch import nn\nfrom transformers import BertTokenizer, VisualBertModel, VisualBertConfig\nimport numpy as np\n\n\nclass VisualBertClassifier(nn.Module):\n def __init__(self,\n visual_bert_model,\n num_classes: int = 8,\n initial_visual_embedding_dim: int = 96,\n final_dropout_rate: float = 0.1):\n \"\"\"\n pooler_output (torch.FloatTensor of shape (batch_size, hidden_size))\n — Last layer hidden-state of the first token of the sequence (classification token)\n after further processing through the layers used for the auxiliary pretraining task.\n E.g. for BERT-family of models, this returns the classification token after processing through\n a linear layer and a tanh activation function.\n The linear layer weights are trained from the next sentence prediction (classification) objective\n during pretraining.\n @param initial_visual_embedding_dim:\n \"\"\"\n super().__init__()\n self.visual_embedding_projection = nn.Linear(initial_visual_embedding_dim, 2048)\n self.visual_bert = visual_bert_model\n self.final_dropout = nn.Dropout(final_dropout_rate)\n self.out = nn.Linear(768, num_classes)\n\n def forward(self,\n text_input_ids,\n text_token_type_ids,\n text_attention_mask,\n visual_embeds,\n visual_token_type_ids,\n visual_attention_mask\n ):\n visual_embeds = self.visual_embedding_projection(visual_embeds)\n output = self.visual_bert(input_ids=text_input_ids,\n token_type_ids=text_token_type_ids,\n attention_mask=text_attention_mask,\n visual_embeds=visual_embeds,\n visual_token_type_ids=visual_token_type_ids,\n visual_attention_mask=visual_attention_mask)\n output = self.final_dropout(output.pooler_output)\n output = self.out(output)\n return output\n\n\nif __name__ == '__main__':\n bert_text_tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n inputs = bert_text_tokenizer(\"What is the man eating?\", return_tensors=\"pt\")\n\n text_input_ids = inputs.data['input_ids'].to('cuda')\n text_token_type_ids = inputs.data['token_type_ids'].to('cuda')\n text_attention_mask = inputs.data['attention_mask'].to('cuda')\n\n sample_face_body_embedding_path = \"/home/gsoykan20/Desktop/self_development/emotion-recognition-drawings/data/emoreccom_face_body_embeddings_96d/train/0_3_4.jpg.npy\"\n sample_face_body_embedding = np.load(sample_face_body_embedding_path)\n visual_embeds = torch.from_numpy(sample_face_body_embedding)\n visual_embeds = visual_embeds.to('cuda')\n visual_embeds = torch.unsqueeze(visual_embeds, 0)\n visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long).to('cuda')\n visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float).to('cuda')\n classifier = VisualBertClassifier()\n classifier.to('cuda')\n classifier.forward(text_input_ids,\n text_token_type_ids,\n text_attention_mask,\n visual_embeds,\n visual_token_type_ids,\n visual_attention_mask)\n\n\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.Dropout",
"numpy.load",
"torch.unsqueeze",
"torch.from_numpy",
"torch.ones"
]
] |
cformosa/transformers
|
[
"708d6fbfcf30b45e051d9783b5f637d3afaf4103"
] |
[
"transformers/modeling_roberta.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"PyTorch RoBERTa model. \"\"\"\n\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport logging\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\n\nfrom .modeling_bert import BertEmbeddings, BertLayerNorm, BertModel, BertPreTrainedModel, gelu\nfrom .configuration_roberta import RobertaConfig\nfrom .file_utils import add_start_docstrings\n\nlogger = logging.getLogger(__name__)\n\nROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP = {\n 'roberta-base': \"https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-pytorch_model.bin\",\n 'roberta-large': \"https://s3.amazonaws.com/models.huggingface.co/bert/roberta-large-pytorch_model.bin\",\n 'roberta-large-mnli': \"https://s3.amazonaws.com/models.huggingface.co/bert/roberta-large-mnli-pytorch_model.bin\",\n}\n\nclass RobertaEmbeddings(BertEmbeddings):\n \"\"\"\n Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.\n \"\"\"\n def __init__(self, config):\n super(RobertaEmbeddings, self).__init__(config)\n self.padding_idx = 1\n self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=self.padding_idx)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size,\n padding_idx=self.padding_idx)\n\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\n seq_length = input_ids.size(1)\n if position_ids is None:\n # Position numbers begin at padding_idx+1. Padding symbols are ignored.\n # cf. fairseq's `utils.make_positions`\n position_ids = torch.arange(self.padding_idx+1, seq_length+self.padding_idx+1, dtype=torch.long, device=input_ids.device)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n return super(RobertaEmbeddings, self).forward(input_ids,\n token_type_ids=token_type_ids,\n position_ids=position_ids)\n\n\nROBERTA_START_DOCSTRING = r\"\"\" The RoBERTa model was proposed in\n `RoBERTa: A Robustly Optimized BERT Pretraining Approach`_\n by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer,\n Veselin Stoyanov. It is based on Google's BERT model released in 2018.\n \n It builds on BERT and modifies key hyperparameters, removing the next-sentence pretraining\n objective and training with much larger mini-batches and learning rates.\n \n This implementation is the same as BertModel with a tiny embeddings tweak as well as a setup for Roberta pretrained \n models.\n\n This model is a PyTorch `torch.nn.Module`_ sub-class. Use it as a regular PyTorch Module and\n refer to the PyTorch documentation for all matter related to general usage and behavior.\n\n .. _`RoBERTa: A Robustly Optimized BERT Pretraining Approach`:\n https://arxiv.org/abs/1907.11692\n\n .. _`torch.nn.Module`:\n https://pytorch.org/docs/stable/nn.html#module\n\n Parameters:\n config (:class:`~transformers.RobertaConfig`): Model configuration class with all the parameters of the \n model. Initializing with a config file does not load the weights associated with the model, only the configuration.\n Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.\n\"\"\"\n\nROBERTA_INPUTS_DOCSTRING = r\"\"\"\n Inputs:\n **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Indices of input sequence tokens in the vocabulary.\n To match pre-training, RoBERTa input sequence should be formatted with <s> and </s> tokens as follows:\n\n (a) For sequence pairs:\n\n ``tokens: <s> Is this Jacksonville ? </s> </s> No it is not . </s>``\n\n (b) For single sequences:\n\n ``tokens: <s> the dog is hairy . </s>``\n\n Fully encoded sequences or sequence pairs can be obtained using the RobertaTokenizer.encode function with \n the ``add_special_tokens`` parameter set to ``True``.\n\n RoBERTa is a model with absolute position embeddings so it's usually advised to pad the inputs on\n the right rather than the left.\n\n See :func:`transformers.PreTrainedTokenizer.encode` and\n :func:`transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.\n **attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, sequence_length)``:\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n **token_type_ids**: (`optional` need to be trained) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Optional segment token indices to indicate first and second portions of the inputs.\n This embedding matrice is not trained (not pretrained during RoBERTa pretraining), you will have to train it\n during finetuning.\n Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``\n corresponds to a `sentence B` token\n (see `BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`_ for more details).\n **position_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Indices of positions of each input sequence tokens in the position embeddings.\n Selected in the range ``[0, config.max_position_embeddings - 1[``.\n **head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.\n\"\"\"\n\n@add_start_docstrings(\"The bare RoBERTa Model transformer outputting raw hidden-states without any specific head on top.\",\n ROBERTA_START_DOCSTRING, ROBERTA_INPUTS_DOCSTRING)\nclass RobertaModel(BertModel):\n r\"\"\"\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``\n Sequence of hidden-states at the output of the last layer of the model.\n **pooler_output**: ``torch.FloatTensor`` of shape ``(batch_size, hidden_size)``\n Last layer hidden-state of the first token of the sequence (classification token)\n further processed by a Linear layer and a Tanh activation function. The Linear\n layer weights are trained from the next sentence prediction (classification)\n objective during Bert pretraining. This output is usually *not* a good summary\n of the semantic content of the input, you're often better with averaging or pooling\n the sequence of hidden-states for the whole input sequence.\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = RobertaTokenizer.from_pretrained('roberta-base')\n model = RobertaModel.from_pretrained('roberta-base')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n outputs = model(input_ids)\n last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\n\n \"\"\"\n config_class = RobertaConfig\n pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"roberta\"\n\n def __init__(self, config):\n super(RobertaModel, self).__init__(config)\n\n self.embeddings = RobertaEmbeddings(config)\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None):\n if input_ids[:, 0].sum().item() != 0:\n logger.warning(\"A sequence with no special tokens has been passed to the RoBERTa model. \"\n \"This model requires special tokens in order to work. \"\n \"Please specify add_special_tokens=True in your tokenize.encode()\"\n \"or tokenizer.convert_tokens_to_ids().\")\n return super(RobertaModel, self).forward(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n\n\n@add_start_docstrings(\"\"\"RoBERTa Model with a `language modeling` head on top. \"\"\",\n ROBERTA_START_DOCSTRING, ROBERTA_INPUTS_DOCSTRING)\nclass RobertaForMaskedLM(BertPreTrainedModel):\n r\"\"\"\n **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for computing the masked language modeling loss.\n Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)\n Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels\n in ``[0, ..., config.vocab_size]``\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Masked language modeling loss.\n **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = RobertaTokenizer.from_pretrained('roberta-base')\n model = RobertaForMaskedLM.from_pretrained('roberta-base')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, masked_lm_labels=input_ids)\n loss, prediction_scores = outputs[:2]\n\n \"\"\"\n config_class = RobertaConfig\n pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"roberta\"\n\n def __init__(self, config):\n super(RobertaForMaskedLM, self).__init__(config)\n\n self.roberta = RobertaModel(config)\n self.lm_head = RobertaLMHead(config)\n\n self.init_weights()\n self.tie_weights()\n\n def tie_weights(self):\n \"\"\" Make sure we are sharing the input and output embeddings.\n Export to TorchScript can't handle parameter sharing so we are cloning them instead.\n \"\"\"\n self._tie_or_clone_weights(self.lm_head.decoder, self.roberta.embeddings.word_embeddings)\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,\n masked_lm_labels=None):\n outputs = self.roberta(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n sequence_output = outputs[0]\n prediction_scores = self.lm_head(sequence_output)\n\n outputs = (prediction_scores,) + outputs[2:] # Add hidden states and attention if they are here\n\n if masked_lm_labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n outputs = (masked_lm_loss,) + outputs\n\n return outputs # (masked_lm_loss), prediction_scores, (hidden_states), (attentions)\n\n\nclass RobertaLMHead(nn.Module):\n \"\"\"Roberta Head for masked language modeling.\"\"\"\n\n def __init__(self, config):\n super(RobertaLMHead, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.layer_norm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n def forward(self, features, **kwargs):\n x = self.dense(features)\n x = gelu(x)\n x = self.layer_norm(x)\n\n # project back to size of vocabulary with bias\n x = self.decoder(x) + self.bias\n\n return x\n\n\n@add_start_docstrings(\"\"\"RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer \n on top of the pooled output) e.g. for GLUE tasks. \"\"\",\n ROBERTA_START_DOCSTRING, ROBERTA_INPUTS_DOCSTRING)\nclass RobertaForSequenceClassification(BertPreTrainedModel):\n r\"\"\"\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the sequence classification/regression loss.\n Indices should be in ``[0, ..., config.num_labels]``.\n If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss),\n If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy).\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification (or regression if config.num_labels==1) loss.\n **logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``\n Classification (or regression if config.num_labels==1) scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = RobertaTokenizer.from_pretrained('roberta-base')\n model = RobertaForSequenceClassification.from_pretrained('roberta-base')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n labels = torch.tensor([1]).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=labels)\n loss, logits = outputs[:2]\n\n \"\"\"\n config_class = RobertaConfig\n pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"roberta\"\n\n def __init__(self, config):\n super(RobertaForSequenceClassification, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.roberta = RobertaModel(config)\n self.classifier = RobertaClassificationHead(config)\n \n def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,\n labels=None):\n outputs = self.roberta(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n sequence_output = outputs[0]\n logits = self.classifier(sequence_output)\n\n outputs = (logits,) + outputs[2:]\n if labels is not None:\n if self.num_labels == 1:\n # We are doing regression\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), labels.view(-1))\n else:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), logits, (hidden_states), (attentions)\n\n@add_start_docstrings(\"\"\"Roberta Model with a multiple choice classification head on top (a linear layer on top of\n the pooled output and a softmax) e.g. for RocStories/SWAG tasks. \"\"\",\n ROBERTA_START_DOCSTRING, ROBERTA_INPUTS_DOCSTRING)\nclass RobertaForMultipleChoice(BertPreTrainedModel):\n r\"\"\"\n Inputs:\n **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``:\n Indices of input sequence tokens in the vocabulary.\n The second dimension of the input (`num_choices`) indicates the number of choices to score.\n To match pre-training, RoBerta input sequence should be formatted with [CLS] and [SEP] tokens as follows:\n\n (a) For sequence pairs:\n\n ``tokens: [CLS] is this jack ##son ##ville ? [SEP] [SEP] no it is not . [SEP]``\n\n ``token_type_ids: 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1``\n\n (b) For single sequences:\n\n ``tokens: [CLS] the dog is hairy . [SEP]``\n\n ``token_type_ids: 0 0 0 0 0 0 0``\n\n Indices can be obtained using :class:`transformers.BertTokenizer`.\n See :func:`transformers.PreTrainedTokenizer.encode` and\n :func:`transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.\n **token_type_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``:\n Segment token indices to indicate first and second portions of the inputs.\n The second dimension of the input (`num_choices`) indicates the number of choices to score.\n Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``\n **attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, num_choices, sequence_length)``:\n Mask to avoid performing attention on padding token indices.\n The second dimension of the input (`num_choices`) indicates the number of choices to score.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n **head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the multiple choice classification loss.\n Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension\n of the input tensors. (see `input_ids` above)\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification loss.\n **classification_scores**: ``torch.FloatTensor`` of shape ``(batch_size, num_choices)`` where `num_choices` is the size of the second dimension\n of the input tensors. (see `input_ids` above).\n Classification scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = RobertaTokenizer.from_pretrained('roberta-base')\n model = RobertaForMultipleChoice.from_pretrained('roberta-base')\n choices = [\"Hello, my dog is cute\", \"Hello, my cat is amazing\"]\n input_ids = torch.tensor([tokenizer.encode(s, add_special_tokens=True) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices\n labels = torch.tensor(1).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=labels)\n loss, classification_scores = outputs[:2]\n\n \"\"\"\n config_class = RobertaConfig\n pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"roberta\"\n\n def __init__(self, config):\n super(RobertaForMultipleChoice, self).__init__(config)\n\n self.roberta = RobertaModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, 1)\n\n self.init_weights()\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None,\n position_ids=None, head_mask=None):\n num_choices = input_ids.shape[1]\n\n flat_input_ids = input_ids.view(-1, input_ids.size(-1))\n flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None\n flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None\n flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None\n outputs = self.roberta(flat_input_ids, position_ids=flat_position_ids, token_type_ids=flat_token_type_ids,\n attention_mask=flat_attention_mask, head_mask=head_mask)\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n reshaped_logits = logits.view(-1, num_choices)\n\n outputs = (reshaped_logits,) + outputs[2:] # add hidden states and attention if they are here\n\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(reshaped_logits, labels)\n outputs = (loss,) + outputs\n\n return outputs # (loss), reshaped_logits, (hidden_states), (attentions)\n\n@add_start_docstrings(\"\"\"Roberta Model with a token classification head on top (a linear layer on top of\n the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. \"\"\",\n ROBERTA_START_DOCSTRING, ROBERTA_INPUTS_DOCSTRING)\nclass RobertaForTokenClassification(BertPreTrainedModel):\n r\"\"\"\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for computing the token classification loss.\n Indices should be in ``[0, ..., config.num_labels - 1]``.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification loss.\n **scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.num_labels)``\n Classification scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = RobertaTokenizer.from_pretrained('roberta-base')\n model = RobertaForTokenClassification.from_pretrained('roberta-base')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=labels)\n loss, scores = outputs[:2]\n\n \"\"\"\n config_class = RobertaConfig\n pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"roberta\"\n\n \n def __init__(self, config):\n super(RobertaForTokenClassification, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.roberta = RobertaModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None,\n position_ids=None, head_mask=None, labels=None):\n\n outputs = self.roberta(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids, \n head_mask=head_mask)\n\n sequence_output = outputs[0]\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1) == 1\n active_logits = logits.view(-1, self.num_labels)[active_loss]\n active_labels = labels.view(-1)[active_loss]\n loss = loss_fct(active_logits, active_labels)\n else:\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), scores, (hidden_states), (attentions)\n\n\n\nclass RobertaClassificationHead(nn.Module):\n \"\"\"Head for sentence-level classification tasks.\"\"\"\n\n def __init__(self, config):\n super(RobertaClassificationHead, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.out_proj = nn.Linear(config.hidden_size, config.num_labels)\n\n def forward(self, features, **kwargs):\n x = features[:, 0, :] # take <s> token (equiv. to [CLS])\n x = self.dropout(x)\n x = self.dense(x)\n x = torch.tanh(x)\n x = self.dropout(x)\n x = self.out_proj(x)\n return x\n"
] |
[
[
"torch.nn.Linear",
"torch.zeros",
"torch.nn.Dropout",
"torch.nn.MSELoss",
"torch.arange",
"torch.nn.CrossEntropyLoss",
"torch.tanh",
"torch.nn.Embedding"
]
] |
tuxedcat/PER-D3QN
|
[
"c3a5edf87f93fba5cbd391a59e93826b615bdbba"
] |
[
"Pretrained/w1model.py"
] |
[
"import torch as tc\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom config import NROW,NCOL\nfrom core import DEVICE\n\nclass Conv(nn.Module):\n\tdef __init__(self, chn_in, chn_out, ker_sz=3):\n\t\tsuper().__init__()\n\t\tself.c=nn.Conv2d(chn_in,chn_out,ker_sz,padding=ker_sz//2,padding_mode=\"circular\",bias=False)\n\t\tself.b=nn.BatchNorm2d(chn_out)\n\t\tself.a=nn.LeakyReLU(0.1)\n\n\tdef forward(self, x):\n\t\treturn self.a(self.b(self.c(x)))\n\nclass Resi(nn.Module):\n\tdef __init__(self, chn, ker_sz=3):\n\t\tsuper().__init__()\n\t\tself.pre=nn.Sequential(\n\t\t\tnn.Conv2d(chn,chn,ker_sz,padding=ker_sz//2,padding_mode=\"circular\",bias=False),\n\t\t\tnn.BatchNorm2d(chn),\n\t\t\tnn.LeakyReLU(0.1),\n\t\t\tnn.Conv2d(chn,chn,ker_sz,padding=ker_sz//2,padding_mode=\"circular\",bias=False),\n\t\t\tnn.BatchNorm2d(chn),\n\t\t)\n\t\tself.post=nn.LeakyReLU(0.1)\n\n\tdef forward(self, x):\n\t\treturn self.post(self.pre(x)+x)\n\t\nclass Full(nn.Module):\n\tdef __init__(self, N_in, N_out, afunc=nn.LeakyReLU(0.1), drop_out=False):\n\t\tsuper().__init__()\n\t\tself.l=nn.Linear(N_in,N_out)\n\t\tself.drop_out=drop_out\n\t\tif self.drop_out: self.d=nn.Dropout(0.5)\n\t\tself.a=afunc\n\n\tdef forward(self, x):\n\t\tx=self.l(x)\n\t\tif self.drop_out: x=self.d(x)\n\t\treturn self.a(x)\n\nclass SnakeNet(nn.Module):\n\tdef __init__(self):\n\t\tsuper(SnakeNet,self).__init__()\n\t\tself.chn_in=5\n\t\tself.chn_mid=64\n\t\tself.chn_out=12\n\n\t\tself.feature=nn.Sequential(\n\t\t\tConv(self.chn_in,self.chn_mid),\n\t\t\tResi(self.chn_mid),\n\t\t\tResi(self.chn_mid),\n\t\t\tResi(self.chn_mid),\n\t\t\tResi(self.chn_mid),\n\t\t\tConv(self.chn_mid,self.chn_out),\n\t\t\tnn.Flatten(),\n\t\t)\n\t\tself.adv = nn.Sequential(\n\t\t\tFull(self.chn_out*NROW*NCOL,256),\n\t\t\tFull(256,4),\n\t\t)\n\t\tself.stval = nn.Sequential(\n\t\t\tFull(self.chn_out*NROW*NCOL,256),\n\t\t\tFull(256,1),\n\t\t)\n\t\tfor x in self.modules():\n\t\t\tif isinstance(x,nn.Conv2d) or isinstance(x,nn.Linear):\n\t\t\t\tinit.xavier_uniform_(x.weight.data)\n\t\t\t\tif x.bias != None:\n\t\t\t\t\tinit.zeros_(x.bias)\n\n\tdef forward(self,x):\n\t\tx = x.reshape(-1,self.chn_in,NROW,NCOL)\n\t\tx = self.feature(x)\n\t\tadv = self.adv(x)\n\t\tstval = self.stval(x)\n\t\tqval = (adv-adv.mean())+stval\n\t\treturn qval"
] |
[
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.nn.BatchNorm2d",
"torch.nn.LeakyReLU",
"torch.nn.init.xavier_uniform_",
"torch.nn.Conv2d",
"torch.nn.init.zeros_",
"torch.nn.Flatten"
]
] |
gawy/CarND-Semantic-Segmentation
|
[
"f628807eb411844dfbc0396f072c381d93d03a0c"
] |
[
"main.py"
] |
[
"#!/usr/bin/env python3\nimport os.path\nimport tensorflow as tf\nimport helper\nimport warnings\nfrom distutils.version import LooseVersion\nimport project_tests as tests\nfrom glob import glob\nfrom tqdm import tqdm\n\n\nCOLLECTION_ASSERTS = 'ASSERTS'\nCOLLECTION_METRICS = 'METRICS'\nCOLLECTION_METRICS_UPDATES = 'METRICS_UPDATES'\n\n# Check TensorFlow Version\nfrom helper import gen_batch_function\n\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\n\n\ndef load_vgg(sess, vgg_path):\n \"\"\"\n Load Pretrained VGG Model into TensorFlow.\n :param sess: TensorFlow Session\n :param vgg_path: Path to vgg folder, containing \"variables/\" and \"saved_model.pb\"\n :return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out)\n \"\"\"\n\n # Use tf.saved_model.loader.load to load the model and weights\n vgg_tag = 'vgg16'\n vgg_input_tensor_name = 'image_input:0'\n vgg_keep_prob_tensor_name = 'keep_prob:0'\n vgg_layer3_out_tensor_name = 'layer3_out:0'\n vgg_layer4_out_tensor_name = 'layer4_out:0'\n vgg_layer7_out_tensor_name = 'layer7_out:0'\n\n graph = tf.get_default_graph()\n\n tf.saved_model.loader.load(sess, [vgg_tag], vgg_path)\n\n l_input = graph.get_tensor_by_name(vgg_input_tensor_name)\n l_keep = graph.get_tensor_by_name(vgg_keep_prob_tensor_name)\n\n l_out3 = graph.get_tensor_by_name(vgg_layer3_out_tensor_name)\n l_out4 = graph.get_tensor_by_name(vgg_layer4_out_tensor_name)\n l_out5 = graph.get_tensor_by_name(vgg_layer7_out_tensor_name)\n l_out5 = tf.stop_gradient(l_out5)\n\n return l_input, l_keep, l_out3, l_out4, l_out5\ntests.test_load_vgg(load_vgg, tf)\n\n\ndef layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes):\n \"\"\"\n Create the layers for a fully convolutional network. Build skip-layers using the vgg layers.\n :param vgg_layer3_out: TF Tensor for VGG Layer 3 output\n :param vgg_layer4_out: TF Tensor for VGG Layer 4 output\n :param vgg_layer7_out: TF Tensor for VGG Layer 7 output\n :param num_classes: Number of classes to classify\n :return: The Tensor for the last layer of output\n \"\"\"\n\n regularizer = tf.contrib.layers.l2_regularizer(scale=0.1)\n\n # l_1x1 = tf.layers.conv2d(vgg_layer7_out, num_classes, 1, 1, padding='same')\n l_upsc_1 = tf.layers.conv2d_transpose(vgg_layer7_out, 512, 4, 2, padding='same', name='l_conv_1x1',\n kernel_regularizer=regularizer)\n l_upsc_1_norm = tf.layers.batch_normalization(l_upsc_1)\n l_upsc_1_relu = tf.nn.relu(l_upsc_1_norm)\n\n l_vgg_out4_scaled = tf.multiply(vgg_layer4_out, 1e-4)\n l_4_skip = tf.add(l_upsc_1_relu, l_vgg_out4_scaled)\n l_upsc_2 = tf.layers.conv2d_transpose(l_4_skip, 256, 4, 2, padding='same', kernel_regularizer=regularizer,\n activation=None)\n\n l_upsc_2_norm = tf.layers.batch_normalization(l_upsc_2)\n l_upsc_2_relu = tf.nn.relu(l_upsc_2_norm)\n\n l_vgg_out3_scaled = tf.multiply(vgg_layer3_out, 1e-2)\n l_3_skip = tf.add(l_upsc_2_relu, l_vgg_out3_scaled)\n l_upsc_3 = tf.layers.conv2d_transpose(l_3_skip, num_classes, 16, 8, padding='same', name='l_ups_last',\n kernel_regularizer=regularizer)\n\n return l_upsc_3\ntests.test_layers(layers)\n\n\ndef optimize(nn_last_layer, correct_label, learning_rate, num_classes):\n \"\"\"\n Build the TensorFLow loss and optimizer operations.\n :param nn_last_layer: TF Tensor of the last layer in the neural network\n :param correct_label: TF Placeholder for the correct label image\n :param learning_rate: TF Placeholder for the learning rate\n :param num_classes: Number of classes to classify\n :return: Tuple of (logits, train_op, cross_entropy_loss)\n \"\"\"\n\n l_logits = tf.reshape(nn_last_layer, [-1, num_classes])\n loss_cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=nn_last_layer, labels=correct_label)\n\n tf.Print(loss_cross_entropy, [tf.losses.get_regularization_losses()], message=\"L2 losses: \")\n loss = tf.add(tf.reduce_mean(loss_cross_entropy), sum(tf.losses.get_regularization_losses()))\n\n train_op = tf.train.AdamOptimizer(learning_rate).minimize(loss)\n\n # Accuracy metrics\n l_prediction_indexes = tf.argmax(tf.nn.softmax(l_logits), axis=1)\n l_predictions_1_hot = tf.one_hot(l_prediction_indexes, num_classes) # convert last dimention to 1-hot\n\n # tf.add_to_collection(COLLECTION_ASSERTS, tf.Print(l_predictions_1_hot, [tf.shape(l_predictions_1_hot)], message='Prediction 1-hot size: '))\n # tf.add_to_collection(COLLECTION_ASSERTS, tf.assert_equal(tf.shape(l_predictions_1_hot), [-1, 2], message=\"Predictions 1_hot shape: \", name=\"pred-1hot-size\"))\n tests._assert_tensor_shape(l_predictions_1_hot, [None, 2], \"Predictions 1_hot shape\")\n\n l_label_1_hot = tf.one_hot(tf.argmax(tf.reshape(correct_label, (-1, num_classes)), axis=1), num_classes)\n # tf.add_to_collection(COLLECTION_ASSERTS, tf.Assert(l_label_1_hot.get_shape() == (-1, 3), data=[\"Labels 1-hot shape: \"], name=\"label-1hot-size\"))\n tests._assert_tensor_shape(l_label_1_hot, [None, 2], \"Labels 1_hot shape\")\n\n # IOU\n tf.metrics.mean_iou(l_label_1_hot, l_predictions_1_hot, num_classes, name=\"metric_iou\",\n metrics_collections=COLLECTION_METRICS, updates_collections=COLLECTION_METRICS_UPDATES)\n\n # True positives of road surface. Non-road pixel will be masked\n total_road = tf.Variable(lambda: 0.0, name='metric_total_road', trainable=False)\n total_non_road = tf.Variable(lambda: 0.0, name='metric_total_non_road', trainable=False)\n tf.add_to_collection(COLLECTION_METRICS, total_road)\n tf.add_to_collection(COLLECTION_METRICS, total_non_road)\n\n gt_non_road, gt_road = tf.unstack(l_label_1_hot, axis=-1) #unpack along the last axis and we will have masks for road and non-road\n total_road_update = tf.assign_add(total_road, tf.reduce_sum(gt_road))\n total_non_road_update = tf.assign_add(total_non_road, tf.reduce_sum(gt_non_road))\n\n tf.add_to_collection(COLLECTION_METRICS_UPDATES, total_road_update)\n tf.add_to_collection(COLLECTION_METRICS_UPDATES, total_non_road_update)\n\n _, predict_road = tf.unstack(l_predictions_1_hot, axis=-1) #predicted road as mask\n\n # tf.metrics.precision(l_label_indexes, l_prediction_indexes, weights=mask_road)\n\n #true-positives for road pixels\n tf.metrics.true_positives(gt_road, predict_road, name='metric_tp_road', metrics_collections=COLLECTION_METRICS, updates_collections=COLLECTION_METRICS_UPDATES)\n #false-positives out of non-road pixels\n tf.metrics.false_positives(gt_road, predict_road, name='metric_fp_road', metrics_collections=COLLECTION_METRICS, updates_collections=COLLECTION_METRICS_UPDATES)\n\n return l_logits, train_op, loss\ntests.test_optimize(optimize)\ntests.test_metrics(optimize)\n\n\ndef train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,\n correct_label, keep_prob, learning_rate, data_folder=''):\n \"\"\"\n Train neural network and print out the loss during training.\n :param sess: TF Session\n :param epochs: Number of epochs\n :param batch_size: Batch size\n :param get_batches_fn: Function to get batches of training data. Call using get_batches_fn(batch_size)\n :param train_op: TF Operation to train the neural network\n :param cross_entropy_loss: TF Tensor for the amount of loss\n :param input_image: TF Placeholder for input images\n :param correct_label: TF Placeholder for label images\n :param keep_prob: TF Placeholder for dropout keep probability\n :param learning_rate: TF Placeholder for learning rate\n \"\"\"\n\n image_paths = glob(os.path.join(data_folder, 'image_2', '*.png'))\n batch_count = int(len(image_paths) / batch_size) + 1\n\n print(\"Started training\")\n tf.global_variables_initializer().run()\n tf.local_variables_initializer().run()\n\n metrics_updates = tf.get_collection(COLLECTION_METRICS_UPDATES)\n run_vars = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope='metric_iou') \\\n + tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope='metric_tp_road') \\\n + tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope='metric_fp_road') \\\n + tf.get_collection(COLLECTION_METRICS, scope='metric_total_road') \\\n + tf.get_collection(COLLECTION_METRICS, scope='metric_total_non_road')\n\n metrics_initializer = tf.variables_initializer(run_vars)\n\n metric_iou = tf.get_collection(COLLECTION_METRICS, scope='metric_iou')[0]\n metric_tp_road = tf.get_collection(COLLECTION_METRICS, scope='metric_tp_road')[0]\n metric_fp_road = tf.get_collection(COLLECTION_METRICS, scope='metric_fp_road')[0]\n metric_total_road = tf.get_collection(COLLECTION_METRICS, scope='metric_total_road')[0]\n metric_total_non_road = tf.get_collection(COLLECTION_METRICS, scope='metric_total_non_road')[0]\n\n print(\"Variables initialized\")\n\n asserts = tf.get_collection(COLLECTION_ASSERTS)\n\n loss_hist = []\n\n with tf.control_dependencies(asserts) :\n\n for epoch in range(epochs):\n batches_pbar = tqdm(total=batch_count, desc='Epoch {:>2}/{}'.format(epoch+1, epochs), unit='batch')\n metrics_initializer.run()\n\n for batch in get_batches_fn(batch_size):\n fetches = [train_op, cross_entropy_loss] + metrics_updates\n hist = sess.run(fetches, feed_dict={input_image: batch[0], correct_label: batch[1], keep_prob: 0.5})\n batches_pbar.update()\n\n batches_pbar.write(\"Loss={:.2f}\".format(hist[1]))\n loss_hist += hist[1]\n\n iou, tp, fp, total_road, total_non_road = sess.run([metric_iou, metric_tp_road, metric_fp_road, metric_total_road, metric_total_non_road])\n print(\"Epoch ended. Loss={:.2f}, iou={:.2f}, true-p={:.2f}, false-p={:.2f}\"\n .format(hist[1], iou, tp/total_road, fp/total_non_road)) # , road={}, non_road={} , total_road, total_non_road\n batches_pbar.close()\n\n saver = tf.train.Saver()\n saver.save(sess, './runs/model.ckpt')\n pass\ntests.test_train_nn(train_nn)\n\n\ndef run():\n epochs = 10\n batch_size = 20\n learn_rate = 1e-3\n\n num_classes = 2\n image_shape = (160, 576)\n label_channels = 2\n data_dir = '/data'\n runs_dir = './runs'\n tests.test_for_kitti_dataset(data_dir)\n\n # Download pretrained vgg model\n helper.maybe_download_pretrained_vgg(data_dir)\n\n # OPTIONAL: Train and Inference on the cityscapes dataset instead of the Kitti dataset.\n # You'll need a GPU with at least 10 teraFLOPS to train on.\n # https://www.cityscapes-dataset.com/\n\n with tf.Session() as sess:\n\n # Path to vgg model\n vgg_path = os.path.join(data_dir, 'vgg')\n # Create function to get batches\n images_path = os.path.join(data_dir, 'data_road/training')\n get_batches_fn = helper.gen_batch_function(images_path, image_shape)\n\n # OPTIONAL: Augment Images for better results\n # https://datascience.stackexchange.com/questions/5224/how-to-prepare-augment-images-for-neural-network\n\n l_input, l_keep, l_out3, l_out4, l_out7 = load_vgg(sess, vgg_path)\n l_out = layers(l_out3, l_out4, l_out7, num_classes)\n\n l_label = tf.placeholder(tf.float32, (None, image_shape[0], image_shape[1], label_channels), name='Label')\n l_logits, train_op, loss_op = optimize(l_out, l_label, learn_rate, num_classes)\n\n train_nn(sess, epochs, batch_size, get_batches_fn, train_op, loss_op, l_input, l_label, l_keep,\n learn_rate, images_path)\n\n helper.save_inference_samples(runs_dir, data_dir, sess, image_shape, l_logits, l_keep, l_input)\n\n # OPTIONAL: Apply the trained model to a video\n\n\nif __name__ == '__main__':\n run()\n"
] |
[
[
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.reshape",
"tensorflow.control_dependencies",
"tensorflow.nn.softmax",
"tensorflow.local_variables_initializer",
"tensorflow.one_hot",
"tensorflow.global_variables_initializer",
"tensorflow.add_to_collection",
"tensorflow.get_default_graph",
"tensorflow.layers.batch_normalization",
"tensorflow.Variable",
"tensorflow.train.Saver",
"tensorflow.metrics.true_positives",
"tensorflow.layers.conv2d_transpose",
"tensorflow.add",
"tensorflow.get_collection",
"tensorflow.metrics.mean_iou",
"tensorflow.test.gpu_device_name",
"tensorflow.train.AdamOptimizer",
"tensorflow.nn.relu",
"tensorflow.Session",
"tensorflow.placeholder",
"tensorflow.reduce_sum",
"tensorflow.saved_model.loader.load",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.unstack",
"tensorflow.metrics.false_positives",
"tensorflow.multiply",
"tensorflow.losses.get_regularization_losses",
"tensorflow.variables_initializer",
"tensorflow.reduce_mean",
"tensorflow.stop_gradient"
]
] |
huachao2017/goodsdl
|
[
"3616d53b90696a97a5d56a064e2a14d484b821d7",
"3616d53b90696a97a5d56a064e2a14d484b821d7"
] |
[
"dl/imagedetectionV3.py",
"dl/test_load.py"
] |
[
"import tensorflow as tf\nimport os\nfrom PIL import Image\nimport numpy as np\nimport logging\nimport time\nfrom goods.models import ProblemGoods\nfrom dl.step1_cnn import Step1CNN\nfrom dl.step2_cnn import Step2CNN\nfrom dl.step3_cnn import Step3CNN\nfrom dl.tradition_match import TraditionMatch\nfrom dl.util import visualize_boxes_and_labels_on_image_array_V2\nfrom dl import common\nfrom goods.models import ExportAction\n\nlogger = logging.getLogger(\"detect\")\n\nstep2_model_names = ['inception_resnet_v2','nasnet_large']\n\n\nclass ImageDetectorFactory:\n _detector = {}\n\n @staticmethod\n def get_static_detector(deviceid):\n key = deviceid\n if key not in ImageDetectorFactory._detector:\n export1s = ExportAction.objects.filter(train_action__action='T1').filter(\n checkpoint_prefix__gt=0).order_by(\n '-update_time')[:1]\n export2s = ExportAction.objects.filter(train_action__action='T2').filter(train_action__serial='').filter(\n checkpoint_prefix__gt=0).order_by(\n '-update_time')[:1]\n export3s = ExportAction.objects.filter(train_action__action='T3').filter(train_action__serial='').filter(\n checkpoint_prefix__gt=0).order_by(\n '-update_time')\n\n if len(export1s) == 0 or len(export2s) == 0:\n logger.error('not found detection model!')\n return None\n\n ImageDetectorFactory._detector[key] = ImageDetector(deviceid, export1s[0].pk,export2s[0].pk,export3s,export2s[0].model_name)\n return ImageDetectorFactory._detector[key]\n\nclass ImageDetector:\n def __init__(self, deviceid, export1id, export2id, export3_arr, step2_model_name):\n self.deviceid = deviceid\n file_path, _ = os.path.split(os.path.realpath(__file__))\n self.step1_cnn = Step1CNN(os.path.join(file_path, 'model', str(export1id)))\n self.step2_cnn = Step2CNN(os.path.join(file_path, 'model', str(export2id)),step2_model_name)\n self.step3_cnn = Step3CNN(os.path.join(file_path, 'model'), export3_arr)\n self.tradition_match = TraditionMatch()\n\n self.counter = 0\n self.config = tf.ConfigProto()\n self.config.gpu_options.allow_growth = True\n\n\n def load(self):\n if self.counter > 0:\n logger.info('waiting model to load (3s) ...')\n time.sleep(3)\n return\n self.counter = self.counter + 1\n if not self.step2_cnn.is_load():\n self.tradition_match.load()\n self.step1_cnn.load(self.config)\n self.step2_cnn.load(self.config)\n self.counter = 0\n\n def add_baseline_image(self, image_path, upc):\n if not self.step2S_cnn.is_load():\n self.load()\n self.tradition_match.add_baseline_image(image_path, upc)\n\n def detect(self, image_instance, step1_min_score_thresh=.5, step2_min_score_thresh=.5):\n if not self.step2_cnn.is_load():\n self.load()\n if not self.step2_cnn.is_load():\n logger.warning('loading model failed')\n return None, .0\n\n import time\n time0 = time.time()\n\n image_path = image_instance.source.path\n image = Image.open(image_path)\n if image.mode != 'RGB':\n image = image.convert('RGB')\n\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image_np = np.array(image)\n\n (boxes, scores) = self.step1_cnn.detect(image_np)\n\n # data solving\n boxes = np.squeeze(boxes)\n # classes = np.squeeze(classes).astype(np.int32)\n scores = np.squeeze(scores)\n\n time1 = time.time()\n\n boxes[:,0] = boxes[:,0]*image.size[1]\n boxes[:,1] = boxes[:,1]*image.size[0]\n boxes[:,2] = boxes[:,2]*image.size[1]\n boxes[:,3] = boxes[:,3]*image.size[0]\n boxes = np.array(boxes,dtype=np.int)\n\n boxes_step1 = []\n scores_step1 = []\n step2_images = []\n step2_image_paths = []\n for i in range(boxes.shape[0]):\n if scores[i] > step1_min_score_thresh:\n # sub_time0 = time.time()\n ymin, xmin, ymax, xmax = boxes[i]\n boxes_step1.append([ymin, xmin, ymax, xmax])\n scores_step1.append(scores[i])\n\n newimage = image.crop((xmin, ymin, xmax, ymax))\n\n # 生成新的图片\n newimage_split = os.path.split(image_path)\n single_image_dir = os.path.join(newimage_split[0], 'single')\n if not tf.gfile.Exists(single_image_dir):\n tf.gfile.MakeDirs(single_image_dir)\n new_image_path = os.path.join(single_image_dir, \"{}_{}\".format(i, newimage_split[1]))\n step2_image_paths.append(new_image_path)\n newimage.save(new_image_path, 'JPEG')\n step2_images.append(self.step2_cnn.pre_detect(new_image_path))\n\n if len(step2_images) <= 0:\n time2 = time.time()\n logger.info('detectV3: %s, 0, %.2f, %.2f, %.2f' % (image_instance.deviceid, time2 - time0, time1 - time0, time2 - time1))\n return [], time2-time0\n\n # upcs_match, scores_match = self.tradition_match.detect(step2_image_paths)\n # time2 = time.time()\n\n upcs_step2, scores_step2 = self.step2_cnn.detect(step2_images)\n time2 = time.time()\n\n types_step2 = []\n for i in range(len(step2_image_paths)):\n if upcs_step2[i] == 'bottled-drink-stand' or upcs_step2[i] == 'ziptop-drink-stand':\n types_step2.append(common.MATCH_TYPE_DEEPLEARNING)\n continue\n if upcs_step2[i] in self.step2_cnn.cluster_upc_to_traintype:\n within_upcs = self.step2_cnn.cluster_traintype_to_class_names[self.step2_cnn.cluster_upc_to_traintype[upcs_step2[i]]]\n else:\n within_upcs = [upcs_step2[i]]\n score_verify = self.tradition_match.verify_score(step2_image_paths[i], within_upcs)\n if score_verify > 0.6:\n types_step2.append(common.MATCH_TYPE_BOTH)\n else:\n time3_0 = time.time()\n upc_match, score_match = self.tradition_match.detect_one(step2_image_paths[i])\n time3_1 = time.time()\n logger.info('step2 tridition match: %.2f,%s, %.2f' % (time3_1-time3_0, upc_match, score_match))\n if score_match > 0.6: # TODO\n upcs_step2[i] = upc_match\n scores_step2[i] = score_match\n types_step2.append(common.MATCH_TYPE_TRADITION)\n if upc_match in self.step2_cnn.cluster_class_names_to_main_class:\n upcs_step2[i] = self.step2_cnn.cluster_class_names_to_main_class[upc_match]\n else:\n types_step2.append(common.MATCH_TYPE_DEEPLEARNING) # TODO 暂时做乐观处理\n\n logger.info(types_step2)\n time3 = time.time()\n\n ret = self.do_addition_logic_work(boxes_step1, scores_step1, upcs_step2, scores_step2, types_step2, step2_image_paths, image_instance, image_np, step2_min_score_thresh)\n\n time4 = time.time()\n logger.info('detectV3: %s, %d, %.2f, %.2f, %.2f, %.2f, %.2f' %(image_instance.deviceid, len(ret), time4-time0, time1-time0, time2-time1, time3-time2, time4-time3))\n return ret, time4-time0\n\n def do_addition_logic_work(self, boxes_step1, scores_step1, upcs_step2, scores_step2, match_types_step2, step2_image_paths, image_instance, image_np, step2_min_score_thresh):\n ret = []\n for i in range(len(boxes_step1)):\n ymin, xmin, ymax, xmax = boxes_step1[i]\n\n score2 = scores_step2[i]\n action = 0\n upc = upcs_step2[i]\n match_type = match_types_step2[i]\n if match_type == -1:\n # 识别度不够\n upc = ''\n elif match_type == 1 and (upc == 'bottled-drink-stand' or upc == 'ziptop-drink-stand'):\n # 立姿水需要躺倒平放\n upc = ''\n action = 2\n elif match_type != -1 and upc in self.step2_cnn.cluster_upc_to_traintype:\n traintype = self.step2_cnn.cluster_upc_to_traintype[upc]\n probabilities, step3_labels_to_names = self.step3_cnn.detect(self.config, step2_image_paths[i], traintype)\n if step3_labels_to_names is not None:\n sorted_inds = [j[0] for j in sorted(enumerate(-probabilities[0]), key=lambda x: x[1])]\n step3_class_type = sorted_inds[0]\n score2 = probabilities[0][sorted_inds[0]]\n\n if step3_labels_to_names[step3_class_type][:6] == 'action':\n try:\n action = int(step3_labels_to_names[step3_class_type][6:])\n except ValueError:\n action = 3\n else:\n upc = step3_labels_to_names[step3_class_type]\n logger.info('step3: %d, %s, %d' % (traintype, upc, action))\n\n ret.append({'class': match_type,\n 'score': scores_step1[i],\n 'score2': score2,\n 'action': action,\n 'upc': upc,\n 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax\n })\n\n # visualization\n if len(ret) > 0:\n # TODO need add step3\n image_path = image_instance.source.path\n image_dir = os.path.dirname(image_path)\n output_image_path = os.path.join(image_dir, 'visual_' + os.path.split(image_path)[-1])\n visualize_boxes_and_labels_on_image_array_V2(\n image_np,\n np.array(boxes_step1),\n np.array(upcs_step2),\n scores_step1,\n scores_step2,\n use_normalized_coordinates=False,\n step2_min_score_thresh=step2_min_score_thresh,\n line_thickness=2)\n output_image = Image.fromarray(image_np)\n output_image.save(output_image_path)\n return ret\n\n def log_problem_goods(self, i, image_instance, type_to_probability, sorted_inds):\n ProblemGoods.objects.create(image_id=image_instance.pk,\n index=i,\n class_type_0=sorted_inds[0],\n class_type_1=sorted_inds[1],\n class_type_2=sorted_inds[2],\n class_type_3=sorted_inds[3],\n class_type_4=sorted_inds[4],\n score_0=type_to_probability[sorted_inds[0]],\n score_1=type_to_probability[sorted_inds[1]],\n score_2=type_to_probability[sorted_inds[2]],\n score_3=type_to_probability[sorted_inds[3]],\n score_4=type_to_probability[sorted_inds[4]],\n )\n",
"import os\nimport tensorflow as tf\nfrom nets import nets_factory\nimport time\nfrom dl.step1_cnn import Step1CNN\nfrom dl.step2_cnn import Step2CNN\nfrom dl.util import get_labels_to_names\nimport GPUtil as GPU\n\nimport django\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"main.settings\")\ndjango.setup()\nfrom goods.models import ExportAction\n\ndef load_step3_one(config, model_dir, export):\n time0 = time.time()\n\n traintype_modeldir = os.path.join(model_dir, str(export.pk))\n checkpoint = tf.train.latest_checkpoint(traintype_modeldir)\n tf.logging.info('begin loading step3 model: {}-{}'.format(export.train_action.traintype, checkpoint))\n labels_to_names = get_labels_to_names(os.path.join(traintype_modeldir, 'labels.txt'))\n\n network_fn = nets_factory.get_network_fn(\n export.model_name,\n num_classes=len(labels_to_names),\n is_training=False)\n image_size = network_fn.default_image_size\n\n time1 = time.time()\n\n _graph = tf.Graph()\n with _graph.as_default():\n input_image_path = tf.placeholder(dtype=tf.string, name='input_image')\n image_string = tf.read_file(input_image_path)\n image = tf.image.decode_jpeg(image_string, channels=3, name='image_tensor')\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n image = tf.expand_dims(image, 0)\n images = tf.image.resize_bilinear(image, [image_size, image_size], align_corners=False)\n images = tf.subtract(images, 0.5)\n images = tf.multiply(images, 2.0)\n logits, _ = network_fn(images)\n probabilities = tf.nn.softmax(logits, name='detection_classes')\n time2 = time.time()\n variables_to_restore = tf.global_variables()\n saver = tf.train.Saver(variables_to_restore)\n session = tf.Session(config=config)\n saver.restore(session, checkpoint)\n time3 = time.time()\n\n tf.logging.info('end loading: %.2f, %.2f, %.2f, %.2f' % (time3 - time0, time1 - time0, time2 - time1, time3 - time2))\n return session\n\ndef load_all(model_dir, traintype_to_session):\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n time0 = time.time()\n\n export1s = ExportAction.objects.filter(train_action__action='T1').filter(checkpoint_prefix__gt=0).order_by(\n '-update_time')[:1]\n step1_cnn = Step1CNN(os.path.join(model_dir, str(export1s[0].pk)))\n step1_cnn.load(config)\n traintype_to_session[0] = step1_cnn._session\n GPU.showUtilization(True)\n time1 = time.time()\n\n export2s = ExportAction.objects.filter(train_action__action='T2').filter(checkpoint_prefix__gt=0).order_by(\n '-update_time')[:1]\n step2_cnn = Step2CNN(os.path.join(model_dir, str(export2s[0].pk)), export2s[0].model_name)\n step2_cnn.load(config)\n traintype_to_session[0] = step2_cnn._session\n GPU.showUtilization(True)\n time2 = time.time()\n\n export3s = ExportAction.objects.filter(train_action__action='T3').filter(checkpoint_prefix__gt=0).order_by(\n '-update_time')\n\n for export in export3s:\n traintype = export.train_action.traintype\n if traintype not in traintype_to_session:\n session = load_step3_one(config, model_dir, export)\n traintype_to_session[traintype] = session\n GPU.showUtilization(True)\n\n time3 = time.time()\n tf.logging.info('loading finish: %.2f, %.2f, %.2f, %.2f' % (time3 - time0, time1 - time0, time2 - time1, time3 - time2))\n\ndef main(_):\n\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n tf.logging.set_verbosity('INFO')\n traintype_to_session = {}\n model_dir = '/home/src/goodsdl/dl/model'\n load_all(model_dir, traintype_to_session)\n\n time0 = time.time()\n image_path = '/home/src/goodsdl/images/test_1.jpg'\n test_traintype = 7\n if test_traintype in traintype_to_session:\n probabilities = traintype_to_session[test_traintype].run(\n traintype_to_session[test_traintype].graph.get_tensor_by_name('detection_classes:0'),\n feed_dict={traintype_to_session[test_traintype].graph.get_tensor_by_name('input_image:0'): image_path}\n )\n time1 = time.time()\n tf.logging.info('test image: %.2f' % (time1 - time0))\n\nif __name__ == '__main__':\n tf.app.run()"
] |
[
[
"numpy.array",
"tensorflow.gfile.Exists",
"tensorflow.ConfigProto",
"tensorflow.gfile.MakeDirs",
"numpy.squeeze"
],
[
"tensorflow.image.resize_bilinear",
"tensorflow.logging.set_verbosity",
"tensorflow.multiply",
"tensorflow.train.latest_checkpoint",
"tensorflow.expand_dims",
"tensorflow.read_file",
"tensorflow.Graph",
"tensorflow.image.convert_image_dtype",
"tensorflow.subtract",
"tensorflow.logging.info",
"tensorflow.global_variables",
"tensorflow.train.Saver",
"tensorflow.Session",
"tensorflow.ConfigProto",
"tensorflow.placeholder",
"tensorflow.nn.softmax",
"tensorflow.app.run",
"tensorflow.image.decode_jpeg"
]
] |
gcinbis/deep-generative-models-spring20
|
[
"d377bd63d5e79539477cca47c71462e5cc12adfa"
] |
[
"SphereGAN/resnet.py"
] |
[
"from torch import nn\nfrom torch.autograd import grad\nimport torch\n\nfrom model_utils import *\n\nclass conv3x3(nn.Module):\n '''\n 3x3 Conv utility class\n '''\n def __init__(self, input_dim, output_dim = None, bias = False):\n super(conv3x3, self).__init__()\n \n if output_dim == None:\n output_dim = input_dim\n\n self.conv = nn.Conv2d(input_dim, output_dim, 3, stride=1, padding=1, bias = bias)\n\n def forward(self, input):\n output = self.conv(input)\n return output\n\n\nclass ResidualBlockDownSample(nn.Module):\n '''\n Residual block with downsplampled shortcut, which reduces the spatial size by half.\n To be used in Discrimintor.\n\n Args:\n input_dim: number of features\n size: spatial dimension of the input.\n\n '''\n def __init__(self, input_dim, size=48):\n super(ResidualBlockDownSample, self).__init__()\n \n half_size = size//2\n\n self.avg_pool1 = nn.AdaptiveAvgPool2d((half_size,half_size))\n self.conv_shortcut = nn.Conv2d(input_dim, input_dim, kernel_size = 1)\n\n self.relu1 = nn.LeakyReLU(0.2)\n self.relu2 = nn.LeakyReLU(0.2)\n\n self.ln1 = nn.LayerNorm([input_dim, size, size])\n self.ln2 = nn.LayerNorm([input_dim, half_size, half_size])\n \n self.conv_1 = conv3x3(input_dim, input_dim, bias = False)\n self.conv_2 = conv3x3(input_dim, input_dim, bias = False)\n \n self.avg_pool2 = nn.AdaptiveAvgPool2d((half_size, half_size))\n \n \n def forward(self, input):\n shortcut = self.avg_pool1(input)\n shortcut = self.conv_shortcut(shortcut)\n\n output = self.ln1(input)\n output = self.relu1(output)\n output = self.conv_1(output)\n\n output = self.avg_pool2(output)\n\n output = self.ln2(output)\n output = self.relu2(output)\n output = self.conv_2(output)\n\n return shortcut + output\n\nclass ResidualBlockUpSample(nn.Module):\n \"\"\"\n Residual block with upsampled shortcut, which doubles the spatial size.\n To be used in Discrimintor.\n\n Args:\n input_dim: number of features\n size: spatial dimension of the input.\n \"\"\"\n def __init__(self, input_dim, size):\n super(ResidualBlockUpSample, self).__init__()\n \n self.upsample1 = nn.Upsample(scale_factor=2)\n self.conv_shortcut = nn.Conv2d(input_dim, input_dim, kernel_size = 1)\n\n self.relu1 = nn.ReLU(True)\n self.relu2 = nn.ReLU(True)\n\n self.bn1 = nn.BatchNorm2d(input_dim)\n self.bn2 = nn.BatchNorm2d(input_dim)\n \n self.conv_1 = conv3x3(input_dim, input_dim, bias = False)\n self.conv_2 = conv3x3(input_dim, input_dim, bias = False) \n self.upsample2 = nn.Upsample(scale_factor=2)\n \n \n def forward(self, input):\n shortcut = self.upsample1(input)\n shortcut = self.conv_shortcut(shortcut)\n\n output = self.bn1(input)\n output = self.relu1(output)\n output = self.conv_1(output)\n\n output = self.upsample2(output)\n\n output = self.bn2(output)\n output = self.relu2(output)\n output = self.conv_2(output)\n\n return shortcut + output\n\nclass ResidualBlock(nn.Module):\n \"\"\"\n Standart residual block with layernorm instead of batchnorm.\n\n \"\"\"\n def __init__(self, input_dim, size):\n super(ResidualBlock, self).__init__()\n \n self.conv_shortcut = nn.Conv2d(input_dim, input_dim, kernel_size = 1)\n\n self.relu1 = nn.LeakyReLU(0.2)\n self.relu2 = nn.LeakyReLU(0.2)\n\n self.ln1 = nn.LayerNorm([input_dim, size, size])\n self.ln2 = nn.LayerNorm([input_dim, size, size])\n \n self.conv_1 = conv3x3(input_dim, input_dim, bias = False)\n self.conv_2 = conv3x3(input_dim, input_dim, bias = False) \n \n \n def forward(self, input):\n shortcut = self.conv_shortcut(input)\n\n output = self.ln1(input)\n output = self.relu1(output)\n output = self.conv_1(output)\n\n output = self.ln2(output)\n output = self.relu2(output)\n output = self.conv_2(output)\n\n return shortcut + output\n\n\nclass GeneratorResNet(nn.Module):\n \"\"\"\n Resnet Generator Network\n\n Dimension flow:\n 128 => dim,3,3 => dim,6,6 => dim,12,12 => dim,24,24 => dim,48,48 => 3,48,48\n\n Args:\n dim: number of features\n \"\"\"\n def __init__(self, dim=256):\n super(GeneratorResNet, self).__init__()\n\n self.dim = dim\n \n self.ln1 = nn.Linear(128, 3*3*self.dim, bias=False)\n self.reshape = View((self.dim, 3, 3))\n self.bn_ln = nn.BatchNorm2d(self.dim)\n \n self.rb1 = ResidualBlockUpSample(self.dim, size=3)\n self.rb2 = ResidualBlockUpSample(self.dim, size=6)\n self.rb3 = ResidualBlockUpSample(self.dim, size=12)\n self.rb4 = ResidualBlockUpSample(self.dim, size=24)\n self.bn = nn.BatchNorm2d(self.dim)\n\n self.conv1 = conv3x3(self.dim, 3)\n self.relu = nn.ReLU(True)\n self.tanh = nn.Tanh()\n\n def forward(self, input):\n output = input\n \n output = self.ln1(output)\n output = self.reshape(output)\n output = self.bn_ln(output)\n \n output = self.rb1(output)\n output = self.rb2(output)\n output = self.rb3(output)\n output = self.rb4(output)\n output = self.bn(output)\n\n output = self.relu(output)\n output = self.conv1(output)\n output = self.tanh(output)\n\n return output\n\nclass DiscriminatorResNet(nn.Module):\n \"\"\"\n Resnet Discriminator Network attached with Geometric block.\n\n Dimension flow:\n 3,48,48 => dim,48,48 => dim,24,24 => dim,12,12 => dim,6,6 => dim,3,3\n\n Args:\n dim: number of features\n \"\"\"\n def __init__(self, dim=256):\n super(DiscriminatorResNet, self).__init__()\n\n self.dim = dim\n\n self.conv1 = conv3x3(3, self.dim)\n self.rb1 = ResidualBlockDownSample(self.dim, size=48)\n self.rb2 = ResidualBlockDownSample(self.dim, size=24)\n self.rb3 = ResidualBlockDownSample(self.dim, size=12)\n self.rb4 = ResidualBlockDownSample(self.dim, size=6)\n self.rb5 = ResidualBlock(self.dim, size=3)\n\n self.gb = GeometricBlock(dim=self.dim, pool=True)\n\n\n def forward(self, input):\n output = input\n output = self.conv1(output)\n output = self.rb1(output)\n output = self.rb2(output)\n output = self.rb3(output)\n output = self.rb4(output)\n output = self.rb5(output)\n output = self.gb(output)\n \n return output\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.LayerNorm",
"torch.nn.Tanh",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm2d",
"torch.nn.Upsample",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.AdaptiveAvgPool2d"
]
] |
jeremiedecock/snippets
|
[
"4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"4bd4e7f459eee610d5cf19f845299ca942ff4b64"
] |
[
"python/tkinter/python3/matplotlib_canvas_with_animation.py",
"python/matplotlib/tkinter_with_navigation_toolbar.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2012 Jérémie DECOCK (http://www.jdhp.org)\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n# See: http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html\n# http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk2.html\n# http://stackoverflow.com/questions/18675266/how-to-make-matplotlibpyplot-resizeable-with-the-tkinter-window-in-python\n\nimport matplotlib\nmatplotlib.use('TkAgg')\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\nimport tkinter as tk\nimport time\n\nDELTA_TIME_MS = 100\n\nclass Gui:\n\n def __init__(self, root):\n\n # Matplotlib ##################\n\n self.fig = plt.figure(figsize=(8.0, 8.0))\n\n # Make widgets ################\n\n self.root = root\n\n # Add a callback on WM_DELETE_WINDOW events\n self.root.protocol(\"WM_DELETE_WINDOW\", self.quit)\n\n # Canvas\n self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)\n self.canvas.get_tk_widget().pack(fill=\"both\", expand=True)\n\n # Draw the figure #############\n\n self.draw_figure()\n\n\n def update_canvas(self):\n # Draw the figure\n self.draw_figure()\n\n # Reschedule event in DELTA_TIME_MS milli seconds\n self.root.after(DELTA_TIME_MS, self.update_canvas)\n\n\n def draw_figure(self):\n \"\"\"\n Draw the figure.\n \"\"\"\n self.fig.clf()\n \n ax = self.fig.add_subplot(111)\n\n t = time.time() % (2. * np.pi)\n x = np.arange(-10, 10, 0.01)\n y = np.sin(x + t)\n ax.plot(x, y)\n\n self.fig.canvas.draw()\n\n\n def run(self):\n \"\"\"\n Launch the main loop (Tk event loop).\n \"\"\"\n # Schedule event in DELTA_TIME_MS milli seconds\n self.root.after(DELTA_TIME_MS, self.update_canvas)\n\n # Launch the main loop\n self.root.mainloop()\n\n\n def quit(self):\n \"\"\"\n Clean exit.\n \"\"\"\n self.root.quit() # stops mainloop\n self.root.destroy() # this is necessary on Windows to prevent\n # Fatal Python Error: PyEval_RestoreThread: NULL tstate\n\ndef main():\n root = tk.Tk()\n gui = Gui(root)\n gui.run()\n\n\nif __name__ == \"__main__\":\n main()\n",
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2012 Jérémie DECOCK (http://www.jdhp.org)\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n# See: http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html\n# http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk2.html\n# http://stackoverflow.com/questions/18675266/how-to-make-matplotlibpyplot-resizeable-with-the-tkinter-window-in-python\n\nimport matplotlib\nmatplotlib.use('TkAgg')\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\n# implement the default mpl key bindings\nfrom matplotlib.backend_bases import key_press_handler\n\nimport tkinter as tk\n\n# MATPLOTLIB ##################################################################\n\nx_vec = np.arange(-10, 10, 0.01)\ny_vec = np.sin(2 * 2 * np.pi * x_vec) * 1/np.sqrt(2*np.pi) * np.exp(-(x_vec**2)/2)\n\nfig = plt.figure(figsize=(12.0, 6.0))\nax = fig.add_subplot(111)\nax.plot(x_vec, y_vec, \"-\", label=\"Test\")\n\n# Title and labels\nax.set_title(r\"Test\", fontsize=20)\nax.set_xlabel(r\"$x$\", fontsize=32)\nax.set_ylabel(r\"$f(x)$\", fontsize=32)\n\n# Legend\nax.legend(loc='lower right', fontsize=20)\n\n# TKINTER #####################################################################\n\nroot = tk.Tk()\n\ncanvas = FigureCanvasTkAgg(fig, master=root)\ncanvas.get_tk_widget().pack(fill=tk.BOTH, expand=1)\n\ntoolbar = NavigationToolbar2TkAgg( canvas, root )\ntoolbar.update()\ncanvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n\ndef on_key_event(event):\n print('you pressed %s'%event.key)\n key_press_handler(event, canvas, toolbar)\n\ncanvas.mpl_connect('key_press_event', on_key_event)\n\ndef _quit():\n root.quit() # stops mainloop\n root.destroy() # this is necessary on Windows to prevent\n # Fatal Python Error: PyEval_RestoreThread: NULL tstate\n\nbutton = tk.Button(master=root, text='Quit', command=_quit)\nbutton.pack(side=tk.BOTTOM)\n\n# Add a callback on WM_DELETE_WINDOW event\nroot.protocol(\"WM_DELETE_WINDOW\", _quit)\n\nroot.mainloop()\n"
] |
[
[
"matplotlib.use",
"numpy.sin",
"matplotlib.pyplot.figure",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg",
"numpy.arange"
],
[
"matplotlib.use",
"numpy.sin",
"matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg",
"matplotlib.backend_bases.key_press_handler",
"numpy.exp",
"matplotlib.pyplot.figure",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg",
"numpy.arange",
"numpy.sqrt"
]
] |
adriangrepo/segmentl
|
[
"9b520bf6cfd005eef9bba3db36ee6b3bb373b085"
] |
[
"similarity/experimental.py"
] |
[
"\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom math import exp\nimport numpy as np\nfrom segmentl.utils import get_activation_fn\nfrom skimage.feature import masked_register_translation\nfrom skimage import data, img_as_float\nfrom skimage.metrics import structural_similarity as ssim\nfrom skimage import transform as tf\nfrom math import exp\nimport numpy as np\nfrom segmentl.utils import get_activation_fn\nfrom segmentl.distance.utils import get_edges, binary_mask, binarize_thresh, downsample, crop_center\nfrom matplotlib import pyplot as plt\n\ndef gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])\n return gauss/gauss.sum()\n\n\ndef create_window(window_size, channel=1):\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()\n return window\n\n\ndef ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None, pad=False):\n # Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).\n if val_range is None:\n if torch.max(img1) > 128:\n max_val = 255\n else:\n max_val = 1\n\n if torch.min(img1) < -0.5:\n min_val = -1\n else:\n min_val = 0\n L = max_val - min_val\n else:\n L = val_range\n\n if pad:\n padding = window_size // 2\n else:\n padding = 0\n (_, channel, height, width) = img1.size()\n if window is None:\n real_size = min(window_size, height, width)\n window = create_window(real_size, channel=channel).to(img1.device)\n\n if torch.isnan(window).any():\n print(f'isnan(window): {torch.isnan(window).any()}, {window}')\n\n '''F.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) '''\n mu1 = F.conv2d(img1, window, padding=padding, groups=channel)\n mu2 = F.conv2d(img2, window, padding=padding, groups=channel)\n\n if torch.isnan(mu1).any():\n print(f'--ssim() isnan(img1).any(): {torch.isnan(img1).any()}')\n print(f'--ssim() isnan(window).any(): {torch.isnan(window).any()}')\n print(f'--ssim() isnan(mu1): {torch.isnan(mu1).any()}, {mu1}')\n if torch.isnan(mu2).any():\n print(f'--ssim() isnan(img2).any(): {torch.isnan(img2).any()}')\n print(f'--ssim() isnan(window).any(): {torch.isnan(window).any()}')\n print(f'--ssim() isnan(mu2): {torch.isnan(mu2).any()}, {mu2}')\n\n mu1_sq = mu1.pow(2)\n mu2_sq = mu2.pow(2)\n mu1_mu2 = mu1 * mu2\n\n if torch.isnan(mu1_sq).any():\n print(f'isnan(mu1_sq): {torch.isnan(mu1_sq).any()}, {mu1_sq}')\n if torch.isnan(mu2_sq).any():\n print(f'isnan(mu2_sq): {torch.isnan(mu2_sq).any()}, {mu2_sq}')\n if torch.isnan(mu1_mu2).any():\n print(f'isnan(mu1_mu2): {torch.isnan(mu1_mu2).any()}, {mu1_mu2}')\n\n sigma1_sq = F.conv2d(img1 * img1, window, padding=padding, groups=channel) - mu1_sq\n sigma2_sq = F.conv2d(img2 * img2, window, padding=padding, groups=channel) - mu2_sq\n sigma12 = F.conv2d(img1 * img2, window, padding=padding, groups=channel) - mu1_mu2\n\n if torch.isnan(sigma1_sq).any():\n print(f'--ssim() isnan(sigma1_sq): {torch.isnan(sigma1_sq).any()}, {sigma1_sq}')\n print(f'--ssim() isnan(sigma1_sq) shapes sigma1_sq: {sigma1_sq.shape}, window: {window.shape}, \\\n img1: {img1.shape}, mu1_sq: {mu1_sq.shape}')\n print(f'--ssim() isnan(sigma1_sq) padding: {padding}, channel: {channel}')\n print(f'--ssim() isnan(sigma1_sq) isnan(img1): {torch.isnan(img1).any()}, {img1}')\n print(f'--ssim() isnan(sigma1_sq) isnan(window): {torch.isnan(window).any()}, {window}')\n print(f'--ssim() isnan(sigma1_sq) isnan(mu1_sq): {torch.isnan(mu1_sq).any()}, {mu1_sq}')\n if torch.isnan(sigma2_sq).any():\n print(f'--ssim() isnan(sigma2_sq): {torch.isnan(sigma2_sq).any()}, {sigma2_sq}')\n if torch.isnan(sigma12).any():\n print(f'--ssim() isnan(sigma12): {torch.isnan(sigma12).any()}, {sigma12}')\n\n K1 = 0.01 #default settings\n K2 = 0.03\n C1 = (K1 * L) ** 2\n C2 = (K2 * L) ** 2\n v1 = 2.0 * sigma12 + C2\n v2 = sigma1_sq + sigma2_sq + C2\n epsilon = 1e-7\n ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)\n if torch.isnan(ssim_map).any():\n print(f'--ssim() isnan(ssim_map): {torch.isnan(ssim_map).any()}, {ssim_map}')\n #hack to set any nan to epsilon\n ssim_map[ssim_map != ssim_map] = epsilon\n\n if size_average:\n ret = ssim_map.mean()\n else:\n ret = ssim_map.mean(1).mean(1).mean(1)\n\n cs = torch.mean(v1 / v2) # contrast sensitivity\n if full:\n return ret, cs\n return ret\n\n\ndef msssim(img1, img2, window_size=11, size_average=True, val_range=None, normalize=True, avg_pool=False, pad=False):\n device = img1.device\n weights = torch.FloatTensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]).to(device)\n levels = weights.size()[0]\n mssim = []\n mcs = []\n for _ in range(levels):\n\n if avg_pool:\n '''\n Applies 2D average-pooling operation in kH×kW regions by step size sH×sW steps. \n input – input tensor (minibatch,in_channels,iH,iW)\n kernel_size – size of the pooling region. Can be a single number or a tuple (kH, kW)\n stride – stride of the pooling operation. Can be a single number or a tuple (sH, sW). Default: kernel_size\n '''\n img1 = F.avg_pool2d(img1, (2, 2))\n img2 = F.avg_pool2d(img2, (2, 2))\n sim, cs = ssim(img1, img2, window_size=window_size, size_average=size_average, full=True, val_range=val_range, pad=pad)\n\n if torch.isnan(sim).any():\n print(f'--mssim: sim nans: {sim}')\n if torch.isnan(cs).any():\n print(f'--mssim: cs nans: {cs}')\n\n mssim.append(sim)\n mcs.append(cs)\n\n\n\n mssim = torch.stack(mssim)\n mcs = torch.stack(mcs)\n\n # Normalize (to avoid NaNs during training unstable models, not compliant with original definition)\n if normalize:\n mssim = (mssim + 1) / 2\n mcs = (mcs + 1) / 2\n\n if torch.isnan(mssim).any():\n print(f'--mssim: mssim nans: {mssim}')\n if torch.isnan(mcs).any():\n print(f'--mssim: mcs nans: {mcs}')\n\n mcsw = mcs ** weights\n mssimw = mssim ** weights\n\n if torch.isnan(mcsw).any():\n print(f'--mssim: mcsw nans: {mcsw}')\n if torch.isnan(mssimw).any():\n print(f'--mssim: mssimw nans: {mssimw}')\n\n # From Matlab implementation https://ece.uwaterloo.ca/~z70wang/research/iwssim/\n #overall_mssim = prod(mcs_array(1:level - 1).^ weight(1: level - 1))*(mssim_array(level). ^ weight(level));\n #output = torch.prod(mcsw[:-1] * mssimw[-1])\n output = torch.prod(mcsw[1:-1] * mssimw)\n return output\n\n\n\nclass SSIM(torch.nn.Module):\n # after https://github.com/jorge-pessoa/pytorch-msssim/blob/master/pytorch_msssim/__init__.py\n def __init__(self, apply_nonlin='Sigmoid', window_size=11, size_average=True, val_range=None, pad=False):\n super(SSIM, self).__init__()\n self.window_size = window_size\n self.size_average = size_average\n self.val_range = val_range\n self.apply_nonlin=apply_nonlin\n\n # Assume 1 channel for SSIM\n self.channel = 1\n self.window = create_window(window_size)\n\n def forward(self, pred, gt):\n if self.apply_nonlin:\n activation_fn = get_activation_fn(self.apply_nonlin)\n pred = activation_fn(pred)\n (_, channel, _, _) = pred.size()\n\n if channel == self.channel and self.window.dtype == pred.dtype:\n window = self.window\n else:\n window = create_window(self.window_size, channel).to(pred.device).type(pred.dtype)\n self.window = window\n self.channel = channel\n\n ssm, cs =ssim(pred, gt, window=window, window_size=self.window_size, size_average=self.size_average, \\\n full=True, val_range=None, pad=False)\n print(f'cs: {cs}, ssim: {ssm}, loss: {1-ssm}')\n return 1-ssm\n\nclass MSSSIM(torch.nn.Module):\n '''Multi-scale Structural Similarity Index (MS-SSIM)\n Z. Wang, E. P. Simoncelli and A. C. Bovik, \"Multi-scale structural similarity\n for image quality assessment,\" Invited Paper, IEEE Asilomar Conference on\n Signals, Systems and Computers, Nov. 2003\n # after https://github.com/jorge-pessoa/pytorch-msssim/blob/master/pytorch_msssim/__init__.py\n '''\n def __init__(self, apply_nonlin='Sigmoid', window_size=11, size_average=True, channel=3, normalize=True, \\\n avg_pool=False, pad=False):\n super(MSSSIM, self).__init__()\n self.window_size = window_size\n self.size_average = size_average\n self.channel = channel\n self.normalize=normalize\n self.apply_nonlin = apply_nonlin\n self.avg_pool=avg_pool\n self.pad=pad\n\n def forward(self, pred, gt):\n if self.apply_nonlin:\n activation_fn = get_activation_fn(self.apply_nonlin)\n pred = activation_fn(pred)\n sim=msssim(pred, gt, window_size=self.window_size, size_average=self.size_average, \\\n normalize=self.normalize, avg_pool=self.avg_pool, pad=self.pad)\n print(f'<<MSSSIM mssim: {sim}, loss: {1-sim}')\n return 1-sim\n\n\nclass TransformEstimate(torch.nn.Module):\n '''Estimate 2D geometric transformation parameters.\n see https://scikit-image.org/docs/dev/api/skimage.transform.html?highlight=similarity#skimage.transform.estimate_transform\n Convert to np then back to torch'''\n def __init__(self, apply_nonlin='Sigmoid'):\n super(TransformEstimate, self).__init__()\n self.apply_nonlin = apply_nonlin\n\n def forward(self, pred, gt):\n if self.apply_nonlin:\n activation_fn = get_activation_fn(self.apply_nonlin)\n pred = activation_fn(pred)\n print(f'pred: {pred.shape}, gt: {gt.shape}')\n predn=pred.detach().cpu().numpy()\n gtn=gt.detach().cpu().numpy()\n #delta=gtn-predn\n tform = tf.estimate_transform('euclidean', predn, gtn)\n tform=tform.type(torch.float32).to(device=gt.device)\n diff=tform(predn)-gtn\n mt=diff.mean()\n print(f'<<TransformEstimate difference: {mt}, loss: {1-mt}')\n return 1-mt\n\n\nclass SKMSSIM(torch.nn.Module):\n '''Mean structural Similarity with skimage\n When comparing images, the mean squared error (MSE)–while simple to implement–is not highly indicative of perceived similarity.\n Structural similarity aims to address this shortcoming by taking texture into account\n Convert to np then back to torch'''\n\n '''\n ~/.virtualenvs/catalyst_base/lib/python3.7/site-packages/skimage/metrics/_structural_similarity.py \n in structural_similarity(im1, im2, win_size, gradient, data_range, multichannel, gaussian_weights, full, **kwargs)\n 151 if np.any((np.asarray(im1.shape) - win_size) < 0):\n 152 raise ValueError(\n--> 153 \"win_size exceeds image extent. If the input is a multichannel \"\n 154 \"(color) image, set multichannel=True.\")\n '''\n\n def __init__(self, apply_nonlin='Sigmoid'):\n super(SKMSSIM, self).__init__()\n self.apply_nonlin = apply_nonlin\n\n def forward(self, pred, gt):\n if self.apply_nonlin:\n activation_fn = get_activation_fn(self.apply_nonlin)\n pred = activation_fn(pred)\n predn=pred.detach().cpu().numpy()\n gtn=gt.detach().cpu().numpy()\n sim=ssim(predn, gtn, data_range=gtn.max() - gtn.min())\n sim=sim.type(torch.float32).to(device=gt.device)\n print(f'<<MSSSIM mssim: {sim}, loss: {1-sim}')\n return 1-sim\n\ndef ang(a, b):\n epsilon=1e-7\n nza=len(torch.nonzero(a))\n nzb=len(torch.nonzero(b))\n if nza < 1 and nzb < 1:\n #if both pred and gt are zeros want high correlation -\n # but for edges loss this encourages network to just pred nothing all the time - a dillemma I haven't overcome\n cosangle = 1.0\n else:\n cosangle = torch.dot(a, b) / ((torch.norm(a) * torch.norm(b))+epsilon)\n '''\n if nzb < 1 and nza >1 and cosangle > 0.2:\n #cosagle can be pretty unstable eg where get high correlation of full image to empty mask\n #here we use a total hack to give cosangle an arbitrary low value correlated to inverse of preds\n print(f'unstable - nzb: {nzb} nza: {nza} cosangle: {cosangle}')\n cosangle = (a.shape[2]*a.shape[2]-nza)/(a.shape[2]*a.shape[2])\n print(f'unstable cosangle set to: {cosangle}')\n '''\n return cosangle\n\nclass CosEdgeEmbedding(torch.nn.Module):\n '''Measures the loss given inputs x1, x2, and a label tensor y containing values (1 or -1).\n This is used for measuring whether two inputs are similar or dissimilar, using the cosine distance,\n and is typically used for learning nonlinear embeddings or semi-supervised learning.\n\n Too unstable to use (using edges very sensitive to what to decide a loss value for expty pred==empty mask\n For non edges slightly more robust but gets unstable when mask (and preds) fill a large portion of the image\n '''\n def __init__(self, apply_nonlin='Sigmoid', batch=False, edges=True, debug_text=None):\n super(CosEdgeEmbedding, self).__init__()\n self.apply_nonlin = apply_nonlin\n self.batch=batch\n self.edges=edges\n self.debug_text=debug_text\n\n def forward(self, pred, gt):\n if self.apply_nonlin:\n activation_fn = get_activation_fn(self.apply_nonlin)\n pred = activation_fn(pred)\n if self.batch:\n raise NotImplementedError('batch functionality not implemented yet')\n else:\n cels=[]\n i=0\n subsample=0.5\n trim_pix=0\n for pi, gi in zip(pred, gt):\n if self.edges:\n #run the loss on edges of preds and mask\n #cosine similary ias a poor loss function when preds (and mask) cover most of the image\n g = gi.detach().cpu().numpy()\n p = pi.detach().cpu().numpy()\n p = p.squeeze()\n g = g.squeeze()\n #downsample to get thicker edges\n lr_img_2x = downsample(p, fx=subsample, fy=subsample)\n lr_m_2x = downsample(g, fx=subsample, fy=subsample)\n if trim_pix>0:\n lr_img_2x=crop_center(lr_img_2x, lr_img_2x.shape[0]-2,lr_img_2x.shape[0]-trim_pix)\n lr_m_2x = crop_center(lr_m_2x, lr_img_2x.shape[0]-2,lr_img_2x.shape[0]-trim_pix)\n p = binarize_thresh(lr_img_2x, thresh=0.5)\n g = binarize_thresh(lr_m_2x, thresh=0.5)\n edges_m = get_edges(g, 2)\n edges_p = get_edges(p, 2)\n\n p = np.where(edges_p > 0.1, 1, edges_p)\n g = np.where(edges_m > 0.1, 1, edges_m)\n\n p=torch.from_numpy(p).to(pred.device).type(torch.float32)\n g = torch.from_numpy(g).to(pred.device).type(torch.float32)\n p= p.squeeze().flatten()\n g = g.squeeze().flatten()\n else:\n p = pi.squeeze().flatten()\n g = gi.squeeze().flatten()\n\n c = ang(p, g)\n\n if self.debug_text:\n #for debugging qc images that are very similar\n if c and c>0.5 and c<1.0:\n s=int(g.shape[0]**(1/2.0))\n g = g.view(s, -1).detach().cpu().numpy()\n plt.imshow(g)\n plt.savefig(f'images/CosEmbedding_{self.debug_text}_{i}_gt_{c}.png')\n p = p.view(s, -1).detach().cpu().numpy()\n plt.imshow(p)\n plt.savefig(f'images/CosEmbedding_{self.debug_text}_{i}_pred_{c}.png')\n i+=1\n cels.append(c)\n cel = sum(cels)/len(cels)\n cel=torch.tensor(cel).to(device=pred.device)\n return cel\n"
] |
[
[
"torch.nonzero",
"torch.prod",
"torch.stack",
"torch.min",
"torch.isnan",
"torch.max",
"torch.nn.functional.avg_pool2d",
"torch.norm",
"torch.FloatTensor",
"matplotlib.pyplot.savefig",
"torch.from_numpy",
"numpy.where",
"torch.tensor",
"torch.nn.functional.conv2d",
"torch.mean",
"torch.dot",
"matplotlib.pyplot.imshow"
]
] |
anonymous-user-256/mlrc-cgn
|
[
"64f43fcb89b3a13c0ae46db4f19060d9f204a6b1"
] |
[
"cgn_framework/utils/train_utils.py"
] |
[
"import functools\n\nimport torch\nfrom torch import nn\n\nclass Optimizers():\n def __init__(self):\n self._modules = {}\n\n def set(self, k, model, lr=3e-3, betas=(0.9, 0.999)):\n self._modules[k] = torch.optim.Adam(model.parameters(), lr=lr, betas=betas)\n\n def step(self, k_list=[], zero=True):\n if not k_list: k_list = self._modules.keys()\n for k in k_list:\n self._modules[k].step()\n if zero:\n self._modules[k].zero_grad()\n\n def zero_grad(self, k_list):\n for k in k_list: self._modules[k].zero_grad()\n\ndef toggle_grad(model, on_or_off):\n for param in model.parameters():\n param.requires_grad = on_or_off\n\n# useful functions from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix\n\ndef get_norm_layer(norm_type='instance'):\n \"\"\"Return a normalization layer\n Parameters:\n norm_type (str) -- the name of the normalization layer: batch | instance | none\n For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).\n For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.\n \"\"\"\n if norm_type == 'batch':\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)\n elif norm_type == 'instance':\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)\n elif norm_type == 'none':\n def norm_layer(x): return nn.Identity()\n else:\n raise NotImplementedError('normalization layer [%s] is not found' % norm_type)\n return norm_layer\n\ndef init_weights(net, init_type='normal', init_gain=0.02):\n \"\"\"Initialize network weights.\n Parameters:\n net (network) -- network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might\n work better for some applications. Feel free to try yourself.\n \"\"\"\n def init_func(m): # define the initialization function\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n if init_type == 'normal':\n nn.init.normal_(m.weight.data, 0.0, init_gain)\n elif init_type == 'xavier':\n nn.init.xavier_normal_(m.weight.data, gain=init_gain)\n elif init_type == 'kaiming':\n nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif init_type == 'orthogonal':\n nn.init.orthogonal_(m.weight.data, gain=init_gain)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n if hasattr(m, 'bias') and m.bias is not None:\n nn.init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.\n nn.init.normal_(m.weight.data, 1.0, init_gain)\n nn.init.constant_(m.bias.data, 0.0)\n\n print('initialize network with %s' % init_type)\n net.apply(init_func) # apply the initialization function <init_func>\n\ndef init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights\n Parameters:\n net (network) -- the network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n Return an initialized network.\n \"\"\"\n if len(gpu_ids) > 0:\n assert(torch.cuda.is_available())\n net.to(gpu_ids[0])\n net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs\n init_weights(net, init_type, init_gain=init_gain)\n return net\n\n# useful functions from https://github.com/fastai/fastai\n\ndef requires_grad(m:nn.Module, b:[bool]=None)->[bool]:\n \"If `b` is not set return `requires_grad` of first param, else set `requires_grad` on all params as `b`\"\n ps = list(m.parameters())\n if not ps: return None\n if b is None: return ps[0].requires_grad\n for p in ps: p.requires_grad=b\n\ndef children(m): return list(m.children())\n\nclass Hook():\n \"Create a hook on `m` with `hook_func`.\"\n def __init__(self, m, hook_func, is_forward=True, detach=True):\n self.hook_func,self.detach,self.stored = hook_func,detach,None\n f = m.register_forward_hook if is_forward else m.register_backward_hook\n self.hook = f(self.hook_fn)\n self.removed = False\n\n def hook_fn(self, module, input, output):\n \"Applies `hook_func` to `module`, `input`, `output`.\"\n if self.detach:\n input = (o.detach() for o in input ) if is_listy(input ) else input.detach()\n output = (o.detach() for o in output) if is_listy(output) else output.detach()\n self.stored = self.hook_func(module, input, output)\n\n def remove(self):\n \"Remove the hook from the model.\"\n if not self.removed:\n self.hook.remove()\n self.removed=True\n\n def __enter__(self, *args): return self\n def __exit__(self, *args): self.remove()\n\nclass Hooks():\n \"Create several hooks on the modules in `ms` with `hook_func`.\"\n def __init__(self, ms, hook_func, is_forward=True, detach=True):\n self.hooks = [Hook(m, hook_func, is_forward, detach) for m in ms]\n\n def __getitem__(self,i): return self.hooks[i]\n def __len__(self): return len(self.hooks)\n def __iter__(self): return iter(self.hooks)\n @property\n def stored(self): return [o.stored for o in self]\n\n def remove(self):\n \"Remove the hooks from the model.\"\n for h in self.hooks: h.remove()\n\n def __enter__(self, *args): return self\n def __exit__ (self, *args): self.remove()\n\ndef is_listy(x): return isinstance(x, (tuple,list))\n\ndef _hook_inner(m,i,o): return o if isinstance(o,torch.Tensor) else o if is_listy(o) else list(o)\n\ndef hook_output (module, detach=True, grad=False):\n \"Return a `Hook` that stores activations of `module` in `self.stored`\"\n return Hook(module, _hook_inner, detach=detach, is_forward=not grad)\n\ndef hook_outputs(modules, detach=True, grad=False):\n \"Return `Hooks` that store activations of all `modules` in `self.stored`\"\n return Hooks(modules, _hook_inner, detach=detach, is_forward=not grad)\n"
] |
[
[
"torch.nn.Identity",
"torch.nn.init.constant_",
"torch.nn.init.kaiming_normal_",
"torch.nn.init.normal_",
"torch.cuda.is_available",
"torch.nn.init.orthogonal_",
"torch.nn.init.xavier_normal_",
"torch.nn.DataParallel"
]
] |
overhacked/tensorflow
|
[
"892ffbc922e31be803e4182b39fb9e647c9d796f"
] |
[
"tensorflow/python/keras/layers/normalization.py"
] |
[
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Normalization layers.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import constraints\nfrom tensorflow.python.keras import initializers\nfrom tensorflow.python.keras import regularizers\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.engine.input_spec import InputSpec\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variables as tf_variables\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util.tf_export import keras_export\n\n\nclass BatchNormalizationBase(Layer):\n \"\"\"Base class of Batch normalization layer (Ioffe and Szegedy, 2014).\n\n Normalize the activations of the previous layer at each batch,\n i.e. applies a transformation that maintains the mean activation\n close to 0 and the activation standard deviation close to 1.\n\n Arguments:\n axis: Integer, the axis that should be normalized\n (typically the features axis).\n For instance, after a `Conv2D` layer with\n `data_format=\"channels_first\"`,\n set `axis=1` in `BatchNormalization`.\n momentum: Momentum for the moving average.\n epsilon: Small float added to variance to avoid dividing by zero.\n center: If True, add offset of `beta` to normalized tensor.\n If False, `beta` is ignored.\n scale: If True, multiply by `gamma`.\n If False, `gamma` is not used.\n When the next layer is linear (also e.g. `nn.relu`),\n this can be disabled since the scaling\n will be done by the next layer.\n beta_initializer: Initializer for the beta weight.\n gamma_initializer: Initializer for the gamma weight.\n moving_mean_initializer: Initializer for the moving mean.\n moving_variance_initializer: Initializer for the moving variance.\n beta_regularizer: Optional regularizer for the beta weight.\n gamma_regularizer: Optional regularizer for the gamma weight.\n beta_constraint: Optional constraint for the beta weight.\n gamma_constraint: Optional constraint for the gamma weight.\n renorm: Whether to use Batch Renormalization\n (https://arxiv.org/abs/1702.03275). This adds extra variables during\n training. The inference is the same for either value of this parameter.\n renorm_clipping: A dictionary that may map keys 'rmax', 'rmin', 'dmax' to\n scalar `Tensors` used to clip the renorm correction. The correction\n `(r, d)` is used as `corrected_value = normalized_value * r + d`, with\n `r` clipped to [rmin, rmax], and `d` to [-dmax, dmax]. Missing rmax, rmin,\n dmax are set to inf, 0, inf, respectively.\n renorm_momentum: Momentum used to update the moving means and standard\n deviations with renorm. Unlike `momentum`, this affects training\n and should be neither too small (which would add noise) nor too large\n (which would give stale estimates). Note that `momentum` is still applied\n to get the means and variances for inference.\n fused: if `True`, use a faster, fused implementation, or raise a ValueError\n if the fused implementation cannot be used. If `None`, use the faster\n implementation if possible. If False, do not used the fused\n implementation.\n trainable: Boolean, if `True` the variables will be marked as trainable.\n virtual_batch_size: An `int`. By default, `virtual_batch_size` is `None`,\n which means batch normalization is performed across the whole batch. When\n `virtual_batch_size` is not `None`, instead perform \"Ghost Batch\n Normalization\", which creates virtual sub-batches which are each\n normalized separately (with shared gamma, beta, and moving statistics).\n Must divide the actual batch size during execution.\n adjustment: A function taking the `Tensor` containing the (dynamic) shape of\n the input tensor and returning a pair (scale, bias) to apply to the\n normalized values (before gamma and beta), only during training. For\n example, if axis==-1,\n `adjustment = lambda shape: (\n tf.random_uniform(shape[-1:], 0.93, 1.07),\n tf.random_uniform(shape[-1:], -0.1, 0.1))`\n will scale the normalized value by up to 7% up or down, then shift the\n result by up to 0.1 (with independent scaling and bias for each feature\n but shared across all examples), and finally apply gamma and/or beta. If\n `None`, no adjustment is applied. Cannot be specified if\n virtual_batch_size is specified.\n\n Call arguments:\n inputs: Input tensor (of any rank).\n training: Python boolean indicating whether the layer should behave in\n training mode or in inference mode.\n - `training=True`: The layer will normalize its inputs using the\n mean and variance of the current batch of inputs.\n - `training=False`: The layer will normalize its inputs using the\n mean and variance of its moving statistics, learned during training.\n\n Input shape:\n Arbitrary. Use the keyword argument `input_shape`\n (tuple of integers, does not include the samples axis)\n when using this layer as the first layer in a model.\n\n Output shape:\n Same shape as input.\n\n References:\n - [Batch Normalization: Accelerating Deep Network Training by Reducing\n Internal Covariate Shift](https://arxiv.org/abs/1502.03167)\n \"\"\"\n\n # By default, the base class uses V2 behavior. The BatchNormalization V1\n # subclass sets this to False to use the V1 behavior.\n _USE_V2_BEHAVIOR = True\n\n def __init__(self,\n axis=-1,\n momentum=0.99,\n epsilon=1e-3,\n center=True,\n scale=True,\n beta_initializer='zeros',\n gamma_initializer='ones',\n moving_mean_initializer='zeros',\n moving_variance_initializer='ones',\n beta_regularizer=None,\n gamma_regularizer=None,\n beta_constraint=None,\n gamma_constraint=None,\n renorm=False,\n renorm_clipping=None,\n renorm_momentum=0.99,\n fused=None,\n trainable=True,\n virtual_batch_size=None,\n adjustment=None,\n name=None,\n **kwargs):\n super(BatchNormalizationBase, self).__init__(\n name=name, trainable=trainable, **kwargs)\n if isinstance(axis, list):\n self.axis = axis[:]\n elif isinstance(axis, int):\n self.axis = axis\n else:\n raise TypeError('axis must be int or list, type given: %s'\n % type(self.axis))\n self.momentum = momentum\n self.epsilon = epsilon\n self.center = center\n self.scale = scale\n self.beta_initializer = initializers.get(beta_initializer)\n self.gamma_initializer = initializers.get(gamma_initializer)\n self.moving_mean_initializer = initializers.get(moving_mean_initializer)\n self.moving_variance_initializer = initializers.get(\n moving_variance_initializer)\n self.beta_regularizer = regularizers.get(beta_regularizer)\n self.gamma_regularizer = regularizers.get(gamma_regularizer)\n self.beta_constraint = constraints.get(beta_constraint)\n self.gamma_constraint = constraints.get(gamma_constraint)\n self.renorm = renorm\n self.virtual_batch_size = virtual_batch_size\n self.adjustment = adjustment\n if self._USE_V2_BEHAVIOR:\n if fused:\n self._raise_if_fused_cannot_be_used()\n # We leave fused as None if self._fused_can_be_used()==True, since we\n # still may set it to False in self.build() if the input rank is not 4.\n elif fused is None and not self._fused_can_be_used():\n fused = False\n elif fused is None:\n fused = True\n self.supports_masking = True\n\n self.fused = fused\n self._bessels_correction_test_only = True\n\n if renorm:\n renorm_clipping = renorm_clipping or {}\n keys = ['rmax', 'rmin', 'dmax']\n if set(renorm_clipping) - set(keys):\n raise ValueError('renorm_clipping %s contains keys not in %s' %\n (renorm_clipping, keys))\n self.renorm_clipping = renorm_clipping\n self.renorm_momentum = renorm_momentum\n\n def _raise_if_fused_cannot_be_used(self):\n \"\"\"Raises a ValueError if fused implementation cannot be used.\n\n In addition to the checks done in this function, the input tensors rank must\n be 4. The input rank check can only be done once the input shape is known.\n \"\"\"\n # Currently fused batch norm doesn't support renorm. It also only supports a\n # channel dimension on axis 1 or 3, when no virtual batch size or adjustment\n # is used.\n if self.renorm:\n raise ValueError('Passing both fused=True and renorm=True is '\n 'unsupported')\n axis = [self.axis] if isinstance(self.axis, int) else self.axis\n # Axis -3 is equivalent to 1, and axis -1 is equivalent to 3, because the\n # input rank is required to be 4 (which is checked later).\n if len(axis) > 1 or axis[0] not in (-3, -1, 1, 3):\n raise ValueError('Passing fused=True is only supported when axis is 1 '\n 'or 3')\n if self.virtual_batch_size is not None:\n raise ValueError('Passing fused=True is unsupported when '\n 'virtual_batch_size is specified.')\n if self.adjustment is not None:\n raise ValueError('Passing fused=True is unsupported when '\n 'adjustment is specified.')\n\n def _fused_can_be_used(self):\n try:\n self._raise_if_fused_cannot_be_used()\n return True\n except ValueError:\n return False\n\n @property\n def _param_dtype(self):\n # Raise parameters of fp16 batch norm to fp32\n if self.dtype == dtypes.float16 or self.dtype == dtypes.bfloat16:\n return dtypes.float32\n else:\n return self.dtype or dtypes.float32\n\n def build(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape)\n if not input_shape.ndims:\n raise ValueError('Input has undefined rank:', input_shape)\n ndims = len(input_shape)\n\n # Convert axis to list and resolve negatives\n if isinstance(self.axis, int):\n self.axis = [self.axis]\n\n for idx, x in enumerate(self.axis):\n if x < 0:\n self.axis[idx] = ndims + x\n\n # Validate axes\n for x in self.axis:\n if x < 0 or x >= ndims:\n raise ValueError('Invalid axis: %d' % x)\n if len(self.axis) != len(set(self.axis)):\n raise ValueError('Duplicate axis: %s' % self.axis)\n\n if self.virtual_batch_size is not None:\n if self.virtual_batch_size <= 0:\n raise ValueError('virtual_batch_size must be a positive integer that '\n 'divides the true batch size of the input Tensor')\n # If using virtual batches, the first dimension must be the batch\n # dimension and cannot be the batch norm axis\n if 0 in self.axis:\n raise ValueError('When using virtual_batch_size, the batch dimension '\n 'must be 0 and thus axis cannot include 0')\n if self.adjustment is not None:\n raise ValueError('When using virtual_batch_size, adjustment cannot '\n 'be specified')\n\n if self.fused in (None, True):\n # TODO(yaozhang): if input is not 4D, reshape it to 4D and reshape the\n # output back to its original shape accordingly.\n if self._USE_V2_BEHAVIOR:\n if self.fused is None:\n self.fused = (ndims == 4)\n elif self.fused and ndims != 4:\n raise ValueError('Batch normalization layers with fused=True only '\n 'support 4D input tensors.')\n else:\n assert self.fused is not None\n self.fused = (ndims == 4 and self._fused_can_be_used())\n # TODO(chrisying): fused batch norm is currently not supported for\n # multi-axis batch norm and by extension virtual batches. In some cases,\n # it might be possible to use fused batch norm but would require reshaping\n # the Tensor to 4D with the axis in 1 or 3 (preferred 1) which is\n # particularly tricky. A compromise might be to just support the most\n # common use case (turning 5D w/ virtual batch to NCHW)\n\n if self.fused:\n if self.axis == [1]:\n self._data_format = 'NCHW'\n elif self.axis == [3]:\n self._data_format = 'NHWC'\n else:\n raise ValueError('Unsupported axis, fused batch norm only supports '\n 'axis == [1] or axis == [3]')\n\n axis_to_dim = {x: input_shape.dims[x].value for x in self.axis}\n for x in axis_to_dim:\n if axis_to_dim[x] is None:\n raise ValueError('Input has undefined `axis` dimension. Input shape: ',\n input_shape)\n self.input_spec = InputSpec(ndim=ndims, axes=axis_to_dim)\n\n if len(axis_to_dim) == 1 and self.virtual_batch_size is None:\n # Single axis batch norm (most common/default use-case)\n param_shape = (list(axis_to_dim.values())[0],)\n else:\n # Parameter shape is the original shape but with 1 in all non-axis dims\n param_shape = [axis_to_dim[i] if i in axis_to_dim\n else 1 for i in range(ndims)]\n if self.virtual_batch_size is not None:\n # When using virtual batches, add an extra dim at index 1\n param_shape.insert(1, 1)\n for idx, x in enumerate(self.axis):\n self.axis[idx] = x + 1 # Account for added dimension\n\n if self.scale:\n self.gamma = self.add_weight(\n name='gamma',\n shape=param_shape,\n dtype=self._param_dtype,\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint,\n trainable=True,\n experimental_autocast=False)\n else:\n self.gamma = None\n if self.fused:\n self._gamma_const = K.constant(\n 1.0, dtype=self._param_dtype, shape=param_shape)\n\n if self.center:\n self.beta = self.add_weight(\n name='beta',\n shape=param_shape,\n dtype=self._param_dtype,\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint,\n trainable=True,\n experimental_autocast=False)\n else:\n self.beta = None\n if self.fused:\n self._beta_const = K.constant(\n 0.0, dtype=self._param_dtype, shape=param_shape)\n\n try:\n # Disable variable partitioning when creating the moving mean and variance\n if hasattr(self, '_scope') and self._scope:\n partitioner = self._scope.partitioner\n self._scope.set_partitioner(None)\n else:\n partitioner = None\n self.moving_mean = self.add_weight(\n name='moving_mean',\n shape=param_shape,\n dtype=self._param_dtype,\n initializer=self.moving_mean_initializer,\n synchronization=tf_variables.VariableSynchronization.ON_READ,\n trainable=False,\n aggregation=tf_variables.VariableAggregation.MEAN,\n experimental_autocast=False)\n\n self.moving_variance = self.add_weight(\n name='moving_variance',\n shape=param_shape,\n dtype=self._param_dtype,\n initializer=self.moving_variance_initializer,\n synchronization=tf_variables.VariableSynchronization.ON_READ,\n trainable=False,\n aggregation=tf_variables.VariableAggregation.MEAN,\n experimental_autocast=False)\n\n if self.renorm:\n # Create variables to maintain the moving mean and standard deviation.\n # These are used in training and thus are different from the moving\n # averages above. The renorm variables are colocated with moving_mean\n # and moving_variance.\n # NOTE: below, the outer `with device` block causes the current device\n # stack to be cleared. The nested ones use a `lambda` to set the desired\n # device and ignore any devices that may be set by the custom getter.\n def _renorm_variable(name, shape):\n \"\"\"Create a renorm variable.\"\"\"\n var = self.add_weight(\n name=name,\n shape=shape,\n dtype=self._param_dtype,\n initializer=init_ops.zeros_initializer(),\n synchronization=tf_variables.VariableSynchronization.ON_READ,\n trainable=False,\n aggregation=tf_variables.VariableAggregation.MEAN,\n experimental_autocast=False)\n return var\n\n with distribution_strategy_context.get_strategy(\n ).extended.colocate_vars_with(self.moving_mean):\n self.renorm_mean = _renorm_variable('renorm_mean', param_shape)\n self.renorm_mean_weight = _renorm_variable('renorm_mean_weight', ())\n # We initialize renorm_stddev to 0, and maintain the (0-initialized)\n # renorm_stddev_weight. This allows us to (1) mix the average\n # stddev with the minibatch stddev early in training, and (2) compute\n # the unbiased average stddev by dividing renorm_stddev by the weight.\n with distribution_strategy_context.get_strategy(\n ).extended.colocate_vars_with(self.moving_variance):\n self.renorm_stddev = _renorm_variable('renorm_stddev', param_shape)\n self.renorm_stddev_weight = _renorm_variable('renorm_stddev_weight',\n ())\n finally:\n if partitioner:\n self._scope.set_partitioner(partitioner)\n self.built = True\n\n def _assign_moving_average(self, variable, value, momentum):\n with ops.name_scope(None, 'AssignMovingAvg',\n [variable, value, momentum]) as scope:\n with ops.colocate_with(variable):\n decay = ops.convert_to_tensor(1.0 - momentum, name='decay')\n if decay.dtype != variable.dtype.base_dtype:\n decay = math_ops.cast(decay, variable.dtype.base_dtype)\n update_delta = (\n variable - math_ops.cast(value, variable.dtype)) * decay\n return state_ops.assign_sub(variable, update_delta, name=scope)\n\n def _fused_batch_norm(self, inputs, training):\n \"\"\"Returns the output of fused batch norm.\"\"\"\n beta = self.beta if self.center else self._beta_const\n gamma = self.gamma if self.scale else self._gamma_const\n\n def _fused_batch_norm_training():\n return nn.fused_batch_norm(\n inputs,\n gamma,\n beta,\n epsilon=self.epsilon,\n data_format=self._data_format)\n\n def _fused_batch_norm_inference():\n return nn.fused_batch_norm(\n inputs,\n gamma,\n beta,\n mean=self.moving_mean,\n variance=self.moving_variance,\n epsilon=self.epsilon,\n is_training=False,\n data_format=self._data_format)\n\n output, mean, variance = tf_utils.smart_cond(\n training, _fused_batch_norm_training, _fused_batch_norm_inference)\n if not self._bessels_correction_test_only:\n # Remove Bessel's correction to be consistent with non-fused batch norm.\n # Note that the variance computed by fused batch norm is\n # with Bessel's correction.\n sample_size = math_ops.cast(\n array_ops.size(inputs) / array_ops.size(variance), variance.dtype)\n factor = (sample_size - math_ops.cast(1.0, variance.dtype)) / sample_size\n variance *= factor\n\n training_value = tf_utils.constant_value(training)\n if training_value is None:\n momentum = tf_utils.smart_cond(training,\n lambda: self.momentum,\n lambda: 1.0)\n else:\n momentum = ops.convert_to_tensor(self.momentum)\n if training_value or training_value is None:\n if distribution_strategy_context.in_cross_replica_context():\n strategy = distribution_strategy_context.get_strategy()\n mean_update = strategy.extended.update(\n self.moving_mean, self._assign_moving_average,\n (mean, self.momentum))\n variance_update = strategy.extended.update(\n self.moving_variance, self._assign_moving_average,\n (variance, self.momentum))\n else:\n mean_update = self._assign_moving_average(self.moving_mean, mean,\n momentum)\n variance_update = self._assign_moving_average(self.moving_variance,\n variance, momentum)\n self.add_update(mean_update, inputs=True)\n self.add_update(variance_update, inputs=True)\n\n return output\n\n def _renorm_correction_and_moments(self, mean, variance, training):\n \"\"\"Returns the correction and update values for renorm.\"\"\"\n stddev = math_ops.sqrt(variance + self.epsilon)\n # Compute the average mean and standard deviation, as if they were\n # initialized with this batch's moments.\n mixed_renorm_mean = (self.renorm_mean +\n (1. - self.renorm_mean_weight) * mean)\n mixed_renorm_stddev = (self.renorm_stddev +\n (1. - self.renorm_stddev_weight) * stddev)\n # Compute the corrections for batch renorm.\n r = stddev / mixed_renorm_stddev\n d = (mean - mixed_renorm_mean) / mixed_renorm_stddev\n # Ensure the corrections use pre-update moving averages.\n with ops.control_dependencies([r, d]):\n mean = array_ops.identity(mean)\n stddev = array_ops.identity(stddev)\n rmin, rmax, dmax = [self.renorm_clipping.get(key)\n for key in ['rmin', 'rmax', 'dmax']]\n if rmin is not None:\n r = math_ops.maximum(r, rmin)\n if rmax is not None:\n r = math_ops.minimum(r, rmax)\n if dmax is not None:\n d = math_ops.maximum(d, -dmax)\n d = math_ops.minimum(d, dmax)\n # When not training, use r=1, d=0.\n r = tf_utils.smart_cond(training, lambda: r, lambda: array_ops.ones_like(r))\n d = tf_utils.smart_cond(training,\n lambda: d,\n lambda: array_ops.zeros_like(d))\n\n def _update_renorm_variable(var, weight, value):\n \"\"\"Updates a moving average and weight, returns the unbiased value.\"\"\"\n value = array_ops.identity(value)\n def _do_update():\n \"\"\"Updates the var and weight, returns their updated ratio.\"\"\"\n # Update the variables without zero debiasing. The debiasing will be\n # accomplished by dividing the exponential moving average by the weight.\n # For example, after a single update, the moving average would be\n # (1-decay) * value. and the weight will be 1-decay, with their ratio\n # giving the value.\n # Make sure the weight is not updated until before r and d computation.\n with ops.control_dependencies([value]):\n weight_value = array_ops.constant(1., dtype=weight.dtype)\n new_var = self._assign_moving_average(var, value, self.renorm_momentum)\n new_weight = self._assign_moving_average(weight, weight_value,\n self.renorm_momentum)\n # TODO(yuefengz): the updates to var and weighted can not be batched\n # together if we fetch their updated values here. Consider calculating\n # new values and delaying the updates.\n return new_var / new_weight\n\n def _fake_update():\n return array_ops.identity(var)\n return tf_utils.smart_cond(training, _do_update, _fake_update)\n\n # TODO(yuefengz): colocate the operations\n new_mean = _update_renorm_variable(self.renorm_mean,\n self.renorm_mean_weight, mean)\n new_stddev = _update_renorm_variable(self.renorm_stddev,\n self.renorm_stddev_weight, stddev)\n # Make sqrt(moving_variance + epsilon) = new_stddev.\n new_variance = math_ops.square(new_stddev) - self.epsilon\n\n return (r, d, new_mean, new_variance)\n\n def _moments(self, inputs, reduction_axes, keep_dims):\n return nn.moments(inputs, reduction_axes, keep_dims=keep_dims)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n in_eager_mode = context.executing_eagerly()\n if self.virtual_batch_size is not None:\n # Virtual batches (aka ghost batches) can be simulated by reshaping the\n # Tensor and reusing the existing batch norm implementation\n original_shape = [-1] + inputs.shape.as_list()[1:]\n expanded_shape = [self.virtual_batch_size, -1] + original_shape[1:]\n\n # Will cause errors if virtual_batch_size does not divide the batch size\n inputs = array_ops.reshape(inputs, expanded_shape)\n\n def undo_virtual_batching(outputs):\n outputs = array_ops.reshape(outputs, original_shape)\n return outputs\n\n if self.fused:\n outputs = self._fused_batch_norm(inputs, training=training)\n if self.virtual_batch_size is not None:\n # Currently never reaches here since fused_batch_norm does not support\n # virtual batching\n outputs = undo_virtual_batching(outputs)\n return outputs\n\n # Compute the axes along which to reduce the mean / variance\n input_shape = inputs.get_shape()\n ndims = len(input_shape)\n reduction_axes = [i for i in range(ndims) if i not in self.axis]\n if self.virtual_batch_size is not None:\n del reduction_axes[1] # Do not reduce along virtual batch dim\n\n # Broadcasting only necessary for single-axis batch norm where the axis is\n # not the last dimension\n broadcast_shape = [1] * ndims\n broadcast_shape[self.axis[0]] = input_shape.dims[self.axis[0]].value\n def _broadcast(v):\n if (v is not None and\n len(v.get_shape()) != ndims and\n reduction_axes != list(range(ndims - 1))):\n return array_ops.reshape(v, broadcast_shape)\n return v\n\n scale, offset = _broadcast(self.gamma), _broadcast(self.beta)\n\n def _compose_transforms(scale, offset, then_scale, then_offset):\n if then_scale is not None:\n scale *= then_scale\n offset *= then_scale\n if then_offset is not None:\n offset += then_offset\n return (scale, offset)\n\n # Determine a boolean value for `training`: could be True, False, or None.\n training_value = tf_utils.constant_value(training)\n if training_value is not False:\n if self.adjustment:\n adj_scale, adj_bias = self.adjustment(array_ops.shape(inputs))\n # Adjust only during training.\n adj_scale = tf_utils.smart_cond(training,\n lambda: adj_scale,\n lambda: array_ops.ones_like(adj_scale))\n adj_bias = tf_utils.smart_cond(training,\n lambda: adj_bias,\n lambda: array_ops.zeros_like(adj_bias))\n scale, offset = _compose_transforms(adj_scale, adj_bias, scale, offset)\n\n # Some of the computations here are not necessary when training==False\n # but not a constant. However, this makes the code simpler.\n keep_dims = self.virtual_batch_size is not None or len(self.axis) > 1\n mean, variance = self._moments(\n math_ops.cast(inputs, self._param_dtype),\n reduction_axes,\n keep_dims=keep_dims)\n\n moving_mean = self.moving_mean\n moving_variance = self.moving_variance\n\n mean = tf_utils.smart_cond(training,\n lambda: mean,\n lambda: moving_mean)\n variance = tf_utils.smart_cond(training,\n lambda: variance,\n lambda: moving_variance)\n\n if self.virtual_batch_size is not None:\n # This isn't strictly correct since in ghost batch norm, you are\n # supposed to sequentially update the moving_mean and moving_variance\n # with each sub-batch. However, since the moving statistics are only\n # used during evaluation, it is more efficient to just update in one\n # step and should not make a significant difference in the result.\n new_mean = math_ops.reduce_mean(mean, axis=1, keepdims=True)\n new_variance = math_ops.reduce_mean(variance, axis=1, keepdims=True)\n else:\n new_mean, new_variance = mean, variance\n\n if self.renorm:\n r, d, new_mean, new_variance = self._renorm_correction_and_moments(\n new_mean, new_variance, training)\n # When training, the normalized values (say, x) will be transformed as\n # x * gamma + beta without renorm, and (x * r + d) * gamma + beta\n # = x * (r * gamma) + (d * gamma + beta) with renorm.\n r = _broadcast(array_ops.stop_gradient(r, name='renorm_r'))\n d = _broadcast(array_ops.stop_gradient(d, name='renorm_d'))\n scale, offset = _compose_transforms(r, d, scale, offset)\n\n if distribution_strategy_context.in_cross_replica_context():\n strategy = distribution_strategy_context.get_strategy()\n\n def _do_update(var, value):\n \"\"\"Compute the updates for mean and variance.\"\"\"\n if in_eager_mode and not self.trainable:\n return\n return strategy.extended.update(\n var, self._assign_moving_average, (value, self.momentum),\n group=False)\n # We need to unwrap the moving_mean or moving_variance in the case of\n # training being false to match the output of true_fn and false_fn\n # in the smart cond.\n mean_update = tf_utils.smart_cond(\n training,\n lambda: _do_update(self.moving_mean, new_mean),\n lambda: strategy.unwrap(self.moving_mean))\n variance_update = tf_utils.smart_cond(\n training,\n lambda: _do_update(self.moving_variance, new_variance),\n lambda: strategy.unwrap(self.moving_variance))\n else:\n def _do_update(var, value):\n \"\"\"Compute the updates for mean and variance.\"\"\"\n if in_eager_mode and not self.trainable:\n return\n return self._assign_moving_average(var, value, self.momentum)\n mean_update = tf_utils.smart_cond(\n training,\n lambda: _do_update(self.moving_mean, new_mean),\n lambda: self.moving_mean)\n variance_update = tf_utils.smart_cond(\n training,\n lambda: _do_update(self.moving_variance, new_variance),\n lambda: self.moving_variance)\n if not context.executing_eagerly():\n self.add_update(mean_update, inputs=True)\n self.add_update(variance_update, inputs=True)\n\n else:\n mean, variance = self.moving_mean, self.moving_variance\n\n mean = math_ops.cast(mean, inputs.dtype)\n variance = math_ops.cast(variance, inputs.dtype)\n if offset is not None:\n offset = math_ops.cast(offset, inputs.dtype)\n if scale is not None:\n scale = math_ops.cast(scale, inputs.dtype)\n # TODO(reedwm): Maybe do math in float32 if given float16 inputs, if doing\n # math in float16 hurts validation accuracy of popular models like resnet.\n outputs = nn.batch_normalization(inputs,\n _broadcast(mean),\n _broadcast(variance),\n offset,\n scale,\n self.epsilon)\n # If some components of the shape got lost due to adjustments, fix that.\n outputs.set_shape(input_shape)\n\n if self.virtual_batch_size is not None:\n outputs = undo_virtual_batching(outputs)\n return outputs\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {\n 'axis': self.axis,\n 'momentum': self.momentum,\n 'epsilon': self.epsilon,\n 'center': self.center,\n 'scale': self.scale,\n 'beta_initializer': initializers.serialize(self.beta_initializer),\n 'gamma_initializer': initializers.serialize(self.gamma_initializer),\n 'moving_mean_initializer':\n initializers.serialize(self.moving_mean_initializer),\n 'moving_variance_initializer':\n initializers.serialize(self.moving_variance_initializer),\n 'beta_regularizer': regularizers.serialize(self.beta_regularizer),\n 'gamma_regularizer': regularizers.serialize(self.gamma_regularizer),\n 'beta_constraint': constraints.serialize(self.beta_constraint),\n 'gamma_constraint': constraints.serialize(self.gamma_constraint)\n }\n # Only add TensorFlow-specific parameters if they are set, so as to preserve\n # model compatibility with external Keras.\n if self.renorm:\n config['renorm'] = True\n config['renorm_clipping'] = self.renorm_clipping\n config['renorm_momentum'] = self.renorm_momentum\n if self.virtual_batch_size is not None:\n config['virtual_batch_size'] = self.virtual_batch_size\n # Note: adjustment is not serializable.\n if self.adjustment is not None:\n logging.warning('The `adjustment` function of this `BatchNormalization` '\n 'layer cannot be serialized and has been omitted from '\n 'the layer config. It will not be included when '\n 're-creating the layer from the saved config.')\n base_config = super(BatchNormalizationBase, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef _replace_in_base_docstring(old, new):\n string = BatchNormalizationBase.__doc__\n if old not in string:\n raise ValueError('Could not find following string in BatchNormalizationBase'\n ' docstring: \"{}\"'.format(old))\n return string.replace(old, new)\n\n\n@keras_export(v1=['keras.layers.BatchNormalization']) # pylint: disable=missing-docstring\nclass BatchNormalization(BatchNormalizationBase):\n\n __doc__ = _replace_in_base_docstring(\n '''\n fused: if `True`, use a faster, fused implementation, or raise a ValueError\n if the fused implementation cannot be used. If `None`, use the faster\n implementation if possible. If False, do not used the fused\n implementation.''',\n\n '''\n fused: if `None` or `True`, use a faster, fused implementation if possible.\n If `False`, use the system recommended implementation.''')\n\n _USE_V2_BEHAVIOR = False\n\n\n@keras_export('keras.layers.experimental.LayerNormalization')\nclass LayerNormalization(Layer):\n \"\"\"Layer normalization layer (Ba et al., 2016).\n\n Normalize the activations of the previous layer for each given example in a\n batch independently, rather than across a batch like Batch Normalization.\n i.e. applies a transformation that maintains the mean activation within each\n example close to 0 and the activation standard deviation close to 1.\n\n Given a tensor `inputs` of rank `R`, moments are calculated and normalization\n is performed over all axes in norm_axis. Scaling and centering,\n if requested, is performed over all axes in params_axis.\n\n By default, normalization is performed over all but the first axis\n (the `HWC` if `inputs` is `NHWC`), while the `beta` and `gamma` trainable\n parameters are calculated for the rightmost axis (the `C` if `inputs` is\n `NHWC`). Scaling and recentering is performed via broadcast of the\n `beta` and `gamma` parameters with the normalized tensor.\n\n The shapes of `beta` and `gamma` are\n `[inputs.shape[i] for i in (param axes)]`,\n and this part of the inputs' shape must be fully defined.\n\n Arguments:\n norm_axis: Integer or List. normalization will be\n performed along these dimensions. If unspecified (None), it will default\n to the dimensions `begin_norm_axis : rank(inputs)`\n params_axis: Integer or List. The (beta, gamma) dimensions: scale\n and centering parameters will have take their shapes from these axes and\n will be broadcast with the normalized inputs accordingly. If unspecified\n (None), it will default to the last dimension\n epsilon: Small float added to variance to avoid dividing by zero.\n center: If True, add offset of `beta` to normalized tensor.\n If False, `beta` is ignored.\n scale: If True, multiply by `gamma`.\n If False, `gamma` is not used.\n When the next layer is linear (also e.g. `nn.relu`),\n this can be disabled since the scaling\n will be done by the next layer.\n beta_initializer: Initializer for the beta weight.\n gamma_initializer: Initializer for the gamma weight.\n beta_regularizer: Optional regularizer for the beta weight.\n gamma_regularizer: Optional regularizer for the gamma weight.\n beta_constraint: Optional constraint for the beta weight.\n gamma_constraint: Optional constraint for the gamma weight.\n trainable: Boolean, if `True` the variables will be marked as trainable.\n\n Input shape:\n Arbitrary. Use the keyword argument `input_shape`\n (tuple of integers, does not include the samples axis)\n when using this layer as the first layer in a model.\n\n Output shape:\n Same shape as input.\n\n References:\n - [Layer Normalization](https://arxiv.org/abs/1607.06450)\n \"\"\"\n\n def __init__(self,\n norm_axis=None,\n params_axis=-1,\n epsilon=1e-12,\n center=True,\n scale=True,\n beta_initializer='zeros',\n gamma_initializer='ones',\n beta_regularizer=None,\n gamma_regularizer=None,\n beta_constraint=None,\n gamma_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(LayerNormalization, self).__init__(\n name=name, trainable=trainable, **kwargs)\n if isinstance(norm_axis, list):\n self.norm_axis = norm_axis[:]\n elif isinstance(norm_axis, int):\n self.norm_axis = norm_axis\n elif norm_axis is None:\n self.norm_axis = None\n else:\n raise TypeError('norm_axis must be int or list or None, type given: %s'\n % type(norm_axis))\n\n if isinstance(params_axis, list):\n self.params_axis = params_axis[:]\n elif isinstance(params_axis, int):\n self.params_axis = params_axis\n else:\n raise TypeError('params_axis must be int or list, type given: %s'\n % type(params_axis))\n\n self.epsilon = epsilon\n self.center = center\n self.scale = scale\n self.beta_initializer = initializers.get(beta_initializer)\n self.gamma_initializer = initializers.get(gamma_initializer)\n self.beta_regularizer = regularizers.get(beta_regularizer)\n self.gamma_regularizer = regularizers.get(gamma_regularizer)\n self.beta_constraint = constraints.get(beta_constraint)\n self.gamma_constraint = constraints.get(gamma_constraint)\n\n self.supports_masking = True\n\n def build(self, input_shape):\n ndims = len(input_shape)\n if ndims is None:\n raise ValueError('Input shape %s has undefined rank.' % input_shape)\n\n # Handle an unspecified norm_axis\n if self.norm_axis is None:\n self.norm_axis = list(range(1, ndims))\n\n # Convert axes to lists and resolve negatives\n if isinstance(self.norm_axis, int):\n self.norm_axis = [self.norm_axis]\n for idx, x in enumerate(self.norm_axis):\n if x < 0:\n self.norm_axis[idx] = ndims + x\n\n if isinstance(self.params_axis, int):\n self.params_axis = [self.params_axis]\n for idx, x in enumerate(self.params_axis):\n if x < 0:\n self.params_axis[idx] = ndims + x\n\n # Validate axes\n for x in self.norm_axis:\n if x < 0 or x >= ndims:\n raise ValueError('Invalid axis: %d' % x)\n if len(self.norm_axis) != len(set(self.norm_axis)):\n raise ValueError('Duplicate axis: %s' % self.norm_axis)\n\n for x in self.params_axis:\n if x < 0 or x >= ndims:\n raise ValueError('Invalid axis: %d' % x)\n if len(self.params_axis) != len(set(self.params_axis)):\n raise ValueError('Duplicate axis: %s' % self.params_axis)\n\n param_shape = [input_shape[dim] for dim in self.params_axis]\n\n if self.scale:\n self.gamma = self.add_weight(\n name='gamma',\n shape=param_shape,\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint,\n trainable=True,\n experimental_autocast=False)\n else:\n self.gamma = None\n\n if self.center:\n self.beta = self.add_weight(\n name='beta',\n shape=param_shape,\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint,\n trainable=True,\n experimental_autocast=False)\n else:\n self.beta = None\n\n def call(self, inputs):\n # Compute the axes along which to reduce the mean / variance\n input_shape = inputs.get_shape()\n ndims = len(input_shape)\n\n # Calculate the moments on the last axis (layer activations).\n mean, variance = nn.moments(inputs, self.norm_axis, keep_dims=True)\n\n # Broadcasting only necessary for norm where the params axes aren't just\n # the last dimension\n broadcast_shape = [1] * ndims\n for dim in self.params_axis:\n broadcast_shape[dim] = input_shape.dims[dim].value\n def _broadcast(v):\n if (v is not None and\n len(v.get_shape()) != ndims and\n self.params_axis != [ndims - 1]):\n return array_ops.reshape(v, broadcast_shape)\n return v\n scale, offset = _broadcast(self.gamma), _broadcast(self.beta)\n\n # Compute layer normalization using the batch_normalization function.\n outputs = nn.batch_normalization(\n inputs,\n mean,\n variance,\n offset=offset,\n scale=scale,\n variance_epsilon=self.epsilon)\n\n # If some components of the shape got lost due to adjustments, fix that.\n outputs.set_shape(input_shape)\n\n return outputs\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {\n 'norm_axis': self.norm_axis,\n 'params_axis': self.params_axis,\n 'epsilon': self.epsilon,\n 'center': self.center,\n 'scale': self.scale,\n 'beta_initializer': initializers.serialize(self.beta_initializer),\n 'gamma_initializer': initializers.serialize(self.gamma_initializer),\n 'beta_regularizer': regularizers.serialize(self.beta_regularizer),\n 'gamma_regularizer': regularizers.serialize(self.gamma_regularizer),\n 'beta_constraint': constraints.serialize(self.beta_constraint),\n 'gamma_constraint': constraints.serialize(self.gamma_constraint)\n }\n base_config = super(LayerNormalization, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n"
] |
[
[
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.keras.backend.learning_phase",
"tensorflow.python.ops.math_ops.minimum",
"tensorflow.python.distribute.distribution_strategy_context.in_cross_replica_context",
"tensorflow.python.distribute.distribution_strategy_context.get_strategy",
"tensorflow.python.ops.array_ops.ones_like",
"tensorflow.python.keras.engine.input_spec.InputSpec",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.ops.state_ops.assign_sub",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.keras.utils.tf_utils.constant_value",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.framework.ops.colocate_with",
"tensorflow.python.ops.nn.moments",
"tensorflow.python.ops.math_ops.sqrt",
"tensorflow.python.keras.initializers.get",
"tensorflow.python.keras.constraints.get",
"tensorflow.python.ops.math_ops.maximum",
"tensorflow.python.ops.init_ops.zeros_initializer",
"tensorflow.python.keras.backend.constant",
"tensorflow.python.keras.utils.tf_utils.smart_cond",
"tensorflow.python.keras.regularizers.get",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.keras.initializers.serialize",
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.ops.array_ops.constant",
"tensorflow.python.ops.nn.batch_normalization",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.math_ops.reduce_mean",
"tensorflow.python.keras.constraints.serialize",
"tensorflow.python.ops.array_ops.zeros_like",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.nn.fused_batch_norm",
"tensorflow.python.keras.regularizers.serialize",
"tensorflow.python.ops.array_ops.stop_gradient",
"tensorflow.python.ops.array_ops.size",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.framework.ops.name_scope"
]
] |
guyujun/RFDesign
|
[
"9fea2bafbbb7cbf702c9884e8b3ec69ed50ff2f5",
"9fea2bafbbb7cbf702c9884e8b3ec69ed50ff2f5"
] |
[
"hallucination/models/rf_v01/SE3_network.py",
"inpainting/model/performer_pytorch.py"
] |
[
"import torch\nimport torch.nn as nn\n\nimport sys, os\nscript_dir = os.path.dirname(os.path.realpath(__file__))\nsys.path.insert(0,script_dir+'/../../equivariant_attention/')\nfrom equivariant_attention.modules import get_basis_and_r, GSE3Res, GNormBias\nfrom equivariant_attention.modules import GConvSE3, GNormSE3\nfrom equivariant_attention.fibers import Fiber\n\nclass TFN(nn.Module):\n \"\"\"SE(3) equivariant GCN\"\"\"\n def __init__(self, num_layers=2, num_channels=32, num_nonlin_layers=1, num_degrees=3, \n l0_in_features=32, l0_out_features=32,\n l1_in_features=3, l1_out_features=3,\n num_edge_features=32, use_self=True):\n super().__init__()\n # Build the network\n self.num_layers = num_layers\n self.num_nlayers = num_nonlin_layers\n self.num_channels = num_channels\n self.num_degrees = num_degrees\n self.edge_dim = num_edge_features\n self.use_self = use_self\n\n if l1_out_features > 0:\n fibers = {'in': Fiber(dictionary={0: l0_in_features, 1: l1_in_features}),\n 'mid': Fiber(self.num_degrees, self.num_channels),\n 'out': Fiber(dictionary={0: l0_out_features, 1: l1_out_features})}\n else:\n fibers = {'in': Fiber(dictionary={0: l0_in_features, 1: l1_in_features}),\n 'mid': Fiber(self.num_degrees, self.num_channels),\n 'out': Fiber(dictionary={0: l0_out_features})}\n blocks = self._build_gcn(fibers)\n self.block0 = blocks\n\n def _build_gcn(self, fibers):\n\n block0 = []\n fin = fibers['in']\n for i in range(self.num_layers-1):\n block0.append(GConvSE3(fin, fibers['mid'], self_interaction=self.use_self, edge_dim=self.edge_dim))\n block0.append(GNormSE3(fibers['mid'], num_layers=self.num_nlayers))\n fin = fibers['mid']\n block0.append(GConvSE3(fibers['mid'], fibers['out'], self_interaction=self.use_self, edge_dim=self.edge_dim))\n return nn.ModuleList(block0)\n\n @torch.cuda.amp.autocast(enabled=False)\n def forward(self, G, type_0_features, type_1_features):\n # Compute equivariant weight basis from relative positions\n basis, r = get_basis_and_r(G, self.num_degrees-1)\n h = {'0': type_0_features, '1': type_1_features}\n for layer in self.block0:\n h = layer(h, G=G, r=r, basis=basis)\n return h \n\nclass SE3Transformer(nn.Module):\n \"\"\"SE(3) equivariant GCN with attention\"\"\"\n def __init__(self, num_layers=2, num_channels=32, num_degrees=3, n_heads=4, div=4,\n si_m='1x1', si_e='att',\n l0_in_features=32, l0_out_features=32,\n l1_in_features=3, l1_out_features=3,\n num_edge_features=32, x_ij=None):\n super().__init__()\n # Build the network\n self.num_layers = num_layers\n self.num_channels = num_channels\n self.num_degrees = num_degrees\n self.edge_dim = num_edge_features\n self.div = div\n self.n_heads = n_heads\n self.si_m, self.si_e = si_m, si_e\n self.x_ij = x_ij\n\n if l1_out_features > 0:\n fibers = {'in': Fiber(dictionary={0: l0_in_features, 1: l1_in_features}),\n 'mid': Fiber(self.num_degrees, self.num_channels),\n 'out': Fiber(dictionary={0: l0_out_features, 1: l1_out_features})}\n else:\n fibers = {'in': Fiber(dictionary={0: l0_in_features, 1: l1_in_features}),\n 'mid': Fiber(self.num_degrees, self.num_channels),\n 'out': Fiber(dictionary={0: l0_out_features})}\n\n blocks = self._build_gcn(fibers)\n self.Gblock = blocks\n\n def _build_gcn(self, fibers):\n # Equivariant layers\n Gblock = []\n fin = fibers['in']\n for i in range(self.num_layers):\n Gblock.append(GSE3Res(fin, fibers['mid'], edge_dim=self.edge_dim,\n div=self.div, n_heads=self.n_heads,\n learnable_skip=True, skip='cat',\n selfint=self.si_m, x_ij=self.x_ij))\n Gblock.append(GNormBias(fibers['mid']))\n fin = fibers['mid']\n Gblock.append(\n GSE3Res(fibers['mid'], fibers['out'], edge_dim=self.edge_dim,\n div=1, n_heads=min(1, 2), learnable_skip=True,\n skip='cat', selfint=self.si_e, x_ij=self.x_ij))\n return nn.ModuleList(Gblock)\n\n @torch.cuda.amp.autocast(enabled=False)\n def forward(self, G, type_0_features, type_1_features):\n # Compute equivariant weight basis from relative positions\n basis, r = get_basis_and_r(G, self.num_degrees-1)\n h = {'0': type_0_features, '1': type_1_features}\n for layer in self.Gblock:\n h = layer(h, G=G, r=r, basis=basis)\n return h\n",
"import math\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch.cuda.amp import autocast\n\nfrom functools import partial\n\n# helpers\n\ndef exists(val):\n return val is not None\n\ndef empty(tensor):\n return tensor.numel() == 0\n\ndef default(val, d):\n return val if exists(val) else d\n\ndef get_module_device(module):\n return next(module.parameters()).device\n\ndef find_modules(nn_module, type):\n return [module for module in nn_module.modules() if isinstance(module, type)]\n\n# kernel functions\ndef softmax_kernel(data, *, projection_matrix, is_query, normalize_data=True, eps=1e-4, device = None):\n b, h, *_ = data.shape\n\n data_normalizer = (data.shape[-1] ** -0.25) if normalize_data else 1.\n\n ratio = (projection_matrix.shape[0] ** -0.5)\n\n #projection = repeat(projection_matrix, 'j d -> b h j d', b = b, h = h)\n projection = projection_matrix.unsqueeze(0).repeat(h, 1, 1)\n projection = projection.unsqueeze(0).repeat(b, 1, 1, 1) # (b,h,j,d)\n projection = projection.type_as(data)\n\n data_dash = torch.einsum('...id,...jd->...ij', (data_normalizer * data), projection)\n\n diag_data = data ** 2\n diag_data = torch.sum(diag_data, dim=-1)\n diag_data = (diag_data / 2.0) * (data_normalizer ** 2)\n diag_data = diag_data.unsqueeze(dim=-1)\n\n if is_query:\n data_dash = ratio * (\n torch.exp(data_dash - diag_data -\n torch.max(data_dash, dim=-1, keepdim=True).values) + eps)\n else:\n data_dash = ratio * (\n torch.exp(data_dash - diag_data - torch.max(data_dash)) + eps)\n\n return data_dash.type_as(data)\n\ndef generalized_kernel(data, *, projection_matrix, kernel_fn = nn.ReLU(inplace=True), kernel_epsilon = 0.001, normalize_data = True, device = None):\n b, h, *_ = data.shape\n\n data_normalizer = (data.shape[-1] ** -0.25) if normalize_data else 1.\n\n if projection_matrix is None:\n return kernel_fn(data_normalizer * data) + kernel_epsilon\n\n ##projection = repeat(projection_matrix, 'j d -> b h j d', b = b, h = h)\n #projection = projection_matrix.unsqueeze(0).repeat(h, 1, 1)\n #projection = projection.unsqueeze(0).repeat(b, 1, 1, 1) # (b,h,j,d)\n #projection = projection.type_as(data)\n\n #data_dash = torch.einsum('...id,...jd->...ij', (data_normalizer * data), projection)\n #data_dash = torch.einsum('...id,jd->...ij', (data_normalizer*data), projection_matrix)\n data = data_normalizer*data\n data = torch.matmul(data, projection_matrix.T)\n data = kernel_fn(data) + kernel_epsilon\n return data.type_as(data)\n\ndef orthogonal_matrix_chunk(cols, qr_uniform_q = False, device = None):\n unstructured_block = torch.randn((cols, cols), device = device)\n q, r = torch.qr(unstructured_block.cpu(), some = True)\n q, r = map(lambda t: t.to(device), (q, r))\n\n # proposed by @Parskatt\n # to make sure Q is uniform https://arxiv.org/pdf/math-ph/0609050.pdf\n if qr_uniform_q:\n d = torch.diag(r, 0)\n q *= d.sign()\n return q.t()\n\ndef gaussian_orthogonal_random_matrix(nb_rows, nb_columns, scaling = 0, qr_uniform_q = False, device = None):\n nb_full_blocks = int(nb_rows / nb_columns)\n\n block_list = []\n\n for _ in range(nb_full_blocks):\n q = orthogonal_matrix_chunk(nb_columns, qr_uniform_q = qr_uniform_q, device = device)\n block_list.append(q)\n\n remaining_rows = nb_rows - nb_full_blocks * nb_columns\n if remaining_rows > 0:\n q = orthogonal_matrix_chunk(nb_columns, qr_uniform_q = qr_uniform_q, device = device)\n block_list.append(q[:remaining_rows])\n\n final_matrix = torch.cat(block_list)\n\n if scaling == 0:\n multiplier = torch.randn((nb_rows, nb_columns), device = device).norm(dim = 1)\n elif scaling == 1:\n multiplier = math.sqrt((float(nb_columns))) * torch.ones((nb_rows,), device = device)\n else:\n raise ValueError(f'Invalid scaling {scaling}')\n\n return torch.diag(multiplier) @ final_matrix\n\n# linear attention classes with softmax kernel\n\n# non-causal linear attention\ndef linear_attention(q, k, v):\n L = k.shape[-2]\n D_inv = 1. / torch.einsum('...nd,...d->...n', q, k.mean(dim=-2))\n #context = torch.einsum('...nd,...ne->...de', k, v)\n #out = torch.einsum('...de,...nd,...n->...ne', context, q, D_inv)\n context = torch.einsum('...nd,...ne->...de', k/float(L), v)\n out = torch.einsum('...n,...nd->...nd', D_inv, q)\n out = torch.einsum('...nd,...de->...ne', out, context)\n return out\n\nclass FastAttention(nn.Module):\n def __init__(self, dim_heads, nb_features = None, ortho_scaling = 0, generalized_attention = False, kernel_fn = nn.ReLU(inplace=True), qr_uniform_q = False, no_projection = False):\n super().__init__()\n nb_features = default(nb_features, int(dim_heads * math.log(dim_heads)))\n\n self.dim_heads = dim_heads\n self.nb_features = nb_features\n self.ortho_scaling = ortho_scaling\n\n if not no_projection:\n self.create_projection = partial(gaussian_orthogonal_random_matrix, nb_rows = self.nb_features, nb_columns = dim_heads, scaling = ortho_scaling, qr_uniform_q = qr_uniform_q)\n projection_matrix = self.create_projection()\n self.register_buffer('projection_matrix', projection_matrix)\n\n self.generalized_attention = generalized_attention\n self.kernel_fn = kernel_fn\n\n # if this is turned on, no projection will be used\n # queries and keys will be softmax-ed as in the original efficient attention paper\n self.no_projection = no_projection\n\n\n @torch.no_grad()\n def redraw_projection_matrix(self, device):\n projections = self.create_projection(device = device)\n self.projection_matrix.copy_(projections)\n del projections\n\n def forward(self, q, k, v):\n device = q.device\n\n if self.no_projection:\n q = q.softmax(dim = -1)\n k.softmax(dim = -2)\n\n elif self.generalized_attention:\n create_kernel = partial(generalized_kernel, kernel_fn = self.kernel_fn, projection_matrix = self.projection_matrix, device = device)\n q, k = map(create_kernel, (q, k))\n\n else:\n create_kernel = partial(softmax_kernel, projection_matrix = self.projection_matrix, device = device)\n q = create_kernel(q, is_query = True)\n k = create_kernel(k, is_query = False)\n\n attn_fn = linear_attention\n out = attn_fn(q, k, v)\n return out\n\n# classes\n\nclass ReZero(nn.Module):\n def __init__(self, fn):\n super().__init__()\n self.g = nn.Parameter(torch.tensor(1e-3))\n self.fn = fn\n\n def forward(self, x, **kwargs):\n return self.fn(x, **kwargs) * self.g\n\nclass PreScaleNorm(nn.Module):\n def __init__(self, dim, fn, eps=1e-5):\n super().__init__()\n self.fn = fn\n self.g = nn.Parameter(torch.ones(1))\n self.eps = eps\n\n def forward(self, x, **kwargs):\n n = torch.norm(x, dim=-1, keepdim=True).clamp(min=self.eps)\n x = x / n * self.g\n return self.fn(x, **kwargs)\n\nclass PreLayerNorm(nn.Module):\n def __init__(self, dim, fn):\n super().__init__()\n self.norm = nn.LayerNorm(dim)\n self.fn = fn\n def forward(self, x, **kwargs):\n return self.fn(self.norm(x), **kwargs)\n\nclass Chunk(nn.Module):\n def __init__(self, chunks, fn, along_dim = -1):\n super().__init__()\n self.dim = along_dim\n self.chunks = chunks\n self.fn = fn\n\n def forward(self, x, **kwargs):\n if self.chunks == 1:\n return self.fn(x, **kwargs)\n chunks = x.chunk(self.chunks, dim = self.dim)\n return torch.cat([self.fn(c, **kwargs) for c in chunks], dim = self.dim)\n\nclass SelfAttention(nn.Module):\n def __init__(self, dim, k_dim=None, heads = 8, local_heads = 0, local_window_size = 256, nb_features = None, feature_redraw_interval = 1000, generalized_attention = False, kernel_fn = nn.ReLU(inplace=True), qr_uniform_q = False, dropout = 0., no_projection = False):\n super().__init__()\n assert dim % heads == 0, 'dimension must be divisible by number of heads'\n dim_head = dim // heads\n inner_dim = dim_head * heads\n\n if k_dim == None:\n k_dim = dim\n\n self.fast_attention = FastAttention(dim_head, nb_features, generalized_attention = generalized_attention, kernel_fn = kernel_fn, qr_uniform_q = qr_uniform_q, no_projection = no_projection)\n\n self.heads = heads\n\n self.to_query = nn.Linear(dim, inner_dim)\n self.to_key = nn.Linear(k_dim, inner_dim)\n self.to_value = nn.Linear(k_dim, inner_dim)\n self.to_out = nn.Linear(inner_dim, dim)\n self.dropout = nn.Dropout(dropout)\n\n self.feature_redraw_interval = feature_redraw_interval\n self.register_buffer(\"calls_since_last_redraw\", torch.tensor(0))\n \n def check_redraw_projections(self):\n if not self.training:\n return\n\n if exists(self.feature_redraw_interval) and self.calls_since_last_redraw >= self.feature_redraw_interval:\n device = get_module_device(self)\n\n fast_attentions = find_modules(self, FastAttention)\n for fast_attention in fast_attentions:\n fast_attention.redraw_projection_matrix(device)\n\n self.calls_since_last_redraw.zero_()\n return\n\n self.calls_since_last_redraw += 1\n\n def forward(self, query, key, value, **kwargs):\n self.check_redraw_projections()\n \n b1, n1, _, h = *query.shape, self.heads\n b2, n2, _, h = *key.shape, self.heads\n\n q = self.to_query(query)\n k = self.to_key(key)\n v = self.to_value(value)\n \n q = q.reshape(b1, n1, h, -1).permute(0,2,1,3) # (b, h, n, d)\n k = k.reshape(b2, n2, h, -1).permute(0,2,1,3)\n v = v.reshape(b2, n2, h, -1).permute(0,2,1,3)\n\n out = self.fast_attention(q, k, v)\n \n out = out.permute(0,2,1,3).reshape(b1,n1,-1)\n #out = rearrange(out, 'b h n d -> b n (h d)')\n out = self.to_out(out)\n return self.dropout(out)\n\n"
] |
[
[
"torch.cuda.amp.autocast",
"torch.nn.ModuleList"
],
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.LayerNorm",
"torch.nn.Dropout",
"torch.einsum",
"torch.max",
"torch.norm",
"torch.no_grad",
"torch.ones",
"torch.nn.ReLU",
"torch.tensor",
"torch.diag",
"torch.matmul",
"torch.randn",
"torch.sum"
]
] |
harryh5427/gpi
|
[
"c438ea68851cd05577dfc06e2a29e834327d3559"
] |
[
"testshots/hv_meas_browse.py"
] |
[
"\"\"\"\n\n\"\"\"\nfrom MDSplus import *\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ns=int(sys.argv[1])\nmyTree=Tree(\"spectroscopy\",s)\nfor i in range(1,33):\n if i<10:\n node_sig=myTree.getNode(\"GPI.APD_ARRAY.HARDWARE:ACQ196.INPUT_0\"+str(i))\n else:\n node_sig=myTree.getNode(\"GPI.APD_ARRAY.HARDWARE:ACQ196.INPUT_\"+str(i))\n sig=node_sig.getData().data()\n t=node_sig.dim_of().data()\n print(\"Input \"+str(i)+\": \"+str(np.mean(sig)))\n\n"
] |
[
[
"numpy.mean"
]
] |
pchavanne/dl
|
[
"6114234a8a25cfda7a596b9a6e75bb121de6f4d2"
] |
[
"examples/lstm_example.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nThis example show you how to train an LSTM for text generation.\n\"\"\"\nimport numpy as np\nimport yadll\n\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG, format='%(message)s')\n\nalphabet = 'abcdefghijklmnopqrstuvwxyz'\nsequence_length = 2\nnumber_of_chars = len(alphabet)\n# load the data\ndata = yadll.data.Data(yadll.data.alphabet_loader(sequence_length))\n\n# create the model\nmodel = yadll.model.Model(name='lstm', data=data)\n\n# Hyperparameters\nhp = yadll.hyperparameters.Hyperparameters()\nhp('batch_size', 1)\nhp('n_epochs', 100)\nhp('patience', 1000)\n\n# add the hyperparameters to the model\nmodel.hp = hp\n\n# Create connected layers\n# Input layer\nl_in = yadll.layers.InputLayer(input_shape=(hp.batch_size, sequence_length, number_of_chars))\n# LSTM 1\nl_lstm1 = yadll.layers.BNLSTM(incoming=l_in, n_units=16, last_only=False)\n# LSTM 2\nl_lstm2 = yadll.layers.BNLSTM(incoming=l_lstm1, n_units=16)\n# Logistic regression Layer\n\nl_out = yadll.layers.LogisticRegression(incoming=l_lstm2, n_class=number_of_chars)\n\n# Create network and add layers\nnet = yadll.network.Network('stacked lstm')\nnet.add(l_in)\nnet.add(l_lstm1)\nnet.add(l_lstm2)\nnet.add(l_out)\n\n# add the network to the model\nmodel.network = net\n# updates method\nmodel.updates = yadll.updates.rmsprop\n\n# train the model and save it to file at each best\nmodel.compile(compile_arg='all')\nmodel.train()\n\n# prime the model with 'ab' sequence and let it generate the learned alphabet\nsentence = alphabet[:sequence_length]\ngenerated = sentence\nfor iteration in range(number_of_chars - sequence_length):\n x = np.zeros((1, sequence_length, number_of_chars))\n for t, char in enumerate(sentence):\n x[0, t, ord(char) - ord('a')] = 1.\n preds = model.predict(np.asarray(x, dtype='float32'))[0]\n next_char = chr(np.argmax(preds) + ord('a'))\n generated += next_char\n sentence = sentence[1:] + next_char\n\n# check that it did generate the alphabet correctly\nassert(generated == alphabet)\nx = model.data.test_set_x.get_value()[0:3]\nmodel.predict(x)\nchr(np.argmax(model.predict(x)) + ord('a'))\n"
] |
[
[
"numpy.argmax",
"numpy.asarray",
"numpy.zeros"
]
] |
SebastianMuszynski/pytorch-pretrained-BERT
|
[
"1892015692a28096859a46243ae458f9f8aa003f"
] |
[
"examples/run_classifier.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport argparse\nimport csv\nimport logging\nimport os\nimport random\nimport sys\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,\n TensorDataset)\nfrom torch.utils.data.distributed import DistributedSampler\nfrom tqdm import tqdm, trange\n\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom scipy.stats import pearsonr, spearmanr\nfrom sklearn.metrics import matthews_corrcoef, f1_score\n\nfrom pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE, WEIGHTS_NAME, CONFIG_NAME\nfrom pytorch_pretrained_bert.modeling import BertForSequenceClassification, BertConfig\nfrom pytorch_pretrained_bert.tokenization import BertTokenizer\nfrom pytorch_pretrained_bert.optimization import BertAdam, WarmupLinearSchedule\n\nlogger = logging.getLogger(__name__)\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, label_id):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with open(input_file, \"r\", encoding=\"utf-8\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n if sys.version_info[0] == 2:\n line = list(unicode(cell, 'utf-8') for cell in line)\n lines.append(line)\n return lines\n\n\nclass MrpcProcessor(DataProcessor):\n \"\"\"Processor for the MRPC data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n logger.info(\"LOOKING AT {}\".format(os.path.join(data_dir, \"train.tsv\")))\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[3]\n text_b = line[4]\n label = line[0]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MnliProcessor(DataProcessor):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_matched.tsv\")),\n \"dev_matched\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[8]\n text_b = line[9]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MnliMismatchedProcessor(MnliProcessor):\n \"\"\"Processor for the MultiNLI Mismatched data set (GLUE version).\"\"\"\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_mismatched.tsv\")),\n \"dev_matched\")\n\n\nclass ColaProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[3]\n label = line[1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\nclass Sst2Processor(DataProcessor):\n \"\"\"Processor for the SST-2 data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[0]\n label = line[1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\nclass StsbProcessor(DataProcessor):\n \"\"\"Processor for the STS-B data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [None]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[7]\n text_b = line[8]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass QqpProcessor(DataProcessor):\n \"\"\"Processor for the QQP data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n try:\n text_a = line[3]\n text_b = line[4]\n label = line[5]\n except IndexError:\n continue\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass QnliProcessor(DataProcessor):\n \"\"\"Processor for the QNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")),\n \"dev_matched\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"entailment\", \"not_entailment\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass RteProcessor(DataProcessor):\n \"\"\"Processor for the RTE data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"entailment\", \"not_entailment\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass WnliProcessor(DataProcessor):\n \"\"\"Processor for the WNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass SCTProcessor(DataProcessor):\n \"\"\"Processor for the SCT data set.\"\"\"\n\n def get_train_examples(self, data_dir):\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[0]\n text_b = line[1]\n label = \"0\" if line[2] == \"True\" else \"1\"\n examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer, output_mode):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n label_map = {label : i for i, label in enumerate(label_list)}\n\n features = []\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n logger.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n segment_ids = [0] * len(tokens)\n\n if tokens_b:\n tokens += tokens_b + [\"[SEP]\"]\n segment_ids += [1] * (len(tokens_b) + 1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n padding = [0] * (max_seq_length - len(input_ids))\n input_ids += padding\n input_mask += padding\n segment_ids += padding\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n if output_mode == \"classification\":\n label_id = label_map[example.label]\n elif output_mode == \"regression\":\n label_id = float(example.label)\n else:\n raise KeyError(output_mode)\n\n if ex_index < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\" % (example.guid))\n logger.info(\"tokens: %s\" % \" \".join(\n [str(x) for x in tokens]))\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n logger.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n logger.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n logger.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n features.append(\n InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id))\n return features\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef simple_accuracy(preds, labels):\n return (preds == labels).mean()\n\n\ndef acc_and_f1(preds, labels):\n acc = simple_accuracy(preds, labels)\n f1 = f1_score(y_true=labels, y_pred=preds)\n return {\n \"acc\": acc,\n \"f1\": f1,\n \"acc_and_f1\": (acc + f1) / 2,\n }\n\n\ndef pearson_and_spearman(preds, labels):\n pearson_corr = pearsonr(preds, labels)[0]\n spearman_corr = spearmanr(preds, labels)[0]\n return {\n \"pearson\": pearson_corr,\n \"spearmanr\": spearman_corr,\n \"corr\": (pearson_corr + spearman_corr) / 2,\n }\n\n\ndef compute_metrics(task_name, preds, labels):\n assert len(preds) == len(labels)\n if task_name == \"cola\":\n return {\"mcc\": matthews_corrcoef(labels, preds)}\n elif task_name == \"sst-2\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"mrpc\":\n return acc_and_f1(preds, labels)\n elif task_name == \"sts-b\":\n return pearson_and_spearman(preds, labels)\n elif task_name == \"qqp\":\n return acc_and_f1(preds, labels)\n elif task_name == \"mnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"mnli-mm\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"qnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"rte\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"wnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"sct\":\n return {\"acc\": simple_accuracy(preds, labels)}\n else:\n raise KeyError(task_name)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n ## Required parameters\n parser.add_argument(\"--data_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The input data dir. Should contain the .tsv files (or other data files) for the task.\")\n parser.add_argument(\"--bert_model\", default=None, type=str, required=True,\n help=\"Bert pre-trained model selected in the list: bert-base-uncased, \"\n \"bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, \"\n \"bert-base-multilingual-cased, bert-base-chinese.\")\n parser.add_argument(\"--task_name\",\n default=None,\n type=str,\n required=True,\n help=\"The name of the task to train.\")\n parser.add_argument(\"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\")\n\n ## Other parameters\n parser.add_argument(\"--cache_dir\",\n default=\"\",\n type=str,\n help=\"Where do you want to store the pre-trained models downloaded from s3\")\n parser.add_argument(\"--max_seq_length\",\n default=128,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--do_train\",\n action='store_true',\n help=\"Whether to run training.\")\n parser.add_argument(\"--do_eval\",\n action='store_true',\n help=\"Whether to run eval on the dev set.\")\n parser.add_argument(\"--do_lower_case\",\n action='store_true',\n help=\"Set this flag if you are using an uncased model.\")\n parser.add_argument(\"--train_batch_size\",\n default=32,\n type=int,\n help=\"Total batch size for training.\")\n parser.add_argument(\"--eval_batch_size\",\n default=8,\n type=int,\n help=\"Total batch size for eval.\")\n parser.add_argument(\"--learning_rate\",\n default=5e-5,\n type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--num_train_epochs\",\n default=3.0,\n type=float,\n help=\"Total number of training epochs to perform.\")\n parser.add_argument(\"--warmup_proportion\",\n default=0.1,\n type=float,\n help=\"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10%% of training.\")\n parser.add_argument(\"--no_cuda\",\n action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument(\"--local_rank\",\n type=int,\n default=-1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument('--seed',\n type=int,\n default=42,\n help=\"random seed for initialization\")\n parser.add_argument('--gradient_accumulation_steps',\n type=int,\n default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\")\n parser.add_argument('--fp16',\n action='store_true',\n help=\"Whether to use 16-bit float precision instead of 32-bit\")\n parser.add_argument('--loss_scale',\n type=float, default=0,\n help=\"Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\\n\"\n \"0 (default value): dynamic loss scaling.\\n\"\n \"Positive power of 2: static loss scaling value.\\n\")\n parser.add_argument('--server_ip', type=str, default='', help=\"Can be used for distant debugging.\")\n parser.add_argument('--server_port', type=str, default='', help=\"Can be used for distant debugging.\")\n args = parser.parse_args()\n\n if args.server_ip and args.server_port:\n # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script\n import ptvsd\n print(\"Waiting for debugger attach\")\n ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)\n ptvsd.wait_for_attach()\n\n processors = {\n \"cola\": ColaProcessor,\n \"mnli\": MnliProcessor,\n \"mnli-mm\": MnliMismatchedProcessor,\n \"mrpc\": MrpcProcessor,\n \"sst-2\": Sst2Processor,\n \"sts-b\": StsbProcessor,\n \"qqp\": QqpProcessor,\n \"qnli\": QnliProcessor,\n \"rte\": RteProcessor,\n \"wnli\": WnliProcessor,\n \"sct\": SCTProcessor,\n }\n\n output_modes = {\n \"cola\": \"classification\",\n \"mnli\": \"classification\",\n \"mrpc\": \"classification\",\n \"sst-2\": \"classification\",\n \"sts-b\": \"regression\",\n \"qqp\": \"classification\",\n \"qnli\": \"classification\",\n \"rte\": \"classification\",\n \"wnli\": \"classification\",\n \"sct\": \"classification\",\n }\n\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n n_gpu = torch.cuda.device_count()\n else:\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n n_gpu = 1\n # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.distributed.init_process_group(backend='nccl')\n\n logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.INFO if args.local_rank in [-1, 0] else logging.WARN)\n\n logger.info(\"device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}\".format(\n device, n_gpu, bool(args.local_rank != -1), args.fp16))\n\n if args.gradient_accumulation_steps < 1:\n raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format(\n args.gradient_accumulation_steps))\n\n args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n if not args.do_train and not args.do_eval:\n raise ValueError(\"At least one of `do_train` or `do_eval` must be True.\")\n\n if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train:\n raise ValueError(\"Output directory ({}) already exists and is not empty.\".format(args.output_dir))\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n task_name = args.task_name.lower()\n\n if task_name not in processors:\n raise ValueError(\"Task not found: %s\" % (task_name))\n\n processor = processors[task_name]()\n output_mode = output_modes[task_name]\n\n label_list = processor.get_labels()\n num_labels = len(label_list)\n\n tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)\n\n train_examples = None\n num_train_optimization_steps = None\n if args.do_train:\n train_examples = processor.get_train_examples(args.data_dir)\n num_train_optimization_steps = int(\n len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs\n if args.local_rank != -1:\n num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()\n\n # Prepare model\n cache_dir = args.cache_dir if args.cache_dir else os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed_{}'.format(args.local_rank))\n model = BertForSequenceClassification.from_pretrained(args.bert_model,\n cache_dir=cache_dir,\n num_labels=num_labels)\n if args.fp16:\n model.half()\n model.to(device)\n if args.local_rank != -1:\n try:\n from apex.parallel import DistributedDataParallel as DDP\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n\n model = DDP(model)\n elif n_gpu > 1:\n model = torch.nn.DataParallel(model)\n\n # Prepare optimizer\n if args.do_train:\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n if args.fp16:\n try:\n from apex.optimizers import FP16_Optimizer\n from apex.optimizers import FusedAdam\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n\n optimizer = FusedAdam(optimizer_grouped_parameters,\n lr=args.learning_rate,\n bias_correction=False,\n max_grad_norm=1.0)\n if args.loss_scale == 0:\n optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)\n else:\n optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)\n warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,\n t_total=num_train_optimization_steps)\n\n else:\n optimizer = BertAdam(optimizer_grouped_parameters,\n lr=args.learning_rate,\n warmup=args.warmup_proportion,\n t_total=num_train_optimization_steps)\n\n global_step = 0\n nb_tr_steps = 0\n tr_loss = 0\n if args.do_train:\n train_features = convert_examples_to_features(\n train_examples, label_list, args.max_seq_length, tokenizer, output_mode)\n logger.info(\"***** Running training *****\")\n logger.info(\" Num examples = %d\", len(train_examples))\n logger.info(\" Batch size = %d\", args.train_batch_size)\n logger.info(\" Num steps = %d\", num_train_optimization_steps)\n all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)\n\n if output_mode == \"classification\":\n all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.long)\n elif output_mode == \"regression\":\n all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.float)\n\n train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n if args.local_rank == -1:\n train_sampler = RandomSampler(train_data)\n else:\n train_sampler = DistributedSampler(train_data)\n train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)\n\n model.train()\n for _ in trange(int(args.num_train_epochs), desc=\"Epoch\"):\n tr_loss = 0\n nb_tr_examples, nb_tr_steps = 0, 0\n for step, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\")):\n batch = tuple(t.to(device) for t in batch)\n input_ids, input_mask, segment_ids, label_ids = batch\n\n # define a new function to compute loss values for both output_modes\n logits = model(input_ids, segment_ids, input_mask, labels=None)\n\n if output_mode == \"classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))\n elif output_mode == \"regression\":\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), label_ids.view(-1))\n\n if n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu.\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n\n if args.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n tr_loss += loss.item()\n nb_tr_examples += input_ids.size(0)\n nb_tr_steps += 1\n if (step + 1) % args.gradient_accumulation_steps == 0:\n if args.fp16:\n # modify learning rate with special warm up BERT uses\n # if args.fp16 is False, BertAdam is used that handles this automatically\n lr_this_step = args.learning_rate * warmup_linear.get_lr(global_step, args.warmup_proportion)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr_this_step\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):\n # Save a trained model, configuration and tokenizer\n model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self\n\n # If we save using the predefined names, we can load using `from_pretrained`\n output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)\n output_config_file = os.path.join(args.output_dir, CONFIG_NAME)\n\n torch.save(model_to_save.state_dict(), output_model_file)\n model_to_save.config.to_json_file(output_config_file)\n tokenizer.save_vocabulary(args.output_dir)\n\n # Load a trained model and vocabulary that you have fine-tuned\n model = BertForSequenceClassification.from_pretrained(args.output_dir, num_labels=num_labels)\n tokenizer = BertTokenizer.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)\n else:\n model = BertForSequenceClassification.from_pretrained(args.bert_model, num_labels=num_labels)\n model.to(device)\n\n if args.do_eval and (args.local_rank == -1 or torch.distributed.get_rank() == 0):\n eval_examples = processor.get_dev_examples(args.data_dir)\n eval_features = convert_examples_to_features(\n eval_examples, label_list, args.max_seq_length, tokenizer, output_mode)\n logger.info(\"***** Running evaluation *****\")\n logger.info(\" Num examples = %d\", len(eval_examples))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)\n\n if output_mode == \"classification\":\n all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)\n elif output_mode == \"regression\":\n all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.float)\n\n eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n # Run prediction for full data\n eval_sampler = SequentialSampler(eval_data)\n eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)\n\n model.eval()\n eval_loss = 0\n nb_eval_steps = 0\n preds = []\n\n for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc=\"Evaluating\"):\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n label_ids = label_ids.to(device)\n\n with torch.no_grad():\n logits = model(input_ids, segment_ids, input_mask, labels=None)\n\n # create eval loss and other metric required by the task\n if output_mode == \"classification\":\n loss_fct = CrossEntropyLoss()\n tmp_eval_loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))\n elif output_mode == \"regression\":\n loss_fct = MSELoss()\n tmp_eval_loss = loss_fct(logits.view(-1), label_ids.view(-1))\n\n eval_loss += tmp_eval_loss.mean().item()\n nb_eval_steps += 1\n if len(preds) == 0:\n preds.append(logits.detach().cpu().numpy())\n else:\n preds[0] = np.append(\n preds[0], logits.detach().cpu().numpy(), axis=0)\n\n eval_loss = eval_loss / nb_eval_steps\n preds = preds[0]\n if output_mode == \"classification\":\n preds = np.argmax(preds, axis=1)\n elif output_mode == \"regression\":\n preds = np.squeeze(preds)\n result = compute_metrics(task_name, preds, all_label_ids.numpy())\n loss = tr_loss/global_step if args.do_train else None\n\n result['eval_loss'] = eval_loss\n result['global_step'] = global_step\n result['loss'] = loss\n\n output_eval_file = os.path.join(args.output_dir, \"eval_results.txt\")\n with open(output_eval_file, \"w\") as writer:\n logger.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n logger.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n # hack for MNLI-MM\n if task_name == \"mnli\":\n task_name = \"mnli-mm\"\n processor = processors[task_name]()\n\n if os.path.exists(args.output_dir + '-MM') and os.listdir(args.output_dir + '-MM') and args.do_train:\n raise ValueError(\"Output directory ({}) already exists and is not empty.\".format(args.output_dir))\n if not os.path.exists(args.output_dir + '-MM'):\n os.makedirs(args.output_dir + '-MM')\n\n eval_examples = processor.get_dev_examples(args.data_dir)\n eval_features = convert_examples_to_features(\n eval_examples, label_list, args.max_seq_length, tokenizer, output_mode)\n logger.info(\"***** Running evaluation *****\")\n logger.info(\" Num examples = %d\", len(eval_examples))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)\n all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)\n\n eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n # Run prediction for full data\n eval_sampler = SequentialSampler(eval_data)\n eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)\n\n model.eval()\n eval_loss = 0\n nb_eval_steps = 0\n preds = []\n\n for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc=\"Evaluating\"):\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n label_ids = label_ids.to(device)\n\n with torch.no_grad():\n logits = model(input_ids, segment_ids, input_mask, labels=None)\n\n loss_fct = CrossEntropyLoss()\n tmp_eval_loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))\n\n eval_loss += tmp_eval_loss.mean().item()\n nb_eval_steps += 1\n if len(preds) == 0:\n preds.append(logits.detach().cpu().numpy())\n else:\n preds[0] = np.append(\n preds[0], logits.detach().cpu().numpy(), axis=0)\n\n eval_loss = eval_loss / nb_eval_steps\n preds = preds[0]\n preds = np.argmax(preds, axis=1)\n result = compute_metrics(task_name, preds, all_label_ids.numpy())\n loss = tr_loss/global_step if args.do_train else None\n\n result['eval_loss'] = eval_loss\n result['global_step'] = global_step\n result['loss'] = loss\n\n output_eval_file = os.path.join(args.output_dir + '-MM', \"eval_results.txt\")\n with open(output_eval_file, \"w\") as writer:\n logger.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n logger.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"torch.distributed.get_world_size",
"torch.utils.data.RandomSampler",
"scipy.stats.pearsonr",
"torch.cuda.is_available",
"sklearn.metrics.f1_score",
"torch.nn.CrossEntropyLoss",
"torch.nn.DataParallel",
"torch.distributed.init_process_group",
"torch.manual_seed",
"torch.tensor",
"torch.utils.data.DataLoader",
"numpy.argmax",
"torch.distributed.get_rank",
"torch.device",
"torch.cuda.manual_seed_all",
"sklearn.metrics.matthews_corrcoef",
"torch.utils.data.SequentialSampler",
"torch.cuda.device_count",
"torch.cuda.set_device",
"numpy.squeeze",
"torch.utils.data.TensorDataset",
"torch.nn.MSELoss",
"numpy.random.seed",
"torch.no_grad",
"scipy.stats.spearmanr",
"torch.utils.data.distributed.DistributedSampler"
]
] |
j-groeneveld/covid
|
[
"a8d993c866dcd56bf1c5f6f0a2120eae883aa029"
] |
[
"sim/lib/plot.py"
] |
[
"import time\nimport bisect\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nimport scipy\nimport scipy.optimize\nfrom scipy.interpolate import interp1d\nimport scipy as sp\nimport random as rd\nimport os, math\nfrom datetime import datetime\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import date2num, num2date\n\nfrom lib.measures import (MeasureList, BetaMultiplierMeasureBySite,\n SocialDistancingForAllMeasure, BetaMultiplierMeasureByType,\n SocialDistancingForPositiveMeasure, SocialDistancingByAgeMeasure, SocialDistancingForSmartTracing, ComplianceForAllMeasure)\nfrom lib.rt import compute_daily_rts, R_T_RANGE\n\nimport numpy as np\nimport seaborn as sns\nfrom matplotlib.colors import ListedColormap\n\nTO_HOURS = 24.0\nDPI = 200\nNO_PLOT = False\nTEST_LAG = 48.0 # hours\n\nmatplotlib.rcParams.update({\n \"figure.autolayout\": False,\n \"figure.figsize\": (6, 4),\n \"figure.dpi\": 150,\n \"axes.linewidth\": 0.8,\n \"xtick.major.width\": 0.8,\n \"xtick.minor.width\": 0.8,\n \"ytick.major.width\": 0.8,\n \"ytick.minor.width\": 0.8,\n \"text.usetex\": True,\n \"font.family\": \"serif\", # use serif rather than sans-serif\n \"font.serif\": \"Times New Roman\", # use \"Times New Roman\" as the standard font\n \"font.size\": 16,\n \"axes.titlesize\": 16,\n \"axes.labelsize\": 16,\n \"legend.fontsize\": 14,\n \"legend.frameon\": True,\n \"xtick.labelsize\": 14,\n \"ytick.labelsize\": 14,\n \"lines.linewidth\": 2.0,\n \"lines.markersize\": 4,\n \"grid.linewidth\": 0.4,\n})\n\n\ndef days_to_datetime(arr, start_date):\n # timestamps\n ts = arr * 24 * 60 * 60 + pd.Timestamp(start_date).timestamp()\n return pd.to_datetime(ts, unit='s')\n\n\ndef lockdown_widget(lockdown_at, start_date, lockdown_label_y, ymax,\n lockdown_label, ax, ls='--', xshift=0.0, zorder=None):\n # Convert x-axis into posix timestamps and use pandas to plot as dates\n lckdn_x = days_to_datetime(lockdown_at, start_date=start_date)\n ax.plot([lckdn_x, lckdn_x], [0, ymax], linewidth=2.5, linestyle=ls,\n color='black', label='_nolegend_', zorder=zorder)\n lockdown_label_y = lockdown_label_y or ymax*0.4\n ax.text(x=lckdn_x - pd.Timedelta(2.1 + xshift, unit='d'),\n y=lockdown_label_y, s=lockdown_label, rotation=90)\n\n\ndef target_widget(show_target,start_date, ax, zorder=None):\n txx = np.linspace(0, show_target.shape[0] - 1, num=show_target.shape[0])\n txx = days_to_datetime(txx, start_date=start_date)\n ax.plot(txx, show_target, linewidth=4, linestyle='', marker='X', ms=6,\n color='red', label='COVID-19 case data', zorder=zorder)\n\n\nclass Plotter(object):\n \"\"\"\n Plotting class\n \"\"\"\n\n def __init__(self):\n\n # plot constants\n # check out https://colorhunt.co/\n\n self.color_expo = '#ffcc00'\n self.color_iasy = '#00a8cc'\n self.color_ipre = '#005082'\n self.color_isym = '#000839'\n\n self.color_testing = '#ffa41b'\n\n self.color_posi = '#21bf73'\n self.color_nega = '#fd5e53'\n\n self.color_all = '#ffa41b'\n self.color_positive = '#00a8cc'\n self.color_age = '#005082'\n self.color_tracing = '#000839'\n\n self.color_infected = '#000839'\n\n self.filling_alpha = 0.5\n\n self.color_different_scenarios = [\n '#dc2ade',\n '#21ff53',\n '#323edd',\n '#ff9021',\n '#4d089a',\n '#cc0066',\n '#ff6666',\n '#216353',\n '#66cccc',\n '#ff2222'\n ]\n\n self.color_different_scenarios_alt = [\n '#a1dab4',\n '#41b6c4',\n '#2c7fb8',\n '#253494',\n ]\n\n\n\n # sequential\n # self.color_different_scenarios = [\n # # '#ffffcc',\n # '#c7e9b4',\n # '#7fcdbb',\n # '#41b6c4',\n # '#2c7fb8',\n # '#253494',\n # '#000000'\n # ]\n\n\n\n # 2D visualization\n self.density_alpha = 0.7\n\n self.marker_home = \"^\"\n self.marker_site = \"o\"\n\n self.color_home = '#000839'\n self.color_site = '#000000'\n\n self.size_home = 80\n self.size_site = 300\n\n\n\n def __is_state_at(self, sim, r, state, t):\n if state == 'posi' or state == 'nega':\n return (sim.state_started_at[state][r] - TEST_LAG <= t) & (sim.state_ended_at[state][r] - TEST_LAG > t)\n else:\n return (sim.state_started_at[state][r] <= t) & (sim.state_ended_at[state][r] > t)\n\n def __state_started_before(self, sim, r, state, t):\n if state == 'posi' or state == 'nega':\n return (sim.state_started_at[state][r] - TEST_LAG <= t)\n else:\n return (sim.state_started_at[state][r] <= t)\n\n def __is_contained_at(self, sim, r, measure, t):\n contained = np.zeros(sim.n_people, dtype='bool')\n for i in range(sim.n_people):\n if measure == 'SocialDistancingForAllMeasure':\n contained[i] = sim.measure_list[r].is_contained_prob(SocialDistancingForAllMeasure, t=t, j=i)\n elif measure == 'SocialDistancingForSmartTracing':\n contained[i] = sim.measure_list[r].is_contained_prob(SocialDistancingForSmartTracing, t=t, j=i)\n elif measure == 'SocialDistancingByAgeMeasure':\n contained[i] = sim.measure_list[r].is_contained_prob(SocialDistancingByAgeMeasure, t=t, age=sim.people_age[r, i])\n elif measure == 'SocialDistancingForPositiveMeasure':\n contained[i] = sim.measure_list[r].is_contained_prob(SocialDistancingForPositiveMeasure,\n t=t, j=i,\n state_posi_started_at=sim.state_started_at['posi'][r, :],\n state_posi_ended_at=sim.state_ended_at['posi'][r, :],\n state_resi_started_at=sim.state_started_at['resi'][r, :],\n state_dead_started_at=sim.state_started_at['dead'][r, :])\n else:\n raise ValueError('Social distancing measure unknown.')\n return contained\n\n def __comp_state_cumulative(self, sim, state, acc):\n '''\n Computes `state` variable over time [0, self.max_time] with given accuracy `acc\n '''\n ts, means, stds = [], [], []\n for t in np.linspace(0.0, sim.max_time, num=acc, endpoint=True):\n restarts = [np.sum(self.__state_started_before(sim, r, state, t))\n for r in range(sim.random_repeats)]\n ts.append(t/TO_HOURS)\n means.append(np.mean(restarts))\n stds.append(np.std(restarts))\n return np.array(ts), np.array(means), np.array(stds)\n\n def __comp_state_over_time(self, sim, state, acc):\n '''\n Computes `state` variable over time [0, self.max_time] with given accuracy `acc\n '''\n ts, means, stds = [], [], []\n for t in np.linspace(0.0, sim.max_time, num=acc, endpoint=True):\n restarts = [np.sum(self.__is_state_at(sim, r, state, t))\n for r in range(sim.random_repeats)]\n ts.append(t/TO_HOURS)\n means.append(np.mean(restarts))\n stds.append(np.std(restarts))\n return np.array(ts), np.array(means), np.array(stds)\n\n def __comp_contained_over_time(self, sim, measure, acc):\n '''\n Computes `state` variable over time [0, self.max_time] with given accuracy `acc\n '''\n ts, means, stds = [], [], []\n for t in np.linspace(0.0, sim.max_time, num=acc, endpoint=True):\n restarts = [np.sum(self.__is_contained_at(sim, r, measure, t))\n for r in range(sim.random_repeats)]\n ts.append(t/TO_HOURS)\n means.append(np.mean(restarts))\n stds.append(np.std(restarts))\n return np.array(ts), np.array(means), np.array(stds)\n\n def plot_cumulative_infected(self, sim, title='Example', filename='daily_inf_0',\n figsize=(6, 5), errorevery=20, acc=1000, ymax=None,\n lockdown_label='Lockdown', lockdown_at=None,\n lockdown_label_y=None, show_target=None,\n start_date='1970-01-01',\n subplot_adjust=None, legend_loc='upper right'):\n ''''\n Plots daily infected split by group\n averaged over random restarts, using error bars for std-dev\n '''\n\n if acc > sim.max_time:\n acc = int(sim.max_time)\n\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n ts, iasy_mu, iasy_sig = self.__comp_state_cumulative(sim, 'iasy', acc)\n # _, ipre_mu, ipre_sig = self.__comp_state_cumulative(sim, 'ipre', acc)\n _, isym_mu, isym_sig = self.__comp_state_cumulative(sim, 'isym', acc)\n # _, expo_mu, iexpo_sig = self.__comp_state_cumulative(sim, 'expo', acc)\n # _, posi_mu, posi_sig = self.__comp_state_cumulative(sim, 'posi', acc)\n\n line_xaxis = np.zeros(ts.shape)\n line_iasy = iasy_mu\n line_isym = iasy_mu + isym_mu\n\n error_isym = np.sqrt(iasy_sig**2 + isym_sig**2)\n\n # Convert x-axis into posix timestamps and use pandas to plot as dates\n ts = days_to_datetime(ts, start_date=start_date)\n\n # lines\n ax.plot(ts, line_iasy, c='black', linestyle='-')\n ax.errorbar(ts, line_isym, yerr=error_isym, c='black', linestyle='-',\n elinewidth=0.8, errorevery=errorevery, capsize=3.0)\n\n # filling\n ax.fill_between(ts, line_xaxis, line_iasy, alpha=self.filling_alpha, label='Asymptomatic',\n edgecolor=self.color_iasy, facecolor=self.color_iasy, linewidth=0, zorder=0)\n ax.fill_between(ts, line_iasy, line_isym, alpha=self.filling_alpha, label='Symptomatic',\n edgecolor=self.color_isym, facecolor=self.color_isym, linewidth=0, zorder=0)\n\n # limits\n if ymax is None:\n ymax = 1.5 * np.max(iasy_mu + isym_mu)\n ax.set_ylim((0, ymax))\n\n # ax.set_xlabel('Days')\n ax.set_ylabel('People')\n\n # extra\n if lockdown_at is not None:\n lockdown_widget(lockdown_at, start_date,\n lockdown_label_y, ymax,\n lockdown_label, ax)\n if show_target is not None:\n target_widget(show_target, start_date, ax)\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n #set ticks every week\n ax.xaxis.set_major_locator(mdates.WeekdayLocator())\n #set major ticks format\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))\n fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')\n\n # legend\n ax.legend(loc=legend_loc, borderaxespad=0.5)\n\n subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}\n plt.subplots_adjust(**subplot_adjust)\n\n plt.draw()\n\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI, bbox_inches='tight')\n\n if NO_PLOT:\n plt.close()\n return\n\n def plot_daily_infected(self, sim, title='Example', filename='daily_inf_0',\n figsize=(6, 5), errorevery=20, acc=1000, ymax=None,\n lockdown_label='Lockdown', lockdown_at=None,\n lockdown_label_y=None, show_target=None,\n lockdown_end=None,\n start_date='1970-01-01',\n subplot_adjust=None, legend_loc='upper right'):\n ''''\n Plots daily infected split by group\n averaged over random restarts, using error bars for std-dev\n '''\n\n if acc > sim.max_time:\n acc = int(sim.max_time)\n\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n ts, iasy_mu, iasy_sig = self.__comp_state_over_time(sim, 'iasy', acc)\n _, ipre_mu, ipre_sig = self.__comp_state_over_time(sim, 'ipre', acc)\n _, isym_mu, isym_sig = self.__comp_state_over_time(sim, 'isym', acc)\n # _, expo_mu, iexpo_sig = self.__comp_state_over_time(sim, 'expo', acc)\n # _, posi_mu, posi_sig = self.__comp_state_over_time(sim, 'posi', acc)\n\n line_xaxis = np.zeros(ts.shape)\n line_iasy = iasy_mu\n line_ipre = iasy_mu + ipre_mu\n line_isym = iasy_mu + ipre_mu + isym_mu\n error_isym = np.sqrt(iasy_sig**2 + ipre_sig**2 + isym_sig**2)\n\n # Convert x-axis into posix timestamps and use pandas to plot as dates\n ts = days_to_datetime(ts, start_date=start_date)\n\n # lines\n ax.plot(ts, line_iasy,\n c='black', linestyle='-')\n ax.plot(ts, line_ipre,\n c='black', linestyle='-')\n ax.errorbar(ts, line_isym, yerr=error_isym, c='black', linestyle='-',\n elinewidth=0.8, errorevery=errorevery, capsize=3.0)\n\n # filling\n ax.fill_between(ts, line_xaxis, line_iasy, alpha=self.filling_alpha, label='Asymptomatic',\n edgecolor=self.color_iasy, facecolor=self.color_iasy, linewidth=0, zorder=0)\n ax.fill_between(ts, line_iasy, line_ipre, alpha=self.filling_alpha, label='Pre-symptomatic',\n edgecolor=self.color_ipre, facecolor=self.color_ipre, linewidth=0, zorder=0)\n ax.fill_between(ts, line_ipre, line_isym, alpha=self.filling_alpha, label='Symptomatic',\n edgecolor=self.color_isym, facecolor=self.color_isym, linewidth=0, zorder=0)\n\n # limits\n if ymax is None:\n ymax = 1.5 * np.max(iasy_mu + ipre_mu + isym_mu)\n ax.set_ylim((0, ymax))\n\n # ax.set_xlabel('Days')\n ax.set_ylabel('People')\n\n # extra\n if lockdown_at is not None:\n lockdown_widget(lockdown_at, start_date,\n lockdown_label_y, ymax,\n lockdown_label, ax)\n if lockdown_end is not None:\n lockdown_widget(lockdown_at=lockdown_end, start_date=start_date,\n lockdown_label_y=lockdown_label_y, ymax=ymax,\n lockdown_label='End of lockdown', ax=ax, ls='dotted')\n if show_target is not None:\n target_widget(show_target, start_date, ax)\n\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n #set ticks every week\n ax.xaxis.set_major_locator(mdates.WeekdayLocator())\n #set major ticks format\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))\n fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')\n\n # legend\n ax.legend(loc=legend_loc, borderaxespad=0.5)\n\n subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}\n plt.subplots_adjust(**subplot_adjust)\n\n plt.draw()\n\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI, bbox_inches='tight')\n\n if NO_PLOT:\n plt.close()\n return\n\n def plot_daily_tested(self, sim, title='Example', filename='daily_tested_0', figsize=(10, 10), errorevery=20,\n acc=1000, ymax=None):\n\n ''''\n Plots daily tested, positive daily tested, negative daily tested\n averaged over random restarts, using error bars for std-dev\n '''\n\n if acc > sim.max_time:\n acc = int(sim.max_time)\n \n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n # automatically shifted by `test_lag` in the function\n ts, posi_mu, posi_sig = self.__comp_state_over_time(sim, 'posi', acc)\n _, nega_mu, nega_sig = self.__comp_state_over_time(sim, 'nega', acc)\n\n line_xaxis = np.zeros(ts.shape)\n line_posi = posi_mu\n line_nega = posi_mu + nega_mu\n\n error_posi = posi_sig\n error_nega = nega_sig + posi_sig\n\n T = posi_mu.shape[0]\n\n # lines\n ax.errorbar(ts, posi_mu, yerr=posi_sig, elinewidth=0.8, errorevery=errorevery,\n c='black', linestyle='-')\n ax.errorbar(ts, nega_mu, yerr=nega_sig, elinewidth=0.8, errorevery=errorevery,\n c='black', linestyle='-')\n\n # filling\n ax.fill_between(ts, line_xaxis, posi_mu, alpha=self.filling_alpha, label=r'Positive tests',\n edgecolor=self.color_posi, facecolor=self.color_posi, linewidth=0, zorder=0)\n ax.fill_between(ts, posi_mu, nega_mu, alpha=self.filling_alpha, label=r'Negative tests',\n edgecolor=self.color_nega, facecolor=self.color_nega, linewidth=0, zorder=0)\n # axis\n ax.set_xlim((0, np.max(ts)))\n if ymax is None:\n ymax = 1.5 * np.max(posi_mu + nega_mu)\n ax.set_ylim((0, ymax))\n\n ax.set_xlabel(r'$t$ [days]')\n ax.set_ylabel(r'[people]')\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n # legend\n fig.legend(loc='center right', borderaxespad=0.1)\n # Adjust the scaling factor to fit your legend text completely outside the plot\n plt.subplots_adjust(right=0.70)\n ax.set_title(title, pad=20)\n plt.draw()\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI, bbox_inches='tight')\n if NO_PLOT:\n plt.close()\n return\n\n def plot_daily_at_home(self, sim, title='Example', filename='daily_at_home_0', figsize=(10, 10), errorevery=20, acc=1000, ymax=None):\n\n ''''\n Plots daily tested, positive daily tested, negative daily tested\n averaged over random restarts, using error bars for std-dev\n '''\n\n if acc > sim.max_time:\n acc = int(sim.max_time)\n\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n ts, all_mu, all_sig = self.__comp_contained_over_time(sim, 'SocialDistancingForAllMeasure', acc)\n _, positive_mu, positive_sig = self.__comp_contained_over_time(sim, 'SocialDistancingForPositiveMeasure', acc)\n _, age_mu, age_sig = self.__comp_contained_over_time(sim, 'SocialDistancingByAgeMeasure', acc)\n _, tracing_mu, tracing_sig = self.__comp_contained_over_time(sim, 'SocialDistancingForSmartTracing', acc)\n\n _, iasy_mu, iasy_sig = self.__comp_state_over_time(sim, 'iasy', acc)\n _, ipre_mu, ipre_sig = self.__comp_state_over_time(sim, 'ipre', acc)\n _, isym_mu, isym_sig = self.__comp_state_over_time(sim, 'isym', acc)\n\n line_xaxis = np.zeros(ts.shape)\n\n line_all = all_mu\n line_positive = positive_mu\n line_age = age_mu\n line_tracing = tracing_mu\n\n line_infected = iasy_mu + ipre_mu + isym_mu\n\n error_all = all_sig\n error_positive = positive_sig\n error_age = age_sig\n error_tracing = tracing_sig\n\n error_infected = np.sqrt(np.square(iasy_sig) + np.square(ipre_sig) + np.square(isym_sig))\n\n # lines\n ax.errorbar(ts, line_infected, label=r'Total infected', errorevery=errorevery, c=self.color_infected, linestyle='--', yerr=error_infected)\n\n ax.errorbar(ts, line_all, yerr=error_all, elinewidth=0.8, errorevery=errorevery,\n c='black', linestyle='-')\n ax.errorbar(ts, line_positive, yerr=error_positive, elinewidth=0.8, errorevery=errorevery,\n c='black', linestyle='-')\n ax.errorbar(ts, line_age, yerr=error_age, elinewidth=0.8, errorevery=errorevery,\n c='black', linestyle='-')\n ax.errorbar(ts, line_tracing, yerr=error_tracing, elinewidth=0.8, errorevery=errorevery,\n c='black', linestyle='-')\n\n # filling\n ax.fill_between(ts, line_xaxis, line_all, alpha=self.filling_alpha, label=r'SD for all',\n edgecolor=self.color_all, facecolor=self.color_all, linewidth=0, zorder=0)\n ax.fill_between(ts, line_xaxis, line_positive, alpha=self.filling_alpha, label=r'SD for positively tested',\n edgecolor=self.color_positive, facecolor=self.color_positive, linewidth=0, zorder=0)\n ax.fill_between(ts, line_xaxis, line_age, alpha=self.filling_alpha, label=r'SD for age group',\n edgecolor=self.color_age, facecolor=self.color_age, linewidth=0, zorder=0)\n ax.fill_between(ts, line_xaxis, line_tracing, alpha=self.filling_alpha, label=r'SD for traced contacts',\n edgecolor=self.color_tracing, facecolor=self.color_tracing, linewidth=0, zorder=0)\n\n # axis\n ax.set_xlim((0, np.max(ts)))\n if ymax is None:\n ymax = 1.5 * np.max([all_mu, positive_mu, age_mu, tracing_mu])\n ax.set_ylim((0, ymax))\n\n ax.set_xlabel(r'$t$ [days]')\n ax.set_ylabel(r'[people]')\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n # legend\n fig.legend(loc='center right', borderaxespad=0.1)\n # Adjust the scaling factor to fit your legend text completely outside the plot\n plt.subplots_adjust(right=0.70)\n ax.set_title(title, pad=20)\n plt.draw()\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI, bbox_inches='tight')\n if NO_PLOT:\n plt.close()\n return\n\n def compare_total_infections(self, sims, titles, figtitle='Title',\n filename='compare_inf_0', figsize=(10, 10), errorevery=20, acc=1000, ymax=None,\n lockdown_label='Lockdown', lockdown_at=None, lockdown_label_y=None,\n show_positives=False, show_legend=True, legendYoffset=0.0, legend_is_left=False,\n subplot_adjust=None, start_date='1970-01-01', first_one_dashed=False):\n\n ''''\n Plots total infections for each simulation, named as provided by `titles`\n to compare different measures/interventions taken. Colors taken as defined in __init__, and\n averaged over random restarts, using error bars for std-dev\n '''\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n for i in range(len(sims)):\n if acc > sims[i].max_time:\n acc = sims[i].max_time\n\n ts, iasy_mu, iasy_sig = self.__comp_state_over_time(sims[i], 'iasy', acc)\n _, ipre_mu, ipre_sig = self.__comp_state_over_time(sims[i], 'ipre', acc)\n _, isym_mu, isym_sig = self.__comp_state_over_time(sims[i], 'isym', acc)\n _, posi_mu, posi_sig = self.__comp_state_over_time(sims[i], 'posi', acc)\n\n # Convert x-axis into posix timestamps and use pandas to plot as dates\n ts = days_to_datetime(ts, start_date=start_date)\n\n line_xaxis = np.zeros(ts.shape)\n line_infected = iasy_mu + ipre_mu + isym_mu\n error_infected = np.sqrt(np.square(iasy_sig) + np.square(ipre_sig) + np.square(isym_sig))\n\n # lines\n if show_positives:\n ax.errorbar(ts, line_infected, yerr=error_infected, label='[Infected] ' + titles[i], errorevery=errorevery,\n c=self.color_different_scenarios[i], linestyle='-')\n\n T = posi_mu.shape[0]\n ax.errorbar(ts, posi_mu, yerr=posi_sig, label='[Tested positive]', errorevery=errorevery,\n c=self.color_different_scenarios[i], linestyle='--', elinewidth=0.8)\n else:\n\n\n ax.errorbar(ts, line_infected, yerr=error_infected, label=titles[i], errorevery=errorevery, elinewidth=0.8,\n capsize=3.0, c=self.color_different_scenarios[i], linestyle='--' if i == 0 and first_one_dashed else '-')\n\n\n # axis\n # ax.set_xlim((0, np.max(ts)))\n if ymax is None:\n ymax = 1.5 * np.max(iasy_mu + ipre_mu + isym_mu)\n ax.set_ylim((0, ymax))\n\n # ax.set_xlabel('Days')\n ax.set_ylabel('People')\n\n if lockdown_at is not None:\n lockdown_widget(lockdown_at, start_date,\n lockdown_label_y, ymax,\n lockdown_label, ax, xshift=0.5)\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n #set ticks every week\n # ax.xaxis.set_major_locator(mdates.WeekdayLocator())\n ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=2))\n #set major ticks format\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))\n fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')\n\n if show_legend:\n # legend\n if legend_is_left:\n leg = ax.legend(loc='upper left', borderaxespad=0.5)\n else:\n leg = ax.legend(loc='upper right', borderaxespad=0.5)\n\n if legendYoffset != 0.0:\n # Get the bounding box of the original legend\n bb = leg.get_bbox_to_anchor().inverse_transformed(ax.transAxes)\n\n # Change to location of the legend.\n bb.y0 += legendYoffset\n bb.y1 += legendYoffset\n leg.set_bbox_to_anchor(bb, transform = ax.transAxes)\n\n subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}\n plt.subplots_adjust(**subplot_adjust)\n\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI, bbox_inches='tight')\n\n if NO_PLOT:\n plt.close()\n return\n\n def compare_total_fatalities_and_hospitalizations(self, sims, titles, figtitle=r'Hospitalizations and Fatalities',\n filename='compare_inf_0', figsize=(10, 10), errorevery=20, acc=1000, ymax=None, lockdown_at=None,\n subplot_adjust=None, start_date='1970-01-01', first_one_dashed=False):\n ''''\n Plots total fatalities and hospitalizations for each simulation, named as provided by `titles`\n to compare different measures/interventions taken. Colors taken as defined in __init__, and\n averaged over random restarts, using error bars for std-dev\n '''\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n # hospitalizations\n for i in range(len(sims)):\n if acc > sims[i].max_time:\n acc = sims[i].max_time\n\n ts, hosp_mu, hosp_sig = self.__comp_state_over_time(\n sims[i], 'hosp', acc)\n\n ts, dead_mu, dead_sig = self.__comp_state_over_time(\n sims[i], 'dead', acc)\n\n # Convert x-axis into posix timestamps and use pandas to plot as dates\n ts = days_to_datetime(ts, start_date=start_date)\n\n # lines\n ax.errorbar(ts, hosp_mu, yerr=hosp_sig, label=titles[i], errorevery=errorevery,\n c=self.color_different_scenarios[i], linestyle='-', elinewidth=0.8, capsize=3.0)\n\n ax.errorbar(ts, dead_mu, yerr=dead_sig, errorevery=errorevery,\n c=self.color_different_scenarios[i], linestyle='--', elinewidth=0.8, capsize=3.0)\n\n # axis\n if ymax is None:\n ymax = 1.5 * np.max(iasy_mu + ipre_mu + isym_mu)\n ax.set_ylim((0, ymax))\n\n # ax.set_xlabel('Days')\n ax.set_ylabel('People')\n\n\n if lockdown_at is not None:\n ax.plot(lockdown_at * np.ones(acc), np.linspace(0, ymax, num=acc),\n linewidth=1, linestyle='--', color='black', zorder=10)\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n #set ticks every week\n # ax.xaxis.set_major_locator(mdates.WeekdayLocator())\n ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=2))\n #set major ticks format\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))\n fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')\n\n # legend\n # ax.legend(loc='upper right', borderaxespad=0.5)\n ax.legend(loc='upper left', borderaxespad=0.5)\n\n subplot_adjust = subplot_adjust or {\n 'bottom': 0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}\n plt.subplots_adjust(**subplot_adjust)\n\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI, bbox_inches='tight')\n\n if NO_PLOT:\n plt.close()\n return\n\n def plot_2d_infections_at_time(self, sim, at_time, density_bandwidth=1.0, restart=0,\n title='Example', filename='2d_inf_0', figsize=(10, 10), acc=1000, ymax=None):\n\n '''\n Plots 2d visualization using mobility object. The bandwidth set by `density_bandwidth`\n determines the bandwidth of the RBF kernel in KDE used to generate the plot.\n Smaller means more affected by local changes. Set the colors and markers in the __init__ function\n '''\n if acc > sim.max_time:\n acc = int(sim.max_time)\n\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n # infections\n r = restart\n is_expo = self.__is_state_at(sim, r, 'expo', at_time)\n is_iasy = self.__is_state_at(sim, r, 'iasy', at_time)\n is_ipre = self.__is_state_at(sim, r, 'ipre', at_time)\n is_isym = self.__is_state_at(sim, r, 'isym', at_time)\n is_infected = is_iasy | is_ipre | is_isym\n no_state = (1 - is_infected) & (1 - is_expo)\n\n idx_expo = np.where(is_expo)[0]\n idx_infected = np.where(is_infected)[0]\n idx_none = np.where(no_state)[0]\n\n # self.color_isym = 'red'\n # self.color_expo= 'yellow'\n\n\n ### sites\n site_loc = sim.site_loc\n ax.scatter(site_loc[:, 0], site_loc[:, 1], alpha=self.filling_alpha, label='public sites',\n marker=self.marker_site, color=self.color_site, facecolors=self.color_site, s=self.size_site)\n\n\n ### home locations and their states\n home_loc = sim.home_loc\n # no state\n ax.scatter(home_loc[idx_none, 0], home_loc[idx_none, 1],\n marker=self.marker_home, color=self.color_home,\n facecolors='none', s=self.size_home)\n\n try:\n # expo\n ax.scatter(home_loc[idx_expo, 0], home_loc[idx_expo, 1],\n marker=self.marker_home, color=self.color_home,\n facecolors=self.color_expo, s=self.size_home, label='exposed households')\n sns.kdeplot(home_loc[idx_expo, 0], home_loc[idx_expo, 1], shade=True, alpha=self.density_alpha,\n shade_lowest=False, cbar=False, ax=ax, color=self.color_expo, bw=density_bandwidth, zorder=0)\n\n # infected\n ax.scatter(home_loc[idx_infected, 0], home_loc[idx_infected, 1],\n marker=self.marker_home, color=self.color_home,\n facecolors=self.color_isym, s=self.size_home, label='infected households')\n sns.kdeplot(home_loc[idx_infected, 0], home_loc[idx_infected, 1], shade=True, alpha=self.density_alpha,\n shade_lowest=False, cbar=False, ax=ax, color=self.color_isym, bw=density_bandwidth, zorder=0)\n\n except:\n print('KDE failed, likely no exposed and infected at this time. Try different timing.')\n plt.close()\n return\n\n # axis\n ax.set_xlim((-0.1, 1.1))\n ax.set_ylim((-0.1, 1.1))\n plt.axis('off')\n\n # legend\n fig.legend(loc='center right', borderaxespad=0.1)\n # Adjust the scaling factor to fit your legend text completely outside the plot\n plt.subplots_adjust(right=0.85)\n\n ax.set_title(title, pad=20)\n plt.draw()\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI, bbox_inches='tight')\n if NO_PLOT:\n plt.close()\n return\n\n def compare_hospitalizations_over_time(self, sims, titles, figtitle='Hospitalizations', filename='compare_hosp_0',\n capacity_line_at=20, figsize=(10, 10), errorevery=20, acc=1000, ymax=None):\n ''''\n Plots total hospitalizations for each simulation, named as provided by `titles`\n to compare different measures/interventions taken. Colors taken as defined in __init__, and\n averaged over random restarts, using error bars for std-dev.\n The value of `capacity_line_at` defines the y-intercept of the hospitalization capacity line\n '''\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n for i in range(len(sims)):\n if acc > sims[i].max_time:\n acc = sims[i].max_time\n\n ts, line_hosp, error_sig = self.__comp_state_over_time(\n sims[i], 'hosp', acc)\n line_xaxis = np.zeros(ts.shape)\n\n # lines\n ax.errorbar(ts, line_hosp, yerr=error_sig, errorevery=errorevery,\n c='black', linestyle='-', elinewidth=0.8)\n\n # filling\n ax.fill_between(ts, line_xaxis, line_hosp, alpha=self.filling_alpha, zorder=0,\n label=r'Hospitalized under: ' + titles[i], edgecolor=self.color_different_scenarios[i],\n facecolor=self.color_different_scenarios[i], linewidth=0)\n\n # capacity line\n ax.plot(ts, capacity_line_at * np.ones(ts.shape[0]), label=r'Max. hospitalization capacity',\n c='red', linestyle='--', linewidth=4.0)\n\n # axis\n ax.set_xlim((0, np.max(ts)))\n if ymax is None:\n ymax = 1.5 * np.max(line_hosp + error_sig)\n ax.set_ylim((0, ymax))\n\n ax.set_xlabel(r'$t$ [days]')\n ax.set_ylabel(r'[people]')\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n # legend\n fig.legend(loc='center right', borderaxespad=0.1)\n # Adjust the scaling factor to fit your legend text completely outside the plot\n plt.subplots_adjust(right=0.70)\n ax.set_title(figtitle, pad=20)\n plt.draw()\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI, bbox_inches='tight')\n if NO_PLOT:\n plt.close()\n return\n\n def plot_positives_vs_target(self, sim, targets, title='Example',\n filename='inference_0', figsize=(6, 5), errorevery=1, acc=17, ymax=None,\n start_date='1970-01-01', lockdown_label='Lockdown', lockdown_at=None,\n lockdown_label_y=None, subplot_adjust=None):\n ''''\n Plots daily tested averaged over random restarts, using error bars for std-dev\n together with targets from inference\n '''\n\n if acc > sim.max_time:\n acc = int(sim.max_time)\n\n fig, ax = plt.subplots(figsize=figsize)\n\n # inference\n # automatically shifted by `test_lag` in the function\n ts, posi_mu, posi_sig = self.__comp_state_over_time(sim, 'posi', acc)\n\n T = posi_mu.shape[0]\n \n xx = days_to_datetime(ts, start_date=start_date)\n ax.plot(xx, posi_mu, c='k', linestyle='-',\n label='COVID-19 simulated case data')\n ax.fill_between(xx, posi_mu - posi_sig, posi_mu + posi_sig,\n color='grey', alpha=0.1, linewidth=0.0)\n\n # target\n target_widget(targets, start_date, ax)\n\n # axis\n #ax.set_xlim((0, np.max(ts)))\n if ymax is None:\n ymax = 1.5 * np.max(posi_mu)\n ax.set_ylim((0, ymax))\n\n # ax.set_xlabel('Days')\n ax.set_ylabel('Positive cases')\n\n if lockdown_at is not None:\n lockdown_widget(lockdown_at, start_date,\n lockdown_label_y, ymax,\n lockdown_label, ax)\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n\n #set ticks every week\n ax.xaxis.set_major_locator(mdates.WeekdayLocator())\n #set major ticks format\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))\n fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')\n\n # legend\n ax.legend(loc='upper left', borderaxespad=0.5)\n\n subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}\n plt.subplots_adjust(**subplot_adjust)\n\n plt.draw()\n\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI)#, bbox_inches='tight')\n\n if NO_PLOT:\n plt.close()\n return\n\n def plot_daily_rts(self, sims, filename, start_date, titles=None, sigma=None,\n r_t_range=R_T_RANGE, window=3, figsize=(6, 5),\n subplot_adjust=None, lockdown_label='Lockdown',\n lockdown_at=None, lockdown_label_y=None, ymax=None,\n colors=['grey'], fill_between=True, draw_dots=True,\n errorevery=1, show_legend=False, xtick_interval=1, ci=0.9):\n\n # If a single summary is provided\n if not isinstance(sims, list):\n sims = [sims]\n sigma = [sigma]\n\n results = list()\n for i, sim in enumerate(sims):\n res = compute_daily_rts(sim, start_date, sigma[i], r_t_range, window, ci)\n results.append(res)\n\n # Colors\n ABOVE = [1,0,0]\n MIDDLE = [1,1,1]\n BELOW = [0,0,0]\n cmap = ListedColormap(np.r_[\n np.linspace(BELOW,MIDDLE,25),\n np.linspace(MIDDLE,ABOVE,25)\n ])\n color_mapped = lambda y: np.clip(y, .5, 1.5)-.5\n\n ymax_computed = 0.0 # Keep track of max y to set limit\n\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n\n for i, result in enumerate(results):\n index = result['ML'].index\n values = result['ML'].values\n\n # Plot dots and line\n ax.plot(index, values, c=colors[i], zorder=1, alpha=1.0)\n\n if draw_dots:\n ax.scatter(index, values, s=40, lw=0.0,\n c=cmap(color_mapped(values)),\n edgecolors='k', zorder=2)\n\n # Aesthetically, extrapolate credible interval by 1 day either side\n lowfn = interp1d(date2num(index), result[f'Low_{ci*100:.0f}'].values,\n bounds_error=False, fill_value='extrapolate')\n highfn = interp1d(date2num(index), result[f'High_{ci*100:.0f}'].values,\n bounds_error=False, fill_value='extrapolate')\n extended = pd.date_range(start=index[0], end=index[-1])\n error_low = lowfn(date2num(extended))\n error_high = highfn(date2num(extended))\n\n if fill_between:\n ax.fill_between(extended, error_low, error_high,\n color=colors[i], alpha=0.1, linewidth=0.0)\n else:\n # Ignore first value which is just prior, not informed by data\n ax.errorbar(x=index[1:], y=values[1:], label=titles[i],\n yerr=np.vstack((result[f'Low_{ci*100:.0f}'], result[f'High_{ci*100:.0f}']))[:,1:],\n color=colors[i], linewidth=1.0,\n elinewidth=0.8, capsize=3.0,\n errorevery=errorevery)\n\n ymax_computed = max(ymax_computed, np.max(error_high))\n\n # Plot horizontal line at R_t = 1\n ax.axhline(1.0, c='k', lw=1, alpha=.25);\n\n # limits\n ymax = ymax or 1.2 * ymax_computed\n ax.set_ylim((0, ymax_computed))\n\n if show_legend:\n ax.legend(loc='upper left', borderaxespad=0.5)\n\n # extra\n if lockdown_at is not None:\n lockdown_widget(lockdown_at, start_date,\n lockdown_label_y, ymax,\n lockdown_label, ax, zorder=-200)\n\n # Hide the right and top spines\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n # Only show ticks on the left and bottom spines\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n # Set label\n ax.set_ylabel(r'$R_t$')\n\n #set ticks every week\n ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=xtick_interval))\n #set major ticks format\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))\n fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')\n\n subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}\n plt.subplots_adjust(**subplot_adjust)\n\n plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,\n dpi=DPI)#, bbox_inches='tight')\n\n if NO_PLOT:\n plt.close()\n"
] |
[
[
"matplotlib.dates.DateFormatter",
"numpy.mean",
"numpy.where",
"pandas.Timestamp",
"matplotlib.pyplot.draw",
"numpy.max",
"pandas.Timedelta",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"numpy.sqrt",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.axis",
"numpy.vstack",
"pandas.to_datetime",
"numpy.square",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.std",
"matplotlib.rcParams.update",
"matplotlib.dates.WeekdayLocator",
"numpy.clip",
"pandas.date_range",
"numpy.ones",
"numpy.linspace",
"matplotlib.dates.date2num"
]
] |
yimaverickxia/csld
|
[
"002cc1d4bd644cbd7adffb8f2bcc8675cbd7f4bb"
] |
[
"csld/common_main.py"
] |
[
"#!/usr/bin/env python3\n\n\"\"\"\nMisc subroutines for linear fitting:\n * init correlation matrix A, value vector b\n * fit to get unknown coefficients x\n * predict using fitted x\n\"\"\"\n\nimport re\nimport glob\nimport logging\nimport numpy as np\nimport scipy\nimport scipy.sparse\nfrom cssolve.csfit import csfit, predict_holdout\n\n\ndef print_version(version):\n print(\" \" * 3, version, \"\\n\")\n\n\ndef print_end():\n print(\"Done\")\n\n\ndef add_common_parameter(parser):\n \"\"\"\n Add a few command-line parameters common to different models\n :return:\n \"\"\"\n parser.add_argument(\"--log_level\", type=int, help=\"Logging level. Default 1\", default=1)\n parser.add_argument(\"--symm_step\", type=int, help=\"Space group. 1 = file, *2 = spglib, 3 = spglib & save\", default=2)\n parser.add_argument(\"--symm_prim\", action='store_false',\n help=\"Symmetrize primitive cell with space group and save to POSCAR_sym. Default: True\", default=True)\n parser.add_argument(\"--clus_step\", type=int, help=\"Clusters. 0 = ignore & exit, 1 = file, 2 = generate, *3 = generate & save\", default=3)\n parser.add_argument(\"--symC_step\", type=int, help=\"Independent parameters. 0 = ignore & exit, 1 = file, 2 = generate, *3 = generate & save\", default=3)\n parser.add_argument(\"--train_step\", type=int, help=\"Correlation matrix. 0 = ignore & exit, 1 = file, 2 = generate, *3 = generate & save, 4 = skip\", default=3)\n parser.add_argument(\"--fit_step\", type=int, help=\"Fitting. 0 = ignore & exit, 1 = file, 2 = generate, *3 = generate & save\", default=3)\n parser.add_argument(\"--pred_step\", type=int, help=\"Prediction. *0 = skip, 1 = file, 2 = generate, 3 = generate & save\", default=0)\n parser.add_argument(\"--refit\", action='store_true',\n help=\"Perform another fitting, equivalent to \\\"--clus_step 1 --symC_step 1 --train_step 1\\\". Default: False\", default=False)\n parser.add_argument(\"--cont\", \"-c\", action='store_true',\n help=\"Continue from previous run, equivalent to \\\"--clus_step 1 --symC_step 1 --train_step 4 --fit_step 1\\\". Default: False\", default=False)\n parser.add_argument(\"--predict\", action='store_true',\n help=\"predict, equivalent to \\\"--cont --pred_step 2 and skipping magnon/phonon steps\\\". Default: False\", default=False)\n parser.add_argument(\"--override\", \"-o\", action=\"append\", help=\"Override setting file from command line, e.g. \\\"[structure] epsilon_inf=eps.txt\\\"\")\n\n\ndef process_common_options(options):\n # Quick prediction mode\n if options.predict:\n options.cont= True\n options.pred_step = 2\n # Assuming fitting is available from previous run\n if options.cont:\n options.clus_step = 1\n options.symC_step = 1\n options.train_step = 4\n options.fit_step = 1 \n # Another fit reusing existing info\n if options.refit:\n options.clus_step = 1\n options.symC_step = 1\n options.train_step = 1\n\n\ndef override_from_commandline(override_list, settings):\n if not override_list:\n return\n pattern = re.compile(r\"\\[\\w+\\] *\\w+ *=.*\")\n for x in override_list:\n if not pattern.match(x):\n print('ERROR: %s is not a valid override. Expecting e.g. [sec] name=val'%(x))\n return\n sec, other = re.split(r'\\]', x[1:], maxsplit=1)\n sec = sec.lower()\n other = other.strip()\n tag, val = re.split(r'=', other, 1)\n tag = tag.rstrip()\n val = val.lstrip()\n if sec not in settings:\n settings.add_section(sec)\n settings.set(sec, tag, val)\n\n\ndef upon_exit(pdfout):\n if pdfout is not None:\n pdfout.close()\n\n\ndef init_training(model, setting, step, **kwargs):\n \"\"\"\n training structures from which to obtain the Correlation matrix\n :return:\n \"\"\"\n from csld.util.io_utils import co, load_matrix\n if step <= 0:\n exit(0)\n elif step == 4:\n Amat = None\n fval = None\n elif step == 1:\n Amat = scipy.sparse.csr_matrix(load_matrix(setting['corr_in']))\n fval = np.zeros((Amat.shape[0], 3))\n fval[:, 0] = np.loadtxt(setting['fval_in'])\n elif step in [2, 3]:\n traindat= [y.split() for x, y in setting.items() if re.match('traindat.*', x) is not None]\n Amat, fval = model.get_correlation([[sc[0],\n [f for subs in sc[1:]\n for f in sorted(glob.glob(subs))]] for sc in traindat],\n corrtype=setting['corr_type'], setting=setting, **kwargs)\n if step == 3:\n scipy.io.mmwrite(setting['corr_out'], Amat)\n np.savetxt(setting['fval_out'], fval[:, 0])\n else:\n print(\"ERROR: Unknown corr_step: \", step)\n exit(-1)\n print(\"+ Correlation matrix for training done\")\n return Amat, fval\n\n\ndef fit_data(model, Amat, fval, setting, step, pdfout):\n \"\"\"\n Fitting\n :param model\n :param Amat:\n :param fval:\n :param setting:\n :param step:\n :param pdfout:\n :return: optimal solution\n \"\"\"\n if step <= 0:\n exit(0)\n elif step == 1:\n solutions = model.load_solution(setting['solution_in'])\n if Amat is not None:\n err = [np.std(Amat.dot(solutions[i])-fval[:,0]) for i in range(solutions.shape[0])]\n ibest = np.argmin(err)\n else:\n ibest = 0\n if solutions.size <= 0:\n logging.error(\"ERROR: empty solution\")\n exit(-1)\n if solutions.shape[0] > 1:\n logging.warning(\"More than 1 solutions found. Returning the first.\")\n elif step in [2, 3]:\n mulist = list(map(float, setting['mulist'].split()))\n submodels = [y.split() for x, y in setting.items() if re.match('submodel.*', x) is not None]\n submodels = [[x[0], ' '.join(x[1:])] for x in submodels]\n knownsol = setting.get('solution_known', '')\n submodels = model.get_submodels(submodels, setting=setting, knownsol=knownsol)\n\n ibest, solutions = csfit(Amat, fval[:,0], 1, mulist,\n method=int(setting['method']),\n maxIter=int(setting['maxiter']),\n tol=float(setting['tolerance']),\n nSubset=int(setting['nsubset']),\n subsetsize=float(setting['subsetsize']),\n holdsize=float(setting['holdsize']),\n lbd=float(setting['lambda']),\n# bcs options\n reweight=setting.getboolean('bcs_reweight', False),\n penalty=setting.get('bcs_penalty', 'arctan'),\n jcutoff=setting.getfloat('bcs_jcutoff',1E-7),\n sigma2=setting.getfloat('bcs_sigma2',-1.0),\n eta=setting.getfloat('bcs_eta',1E-3),\n\n fitf=setting.get('true_v_fit'),\n submodels=submodels, pdfout=pdfout)\n if step == 3:\n np.savetxt(setting['solution_out'], solutions)\n np.savetxt(setting['solution_out']+'_full', model.Cmat.T.dot(np.array(solutions)[:,:model.Cmat.shape[0]].T).T)\n\n else:\n print(\"ERROR: Unknown fit_step: \", step)\n exit(-1)\n print(\"+ Fitting done. Best solution\", ibest)\n return ibest, solutions\n\n\ndef predict(model, sols, setting, step):\n \"\"\"\n\n :param model:\n :param sol:\n :param setting:\n :param step:\n :return:\n \"\"\"\n if step <= 0:\n return\n elif step in [1, 2, 3]:\n Amat, fval = init_training(model, setting, step, delForce=0)\n else:\n print(\"ERROR: Unknown pred_step: \", step)\n exit(-1)\n\n errs = []\n for i in range(len(sols)):\n err = predict_holdout(Amat, fval[:, 0], sols[i])\n errs.append(err[0])\n print(\" sol# %d: err= (%.2f%%) %f\" % (i, err[0], err[1]))\n np.savetxt(\"%s_%d\"%(setting['fval_out'],i), np.transpose(err[2:4]))\n print(\"+ Prediction done\")\n return np.argmin(errs)\n"
] |
[
[
"numpy.array",
"numpy.savetxt",
"numpy.zeros",
"numpy.argmin",
"numpy.loadtxt",
"numpy.transpose",
"scipy.io.mmwrite"
]
] |
aporia-ai/aporia-mars
|
[
"fbebef726f80282b151971849d0b2bc0246c9b58",
"faf098a8113b402197a5bdccd175768bc353cb27"
] |
[
"mars/tensor/spatial/distance/tests/test_distance_execution.py",
"mars/lib/groupby_wrapper.py"
] |
[
"# Copyright 1999-2021 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport pytest\n\nfrom .....core import tile\nfrom ....datasource import tensor\nfrom ... import distance\n\n\n@pytest.mark.skipif(distance.pdist is None, reason=\"scipy not installed\")\ndef test_pdist_execution(setup):\n from scipy.spatial.distance import pdist as sp_pdist\n\n raw = np.random.rand(100, 10)\n\n # test 1 chunk\n x = tensor(raw, chunk_size=100)\n\n dist = distance.pdist(x)\n result = dist.execute().fetch()\n expected = sp_pdist(raw)\n np.testing.assert_array_equal(result, expected)\n\n dist = distance.pdist(x, metric=\"hamming\")\n result = dist.execute().fetch()\n expected = sp_pdist(raw, metric=\"hamming\")\n np.testing.assert_array_equal(result, expected)\n\n f = lambda u, v: np.sqrt(((u - v) ** 2).sum())\n dist = distance.pdist(x, metric=f)\n result = dist.execute().fetch()\n expected = sp_pdist(raw, metric=f)\n np.testing.assert_array_equal(result, expected)\n\n # test more than 1 chunk\n x = tensor(raw, chunk_size=12)\n\n dist = distance.pdist(x)\n tdist = tile(dist)\n assert len(tdist.chunks) == 1\n result = dist.execute().fetch()\n expected = sp_pdist(raw)\n np.testing.assert_array_equal(result, expected)\n\n dist = distance.pdist(x, aggregate_size=3)\n tdist = tile(dist)\n assert len(tdist.chunks) == 3\n result = dist.execute().fetch()\n expected = sp_pdist(raw)\n np.testing.assert_array_equal(result, expected)\n\n dist = distance.pdist(x, metric=\"hamming\", aggregate_size=2)\n tdist = tile(dist)\n assert len(tdist.chunks) == 2\n result = dist.execute().fetch()\n expected = sp_pdist(raw, metric=\"hamming\")\n np.testing.assert_array_equal(result, expected)\n\n f = lambda u, v: np.sqrt(((u - v) ** 2).sum())\n dist = distance.pdist(x, metric=f, aggregate_size=2)\n result = dist.execute().fetch()\n expected = sp_pdist(raw, metric=f)\n np.testing.assert_array_equal(result, expected)\n\n for x in [tensor(raw), tensor(raw, chunk_size=12)]:\n # test w\n weight = np.random.rand(10)\n w = tensor(weight, chunk_size=7)\n dist = distance.pdist(x, metric=\"wminkowski\", p=3, w=w)\n result = dist.execute().fetch()\n expected = sp_pdist(raw, metric=\"minkowski\", p=3, w=weight)\n np.testing.assert_array_equal(result, expected)\n\n # test V\n v = np.random.rand(10)\n V = tensor(v, chunk_size=7)\n dist = distance.pdist(x, metric=\"seuclidean\", V=V)\n result = dist.execute().fetch()\n expected = sp_pdist(raw, metric=\"seuclidean\", V=v)\n np.testing.assert_array_equal(result, expected)\n\n # test VI\n vi = np.random.rand(10, 10)\n VI = tensor(vi, chunk_size=8)\n dist = distance.pdist(x, metric=\"mahalanobis\", VI=VI)\n result = dist.execute().fetch()\n expected = sp_pdist(raw, metric=\"mahalanobis\", VI=vi)\n np.testing.assert_array_equal(result, expected)\n\n\n@pytest.mark.skipif(distance.cdist is None, reason=\"scipy not installed\")\ndef test_cdist_execution(setup):\n from scipy.spatial.distance import cdist as sp_cdist\n\n raw_a = np.random.rand(100, 10)\n raw_b = np.random.rand(89, 10)\n\n # test 1 chunk\n xa = tensor(raw_a, chunk_size=100)\n xb = tensor(raw_b, chunk_size=100)\n\n dist = distance.cdist(xa, xb)\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b)\n np.testing.assert_array_equal(result, expected)\n\n dist = distance.cdist(xa, xb, metric=\"hamming\")\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b, metric=\"hamming\")\n np.testing.assert_array_equal(result, expected)\n\n f = lambda u, v: np.sqrt(((u - v) ** 2).sum())\n dist = distance.cdist(xa, xb, metric=f)\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b, metric=f)\n np.testing.assert_array_equal(result, expected)\n\n # test more than 1 chunk\n xa = tensor(raw_a, chunk_size=12)\n xb = tensor(raw_b, chunk_size=13)\n\n dist = distance.cdist(xa, xb)\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b)\n np.testing.assert_array_equal(result, expected)\n\n dist = distance.cdist(xa, xb, metric=\"hamming\")\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b, metric=\"hamming\")\n np.testing.assert_array_equal(result, expected)\n\n f = lambda u, v: np.sqrt(((u - v) ** 2).sum())\n dist = distance.cdist(xa, xb, metric=f)\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b, metric=f)\n np.testing.assert_array_equal(result, expected)\n\n for xa, xb in [\n (tensor(raw_a), tensor(raw_b)),\n (tensor(raw_a, chunk_size=12), tensor(raw_b, chunk_size=13)),\n ]:\n # test w\n weight = np.random.rand(10)\n w = tensor(weight, chunk_size=7)\n dist = distance.cdist(xa, xb, metric=\"wminkowski\", p=3, w=w)\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b, metric=\"minkowski\", p=3, w=weight)\n np.testing.assert_array_equal(result, expected)\n\n # test V\n v = np.random.rand(10)\n V = tensor(v, chunk_size=7)\n dist = distance.cdist(xa, xb, metric=\"seuclidean\", V=V)\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b, metric=\"seuclidean\", V=v)\n np.testing.assert_array_equal(result, expected)\n\n # test VI\n vi = np.random.rand(10, 10)\n VI = tensor(vi, chunk_size=8)\n dist = distance.cdist(xa, xb, metric=\"mahalanobis\", VI=VI)\n result = dist.execute().fetch()\n expected = sp_cdist(raw_a, raw_b, metric=\"mahalanobis\", VI=vi)\n np.testing.assert_array_equal(result, expected)\n\n\n@pytest.mark.skipif(distance.cdist is None, reason=\"scipy not installed\")\ndef test_squareform_execution(setup):\n from scipy.spatial.distance import pdist as sp_pdist, squareform as sp_squareform\n\n raw_a = np.random.rand(80, 10)\n raw_pdsit = sp_pdist(raw_a)\n raw_square = sp_squareform(raw_pdsit)\n\n # tomatrix, test 1 chunk\n vec = tensor(raw_pdsit, chunk_size=raw_pdsit.shape[0])\n mat = distance.squareform(vec, chunk_size=100)\n result = mat.execute().fetch()\n np.testing.assert_array_equal(result, raw_square)\n\n # tomatrix, test more than 1 chunk\n vec = tensor(raw_pdsit, chunk_size=33)\n assert len(tile(vec).chunks) > 1\n mat = distance.squareform(vec, chunk_size=34)\n result = mat.execute().fetch()\n np.testing.assert_array_equal(result, raw_square)\n\n # tovec, test 1 chunk\n mat = tensor(raw_square)\n vec = distance.squareform(mat, chunk_size=raw_pdsit.shape[0])\n assert len(tile(mat).chunks) == 1\n assert len(tile(vec).chunks) == 1\n result = vec.execute().fetch()\n np.testing.assert_array_equal(result, raw_pdsit)\n\n # tovec, test more than 1 chunk\n mat = tensor(raw_square, chunk_size=31)\n vec = distance.squareform(mat, chunk_size=40)\n assert len(tile(vec).chunks) > 1\n result = vec.execute().fetch()\n np.testing.assert_array_equal(result, raw_pdsit)\n\n # test checks\n # generate non-symmetric matrix\n non_sym_arr = np.random.RandomState(0).rand(10, 10)\n\n # 1 chunk\n mat = tensor(non_sym_arr)\n vec = distance.squareform(mat, checks=True, chunk_size=100)\n with pytest.raises(ValueError):\n _ = vec.execute().fetch()\n # force checks=False\n vec = distance.squareform(mat, checks=False, chunk_size=100)\n _ = vec.execute().fetch()\n\n # more than 1 chunk\n mat = tensor(non_sym_arr, chunk_size=6)\n vec = distance.squareform(mat, checks=True, chunk_size=8)\n assert len(tile(vec).chunks) > 1\n with pytest.raises(ValueError):\n _ = vec.execute().fetch()\n # force checks=False\n vec = distance.squareform(mat, checks=False, chunk_size=100)\n _ = vec.execute().fetch()\n",
"# Copyright 1999-2021 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nfrom collections.abc import Iterable\n\nimport cloudpickle\nimport numpy as np\nfrom pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy\n\nfrom ..utils import estimate_pandas_size, pd_release_version\n\n_HAS_SQUEEZE = pd_release_version < (1, 1, 0)\n\n\nclass GroupByWrapper:\n def __init__(\n self,\n obj,\n groupby_obj=None,\n keys=None,\n axis=0,\n level=None,\n grouper=None,\n exclusions=None,\n selection=None,\n as_index=True,\n sort=True,\n group_keys=True,\n squeeze=False,\n observed=False,\n mutated=False,\n grouper_cache=None,\n ):\n def fill_value(v, key):\n return (\n v if v is not None or groupby_obj is None else getattr(groupby_obj, key)\n )\n\n self.obj = obj\n self.keys = fill_value(keys, \"keys\")\n self.axis = fill_value(axis, \"axis\")\n self.level = fill_value(level, \"level\")\n self.exclusions = fill_value(exclusions, \"exclusions\")\n self.selection = selection\n self.as_index = fill_value(as_index, \"as_index\")\n self.sort = fill_value(sort, \"sort\")\n self.group_keys = fill_value(group_keys, \"group_keys\")\n self.squeeze = fill_value(squeeze, \"squeeze\")\n self.observed = fill_value(observed, \"observed\")\n self.mutated = fill_value(mutated, \"mutated\")\n\n if groupby_obj is None:\n groupby_kw = dict(\n keys=keys,\n axis=axis,\n level=level,\n grouper=grouper,\n exclusions=exclusions,\n as_index=as_index,\n group_keys=group_keys,\n squeeze=squeeze,\n observed=observed,\n mutated=mutated,\n )\n if not _HAS_SQUEEZE: # pragma: no branch\n groupby_kw.pop(\"squeeze\")\n\n if obj.ndim == 2:\n self.groupby_obj = DataFrameGroupBy(obj, **groupby_kw)\n else:\n self.groupby_obj = SeriesGroupBy(obj, **groupby_kw)\n else:\n self.groupby_obj = groupby_obj\n\n if grouper_cache:\n self.groupby_obj.grouper._cache = grouper_cache\n if selection:\n self.groupby_obj = self.groupby_obj[selection]\n\n self.is_frame = isinstance(self.groupby_obj, DataFrameGroupBy)\n\n def __getitem__(self, item):\n return GroupByWrapper(\n self.obj,\n keys=self.keys,\n axis=self.axis,\n level=self.level,\n grouper=self.groupby_obj.grouper,\n exclusions=self.exclusions,\n selection=item,\n as_index=self.as_index,\n sort=self.sort,\n group_keys=self.group_keys,\n squeeze=self.squeeze,\n observed=self.observed,\n mutated=self.mutated,\n )\n\n def __getattr__(self, item):\n if item.startswith(\"_\"): # pragma: no cover\n return object.__getattribute__(self, item)\n if item in getattr(self.obj, \"columns\", ()):\n return self.__getitem__(item)\n return getattr(self.groupby_obj, item)\n\n def __iter__(self):\n return self.groupby_obj.__iter__()\n\n def __sizeof__(self):\n return sys.getsizeof(self.obj) + sys.getsizeof(\n getattr(self.groupby_obj.grouper, \"_cache\", None)\n )\n\n def estimate_size(self):\n return estimate_pandas_size(self.obj) + estimate_pandas_size(self.obj.index)\n\n def __reduce__(self):\n return (\n type(self).from_tuple,\n (self.to_tuple(pickle_function=True, truncate=True),),\n )\n\n def __bool__(self):\n return bool(np.prod(self.shape))\n\n @property\n def empty(self):\n return self.obj.empty\n\n @property\n def shape(self):\n shape = list(self.groupby_obj.obj.shape)\n if self.is_frame and self.selection:\n shape[1] = len(self.selection)\n return tuple(shape)\n\n @property\n def _selected_obj(self):\n return getattr(self.groupby_obj, \"_selected_obj\")\n\n def to_tuple(self, truncate=False, pickle_function=False):\n if self.selection and truncate:\n if isinstance(self.selection, Iterable) and not isinstance(\n self.selection, str\n ):\n item_list = list(self.selection)\n else:\n item_list = [self.selection]\n item_set = set(item_list)\n\n if isinstance(self.keys, list):\n sel_keys = self.keys\n elif self.keys in self.obj.columns:\n sel_keys = [self.keys]\n else:\n sel_keys = []\n\n all_items = item_list + [k for k in sel_keys or () if k not in item_set]\n if set(all_items) == set(self.obj.columns):\n obj = self.obj\n else:\n obj = self.obj[all_items]\n else:\n obj = self.obj\n\n if pickle_function and callable(self.keys):\n keys = cloudpickle.dumps(self.keys)\n else:\n keys = self.keys\n\n return (\n obj,\n keys,\n self.axis,\n self.level,\n self.exclusions,\n self.selection,\n self.as_index,\n self.sort,\n self.group_keys,\n self.squeeze,\n self.observed,\n self.mutated,\n getattr(self.groupby_obj.grouper, \"_cache\", dict()),\n )\n\n @classmethod\n def from_tuple(cls, tp):\n (\n obj,\n keys,\n axis,\n level,\n exclusions,\n selection,\n as_index,\n sort,\n group_keys,\n squeeze,\n observed,\n mutated,\n grouper_cache,\n ) = tp\n\n if isinstance(keys, (bytes, bytearray)):\n keys = cloudpickle.loads(keys)\n\n return cls(\n obj,\n keys=keys,\n axis=axis,\n level=level,\n exclusions=exclusions,\n selection=selection,\n as_index=as_index,\n sort=sort,\n group_keys=group_keys,\n squeeze=squeeze,\n observed=observed,\n mutated=mutated,\n grouper_cache=grouper_cache,\n )\n\n\ndef wrapped_groupby(\n obj,\n by=None,\n axis=0,\n level=None,\n as_index=True,\n sort=True,\n group_keys=True,\n squeeze=False,\n observed=False,\n):\n groupby_kw = dict(\n by=by,\n axis=axis,\n level=level,\n as_index=as_index,\n sort=sort,\n group_keys=group_keys,\n squeeze=squeeze,\n observed=observed,\n )\n if not _HAS_SQUEEZE: # pragma: no branch\n groupby_kw.pop(\"squeeze\")\n\n groupby_obj = obj.groupby(**groupby_kw)\n return GroupByWrapper(obj, groupby_obj=groupby_obj, as_index=as_index)\n"
] |
[
[
"scipy.spatial.distance.pdist",
"numpy.random.rand",
"numpy.random.RandomState",
"numpy.testing.assert_array_equal",
"scipy.spatial.distance.squareform",
"scipy.spatial.distance.cdist"
],
[
"numpy.prod",
"pandas.core.groupby.SeriesGroupBy",
"pandas.core.groupby.DataFrameGroupBy"
]
] |
fuzihaofzh/pytorch-1
|
[
"d865ea084a9572777d8af657ecc4730712926a0f"
] |
[
"torch/fx/_symbolic_trace.py"
] |
[
"import builtins\nimport functools\nimport inspect\nimport math\nimport os\nfrom types import CodeType, FunctionType, ModuleType\nfrom typing import Any, Dict, NamedTuple, Optional, Set, Tuple, Type, List, Callable, Union\nfrom itertools import chain\nimport torch\nimport torch._C._fx # type: ignore[import]\nfrom torch._C import ScriptObject # type: ignore[attr-defined]\nimport torch.utils._pytree as pytree\n\nimport sys\nfrom .node import Argument, map_aggregate, base_types\nfrom .graph import Graph, _PyTreeInfo\nfrom .graph_module import GraphModule\nfrom .proxy import TracerBase, Proxy\n\nHAS_VARSTUFF = inspect.CO_VARARGS | inspect.CO_VARKEYWORDS\n\n# These need to run in global scope to handle nested calls correctly\n_orig_module_call : Callable = torch.nn.Module.__call__\n_orig_module_getattr : Callable = torch.nn.Module.__getattr__\n\n_proxyable_classes : Dict[Type, None] = {}\n\nclass ProxyableClassMeta(type):\n \"\"\"\n ProxyableClassMeta allows you to make construction of a given Python class\n symbolically traceable. For example::\n\n import torch\n import torch.fx\n\n class TensorPair(metaclass=torch.fx.ProxyableClassMeta):\n def __init__(self, left, right):\n self.left, self.right = left, right\n\n def add(self, other):\n l = self.left + other.left\n r = self.right + other.right\n return TensorPair(l, r)\n\n def mul(self, other):\n l = self.left * other.left\n r = self.right * other.right\n return TensorPair(l, r)\n\n def use_tensor_pair_ctor(x : TensorPair, y : torch.Tensor):\n s = x.add(TensorPair(y, y))\n return s.mul(x)\n\n x = TensorPair(torch.randn(5, 3), torch.randn(5, 3))\n y = torch.randn(5, 3)\n ref_out = use_tensor_pair_ctor(x, y)\n\n traced = torch.fx.symbolic_trace(use_tensor_pair_ctor)\n print(traced.code)\n '''\n def forward(self, x : __main___TensorPair, y : torch.Tensor):\n tensor_pair = __main___TensorPair(y, y); y = None\n add = x.add(tensor_pair); tensor_pair = None\n mul = add.mul(x); add = x = None\n return mul\n '''\n\n From this example, we can see that contruction of a class (``TensorPair``)\n defined with ``ProxyableClassMeta`` as metaclass can be recorded in symbolic\n tracing.\n \"\"\"\n def __init__(cls, name, bases, attrs):\n _proxyable_classes.setdefault(cls)\n super().__init__(name, bases, attrs)\n\n def __call__(cls, *args, **kwargs):\n instance = cls.__new__(cls) # type: ignore[call-overload]\n\n found_proxies = []\n\n def check_proxy(a):\n if isinstance(a, Proxy):\n found_proxies.append(a)\n\n map_aggregate(args, check_proxy)\n map_aggregate(kwargs, check_proxy)\n\n if len(found_proxies) != 0:\n tracer = found_proxies[0].tracer\n return tracer.create_proxy('call_function', cls, args, kwargs)\n else:\n cls.__init__(instance, *args, **kwargs) # type: ignore[misc]\n return instance\n\n\ndef _patch_function(fn: FunctionType, nargs: int) -> FunctionType:\n co = fn.__code__\n co_flags = co.co_flags & ~HAS_VARSTUFF\n co_args : tuple\n if hasattr(co, \"co_posonlyargcount\"):\n co_args = (\n nargs, 0,\n 0, co.co_nlocals, co.co_stacksize,\n co_flags, co.co_code, co.co_consts, co.co_names,\n co.co_varnames, co.co_filename, co.co_name,\n co.co_firstlineno, co.co_lnotab, co.co_freevars,\n co.co_cellvars\n )\n else:\n co_args = (\n nargs, 0, co.co_nlocals,\n co.co_stacksize, co_flags, co.co_code, co.co_consts,\n co.co_names, co.co_varnames, co.co_filename,\n co.co_name, co.co_firstlineno, co.co_lnotab,\n co.co_freevars, co.co_cellvars)\n new_code = CodeType(*co_args) # type: ignore[arg-type]\n return FunctionType(new_code, fn.__globals__, fn.__name__, fn.__defaults__, fn.__closure__)\n\n # we need to insert placeholder nodes for *args and **kwargs\n # we can't call this function normally, otherwise it would try to unpack them\n # instead, let's make python think that args and kwargs are normal variables\n\nclass _CPatchManager(object):\n \"\"\"\n Calls patch_function in order to intercept functions at the C-extension level\n \"\"\"\n def __init__(self, tracer):\n self.tracer = tracer\n patched_fns = [torch.randn, torch.rand, torch.randint]\n\n def patched_impl(to_patch, args, kwargs):\n return tracer.create_proxy('call_function', to_patch, args, kwargs)\n\n c_patch_enabled = True\n\n def patched_in(to_patch, args, kwargs):\n nonlocal c_patch_enabled\n try:\n c_patch_enabled = False\n r = patched_impl(to_patch, args, kwargs)\n finally:\n c_patch_enabled = True\n return r\n\n def trace_func(frame, action, arg):\n if action == 'c_call':\n if c_patch_enabled:\n if arg in patched_fns:\n torch._C._fx.patch_function(arg, patched_in)\n\n self.func = trace_func\n\n def __enter__(self):\n if self.tracer.enable_cpatching:\n sys.setprofile(self.func)\n\n def __exit__(self, type, value, tb):\n sys.setprofile(None)\n\nclass PHBase(object):\n \"\"\"\n Object representing an input placeholder to `concrete_args`\n \"\"\"\n def __repr__(self):\n return 'PH'\n\nPH = PHBase()\n\nclass Tracer(TracerBase):\n # Reference: https://github.com/pytorch/pytorch/issues/54354\n # The first line of this docstring overrides the one Sphinx generates for the\n # documentation. We need it so that Sphinx doesn't leak `math`s path from the\n # build environment (e.g. `<module 'math' from '/leaked/path').\n\n \"\"\"Tracer(autowrap_modules=(math,), enable_cpatching=False)\n\n ``Tracer`` is the class that implements the symbolic tracing functionality\n of ``torch.fx.symbolic_trace``. A call to ``symbolic_trace(m)`` is equivalent\n to ``Tracer().trace(m)``.\n\n Tracer can be subclassed to override various behaviors of the tracing\n process. The different behaviors that can be overridden are described\n in the docstrings of the methods on this class.\n \"\"\"\n def __init__(self, autowrap_modules: Tuple[ModuleType] = (math, ), enable_cpatching: bool = False) -> None:\n # This method's signature is overridden by the first line of this class'\n # docstring. If this method's signature is modified, the signature that\n # overrides it also should be modified accordingly.\n\n \"\"\"\n Construct a Tracer object.\n\n Args:\n\n autowrap_modules (List[ModuleType]): defaults to `[math]`,\n Python modules whose functions should be wrapped automatically\n without needing to use fx.wrap().\n\n enable_cpatching (bool): defaults to `False`,\n Allows you to enable/disable monkeypatching of torch functions at the\n C-level (which captures functins like randn).\n\n C-level monkeypatching works by directly modifying the PyCFunctionObject*\n so that calling it returns a different function.\n\n Turning this on is likely to slow down tracing by 1.5-3x.\n\n \"\"\"\n\n super().__init__()\n\n # Functions we will eagerly wrap when we see them while tracing\n # this captures both `math.sqrt()` and `from math import sqrt` automatically\n self._autowrap_function_ids: Set[int] = {\n id(value) for name, value in chain(*[m.__dict__.items() for m in autowrap_modules])\n if not name.startswith(\"_\") and callable(value)}\n\n # Python modules to apply autowrap to at the start, in addition to\n # modules we see while tracing\n self._autowrap_search: List[ModuleType] = list(autowrap_modules)\n self.enable_cpatching = enable_cpatching\n\n self.submodule_paths: Optional[Dict[torch.nn.Module, str]] = None\n\n def create_arg(self, a: Any) -> 'Argument':\n \"\"\"\n A method to specify the behavior of tracing when preparing values to\n be used as arguments to nodes in the ``Graph``.\n\n By default, the behavior includes:\n\n #. Iterate through collection types (e.g. tuple, list, dict) and recursively\n call ``create_args`` on the elements.\n #. Given a Proxy object, return a reference to the underlying IR ``Node``\n #. Given a non-Proxy Tensor object, emit IR for various cases:\n\n * For a Parameter, emit a ``get_attr`` node referring to that Parameter\n * For a non-Parameter Tensor, store the Tensor away in a special\n attribute referring to that attribute.\n\n This method can be overridden to support more types.\n\n Args:\n\n a (Any): The value to be emitted as an ``Argument`` in the ``Graph``.\n\n\n Returns:\n\n The value ``a`` converted into the appropriate ``Argument``\n \"\"\"\n # The base tracer is used to construct Graphs when there is no associated\n # module hierarchy, so it can never create parameter references.\n # The default tracer adds the ability to refer to parameters when\n # tracing modules.\n if isinstance(a, torch.nn.Parameter):\n for n, p in self.root.named_parameters():\n if a is p:\n return self.create_node('get_attr', n, (), {})\n raise NameError('parameter is not a member of this module')\n elif isinstance(a, torch.Tensor):\n for n_, p_ in self.root.named_buffers():\n if a is p_:\n return self.create_node('get_attr', n_, (), {})\n elif isinstance(a, torch.nn.Module):\n for n_, p_ in self.root.named_modules():\n if a is p_:\n return self.create_node('get_attr', n_, (), {})\n # For NamedTuple instances that appear literally as args, we emit\n # a node to construct the NamedTuple and use that Node as the argument.\n if isinstance(a, tuple) and hasattr(a, '_fields'):\n args = tuple(self.create_arg(elem) for elem in a)\n return self.create_node('call_function', a.__class__, args, {})\n\n # Tensors do not have a reliable string repr() from which they can be\n # constructed (and we probably don't want to rely on that, either), so\n # for any constant Tensor values we encounter, first search for if they\n # are an attribute of some module in the module hierarchy. If so, emit\n # a get_attr to retrieve that tensor. Otherwise, we'll store away the\n # tensor value into a special attribute on the Module s.t. we can\n # retrieve it with a get_attr.\n if isinstance(a, (torch.Tensor, ScriptObject)):\n qualname : Optional[str] = self.tensor_attrs.get(a)\n\n # Tensor was not found in the Module hierarchy, stow it away in a\n # special attribute and set the qualname to refer to that\n if not qualname:\n i = 0\n while True:\n qualname = f'_tensor_constant{i}'\n if not hasattr(self.root, qualname):\n break\n i += 1\n setattr(self.root, qualname, a)\n\n return self.create_node('get_attr', qualname, (), {})\n\n if type(a) in _proxyable_classes:\n # This is an instance of a proxyable class for which we did not\n # witness its construction. Intern this as a constant attribute\n\n # TODO: binary search\n i = 0\n while True:\n qualname = f'_{a.__class__.__name__}_constant_{i}'\n if not hasattr(self.root, qualname):\n break\n i += 1\n setattr(self.root, qualname, a)\n\n return self.create_node('get_attr', qualname, (), {})\n\n return super().create_arg(a)\n\n def is_leaf_module(self, m: torch.nn.Module, module_qualified_name : str) -> bool:\n \"\"\"\n A method to specify whether a given ``nn.Module`` is a \"leaf\" module.\n\n Leaf modules are the atomic units that appear in\n the IR, referenced by ``call_module`` calls. By default,\n Modules in the PyTorch standard library namespace (torch.nn)\n are leaf modules. All other modules are traced through and\n their constituent ops are recorded, unless specified otherwise\n via this parameter.\n\n Args:\n\n m (Module): The module being queried about\n module_qualified_name (str): The path to root of this module. For example,\n if you have a module hierarchy where submodule ``foo`` contains\n submodule ``bar``, which contains submodule ``baz``, that module will\n appear with the qualified name ``foo.bar.baz`` here.\n \"\"\"\n return m.__module__.startswith('torch.nn') and not isinstance(m, torch.nn.Sequential)\n\n def path_of_module(self, mod : torch.nn.Module) -> str:\n \"\"\"\n Helper method to find the qualified name of ``mod`` in the Module hierarchy\n of ``root``. For example, if ``root`` has a submodule named ``foo``, which has\n a submodule named ``bar``, passing ``bar`` into this function will return\n the string \"foo.bar\".\n\n Args:\n\n mod (str): The ``Module`` to retrieve the qualified name for.\n \"\"\"\n # Prefer the O(1) algorithm\n if self.submodule_paths:\n path = self.submodule_paths.get(mod)\n if path is None:\n raise NameError('module is not installed as a submodule')\n assert isinstance(path, str)\n return path\n # O(N^2) fallback in the case that we didn't store the submodule\n # paths.\n else:\n for n, p in self.root.named_modules():\n if mod is p:\n return n\n raise NameError('module is not installed as a submodule')\n\n def call_module(self, m: torch.nn.Module, forward: Callable[..., Any], args : Tuple[Any, ...], kwargs : Dict[str, Any]) -> Any:\n \"\"\"\n Method that specifies the behavior of this ``Tracer`` when it encounters\n a call to an ``nn.Module`` instance.\n\n By default, the behavior is to check if the called module is a leaf module\n via ``is_leaf_module``. If it is, emit a ``call_module`` node referring to\n ``m`` in the ``Graph``. Otherwise, call the ``Module`` normally, tracing through\n the operations in its ``forward`` function.\n\n This method can be overridden to--for example--create nested traced\n GraphModules, or any other behavior you would want while tracing across\n ``Module`` boundaries.\n\n Args:\n\n m (Module): The module for which a call is being emitted\n forward (Callable): The forward() method of the ``Module`` to be invoked\n args (Tuple): args of the module callsite\n kwargs (Dict): kwargs of the module callsite\n\n Return:\n\n The return value from the Module call. In the case that a ``call_module``\n node was emitted, this is a ``Proxy`` value. Otherwise, it is whatever\n value was returned from the ``Module`` invocation.\n \"\"\"\n module_qualified_name = self.path_of_module(m)\n if not self.is_leaf_module(m, module_qualified_name):\n return forward(*args, **kwargs)\n return self.create_proxy('call_module', module_qualified_name, args, kwargs)\n\n def create_args_for_root(self, root_fn, is_module, concrete_args=None):\n \"\"\"\n Create ``placeholder`` nodes corresponding to the signature of the ``root``\n Module. This method introspects root's signature and emits those\n nodes accordingly, also supporting ``*args`` and ``**kwargs``.\n \"\"\"\n # In some cases, a function or method has been decorated with a wrapper\n # defined via ``functools.wraps``. In this case, the outer code object\n # will likely not contain the actual parameters we care about, so unwrap\n # the function to get to the innermost callable.\n fn_for_analysis = inspect.unwrap(root_fn)\n co = fn_for_analysis.__code__\n total_args = co.co_argcount + co.co_kwonlyargcount\n orig_args = list(co.co_varnames)\n names_iter = iter(co.co_varnames)\n args : List[Any] = []\n skip_arg_idx = 0\n if is_module:\n if total_args == 0:\n raise RuntimeError('``self`` argument cannot be part of *args expansion!')\n skip_arg_idx = 1\n next(names_iter) # skip self\n args.append(self.root)\n\n sig = inspect.signature(fn_for_analysis)\n\n def proxy_placeholder(name: str):\n if concrete_args is not None and name in concrete_args :\n cnt = 0\n\n def replace_ph(x):\n nonlocal cnt\n cnt += 1\n out = self.create_proxy('placeholder', f'{name}_{str(cnt)}', (), {})\n if x == PH:\n return out\n # Union[int, bool] == bool in Python <= 3.6\n if type(x) == bool or type(x) in base_types and type(x) != torch.Tensor:\n torch._assert(out == x, f\"{name} has been specialized to have value {x}\")\n else:\n torch.warnings.warn(\n \"Was not able to add assertion to guarantee correct inputs to \"\n \"specialized function. It is up to the user to make sure that your inputs match the \"\n \"inputs you specialized the function with.\"\n )\n\n return x\n\n return pytree.tree_map(replace_ph, concrete_args[name])\n if name[0] == '*':\n default = ()\n else:\n param = sig.parameters[name]\n default = () if param.default is inspect.Parameter.empty else (param.default,) # type: ignore[assignment]\n return self.create_proxy('placeholder', name, default, {},\n type_expr=fn_for_analysis.__annotations__.get(name, None))\n arg_names = [next(names_iter) for idx in range(skip_arg_idx, total_args)]\n if isinstance(concrete_args, tuple):\n assert(len(arg_names) == len(concrete_args))\n concrete_args = {name: val for name, val in zip(arg_names, concrete_args)}\n args.extend(proxy_placeholder(names) for names in arg_names)\n\n\n if co.co_kwonlyargcount > 0 or co.co_flags & HAS_VARSTUFF:\n # TODO: type annotations for *args and **kwargs\n if co.co_flags & inspect.CO_VARARGS:\n args.append(proxy_placeholder('*' + next(names_iter)))\n if co.co_flags & inspect.CO_VARKEYWORDS:\n args.append(proxy_placeholder('**' + next(names_iter)))\n root_fn = _patch_function(root_fn, len(args))\n\n flat_args, in_spec = pytree.tree_flatten(tuple(args))\n if any(not isinstance(i, pytree.LeafSpec) for i in in_spec.children_specs):\n # In the case that we have pytree-flattened inputs in\n # `concrete_args`, generate a flattening wrapper around the\n # original root function and return that.\n self.graph._pytree_info = _PyTreeInfo(orig_args[:total_args], in_spec, None)\n\n def flatten_fn(*args):\n tree_args = pytree.tree_unflatten(list(args), in_spec)\n tree_out = root_fn(*tree_args)\n out_args, out_spec = pytree.tree_flatten(tree_out)\n assert(self.graph._pytree_info is not None)\n self.graph._pytree_info = self.graph._pytree_info._replace(out_spec=out_spec)\n return out_args\n\n return flatten_fn, flat_args\n return root_fn, args\n\n\n def _module_getattr(self, attr, attr_val, parameter_proxy_cache):\n if isinstance(attr_val, torch.nn.Parameter):\n for n, p in self.root.named_parameters():\n if attr_val is p:\n if n not in parameter_proxy_cache:\n parameter_proxy_cache[n] = self.create_proxy('get_attr', n, (), {})\n return parameter_proxy_cache[n]\n return attr_val\n\n\n def trace(self, root: Union[torch.nn.Module, Callable], concrete_args: Optional[Dict[str, Any]] = None) -> Graph:\n \"\"\"\n Trace ``root`` and return the corresponding FX ``Graph`` representation. ``root``\n can either be an ``nn.Module`` instance or a Python callable.\n\n Note that after this call, ``self.root`` may be different from the ``root`` passed\n in here. For example, when a free function is passed to ``trace()``, we will\n create an ``nn.Module`` instance to use as the root and add embedded constants\n to.\n\n\n Args:\n\n root (Union[Module, Callable]): Either a ``Module`` or a function to be\n traced through.\n concrete_args (Optional[Dict[str, any]]): Concrete arguments that should not be treated as Proxies.\n\n Returns:\n\n A ``Graph`` representing the semantics of the passed-in ``root``.\n \"\"\"\n if isinstance(root, torch.nn.Module):\n self.root = root\n fn = type(root).forward\n self.submodule_paths = {mod: name for name, mod in root.named_modules()}\n else:\n self.root = torch.nn.Module()\n fn = root\n self.graph = Graph()\n\n # When we encounter a Tensor value that's not a parameter, we look if it\n # is some other attribute on the model. Construct a dict mapping Tensor\n # values to the qualified name here for efficiency. This is used downstream\n # in create_arg\n self.tensor_attrs : Dict[torch.Tensor, str] = {}\n\n def collect_tensor_attrs(m : torch.nn.Module, prefix_atoms : List[str]):\n for k, v in m.__dict__.items():\n if isinstance(v, (torch.Tensor, ScriptObject)):\n self.tensor_attrs[v] = '.'.join(prefix_atoms + [k])\n for k, v in m.named_children():\n collect_tensor_attrs(v, prefix_atoms + [k])\n\n collect_tensor_attrs(self.root, [])\n\n assert isinstance(fn, FunctionType)\n\n fn_globals = fn.__globals__ # run before it gets patched\n fn, args = self.create_args_for_root(fn, isinstance(root, torch.nn.Module), concrete_args)\n\n parameter_proxy_cache : Dict[str, Proxy] = {} # Reduce number of get_attr calls\n\n # Method dispatch on parameters is not recorded unless it's directly used.\n # Thus, we need to insert a proxy when __getattr__ requests a parameter.\n @functools.wraps(_orig_module_getattr)\n def module_getattr_wrapper(mod, attr):\n attr_val = _orig_module_getattr(mod, attr)\n return self._module_getattr(attr, attr_val, parameter_proxy_cache)\n\n @functools.wraps(_orig_module_call)\n def module_call_wrapper(mod, *args, **kwargs):\n def forward(*args, **kwargs):\n return _orig_module_call(mod, *args, **kwargs)\n\n _autowrap_check(patcher, getattr(getattr(mod, \"forward\", mod), \"__globals__\", {}),\n self._autowrap_function_ids)\n return self.call_module(mod, forward, args, kwargs)\n\n with _CPatchManager(self):\n with _Patcher() as patcher:\n # allow duplicate patches to support the case of nested calls\n patcher.patch_method(torch.nn.Module, \"__getattr__\", module_getattr_wrapper, deduplicate=False)\n patcher.patch_method(torch.nn.Module, \"__call__\", module_call_wrapper, deduplicate=False)\n _patch_wrapped_functions(patcher)\n _autowrap_check(patcher, fn_globals, self._autowrap_function_ids)\n for module in self._autowrap_search:\n _autowrap_check(patcher, module.__dict__, self._autowrap_function_ids)\n self.create_node('output', 'output', (self.create_arg(fn(*args)),), {},\n type_expr=fn.__annotations__.get('return', None))\n\n self.submodule_paths = None\n\n return self.graph\n\n\n# List of pairs of (global dict, function name) functions\n# to patch for the purposes of the wrap() API.\n_wrapped_fns_to_patch : List[Tuple[dict, str]] = []\n\n# List of methods on classes to wrap (class type, function name)\n# this currently only works for Tensor.* methods that aren't traced properly\n_wrapped_methods_to_patch : List[Tuple[type, str]] = []\n\nif os.environ.get(\"FX_PATCH_GETITEM\") == \"1\":\n # This change is needed to trace models like PositionalEmbedding from BERT:\n # https://github.com/pytorch/benchmark/blob/master/torchbenchmark/models/BERT_pytorch/bert_pytorch/model/embedding/position.py\n # but causes issues in quantization documented here:\n # https://github.com/pytorch/pytorch/issues/50710\n # once that is fixed we can make this the default behavior.\n _wrapped_methods_to_patch.append((torch.Tensor, \"__getitem__\"))\n\n\ndef _find_proxy(*objects_to_search):\n \"\"\"\n Recursively search a data structure for a Proxy() and return it,\n return None if not found.\n \"\"\"\n proxy = None\n\n def find_proxy(x):\n nonlocal proxy\n if isinstance(x, Proxy):\n proxy = x\n\n map_aggregate(objects_to_search, find_proxy)\n return proxy\n\n\ndef _create_wrapped_func(orig_fn):\n @functools.wraps(orig_fn)\n def wrapped(*args, **kwargs):\n \"\"\"\n Given an closed-over ``orig_function`` to invoke, search the args and kwargs for\n a Proxy object. If there is one, emit a ``call_function`` node to preserve the\n call to this leaf function directly. Otherwise, just return the results of\n this function call, as this function is not being traced.\n \"\"\"\n proxy = _find_proxy(args, kwargs)\n if proxy is not None:\n return_proxy = proxy.tracer.create_proxy('call_function', orig_fn, args, kwargs)\n return_proxy.node.meta['is_wrapped'] = True\n return return_proxy\n return orig_fn(*args, **kwargs)\n\n return wrapped\n\n\ndef _create_wrapped_method(cls, name):\n orig_fn = getattr(cls, name)\n\n @functools.wraps(orig_fn)\n def wrapped(*args, **kwargs):\n \"\"\"\n Search the args and kwargs for a Proxy object. If there is one,\n emit a ``call_method`` node to preserve the call to this method\n directly. Otherwise, just return the results of this function\n call, as this function is not being traced.\n \"\"\"\n proxy = _find_proxy(args, kwargs)\n if proxy is not None:\n return proxy.tracer.create_proxy('call_method', name, args, kwargs)\n return orig_fn(*args, **kwargs)\n\n return wrapped\n\n\nclass _PatchedFn(NamedTuple):\n frame_dict : Any\n fn_name : str\n orig_fn : Any\n\n def revert(self):\n raise NotImplementedError()\n\n\nclass _PatchedFnSetItem(_PatchedFn):\n def revert(self):\n self.frame_dict[self.fn_name] = self.orig_fn\n\n\nclass _PatchedFnDel(_PatchedFn):\n def revert(self):\n del self.frame_dict[self.fn_name]\n\n\nclass _PatchedFnSetAttr(_PatchedFn):\n def revert(self):\n setattr(self.frame_dict, self.fn_name, self.orig_fn)\n\n\nclass _Patcher(object):\n def __init__(self):\n super(_Patcher, self).__init__()\n self.patches_made : List[_PatchedFn] = []\n self.visited : Set[int] = set()\n\n def patch(self, frame_dict : Dict[str, Any], name : str, new_fn : Callable,\n deduplicate : bool = True):\n \"\"\"\n Replace frame_dict[name] with new_fn until we exit the context manager.\n \"\"\"\n new_fn.__fx_already_patched = deduplicate # type: ignore[attr-defined]\n if name not in frame_dict and hasattr(builtins, name):\n self.patches_made.append(_PatchedFnDel(frame_dict, name, None))\n elif getattr(frame_dict[name], \"__fx_already_patched\", False):\n return # already patched, no need to do it again\n else:\n self.patches_made.append(_PatchedFnSetItem(frame_dict, name, frame_dict[name]))\n frame_dict[name] = new_fn\n\n def patch_method(self, cls: type, name : str, new_fn : Callable,\n deduplicate : bool = True):\n \"\"\"\n Replace object_or_dict.name with new_fn until we exit the context manager.\n \"\"\"\n new_fn.__fx_already_patched = deduplicate # type: ignore[attr-defined]\n orig_fn = getattr(cls, name)\n if getattr(orig_fn, \"__fx_already_patched\", False):\n return # already patched, no need to do it again\n self.patches_made.append(_PatchedFnSetAttr(cls, name, orig_fn))\n setattr(cls, name, new_fn)\n\n def visit_once(self, thing: Any):\n \"\"\" Return True on the first call to with thing, otherwise false \"\"\"\n idx = id(thing)\n if idx in self.visited:\n return False\n self.visited.add(idx)\n return True\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"\n Undo all the changes made via self.patch() and self.patch_method()\n \"\"\"\n while self.patches_made:\n # unpatch in reverse order to handle duplicates correctly\n self.patches_made.pop().revert()\n self.visited.clear()\n\n\ndef _patch_wrapped_functions(patcher : _Patcher):\n \"\"\"\n Go through ``_wrapped_fn_patch_table`` and, for each frame object, wrap\n the listed global functions in the `_create_wrapped_func` wrapper.\n \"\"\"\n for frame_dict, name in _wrapped_fns_to_patch:\n if name not in frame_dict and hasattr(builtins, name):\n orig_fn = getattr(builtins, name)\n else:\n orig_fn = frame_dict[name]\n patcher.patch(frame_dict, name, _create_wrapped_func(orig_fn))\n\n for cls, name in _wrapped_methods_to_patch:\n patcher.patch_method(cls, name, _create_wrapped_method(cls, name))\n\n\ndef _autowrap_check(patcher : _Patcher, frame_dict : Dict[str, Any], function_ids : Set[int]):\n \"\"\"\n Some methods, like `math.sqrt` are common enough we want to automatically wrap them as we see them.\n This method searches a scope for them and patches them if found.\n \"\"\"\n if patcher.visit_once(frame_dict):\n for name, value in frame_dict.items():\n if not name.startswith(\"_\") and callable(value) and id(value) in function_ids:\n patcher.patch(frame_dict, name, _create_wrapped_func(value))\n\n\ndef wrap(fn_or_name : Union[str, Callable]):\n \"\"\"\n This function can be called at module-level scope to register fn_or_name as a \"leaf function\".\n A \"leaf function\" will be preserved as a CallFunction node in the FX trace instead of being\n traced through::\n\n # foo/bar/baz.py\n def my_custom_function(x, y):\n return x * x + y * y\n\n torch.fx.wrap('my_custom_function')\n\n def fn_to_be_traced(x, y):\n # When symbolic tracing, the below call to my_custom_function will be inserted into\n # the graph rather than tracing it.\n return my_custom_function(x, y)\n\n This function can also equivalently be used as a decorator::\n\n # foo/bar/baz.py\n @torch.fx.wrap\n def my_custom_function(x, y):\n return x * x + y * y\n\n A wrapped function can be thought of a \"leaf function\", analogous to the concept of\n \"leaf modules\", that is, they are functions that are left as calls in the FX trace\n rather than traced through.\n\n Args:\n\n fn_or_name (Union[str, Callable]): The function or name of the global function to insert into the\n graph when it's called\n \"\"\"\n if not callable(fn_or_name) and not isinstance(fn_or_name, str):\n raise RuntimeError('Unsupported type for global function! Must be either a callable or '\n 'string name')\n\n if hasattr(fn_or_name, '__code__'):\n assert not isinstance(fn_or_name, str) # to make mypy happy\n fn_name = fn_or_name.__code__.co_name\n else:\n assert isinstance(fn_or_name, str), \"fn_or_name must be a global function or string name\"\n fn_name = fn_or_name\n\n currentframe = inspect.currentframe()\n assert currentframe is not None\n f = currentframe.f_back\n assert f is not None\n if f.f_code.co_name != '<module>':\n raise NotImplementedError('wrap must be called at the top level of a module')\n\n # consider implementing Callable version of this via _autowrap_function_ids / _autowrap_search\n # semantics would be slightly different, but would add support `from x import wrapped_function`\n _wrapped_fns_to_patch.append((f.f_globals, fn_name))\n return fn_or_name\n\ndef symbolic_trace(root : Union[torch.nn.Module, Callable], concrete_args: Optional[Dict[str, Any]] = None,\n enable_cpatching: bool = False) -> GraphModule:\n \"\"\"Symbolic tracing API\n\n Given an ``nn.Module`` or function instance ``root``, this function will return a ``GraphModule``\n constructed by recording operations seen while tracing through ``root``.\n\n ``concrete_args`` allows you to partially specialize your function, whether it's to remove control flow or data structures.\n\n For example::\n\n def f(a, b):\n if b == True:\n return a\n else:\n return a*2\n\n FX can typically not trace through this due to the presence of control\n flow. However, we can use `concrete_args` to specialize on the value of\n `b` to trace through this.\n\n f = fx.symbolic_trace(f, concrete_args={'b': False})\n assert f(3, False) == 6\n\n Note that although you can still pass in different values of `b`, they will be ignored.\n\n We can also use `concrete_args` to eliminate data-structure handling from\n our function. This will use pytrees to flatten your input. To avoid\n overspecializing, pass in `fx.PH` for values that shouldn't be\n specialized. For example::\n\n def f(x):\n out = 0\n for v in x.values():\n out += v\n return out\n f = fx.symbolic_trace(f, concrete_args={'x': {'a': fx.PH, 'b': fx.PH, 'c': fx.PH}})\n assert f({'a': 1, 'b': 2, 'c': 4}) == 7\n\n\n Args:\n root (Union[torch.nn.Module, Callable]): Module or function to be traced and converted\n into a Graph representation.\n concrete_args (Optional[Dict[str, any]]): Inputs to be partially specialized\n enable_cpatching: Enables C-level patching of functions (captures things like `torch.randn`)\n\n Returns:\n GraphModule: a Module created from the recorded operations from ``root``.\n\n \"\"\"\n tracer = Tracer(enable_cpatching=enable_cpatching)\n graph = tracer.trace(root, concrete_args)\n name = root.__class__.__name__ if isinstance(root, torch.nn.Module) else root.__name__\n return GraphModule(tracer.root, graph, name)\n"
] |
[
[
"torch._assert",
"torch.warnings.warn",
"torch.utils._pytree.tree_map",
"torch.nn.Module",
"torch._C._fx.patch_function",
"torch.utils._pytree.tree_flatten"
]
] |
heejinohn/lzho
|
[
"3c34e4dfb499224d3991ac0493c31c2c274122cb"
] |
[
"ticker-2014.py"
] |
[
"import pandas as pd, numpy as np, wrds\nimport datetime as dt\n\ndb = wrds.Connection()\n\n# Create a set including OptionMetrics tickers\nom_name = (db.get_table('optionm','secnmd')\n .groupby(['secid','ticker','issuer'])['effect_date']\n .agg(['min','max']).reset_index().rename({'min':'start','max':'end'},axis=1))\n\nom_name['ticker'] = np.where(om_name['ticker']=='ZZZZ',np.NaN,om_name['ticker'])\n\nticker = set(om_name.ticker.dropna().unique())\nticker.difference_update(set(['I','WSB','SEC']))\n\n# Read data\nsubmission = pd.read_parquet('/scratch/ou/hohn/sub2014.parquet.gzip')\n\n# Remove [deleted] and [removed] indicators\nsubmission['title'] = np.where(submission['title'].isin(['[deleted]','[removed]',None]),\n '', submission['title'])\nsubmission['selftext'] = np.where(submission['selftext'].isin(['[deleted]','[removed]',None]),\n '', submission['selftext'])\n# Remove unwanted symbols\nsubmission['title'] =submission['title'].str.replace('[,.\\?:\\(\\)]',' ',regex=True)\nsubmission['selftext'] =submission['selftext'].str.replace('[,.\\?:\\(\\)]',' ',regex=True)\nsubmission['title'] =submission['title'].str.replace(\"'s\",\"\",regex=True)\nsubmission['selftext'] =submission['selftext'].str.replace(\"'s\",\"\",regex=True)\n\n# Split texts to lists\nsubmission['title'] = submission['title'].str.split(' ')\nsubmission['selftext'] = submission['selftext'].str.split(' ')\n\n# Define function to be applied\ndef find_ticker(textlist):\n global ticker\n a_set = set('$' + tic for tic in ticker)\n if len(textlist) != 0:\n hit_1 = a_set.intersection(textlist)\n if len(hit_1) > 0:\n return [s[1:] for s in hit_1]\n else:\n num_upper = len([word for word in textlist if word.isupper()])\n if num_upper / len(textlist) > .8:\n return []\n else:\n hit_2 = ticker.intersection(textlist)\n if len(hit_2) > 0:\n return [s for s in hit_2]\n else:\n return []\n\n# Find ticker in title and text\nsubmission['ticker_a'] = submission['title'].apply(find_ticker)\nsubmission['ticker_b'] = submission['selftext'].apply(find_ticker)\n\n# Write to file\nsubmission.to_parquet('/scratch/ou/hohn/ticker_2014.parquet.gzip', compression='gzip')\n"
] |
[
[
"numpy.where",
"pandas.read_parquet"
]
] |
torsteinb36/Salmon_lice_simulator
|
[
"8319da4fb6743ad2a444ab58fe327191c0445783"
] |
[
"Simulator_engine/Farm.py"
] |
[
"from .Lice_agent_female import Lice_agent_f\nfrom .Lice_agent_male import Lice_agent_m\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom .Planktonic_agent import Planktonic_agent\nimport pandas as pd\nfrom matplotlib import dates\n\nclass Farm:\n '''\n Ein klassi til at fylgja við støðuni á teimum einstøku farminum\n '''\n count = 1 # ein countari til at hjálpa við at geva farminum navn\n treat_id = 1\n def __init__(self, time,delta_time, fish_count = 1_000_000, L_0=0.2, name=None, farm_start=0,\n prod_len=420_000, fallow=10000, prod_cyc = 0, treatments=None,\n treatment_type = None, NumTreat=0, treat_eff=np.array([[]]),\n weight = 0.2, lusateljingar=[], fish_count_history = None,temperature=None,\n temperature_Average=None,wrasse_data =None,biomass_data =None,initial_start=0,\n cleanEff =None,lice_mortality=None,surface_ratio_switch=None):\n '''\n :params:\n time Tíðin tá ið farmin verður gjørd\n fish_count Hvussu nógvur fiskur er í farmini tá ið hon startar (count)\n L_0 Extern smitta, (Lús per dag per fisk)\n name Hvat er navni á farmini um hettar ikki er sett verður tað sett fyri ein\n farm_start Nær startar productiónin (dagar frá t=0)\n prod_len Hvussu langur er hvør syklus (dagar)\n fallow Brakkleggjing (Hvussu leingi millum hvørja útsetan) (dagar)\n prod_cyc Hvat fyri cycul byrja vit vit við\n treatments Ein listi av datoion av treatments\n treatment_type Hvat fyri treatment verður brúkt\n NumTreat Hvat fyri treatment starta vit við\n treat_eff Ein matrix av treatment effiicies\n lusateljingar Ein listi sum sigur nar vit hava lúsateljingar\n '''\n self.time = time\n\n\n self.delta_time = delta_time\n #self.temperature = temperature\n self.fish_count = fish_count\n self.fish_count_history = fish_count_history\n self.lice_f = []\n self.lice_m = []\n #self.plankton = np.array([0, 0])\n # TODO hettar skal verða eitt anna slag av lús\n self.lice_mortality = lice_mortality\n self.adultlice_f = Lice_agent_f(time, 0, 1000,self.lice_mortality) # Ja eg skilji ikki orduliga hi tú setur hettar til 1000\n self.adultlice_m = Lice_agent_m(time, 0, 1000,self.lice_mortality)\n\n self.L_0 = L_0\n # Hvissi einki navn er sett so gerða vit eitt\n if name == None:\n self.name = 'farm_%s' % self.__class__.count\n self.__class__.count += 1\n else:\n self.name = name\n self.prod_len = prod_len\n self.fallow = fallow\n self.prod_time = -farm_start\n self.__fordeiling__ = [0, 0, 0, 0, 0,0,0,0,0,0]\n self.prod_cyc = prod_cyc\n self.treatment = treatments\n self.SliceON =-1 # -1 merkir at Slice ella Foodtreatment aðrar treatments ikk eru ON. >= 0 eru ON\n self.NumTreat = NumTreat\n self.treatment_type = treatment_type\n self.treat_eff = treat_eff\n self.num_treat_tjek = np.alen(treatments)-1\n dofy = np.arange(0, 366)\n diff_treat = np.append(dofy[0:int(len(dofy)/2)]*0+20,dofy[int(len(dofy)/2):]*0+80)\n self.diff_treatment = [dofy,diff_treat]\n self.num_of_treatments = 0\n\n self.prod_len_tjek = len(self.prod_len)\n self.weight = weight\n self.W0 = 7 # maximum kg av laksinum\n self.K = 0.008 # growth rate í procent pr dag\n self.old_fish_count = 0\n self.fish_count_update = interp1d(\n x = fish_count_history[0], # remember which is which this should be date of fish\n y = fish_count_history[1], # remember which is which this should be number of fish\n bounds_error = False,\n fill_value = 0\n )\n self.Temp_update = interp1d(\n x = temperature[0], # remember which is which this should be date of fish\n y = temperature[1], # remember which is which this should be number of fish\n bounds_error = False,\n fill_value = 0\n )\n# self.Temp_update_average = interp1d(\n# x = temperature_Average.day_of_year.values, # remember which is which this should be date of fish\n# y = temperature_Average.Temp.values, # remember which is which this should be number of fish\n# bounds_error = False,\n# fill_value = 0\n# )\n self.wrasse_data = wrasse_data\n #self.cleaner_count_update = interp1d(\n # x = wrasse_data[0], # remember which is which this should be date of fish\n # y = wrasse_data[1], # remember which is which this should be number of fish\n # bounds_error = False,\n # fill_value = 0\n #)\n self.cleaner_fish = 0\n self.cleanEff = cleanEff\n self.biomass = biomass_data\n self.biomass_update = interp1d(\n x = biomass_data[0], # remember which is which this should be date of fish\n y = biomass_data[1]*0.001, # remember which is which this should be number of fish\n bounds_error = False,\n fill_value = 0\n )\n self.plankton = Planktonic_agent(0, self.delta_time)\n self.initial_start = initial_start\n self.surface_ratio_switch = surface_ratio_switch\n\n def update(self, attached=0):\n '''\n Hvat skal henda tá ið man uppdaterar Farmina\n :params:\n delta_time Hvussu nógv skal tíðin flyta seg\n attached Hvussu nógv lús kemur frá ørðum farms\n '''\n\n self.time += self.delta_time\n\n\n #print(self.temp)\n\n # TODO hettar við start tíð skal sikkurt formilerðast við at gerða\n # TODO self.prod_time negativft í __init__\n # if self.fish_count_gen:\n # self.fish_count = self.fish_count_genirator.__next__()\n self.old_fish_count = self.fish_count\n self.fish_count = self.fish_count_update(self.time)\n # attchedment_ratio = TODO ger ein attachement ratio fiskar í byrjandi skulu ikki hava líka nógva lús\n\n self.temp = self.Temp_update(self.time)\n #print(self.temp)\n #print(self.temp)\n #if self.temp==0:\n time_new = pd.to_datetime(dates.num2date(self.time+self.initial_start))\n dayofyear = time_new.dayofyear\n # self.temp=self.Temp_update_average(dayofyear)\n #print(self.fish_count)\n\n\n # hvussu nógvur fiskur er deyður relatift\n if self.old_fish_count != 0:\n deth_ratio = min(1, self.fish_count / self.old_fish_count)\n else:\n deth_ratio = 1\n\n # ratio between surface area between nógvur fiskur er deyður relatift\n if self.surface_ratio_switch == 1:\n Volumen_farm = (self.biomass_update(self.time)*self.fish_count)/20 #schooling density\n Volumen_grid = 160*3*160*3*15\n A_farm =np.sqrt(Volumen_farm / 15)*np.sqrt(Volumen_farm / 15)\n A_grid = 160*3*160*3\n surface_grid = np.sqrt(Volumen_grid / 15)#4 * 15 * np.sqrt(Volumen_grid / 15) #+ 160*3*2\n surface_farm = np.sqrt(Volumen_farm / 15)#4 * 15 * np.sqrt(Volumen_farm / 15) #+ (Volumen_farm / 10)\n #print(self.biomass_update(self.time),self.fish_count)\n self.surface_ratio = surface_farm/surface_grid\n #self.surface_ratio = A_farm / A_grid\n #self.surface_ratio = Volumen_farm / Volumen_grid\n else:\n self.surface_ratio = 1\n #print(surface_ratio)\n #print(self.fish_count)\n\n if self.prod_cyc < self.prod_len_tjek:\n #self.plankton = Planktonic_agent(0, 0)\n\n if self.prod_time <= self.prod_len[self.prod_cyc] and self.prod_time >= 0:\n\n\n #============ clenar fish effect========\n #self.cleaner_fish = self.cleaner_count_update(self.time)\n self.cleaner_fish += self.cleaner_F_update(self.time)\n #print(self.cleaner_fish)\n #print(self.name,self.time)\n self.cleaner_fish += -self.cleaner_fish*self.delta_time*0.005\n\n self.cleaner_death = self.cleaner_fish * self.cleanEff *self.delta_time # how many lice do cleaner fish eat in one delta time step (0.05 per day)\n #print(self.cleaner_fish,self.cleaner_death,self.time,self.cleanEff)\n if self.cleaner_death <=0 or np.sum(self.get_fordeiling())==0:\n self.cleaner_death_ratio = 1\n else:\n self.cleaner_death_ratio = max([0,(1-self.cleaner_death /\n np.sum([np.sum(self.get_fordeiling()[2:6]), np.sum(self.get_fordeiling()[8:])]) )])\n\n\n #=====================\n self.prod_time += self.delta_time\n while self.lice_f:\n if self.lice_f[0].get_stage() == 'Adult_gravid':\n self.adultlice_f.count += self.lice_f.pop(0).count\n else:\n break # Hví break her??\n self.adultlice_f.update(self.temp, self.delta_time, deth_ratio, self.cleaner_death_ratio)\n while self.lice_m:\n if self.lice_m[0].get_stage() == 'Adult':\n self.adultlice_m.count += self.lice_m.pop(0).count\n else:\n break # Hví break her??\n self.adultlice_m.update(self.temp, self.delta_time, deth_ratio,self.cleaner_death_ratio)\n\n for mylice_f in self.lice_f:\n mylice_f.update(self.temp, self.delta_time, deth_ratio,self.cleaner_death_ratio)\n for mylice_m in self.lice_m:\n mylice_m.update(self.temp, self.delta_time, deth_ratio,self.cleaner_death_ratio)\n # Create a new Lice_agent\n temp_lice_female = Lice_agent_f(self.time, 0, 0,self.lice_mortality)\n temp_lice_male = Lice_agent_m(self.time, 0, 0, self.lice_mortality)\n mu_f = temp_lice_female.get_mu()\n mu_m = temp_lice_male.get_mu()\n self.update_weigh(self.prod_time)\n #print(attached)\n #print(self.time,self.name)\n smitta = (self.L_0 + attached)*self.surface_ratio\n #print(self.surface_ratio)\n #if self.name == 'Lopra':\n # print(smitta,self.name)\n\n temp_lice_female.count = smitta/mu_f * (1 - np.exp(-mu_f * self.delta_time))*0.5\n temp_lice_male.count = smitta / mu_m * (1 - np.exp(-mu_m * self.delta_time))*0.5\n self.lice_f.append(temp_lice_female)\n self.lice_m.append(temp_lice_male)\n #print([np.sum(self.get_fordeiling()[0:6]), np.sum(self.get_fordeiling()[6:])])\n #print(self.name,self.time)\n\n elif self.prod_time >= self.prod_len[self.prod_cyc]:\n #self.get_fordeiling = self.get_fordeiling()*0\n self.fish_count =0\n self.lice_f = []\n self.lice_m = []\n self.plankton = Planktonic_agent(0, self.delta_time)\n self.adultlice_f = Lice_agent_f(self.time, 0, 1000,self.lice_mortality)\n self.adultlice_m = Lice_agent_m(self.time, 0, 1000, self.lice_mortality)\n self.prod_time = -self.fallow[self.prod_cyc]\n self.prod_cyc += 1\n self.cleaner_fish =0\n\n\n else:\n self.prod_time += self.delta_time\n\n\n #print(self.SliceON)\n if self.NumTreat<=self.num_treat_tjek:\n if self.time > self.treatment[self.NumTreat]: # and self.treatment[self.NumTreat]>0:\n #print(self.treatment_type[self.NumTreat])\n if self.treatment_type[self.NumTreat] == 'FoodTreatment:':\n self.NumTreat_slice = self.NumTreat\n self.avlusing('Slice',self.NumTreat_slice, 1, self.temp)\n self.SliceON = 40\n else:\n self.avlusing('TreatmentY', self.NumTreat, 1, self.temp)\n\n self.NumTreat += 1\n\n elif np.isnan(self.treatment[self.NumTreat]):\n self.NumTreat += 1\n if self.SliceON >= 0:\n self.avlusing('Slice', self.NumTreat_slice, 1, self.temp)\n\n #print(self.SliceON,self.NumTreat)\n self.SliceON += -self.delta_time\n\n if self.fish_count!=0:\n #print(self.name,self.get_fordeiling(calculate=True)[4],self.time)\n #print(np.sum([self.get_fordeiling(calculate=True)[4], self.get_fordeiling(calculate=True)[5]]))\n # dayofyear\n relevant_treatment = self.diff_treatment[1][self.diff_treatment[0]==dayofyear]\n if np.sum([self.get_fordeiling(calculate=True)[4:6]]) / self.fish_count > relevant_treatment: # OOurt ther sum sigur nær tað er hvat í løbi av árinum\n self.avlusing('TreatmentX', 1, 1, self.temp)\n self.num_of_treatments += 1\n\n if self.prod_time<0:\n #print(self.time, 'Fasle',self.get_fordeiling())\n self.get_fordeiling(fallow=1)\n else:\n #print(self.time,'True',self.get_fordeiling())\n self.get_fordeiling(calculate=True)\n\n def avlusing(self, slag, NumTreat, consentration, temp):\n '''\n Hvat sker tá ið tað verður avlúsa\n :params:\n slag Hvat fyri slag av avlúsing er talan um\n consentration Hvussu ógvuslig er avlúsingin\n temp Hvat er havtempraturin\n -------------------\n slag = 'X' er ein viðgerð sum drepur 95% av øllum føstum lúsum\n '''\n\n if slag == 'TreatmentY':\n for mylice_f in self.lice_f:\n mylice_f.TreatmentY(self.treat_eff[:, NumTreat])\n for mylice_m in self.lice_m:\n mylice_m.TreatmentY(self.treat_eff[:, NumTreat])\n self.adultlice_f.TreatmentY(self.treat_eff[:, NumTreat])\n self.adultlice_m.TreatmentY(self.treat_eff[:, NumTreat])\n # ==========================================\n elif slag == \"TreatmentX\":\n for mylice_f in self.lice_f:\n mylice_f.TreatmentX()\n for mylice_m in self.lice_m:\n mylice_m.TreatmentX()\n self.adultlice_f.TreatmentX()\n self.adultlice_m.TreatmentX()\n\n elif slag == \"Slice\":\n treat_eff = 1-(1-self.treat_eff[:, NumTreat])*self.delta_time #1-(1-0.95)*1\n for mylice_f in self.lice_f:\n mylice_f.Slice(treat_eff)\n for mylice_m in self.lice_m:\n mylice_m.Slice(treat_eff)\n self.adultlice_f.Slice(treat_eff)\n self.adultlice_m.Slice(treat_eff)\n else:\n raise NotImplementedError\n\n def get_fordeiling(self, calculate=False,fallow = 0):\n '''\n Gevur ein lista av teimum forskelligu stages\n :params:\n calculate skal man brúka tíð sístu frodeilingina ella skal hettar roknast\n '''\n #print(calculate,'calcutale',self.time)\n if calculate:\n Ch1_f, Ch2_f, Pa1_f, Pa2_f, Adult_f,Adult_gravid_f, Ch1_m, Ch2_m, Pa1_m, Pa2_m, Adult_m = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n # Chalimus 1, Chalimus 2, Pre-Adult 1, Pre-Adult 2, Adult\n for lus in self.lice_f:\n my_nr = lus.get_stage()\n if my_nr == 'Ch1':\n Ch1_f += lus.count\n if my_nr == 'Ch2':\n Ch2_f += lus.count\n if my_nr == 'Pa1':\n Pa1_f += lus.count\n if my_nr == 'Pa2':\n Pa2_f += lus.count\n if my_nr == 'Adult':\n Adult_f += lus.count\n if my_nr == 'Adult_gravid':\n Adult_gravid_f += lus.count\n Adult_gravid_f += self.adultlice_f.count\n\n for lus in self.lice_m:\n my_nr = lus.get_stage()\n if my_nr == 'Ch1':\n Ch1_m += lus.count\n if my_nr == 'Ch2':\n Ch2_m += lus.count\n if my_nr == 'Pa1':\n Pa1_m += lus.count\n if my_nr == 'Pa2':\n Pa2_m += lus.count\n if my_nr == 'Adult':\n Adult_m += lus.count\n\n Adult_m += self.adultlice_m.count\n\n self.__fordeiling__ = [Ch1_f, Ch2_f, Pa1_f, Pa2_f, Adult_f,Adult_gravid_f,Ch1_m, Ch2_m, Pa1_m, Pa2_m, Adult_m]\n elif fallow == 1:\n Ch1_f, Ch2_f, Pa1_f, Pa2_f, Adult_f,Adult_gravid_f, Ch1_m, Ch2_m, Pa1_m, Pa2_m, Adult_m = np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan\n self.__fordeiling__ = [Ch1_f, Ch2_f, Pa1_f, Pa2_f, Adult_f,Adult_gravid_f,Ch1_m, Ch2_m, Pa1_m, Pa2_m, Adult_m]\n return self.__fordeiling__\n\n #def __repr__(self):\n # return self.smitta # 'farmin %s sum hevur %s fiskar' % (self.name, self.fish_count)\n\n def update_weigh(self,prod_time):\n self.W = self.W0*(1-np.exp(-self.K*prod_time))**3 #(1-np.exp(-self.K*(t)))**3 #0.0028 * self.W ** (2 / 3) * (1 - (self.W / 6) ** (1 / 3))\n return self.W\n\n\n def cleaner_F_update(self,time):\n idx = np.where(np.logical_and(self.wrasse_data[0] > time - 0.001, self.wrasse_data[0] < time + 0.001))\n if len(idx[0])>0:\n return np.sum(self.wrasse_data[1][idx[0][:]])\n else:\n return 0"
] |
[
[
"numpy.array",
"scipy.interpolate.interp1d",
"numpy.isnan",
"numpy.sum",
"numpy.exp",
"numpy.logical_and",
"matplotlib.dates.num2date",
"numpy.arange",
"numpy.alen",
"numpy.sqrt"
]
] |
jwokaty/curatedMetagenomicAnalyses
|
[
"61b81db0db81eecc001ceadb35600f2870124b6a"
] |
[
"python_tools/aggregate_taxa_profile.py"
] |
[
"#!/usr/bin/env python\n\n\nimport pandas as pd\nimport numpy as np\nimport argparse as ap\nimport sys, os\n\n\ndef read_params():\n p = ap.ArgumentParser()\n add = p.add_argument\n add(\"metaphlan_profile\", type=str, help=\\\n \"This must be a metaphlan-species table to aggregate. \"\n \"It can have the metadata above, but MUST HAVE SAMPLES in COLUMNS.\")\n add(\"-l\", \"--level\", type=str, default=\"g\", choices=\\\n [\"s\", \"g\", \"f\", \"o\", \"c\", \"p\", \"k\", \"S\", \"G\", \"F\", \"O\", \"C\", \"P\", \"K\"], \\\n help=\"The level to which you want to aggregate. Default is g. \"\n \"Other levels are, in order: k, c, p, o, f\")\n add(\"-o\", \"--outfile\", type=str, default=\"\", help=\\\n \"If not specified, it uses the name of the input and attacches the name of the level\")\n return p.parse_args()\n\n\ndef aggregate_table(table_name, level):\n\n aggregation_levels_dic = {\"s__\": 6, \"g__\": 5, \"f__\": 4, \"o__\": 3, \"c__\": 2, \"p__\": 1, \"k__\": 0}\n table = pd.read_csv(table_name, sep=\"\\t\", header=0, index_col=0, low_memory=False, engine=\"c\").fillna(\"NA\")\n N = table.shape[1]\n\n species = [j for j in table.index.tolist() if (\"s__\" in j)]\n aggregated_table = table.copy().drop(species)\n\n desired_level = list( set( [ \"|\".join( i.split(\"|\")[:(aggregation_levels_dic[ level ] + 1)] ) for i in species ] ) )\n desired_level_ab = dict( [ ( taxon, np.zeros(N) ) for taxon in desired_level ] )\n\n for taxon in species:\n if len( taxon.split( \"|\" ) ) > ( aggregation_levels_dic[ level ] +1 ):\n desired_level_ab[ \"|\".join( taxon.split( \"|\" )[ :(aggregation_levels_dic[ level ] + 1) ] ) ] += table.loc[ taxon ].values.astype( float )\n\n for aggregated_taxon in desired_level_ab:\n aggregated_table.loc[ aggregated_taxon ] = desired_level_ab[ aggregated_taxon ]\n\n return aggregated_table\n\n \ndef main():\n args = read_params()\n args.level = args.level.lower()\n\n if args.level == \"s\":\n raise(\"The level required (species) is the standard level of the table, \"\n \"and therefore can't be aggregated\")\n\n if not args.outfile:\n args.outfile = args.metaphlan_profile.split(\".\")[0] + args.level + \"_level.tsv\"\n\n aggregated_table = aggregate_table(args.metaphlan_profile, args.level + \"__\")\n aggregated_table.to_csv(args.outfile, sep=\"\\t\", header=True, index=True)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.read_csv",
"numpy.zeros"
]
] |
ajpina/pyleecan
|
[
"f8d1fce7d108cf443f5767e35d59ff15905fb49f",
"f8d1fce7d108cf443f5767e35d59ff15905fb49f",
"f8d1fce7d108cf443f5767e35d59ff15905fb49f"
] |
[
"pyleecan/Methods/Geometry/Arc3/rotate.py",
"Tests/Methods/Slot/test_SlotM14_meth.py",
"pyleecan/Methods/Slot/SlotW23/_comp_point_coordinate.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom numpy import exp\n\n\ndef rotate(self, angle):\n \"\"\"Rotation of the Arc3 of angle\n\n Parameters\n ----------\n self : Arc3\n An Arc3 Object\n\n angle : float\n the angle of rotation [rad]\n\n\n Returns\n -------\n None\n \"\"\"\n if not isinstance(angle, float) and not isinstance(angle, int):\n raise AngleRotationArc3Error(\"The angle must be a float or int \")\n\n # check if Arc3 is correct\"\n self.check()\n\n # Modification from the rotation of the object\n self.begin = self.begin * exp(1j * angle)\n self.end = self.end * exp(1j * angle)\n\n\nclass AngleRotationArc3Error(Exception):\n \"\"\" \"\"\"\n\n pass\n",
"# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom pyleecan.Classes.LamSlotMag import LamSlotMag\nfrom pyleecan.Classes.SlotM14 import SlotM14\nfrom numpy import pi, exp, sqrt, angle\nfrom pyleecan.Methods.Slot.Slot.comp_height import comp_height\nfrom pyleecan.Methods.Slot.Slot.comp_surface import comp_surface\nfrom pyleecan.Methods.Slot.Slot.comp_angle_opening import comp_angle_opening\nfrom pyleecan.Methods.Slot.Slot.comp_height_active import comp_height_active\nfrom pyleecan.Methods.Slot.Slot.comp_surface_active import comp_surface_active\nfrom pyleecan.Methods import ParentMissingError\n\nMag14_test = list()\n# Internal Slot inset\nlam = LamSlotMag(Rint=40e-3, Rext=90e-3, is_internal=True)\nlam.slot = SlotM14(Zs=4, W0=0.628, H0=0.02, Hmag=0.02, Wmag=0.628, Rtopm=0.04)\nMag14_test.append(\n {\n \"test_obj\": lam,\n \"Rmec\": 90e-3,\n \"S_exp\": 0.0010048,\n \"SA_exp\": 9.022e-4,\n \"Ao\": 0.628,\n \"H_exp\": 0.02,\n \"HA_exp\": 0.02,\n }\n)\n\n# Internal slot surface\nlam = LamSlotMag(Rint=40e-3, Rext=90e-3, is_internal=True)\nlam.slot = SlotM14(Zs=8, W0=0.628, H0=0, Hmag=0.02, Wmag=0.628, Rtopm=0.05)\nMag14_test.append(\n {\n \"test_obj\": lam,\n \"Rmec\": 0.11,\n \"S_exp\": 0,\n \"SA_exp\": 1.1089e-3,\n \"Ao\": 0.628,\n \"H_exp\": 0,\n \"HA_exp\": 0.02,\n }\n)\n\n# For AlmostEqual\nDELTA = 1e-4\n\n\n@pytest.mark.METHODS\nclass Test_Magnet_Type_14_meth(object):\n \"\"\"unittest for MagnetType14 methods\"\"\"\n\n @pytest.mark.parametrize(\"test_dict\", Mag14_test)\n def test_comp_surface(self, test_dict):\n \"\"\"Check that the computation of the surface is correct\"\"\"\n test_obj = test_dict[\"test_obj\"]\n result = test_obj.slot.comp_surface()\n\n a = result\n b = test_dict[\"S_exp\"]\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n assert a == pytest.approx(b, rel=DELTA), msg\n\n # Check that the analytical method returns the same result as the numerical one\n b = comp_surface(test_obj.slot)\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n assert a == pytest.approx(b, rel=DELTA), msg\n\n @pytest.mark.parametrize(\"test_dict\", Mag14_test)\n def test_comp_surface_active(self, test_dict):\n \"\"\"Check that the computation of the active surface is correct\"\"\"\n test_obj = test_dict[\"test_obj\"]\n result = test_obj.slot.comp_surface_active()\n\n a = result\n b = test_dict[\"SA_exp\"]\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n assert a == pytest.approx(b, rel=DELTA), msg\n\n # Check that the analytical method returns the same result as the numerical one\n b = comp_surface_active(test_obj.slot, Ndisc=1000)\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n assert a == pytest.approx(b, rel=DELTA), msg\n\n @pytest.mark.parametrize(\"test_dict\", Mag14_test)\n def test_comp_height(self, test_dict):\n \"\"\"Check that the computation of the height is correct\"\"\"\n test_obj = test_dict[\"test_obj\"]\n result = test_obj.slot.comp_height()\n\n a = result\n b = test_dict[\"H_exp\"]\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n assert a == pytest.approx(b, rel=DELTA), msg\n\n # Check that the analytical method returns the same result as the numerical one\n b = comp_height(test_obj.slot)\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n assert a == pytest.approx(b, rel=DELTA), msg\n\n @pytest.mark.parametrize(\"test_dict\", Mag14_test)\n def test_comp_height_active(self, test_dict):\n \"\"\"Check that the computation of the active height is correct\"\"\"\n test_obj = test_dict[\"test_obj\"]\n result = test_obj.slot.comp_height_active()\n\n a = result\n b = test_dict[\"HA_exp\"]\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n # assert a == pytest.approx(b, rel=DELTA), msg\n\n # Check that the analytical method returns the same result as the numerical one\n b = comp_height_active(test_obj.slot)\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n assert a == pytest.approx(b, rel=DELTA), msg\n\n @pytest.mark.parametrize(\"test_dict\", Mag14_test)\n def test_comp_angle_opening(self, test_dict):\n \"\"\"Check that the computation of the average opening angle is correct\"\"\"\n test_obj = test_dict[\"test_obj\"]\n a = test_obj.slot.comp_angle_opening()\n assert a == pytest.approx(test_dict[\"Ao\"], rel=DELTA)\n # Check that the analytical method returns the same result as the numerical one\n b = comp_angle_opening(test_obj.slot)\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n assert a == pytest.approx(b, rel=DELTA)\n\n @pytest.mark.parametrize(\"test_dict\", Mag14_test)\n def test_comp_width_opening(self, test_dict):\n \"\"\"Check that the computation of the average opening width is correct\"\"\"\n test_obj = test_dict[\"test_obj\"]\n a = test_obj.slot.comp_width_opening()\n point_dict = test_obj.slot._comp_point_coordinate()\n assert a == pytest.approx(abs(point_dict[\"Z1\"] - point_dict[\"Z4\"]), rel=DELTA)\n\n @pytest.mark.parametrize(\"test_dict\", Mag14_test)\n def test_comp_mec_radius(self, test_dict):\n \"\"\"Check that the computation of the mechanical radius is correct\"\"\"\n test_obj = test_dict[\"test_obj\"]\n a = test_obj.comp_radius_mec()\n assert a == pytest.approx(test_dict[\"Rmec\"], rel=DELTA)\n\n @pytest.mark.parametrize(\"test_dict\", Mag14_test)\n def test_comp_point_coordinate(self, test_dict):\n \"\"\"Check that the point coordinates are correct\"\"\"\n test_obj = test_dict[\"test_obj\"]\n point_dict = test_obj.slot._comp_point_coordinate()\n Z1 = point_dict[\"Z1\"]\n Z2 = point_dict[\"Z2\"]\n Z3 = point_dict[\"Z3\"]\n Z4 = point_dict[\"Z4\"]\n ZM0 = point_dict[\"ZM0\"]\n ZM1 = point_dict[\"ZM1\"]\n ZM2 = point_dict[\"ZM2\"]\n ZM3 = point_dict[\"ZM3\"]\n ZM4 = point_dict[\"ZM4\"]\n W0 = test_obj.slot.W0\n H0 = test_obj.slot.H0\n Wmag = test_obj.slot.Wmag\n Hmag = test_obj.slot.Hmag\n Rbo = test_obj.get_Rbo()\n\n assert abs(Z1) == pytest.approx(Rbo, rel=DELTA)\n assert angle(Z1) == pytest.approx(-W0 / 2, rel=DELTA)\n assert abs(Z4) == pytest.approx(Rbo, rel=DELTA)\n assert angle(Z4) == pytest.approx(W0 / 2, rel=DELTA)\n if test_obj.is_internal:\n assert abs(Z2) == pytest.approx(Rbo - H0, rel=DELTA)\n assert abs(Z3) == pytest.approx(Rbo - H0, rel=DELTA)\n else:\n assert abs(Z3) == pytest.approx(Rbo + H0, rel=DELTA)\n assert abs(Z2) == pytest.approx(Rbo + H0, rel=DELTA)\n assert angle(Z2) == pytest.approx(-W0 / 2, rel=DELTA)\n assert angle(Z3) == pytest.approx(W0 / 2, rel=DELTA)\n\n assert angle(ZM1) == pytest.approx(angle(ZM2), rel=DELTA)\n assert angle(ZM1) == pytest.approx(-Wmag / 2, rel=DELTA)\n assert angle(ZM3) == pytest.approx(angle(ZM4), rel=DELTA)\n assert angle(ZM3) == pytest.approx(Wmag / 2, rel=DELTA)\n\n if test_obj.is_internal:\n assert ZM0 == pytest.approx(Rbo + Hmag - H0, rel=DELTA)\n else:\n assert ZM0 == pytest.approx(Rbo - Hmag + H0, rel=DELTA)\n",
"from numpy import arcsin, exp, sqrt\n\n\ndef _comp_point_coordinate(self):\n \"\"\"Compute the point coordinates needed to plot the Slot.\n\n Parameters\n ----------\n self : SlotW23\n A SlotW23 object\n\n Returns\n -------\n point_list: list\n A list of Points\n\n \"\"\"\n Rbo = self.get_Rbo()\n if self.is_cstt_tooth:\n # Compute W1 and W2 to match W3 tooth constraint\n self._comp_W()\n\n # alpha is the angle to rotate Z0 so ||Z1,Z8|| = W0\n alpha = float(arcsin(self.W0 / (2 * Rbo)))\n\n # comp point coordinate (in complex)\n Z0 = Rbo * exp(1j * 0)\n Z1 = Z0 * exp(1j * alpha)\n\n if self.is_outwards():\n Z2 = (Rbo + self.H0) * exp(1j * alpha)\n Z3 = Z2.real + self.H1 + 1j * self.W1 / 2\n\n H2 = sqrt(self.H2 ** 2 - ((self.W2 - self.W1) / 2.0) ** 2)\n Z4 = Z3.real + H2 + 1j * self.W2 / 2\n else: # inward slot\n Z2 = (Rbo - self.H0) * exp(1j * alpha)\n Z3 = Z2.real - self.H1 + 1j * self.W1 / 2\n\n H2 = sqrt(self.H2 ** 2 - ((self.W2 - self.W1) / 2.0) ** 2)\n Z4 = Z3.real - H2 + 1j * self.W2 / 2\n\n # symetry\n Z5 = Z4.conjugate()\n Z6 = Z3.conjugate()\n Z7 = Z2.conjugate()\n Z8 = Z1.conjugate()\n return [Z8, Z7, Z6, Z5, Z4, Z3, Z2, Z1]\n"
] |
[
[
"numpy.exp"
],
[
"numpy.angle"
],
[
"numpy.arcsin",
"numpy.exp",
"numpy.sqrt"
]
] |
GeneralLi95/PyTorch-CIFAR10
|
[
"ee9bf4144ea2a15afd855d3f0f6d320296225519"
] |
[
"main.py"
] |
[
"#!usr/bin/env python \n# -*- coding:utf-8 _*-\n\"\"\" \n@author:yaoli \n@file: main.py.py \n@time: 2019/12/03 \n\"\"\"\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\n\nimport os\nimport argparse\n\nfrom models import *\nfrom utils import get_progress_bar, update_progress_bar\n\n# 0. 从 shell 指定参数\nparser = argparse.ArgumentParser(description='PyTorch CIFAR10')\nparser.add_argument('--lr', default=0.001, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', default=False, action='store_true', help='resume from checkpoint')\nargs = parser.parse_args()\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" # 指定使用的 GPU 编号,0 是 name,不是 number\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n# 1. 载入并标准化 CIFAR10 数据\n# 1. Load and normalizing the CIFAR10 training and test datasets using torchvision\n# data augmentation 数据增强\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))\n])\n\ntransforms_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))\n])\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform_train)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transforms_test)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)\n\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n# 2. 定义卷积神经网络\n# 2. Define a Convolution Neural Network\n\n# net, model_name = LeNet(), 'LeNet'\n# net, model_name = VGG('VGG11'), 'VGG11'\n# net, model_name = VGG('VGG113'), 'VGG13'\n# net, model_name = VGG('VGG16'), 'VGG16'\n# net, model_name = ResNet18(), 'ResNet18'\n# net, model_name = ResNet34(), 'ResNet34'\n# net, model_name = ResNet50(), 'ResNet50'\n# net, model_name = ResNet101(), 'ResNet101'\nnet, model_name = ResNet152(), 'ResNet152'\n\nprint(model_name + ' is ready!')\n\n# 是否使用 GPU\nnet = net.to(device)\nif device == 'cuda':\n net = torch.nn.DataParallel(net)\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs\")\n cudnn.benchmark = True\n\n# 从断点继续训练或者重新训练\nstart_epoch = 0\nbest_acc = 0\n\nif args.resume == True:\n print('==> Resuming from checkpoint..')\n assert os.path.isdir('checkpoint/' + model_name), 'Error : no checkpoint directory found!'\n checkpoint = torch.load('./checkpoint/' + model_name + '/ckpt.pth')\n net.load_state_dict(checkpoint['net'])\n best_acc = checkpoint['acc']\n start_epoch = checkpoint['epoch'] + 1\n\n# 3. 定义损失函数和优化器\n# 3. Define a loss function\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)\n\n\n# 4. 训练神经网络\n# 4. Train the network on the training data\n\ndef train(epoch):\n running_loss = 0.0\n net.train() # 这条代码似乎也不需要...\n correct = 0\n total = 0\n progress_bar_obj = get_progress_bar(len(trainloader))\n print('Epoch', epoch, 'Train')\n for i, data in enumerate(trainloader, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data\n\n inputs, labels = inputs.to(device), labels.to(device) # 在使用cpu的时候这条行代码自动忽略\n\n # 清零梯度缓存 zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # 打印统计数据 print statistics 在 batch_size 不为 4 的情况下打印不出计数,改用 kuangliu 的 progress_bar\n # running_loss += loss.item()\n # if i % 2000 == 1999:\n # print('[%d, %5d] loss: %.3f' %\n # (epoch + 1, i + 1, running_loss / 2000))\n # running_loss = 0.0\n\n running_loss += loss.item()\n _, predicted = outputs.max(1)\n total += labels.size(0)\n correct += predicted.eq(labels).sum().item()\n update_progress_bar(progress_bar_obj, index=i, loss=(running_loss / (i + 1)), acc=100. * (correct / total),\n c=correct, t=total)\n\n\n# 5. 测试网络\n# 5. Test the network on the test data\n\ndef test(epoch):\n global best_acc\n net.eval() # 这条语句似乎也不需要..\n # dataiter = iter(testloader)\n # images, labels = dataiter.next()\n # outputs = net(images)\n\n # class_correct = list(0. for i in range(10))\n # class_total = list(0. for i in range(10))\n correct = 0\n total = 0\n test_loss = 0\n # progress_bar_obj = get_progress_bar(len(testloader))\n with torch.no_grad():\n for i, data in enumerate(testloader):\n images, labels = data\n images, labels = images.to(device), labels.to(device)\n outputs = net(images)\n loss = criterion(outputs, labels)\n\n test_loss += loss.item()\n\n _, predicted = torch.max(outputs, 1)\n total += labels.size(0)\n correct += predicted.eq(labels).sum().item()\n\n # update_progress_bar(progress_bar_obj, index=i, loss=(test_loss / (i + 1)), acc=100. * (correct / total),\n # c=correct, t=total)\n # c = (predicted == labels).squeeze()\n # for i in range(4):\n # label = labels[i]\n # class_correct[label] += c[i].item()\n # class_total[label] += 1\n\n # for i in range(10):\n # correct += class_correct[i]\n # total += class_total[i]\n\n # 输出每类识别准确率\n # print(\"Accuracy of %5s : %2d %%\" % (\n # classes[i], 100 * class_correct[i] / class_total[i]))\n acc = 100 * correct / total\n # 输出总准确率\n print()\n print(\"Accuracy of whole dataset: %.2f %%\" % acc)\n\n # save checkpoint\n\n if acc > best_acc:\n state = {\n 'net': net.state_dict(),\n 'acc': acc,\n 'epoch': epoch,\n }\n if not os.path.isdir('checkpoint/' + model_name):\n os.mkdir('checkpoint/' + model_name)\n torch.save(state, './checkpoint/' + model_name + '/ckpt.pth')\n best_acc = acc\n print('Acc > best_acc, Saving net, acc')\n\n\nfor epoch in range(start_epoch, start_epoch + 200):\n train(epoch)\n test(epoch)\n"
] |
[
[
"torch.max",
"torch.no_grad",
"torch.save",
"torch.cuda.device_count",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"torch.load",
"torch.nn.CrossEntropyLoss",
"torch.nn.DataParallel"
]
] |
hengfei-wang/srf
|
[
"0f5d5e24638edb856b39f2c87a77c23c701ba211"
] |
[
"data/load_xgaze.py"
] |
[
"import os\nimport torch\nimport numpy as np\nimport imageio\nimport cv2\nimport pickle as pkl\nimport random\n\n\ndef image_projection_wo_dist_mat(XX, c2w, ref_pose_idx):\n XXc = np.matmul(XX, c2w[:3, :3]) - np.matmul(c2w[:3, 3], c2w[:3, :3])\n pts = XXc[:, :2] / XXc[:, 2][:, np.newaxis]\n\n pts = pts * fc[ref_pose_idx] + cc\n return pts\n\ndef multi_world2cam_grid_sample_mat(XX, c2w, ref_pose_idx):\n pts = image_projection_wo_dist_mat(XX, c2w, ref_pose_idx)\n pts = np.array(pts) / np.array([nx//2, ny//2]) - 1\n return pts\n\ndef image_projection_wo_dist_mat_torch(XX, c2w, ref_pose_idx, device):\n XXc = torch.matmul(XX, c2w[:3,:3]) - torch.matmul(c2w[:3,3], c2w[:3,:3])\n pts = XXc[:,:2] / XXc[:,2].unsqueeze(-1)\n # print(f'pts.shape:{pts.shape}, \\nfc[ref_pose_idx].shape:{fc[ref_pose_idx].shape}')\n pts = pts * torch.Tensor(fc[ref_pose_idx]).to(device) + torch.Tensor(cc).to(device)\n return pts\n\ndef multi_world2cam_grid_sample_mat_torch(XX, c2w, ref_pose_idx, device):\n pts = image_projection_wo_dist_mat_torch(XX, c2w, ref_pose_idx, device)\n pts = pts / torch.tensor([nx//2, ny//2]).to(device) - 1\n return pts\n\n# def image_projection_wo_dist(XX, pose, ref_pose_idx):\n# Rc, _ = cv2.Rodrigues(np.array(pose_extrinsics['omc_{}'.format(int(pose))]))\n# Tc = np.array(pose_extrinsics['Tc_{}'.format(int(pose))])\n\n# XXc = np.matmul(XX, Rc.T) + Tc\n# pts = XXc[:, :2] / XXc[:, 2][:, np.newaxis]\n\n# pts = pts * fc[ref_pose_idx] + cc\n# # print(Rc,Tc, fc, cc)\n# return pts\n\n# def multi_world2cam_grid_sample(XX, pose):\n# pts = image_projection_wo_dist(XX, pose)\n# pts = np.array(pts) / np.array([nx//2, ny//2]) - 1\n# return pts\n\ndef img_string(scan, pose):\n return f\"{scan}/cam{str(pose).zfill(2)}.JPG\"\n\ndef load_scan_data(scan, mode, num_views, cfg, specific_poses = None, fixed = True, shuffle = False):\n \n if mode == 'train':\n poses_idx = random.sample(cam_idx,num_views)\n elif specific_poses is None:\n if fixed:\n poses_idx = cam_idx[cfg.fixed_batch * num_views:(cfg.fixed_batch + 1) * num_views]\n else:\n poses_idx = random.sample(cam_idx, num_views)\n else:\n if not len(specific_poses) == num_views:\n raise ValueError('Poses are invalid.')\n poses_idx = cam_idx[specific_poses]\n\n if shuffle:\n random.shuffle(poses_idx)\n\n imgs = []\n poses = []\n for pose in poses_idx:\n # always use max lightning images - these have the minimal amount of pose dependent shadows\n img_name = img_string(scan, pose)\n fname = os.path.join(basedir, img_name)\n img = imageio.imread(fname)\n\n if cfg.half_res:\n img_half_res = np.zeros(( ny, nx, 3))\n img_half_res[:] = cv2.resize(img, (nx, ny), interpolation=cv2.INTER_AREA)\n img = img_half_res\n imgs.append(img)\n poses.append(pose_extrinsics[f'c2w_{int(pose)}'])\n\n imgs = (np.array(imgs) / 255.).astype(np.float32)\n poses = np.array(poses).astype(np.float32)\n\n return imgs, poses, poses_idx\n\ndef setup_xgaze(mode, cfg):\n load_parameters()\n\n global basedir, split, val_samples, images, light_cond\n basedir = cfg.datadir\n split = pkl.load(open( basedir + f'/{cfg.split}', 'rb'))\n\n\n global ny, nx, fc, cc\n if cfg.half_res:\n nx = nx//cfg.res_rate\n ny = ny//cfg.res_rate\n fc = fc/cfg.res_rate\n cc = cc/cfg.res_rate\n\n\n return split[mode], ny, nx, fc, cc, 'x_down_y_down_z_cam_dir'\n\n\n\ndef load_parameters():\n global cam_idx \n cam_idx = [i for i in range(0, 18)]\n global pose_extrinsics\n pose_extrinsics = { # Image #1:\n # Image #1:\n 'omc_0': [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],\n 'Tc_0': [0.0, 0.0, 0.0],\n\n # Image #2:\n 'omc_1': [[0.9698392735891082, -0.008270901325641296, -0.24360495806820662], [0.007482661394246074, 0.9999633476147745, -0.0041609140237082965], [0.24363044387475521, 0.0022126044190360875, 0.9698656150204907]],\n 'Tc_1': [221.40055372232777, -1.5731657904339034, 31.980068426505735],\n\n # Image #3:\n 'omc_2': [[0.7863902773688491, 0.02457490982746557, -0.6172409622398017], [-0.01106061557973079, 0.9996083334853352, 0.025706855304923826], [0.6176309532744791, -0.013388556070122345, 0.786354088260254]],\n 'Tc_2': [582.9710529629532, -22.844393775038416, 320.43184257787124],\n\n # Image #4:\n 'omc_3': [[0.7755602021276123, -0.03949806218966534, -0.6300367258811493], [0.17518091275469772, 0.9723082350232455, 0.1546878919386135], [0.606480024965545, -0.23034018144744633, 0.7610028778713976]],\n 'Tc_3': [561.9597220800626, -157.58447391158398, 369.5534503923164],\n\n # Image #5:\n 'omc_4': [[0.9825999161441723, 0.05390649250122117, -0.17773996416023452], [0.03129924419440496, 0.8952123742582904, 0.44453926968007423], [0.18307856812397422, -0.44236737565178846, 0.8779483714049618]],\n 'Tc_4': [177.6096275688536, -481.94275227326216, 283.5903282160665],\n\n # Image #6:\n 'omc_5': [[0.9989049242833686, -0.04326729607798294, 0.017801498041956118], [0.030673361090901165, 0.8929380913269138, 0.4491332875403863], [-0.03532841861483183, -0.4480954208062701, 0.8932874099026734]],\n 'Tc_5': [-10.013619556629912, -456.9689085248577, 265.38605835611116],\n\n # Image #7:\n 'omc_6': [[0.9019530772769576, 0.04517994128615104, 0.4294641071102524], [-0.13693851015385017, 0.9731083451128499, 0.18522416988226556], [-0.40954668943536865, -0.2258736850036109, 0.8838849402469867]],\n 'Tc_6': [-420.0358569418966, -171.7923788742382, 259.90954288588944],\n\n # Image #8:\n 'omc_7': [[0.9034549188351174, -0.015574653729707198, 0.42840009313004496], [0.011507558592957517, 0.9998607911297412, 0.012081988935503852], [-0.42852862883109816, -0.0059856931601699696, 0.9035083761368963]],\n 'Tc_7': [-414.70095212370296, 0.18529135395040885, 218.40313014420755],\n\n # Image #9:\n 'omc_8': [[0.9996565637870843, -0.011139348111773325, 0.023720653469998926], [0.02060862864318743, 0.8932867427089053, -0.4490145651601528], [-0.016187615724566565, 0.4493492074368872, 0.8932095223815043]],\n 'Tc_8': [-30.07439012373554, 459.89480260041273, 186.44674124248863],\n\n # Image #10:\n 'omc_9': [[0.9703608190091254, -0.05040214282229401, -0.23634615488909538], [-0.06367119597705116, 0.8901291606580766, -0.45123835846368376], [0.23312198466637835, 0.4529124654335196, 0.860537296646775]],\n 'Tc_9': [208.8877234017151, 441.51126355535337, 212.89337892226843],\n\n # Image #11:\n 'omc_10': [[0.7742489492229995, -0.0696664581102551, -0.629035093807534], [-0.2921085346500205, 0.8423840347001444, -0.45283743448054686], [0.5614367004495688, 0.5343554273109593, 0.6318647867159739]],\n 'Tc_10': [569.501849456624, 424.81382471370455, 421.42088877272647],\n\n # Image #12:\n 'omc_11': [[0.34157472148589485, -0.06295367652472443, -0.9377438585529919], [0.0658221510385165, 0.9969066022527823, -0.04294963116809793], [0.9375468810008895, -0.04705380958895134, 0.3446618414165842]],\n 'Tc_11': [844.3138574366806, 48.2674946199551, 756.4920827467118],\n\n # Image #13:\n 'omc_12': [[0.6250756419679933, -0.19226107344902638, -0.7565157773996052], [0.6293823011911042, 0.697403106290454, 0.3427926870337463], [0.46169076313663804, -0.6904089997766931, 0.5569354112117983]],\n 'Tc_12': [716.041279620078, -338.4725933497391, 849.1304313456653],\n\n # Image #14:\n 'omc_13': [[0.9983192122010462, 0.032440152283014556, -0.04802485887680596], [0.009636848253201056, 0.7242050571299102, 0.6895173430619479], [0.057147893277242325, -0.6888212190019396, 0.7226752012810835]],\n 'Tc_13': [53.42483923140793, -646.4838434270105, 539.1087085714361],\n\n # Image #15:\n 'omc_14': [[0.7809554621739873, 0.03288192944746085, 0.6237205662926517], [-0.441918154346149, 0.7347861487591912, 0.5145849399768019], [-0.4413806871170363, -0.6775013611111402, 0.5883663779760406]],\n 'Tc_14': [-579.1991528272825, -507.0731519086221, 828.6182606673376],\n\n # Image #16:\n 'omc_15': [[0.5576138145013221, 0.07101464249734504, 0.8270572860620111], [-0.05277587298219646, 0.9973511165258926, -0.05005454620234178], [-0.8284211133887476, -0.015737563837188336, 0.5598846202354716]],\n 'Tc_15': [-780.0477351457396, 52.50352781272512, 560.8080186215651],\n\n # Image #17:\n 'omc_16': [[0.8938667769839744, -0.043001897441954345, 0.4462656404213452], [0.278059686163717, 0.8339942499010018, -0.4765882940889343], [-0.35168877709534163, 0.5500949263067757, 0.7574368462893301]],\n 'Tc_16': [-436.9051119350867, 452.7480705123046, 304.1090086518881],\n\n # Image #18:\n 'omc_17': [[0.9971800904395784, 0.006545799442714842, -0.07475974679310951], [-0.054460308495951223, 0.7485142988847291, -0.6608785207310253], [0.051632761202940886, 0.6630863419455706, 0.7467600425141947]],\n 'Tc_17': [109.78472957158333, 616.3677403386008, 349.0875152926945],\n\n }\n for i in range(0, 18):\n pose = i\n w2c = np.array(pose_extrinsics['omc_{}'.format(pose)])\n c2w = w2c.T\n translation = np.array([pose_extrinsics['Tc_{}'.format(pose)]])\n c2w = np.hstack((c2w, np.matmul(c2w, - translation.T)))\n c2w = np.vstack((c2w, [0, 0, 0, 1]))\n pose_extrinsics[f'c2w_{pose}'] = c2w\n\n # Focal length:\n global fc\n fc = np.array([[13200.70131101025, 13192.49643871068],\n [13303.297441332066, 13289.773010770674],\n [13202.447504723803, 13197.8614274423],\n [13073.634346792553, 13071.096087185497],\n [13868.253087403722, 13856.275256250801],\n [13955.654490144081, 13942.033759177113],\n [14025.849893138095, 14010.600985919233],\n [13220.644426377807, 13217.09834057157],\n [13960.810303292888, 13936.87005052997],\n [13976.934945971894, 13931.733326108262],\n [13371.652735350852, 13361.160302847506],\n [13532.388711357731, 13519.037208138094],\n [14008.281277510245, 13981.885542885882],\n [13552.813628151382, 13549.661562953488],\n [14164.237353620741, 14163.287660930266],\n [13310.748461063455, 13322.183084755576],\n [12802.929140491959, 12806.864869977968],\n [14048.261040714882, 14049.871888688402]])\n\n # Principal point:\n global cc\n cc = np.array([2000, 2000])\n\n # Image size:\n global nx, ny\n nx = 4000\n ny = 4000\n\ndef load_cam_path():\n global camera_path\n poses = [1,3,5,7,1]\n camera_path = []\n\n for i, pose in enumerate(poses[:-1]):\n frames = 14\n for interpol in np.linspace(0,1,frames)[:frames - 1]:\n pose = (1-interpol) * pose_extrinsics[f'c2w_{poses[i]}'] + interpol * pose_extrinsics[f'c2w_{poses[i+1]}']\n camera_path.append(pose)\n return camera_path\n\n\ndef load_pose(pose):\n return pose_extrinsics[f'c2w_{pose}']"
] |
[
[
"numpy.array",
"numpy.matmul",
"numpy.zeros",
"torch.Tensor",
"torch.tensor",
"numpy.linspace",
"torch.matmul",
"numpy.vstack"
]
] |
Adhmir/mcdm
|
[
"c1d8bec4f3628f5d95ee7cd3bfdfb9ff54783dce"
] |
[
"algoritmo_dp2_1.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 25 14:17:29 2021\r\n\r\n@author: Adhmir Renan Voltolini Gomes\r\n\r\nAlgoritmo para cálculo do DP2\r\n\r\n\"\"\"\r\n\"\"\"\r\nA distância DP2 é um indicador sintético elaborado por Trapero (1977) que tem\r\npor finalidade a comparação interespacial e/ou intertemporal de variáveis. Há\r\nduas vantagens inerentes ao método: o primeiro é a atribuição de pontuação a\r\ncada elemento envolvido na análise, formando um ranking dos elementos\r\nenvolvidos frente o que a realidade permite, ou seja, o método trabalha com\r\npontos de referência hierarquicamente construídos. A segunda vantagem é a\r\npossibilidade da mensuração de disparidades entre os envolvidos\r\n\r\n\r\nEm linhas gerais pode-se formular o algoritmo para o cálculo do DP2 como segue:\r\n \r\n1º Estabelecimento da matriz de valores das componentes das m empresas envolvidas. \r\n2º Verificar os critérios das n variáveis envolvidas quanto a sua conduta, \r\n ou seja, classificar as variáveis quanto a seu objetivo: “quanto maior, melhor” \r\n ou “quanto menor, melhor”;\r\n3º Eleição da base de referência em cada variável, determinando seu ideal teórico;\r\n\r\n\r\nTodavia, esses passos não serão abordados aqui. Embora seja possível direcionar o segundo passo,\r\nneste algoritmo espera-se que o conjunto de dados já tenha sido construído.\r\n\r\nProblemas de la medición del bienestar y conceptos afines: una aplicación al caso español. Madrid: Presidencia del Gobierno, Instituto Nacional de Estadística,\r\n\r\n\"\"\"\r\n## Leitura do conjunto de dados========================================================================\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\n#df = pd.read_excel('C:/PHD/Disciplinas/06 - Analise Decisoria/Artigo fama multicriterio/Python DP2/df_dp2.xlsx')\r\n\r\n\r\n### Remover a coluna das empresas para manter apenas os vetores numéricos\r\n\r\n#df = df.drop([\"Empresa\"], axis =1)\r\n#df = pd.read_excel('C:/PHD/Disciplinas/06 - Analise Decisoria/Adriana_df.xlsx') \r\n## 4º Calcular as distâncias de Frechet ===============================================================\r\n\r\n## (|xij-maximo|)/std, exemplo: (|1,5-1,2|)/0.383406\r\n\r\ndef frechet(df):\r\n x = df.copy()\r\n for i in range(len(x.columns)):\r\n df_refer = x.copy()\r\n for j in range(len(x)):\r\n xij = x.iloc[j,i:i+1].values\r\n maximo = df_refer[df_refer.columns[i:i+1]].max()\r\n std = df_refer[df_refer.columns[i:i+1]].std() \r\n valor = (np.abs(xij - maximo))/std\r\n x.iloc[j,i:i+1] = valor\r\n \r\n return x\r\n\r\n\r\n\r\n## 5º Ordenação das componentes de maior para menor à hierarquização do modelo=========================\r\n\r\n\r\n# ordenar e criar uma lista com todos os modelos\r\ndef ordemfrechet(x):\r\n ordem_frechet = x[x.columns].sum().sort_values(ascending=False).rename(\"Distancia\")\r\n ordem_frechet = pd.DataFrame(ordem_frechet).reset_index()\r\n\r\n return ordem_frechet\r\n \r\n\r\ndef modelos(x):\r\n ordem_frechet = ordemfrechet(x)\r\n \r\n modelos = []\r\n for i in range(len(x.columns)):\r\n \r\n ordem_modelos = ordem_frechet.loc[0:i,['index']].values\r\n \r\n if i > 0:\r\n modelos.append(ordem_modelos)\r\n \r\n return modelos\r\n \r\n\r\n## 6º Obtenção do R2 segundo a hierarquia definida em (5º);\r\n#========================================================================================================\r\n\r\ndef rquadrado(x):\r\n df_frechet = frechet(x)\r\n lista_modelos = modelos(df_frechet)\r\n v1_r2 = [1.000]\r\n constante = np.ones((len(x),1))\r\n for i in range(len(x.columns)-1):\r\n #Listas com os nomes dos modelos\r\n dependente = pd.Series(np.reshape(lista_modelos[i][-1],-1)) \r\n independentes = pd.Series(np.reshape(lista_modelos[i][0:len(lista_modelos[i])-1], -1)) \r\n Vetores_y = x[dependente]\r\n \r\n Vetores_X_const = pd.DataFrame(constante)\r\n Vetores_X = x[independentes]\r\n Vetores_X = pd.concat([Vetores_X_const, Vetores_X], ignore_index=True, axis =1)\r\n \r\n regression = np.dot(np.linalg.inv(np.dot(Vetores_X.T,Vetores_X)),np.dot(Vetores_X.T,Vetores_y))\r\n \r\n yhat = np.sum(regression.T * Vetores_X, axis=1)\r\n ybar = np.sum(Vetores_y)/len(Vetores_y) \r\n error_total = (yhat-ybar.values)**2\r\n soma_quadrado_total = np.sum(error_total)\r\n error_res = np.array(Vetores_y) - np.array(yhat).reshape(-1,1)\r\n soma_residuo_total = np.sum(error_res**2)\r\n r2_modelos = (1-(soma_residuo_total/(soma_residuo_total+soma_quadrado_total)))\r\n fator_1r = 1-r2_modelos\r\n v1_r2.append(fator_1r) \r\n \r\n return v1_r2\r\n\r\n## 7º Ponderação dos pesos de acordo com os R2 ======================================================\r\n\r\n'''\r\ndf = pd.read_excel('C:/Users/Usuario/Desktop/DP2 exemplo/DP2 exemplo.xlsx') \r\n\r\ndf_frechet = frechet(df)\r\nlista_modelos = modelos(df_frechet)\r\n\r\ndf_frechet = frechet(df)\r\nordem_de_frechet = ordemfrechet(df_frechet)\r\nordem_modelos = pd.Series(np.reshape(ordem_de_frechet.loc[:,['index']].values,-1))\r\nordem_modelos = ordem_modelos.to_list()\r\n\r\n\r\nVetores = df_frechet[ordem_modelos]\r\nVetores = Vetores.add_suffix('_frechet')\r\n\r\nlista_r2 = np.array(rquadrado(df_frechet)).reshape(1,-1)\r\n\r\nvalor_dp2 = np.sum(Vetores*lista_r2, axis=1)\r\n\r\ndp2 = pd.concat([df, Vetores, valor_dp2 ], axis=1)\r\n \r\nx1 = dp2.columns.to_list()\r\nx1[len(x1)-1] = \"DP2\"\r\n\r\ndp2.columns = x1\r\n\r\ndp2['Ranking'] = dp2['DP2'].rank(ascending=False)\r\n'''\r\n\r\ndef calculo_DP2(x):\r\n \r\n df_frechet = frechet(x)\r\n ordem_de_frechet = ordemfrechet(df_frechet)\r\n ordem_modelos = pd.Series(np.reshape(ordem_de_frechet.loc[:,['index']].values,-1))\r\n ordem_modelos = ordem_modelos.to_list()\r\n \r\n Vetores = df_frechet[ordem_modelos]\r\n Vetores = Vetores.add_suffix('_frechet')\r\n \r\n lista_1_r2 = np.array(rquadrado(df_frechet)).reshape(1,-1)\r\n \r\n valor_dp2 = np.sum(Vetores*lista_1_r2, axis=1)\r\n \r\n dp2 = pd.concat([x.copy(), Vetores, valor_dp2 ], axis=1)\r\n \r\n \r\n x1 = dp2.columns.to_list() \r\n x1[len(x1)-1] = \"DP2\"\r\n dp2.columns = x1\r\n \r\n dp2['Ranking'] = dp2['DP2'].rank(method='min', ascending=False)\r\n \r\n #dp2['Empresas'] = df[\"Empresa\"]\r\n #dp2 = dp2.sort_values(by=['Ranking'])\r\n \r\n return dp2\r\n\r\n##df = pd.read_excel('C:/Users/Usuario/Desktop/DP2 exemplo/Dp2_df.xlsx') \r\n\r\n##df = pd.read_excel('C:/Users/Usuario/Desktop/DP2 exemplo/DP2 exemplo.xlsx')\r\n\r\n\r\n#x = calculo_DP2(df.copy())\r\n\r\n\r\n\r\n"
] |
[
[
"numpy.array",
"numpy.dot",
"numpy.reshape",
"numpy.sum",
"pandas.DataFrame",
"numpy.abs",
"pandas.concat"
]
] |
no-name-xiaosheng/PaddleViT
|
[
"c90a6c8dc3787e69cef3a37b9a260bd59eeff1f7",
"c90a6c8dc3787e69cef3a37b9a260bd59eeff1f7",
"c90a6c8dc3787e69cef3a37b9a260bd59eeff1f7",
"c90a6c8dc3787e69cef3a37b9a260bd59eeff1f7"
] |
[
"image_classification/VOLO/tests/test_fold.py",
"image_classification/ConvMixer/main_multi_gpu.py",
"image_classification/DeiT/tests/test_mixup.py",
"image_classification/Shuffle_Transformer/port_weights/load_pytorch_weights_base.py"
] |
[
"import unittest\nimport numpy as np\nimport paddle\nimport paddle.nn as nn\nfrom fold import fold\n\n\nclass FoldTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n paddle.set_device('cpu')\n \n @classmethod\n def tearDown(cls):\n pass\n\n #@unittest.skip('skip for debug')\n def test_fold_1(self):\n \"\"\"test padding=2, stride=2\"\"\"\n arr = [\n [1, 1, 1, 1, 2, 2, 2, 2],\n [1, 1, 1, 1, 2, 2, 2, 2],\n [1, 1, 1, 1, 2, 2, 2, 2],\n [1, 1, 1, 1, 2, 2, 2, 2],\n [3, 3, 3, 3, 4, 4, 4, 4],\n [3, 3, 3, 3, 4, 4, 4, 4],\n [3, 3, 3, 3, 4, 4, 4, 4],\n [3, 3, 3, 3, 4, 4, 4, 4],\n ]\n arr = np.array(arr)\n tmp = paddle.to_tensor(arr, dtype='float32')\n tmp = tmp.reshape([1, 1, 8, 8])\n \n unfold = paddle.nn.Unfold(3, 2, 2)\n out = unfold(tmp)\n out = fold(out, output_size=(8, 8), kernel_size=3, padding=2, stride=2)\n ans = [[[[4. , 2. , 4. , 2. , 8. , 4. , 8. , 4. ],\n [2. , 1. , 2. , 1. , 4. , 2. , 4. , 2. ],\n [4. , 2. , 4. , 2. , 8. , 4. , 8. , 4. ],\n [2. , 1. , 2. , 1. , 4. , 2. , 4. , 2. ],\n [12., 6. , 12., 6. , 16., 8. , 16., 8. ],\n [6. , 3. , 6. , 3. , 8. , 4. , 8. , 4. ],\n [12., 6. , 12., 6. , 16., 8. , 16., 8. ],\n [6. , 3. , 6. , 3. , 8. , 4. , 8. , 4. ]]]]\n self.assertTrue(np.allclose(np.array(ans), out.numpy()))\n\n def test_fold_2(self):\n \"\"\"test padding=1, stride=1\"\"\"\n arr = [\n [1, 1, 1, 1, 2, 2, 2, 2],\n [1, 1, 1, 1, 2, 2, 2, 2],\n [1, 1, 1, 1, 2, 2, 2, 2],\n [1, 1, 1, 1, 2, 2, 2, 2],\n [3, 3, 3, 3, 4, 4, 4, 4],\n [3, 3, 3, 3, 4, 4, 4, 4],\n [3, 3, 3, 3, 4, 4, 4, 4],\n [3, 3, 3, 3, 4, 4, 4, 4],\n ]\n arr = np.array(arr)\n tmp = paddle.to_tensor(arr, dtype='float32')\n tmp = tmp.reshape([1, 1, 8, 8])\n \n unfold = paddle.nn.Unfold(3, 1, 1)\n out = unfold(tmp)\n out = fold(out, output_size=(8, 8), kernel_size=3, padding=1, stride=1)\n ans = [[[[4. , 6. , 6. , 6. , 12., 12., 12., 8. ],\n [6. , 9. , 9. , 9. , 18., 18., 18., 12.],\n [6. , 9. , 9. , 9. , 18., 18., 18., 12.],\n [6. , 9. , 9. , 9. , 18., 18., 18., 12.],\n [18., 27., 27., 27., 36., 36., 36., 24.],\n [18., 27., 27., 27., 36., 36., 36., 24.],\n [18., 27., 27., 27., 36., 36., 36., 24.],\n [12., 18., 18., 18., 24., 24., 24., 16.]]]]\n\n self.assertTrue(np.allclose(np.array(ans), out.numpy()))\n",
"# Copyright (c) 2021 PPViT Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"ConvMixer training/validation using multiple GPU \"\"\"\n\nimport sys\nimport os\nimport time\nimport logging\nimport argparse\nimport random\nimport numpy as np\nimport paddle\nimport paddle.nn as nn\nimport paddle.nn.functional as F\nimport paddle.distributed as dist\nfrom datasets import get_dataloader\nfrom datasets import get_dataset\nfrom utils import AverageMeter\nfrom utils import WarmupCosineScheduler\nfrom utils import get_exclude_from_weight_decay_fn\nfrom config import get_config\nfrom config import update_config\nfrom mixup import Mixup\nfrom losses import LabelSmoothingCrossEntropyLoss\nfrom losses import SoftTargetCrossEntropyLoss\nfrom losses import DistillationLoss\nfrom convmixer import build_convmixer as build_model\n\n\ndef get_arguments():\n \"\"\"return argumeents, this will overwrite the config after loading yaml file\"\"\"\n parser = argparse.ArgumentParser('ConvMixer')\n parser.add_argument('-cfg', type=str, default=None)\n parser.add_argument('-dataset', type=str, default=None)\n parser.add_argument('-batch_size', type=int, default=None)\n parser.add_argument('-image_size', type=int, default=None)\n parser.add_argument('-data_path', type=str, default=None)\n parser.add_argument('-ngpus', type=int, default=None)\n parser.add_argument('-pretrained', type=str, default=None)\n parser.add_argument('-resume', type=str, default=None)\n parser.add_argument('-last_epoch', type=int, default=None)\n parser.add_argument('-eval', action='store_true')\n parser.add_argument('-amp', action='store_true')\n arguments = parser.parse_args()\n return arguments\n\n\ndef get_logger(filename, logger_name=None):\n \"\"\"set logging file and format\n Args:\n filename: str, full path of the logger file to write\n logger_name: str, the logger name, e.g., 'master_logger', 'local_logger'\n Return:\n logger: python logger\n \"\"\"\n log_format = \"%(asctime)s %(message)s\"\n logging.basicConfig(stream=sys.stdout, level=logging.INFO,\n format=log_format, datefmt=\"%m%d %I:%M:%S %p\")\n # different name is needed when creating multiple logger in one process\n logger = logging.getLogger(logger_name)\n fh = logging.FileHandler(os.path.join(filename))\n fh.setFormatter(logging.Formatter(log_format))\n logger.addHandler(fh)\n return logger\n\n\ndef train(dataloader,\n model,\n criterion,\n optimizer,\n epoch,\n total_epochs,\n total_batch,\n debug_steps=100,\n accum_iter=1,\n mixup_fn=None,\n amp=False,\n local_logger=None,\n master_logger=None):\n \"\"\"Training for one epoch\n Args:\n dataloader: paddle.io.DataLoader, dataloader instance\n model: nn.Layer, a ViT model\n criterion: nn.criterion\n epoch: int, current epoch\n total_epochs: int, total num of epochs\n total_batch: int, total num of batches for one epoch\n debug_steps: int, num of iters to log info, default: 100\n accum_iter: int, num of iters for accumulating gradients, default: 1\n mixup_fn: Mixup, mixup instance, default: None\n amp: bool, if True, use mix precision training, default: False\n local_logger: logger for local process/gpu, default: None\n master_logger: logger for main process, default: None\n Returns:\n train_loss_meter.avg: float, average loss on current process/gpu\n train_acc_meter.avg: float, average top1 accuracy on current process/gpu\n master_train_loss_meter.avg: float, average loss on all processes/gpus\n master_train_acc_meter.avg: float, average top1 accuracy on all processes/gpus\n train_time: float, training time\n \"\"\"\n model.train()\n train_loss_meter = AverageMeter()\n train_acc_meter = AverageMeter()\n master_train_loss_meter = AverageMeter()\n master_train_acc_meter = AverageMeter()\n\n if amp is True:\n scaler = paddle.amp.GradScaler(init_loss_scaling=1024)\n time_st = time.time()\n\n for batch_id, data in enumerate(dataloader):\n image = data[0]\n label = data[1]\n label_orig = label.clone()\n\n if mixup_fn is not None:\n image, label = mixup_fn(image, label_orig)\n \n if amp is True: # mixed precision training\n with paddle.amp.auto_cast():\n output = model(image)\n loss = criterion(output, label)\n scaled = scaler.scale(loss)\n scaled.backward()\n if ((batch_id +1) % accum_iter == 0) or (batch_id + 1 == len(dataloader)):\n scaler.minimize(optimizer, scaled)\n optimizer.clear_grad()\n else: # full precision training\n output = model(image)\n loss = criterion(output, label)\n #NOTE: division may be needed depending on the loss function\n # Here no division is needed:\n # default 'reduction' param in nn.CrossEntropyLoss is set to 'mean'\n #loss = loss / accum_iter\n loss.backward()\n\n if ((batch_id +1) % accum_iter == 0) or (batch_id + 1 == len(dataloader)):\n optimizer.step()\n optimizer.clear_grad()\n\n pred = F.softmax(output)\n if mixup_fn:\n acc = paddle.metric.accuracy(pred, label_orig)\n else:\n acc = paddle.metric.accuracy(pred, label_orig.unsqueeze(1))\n\n batch_size = paddle.to_tensor(image.shape[0])\n\n # sync from other gpus for overall loss and acc\n master_loss = loss.clone()\n master_acc = acc.clone()\n master_batch_size = batch_size.clone()\n dist.all_reduce(master_loss)\n dist.all_reduce(master_acc)\n dist.all_reduce(master_batch_size)\n master_loss = master_loss / dist.get_world_size()\n master_acc = master_acc / dist.get_world_size()\n master_train_loss_meter.update(master_loss.numpy()[0], master_batch_size.numpy()[0])\n master_train_acc_meter.update(master_acc.numpy()[0], master_batch_size.numpy()[0])\n\n train_loss_meter.update(loss.numpy()[0], batch_size.numpy()[0])\n train_acc_meter.update(acc.numpy()[0], batch_size.numpy()[0])\n\n if batch_id % debug_steps == 0:\n if local_logger:\n local_logger.info(\n f\"Epoch[{epoch:03d}/{total_epochs:03d}], \" +\n f\"Step[{batch_id:04d}/{total_batch:04d}], \" +\n f\"Avg Loss: {train_loss_meter.avg:.4f}, \" +\n f\"Avg Acc: {train_acc_meter.avg:.4f}\")\n if master_logger and dist.get_rank() == 0:\n master_logger.info(\n f\"Epoch[{epoch:03d}/{total_epochs:03d}], \" +\n f\"Step[{batch_id:04d}/{total_batch:04d}], \" +\n f\"Avg Loss: {master_train_loss_meter.avg:.4f}, \" +\n f\"Avg Acc: {master_train_acc_meter.avg:.4f}\")\n\n train_time = time.time() - time_st\n return (train_loss_meter.avg,\n train_acc_meter.avg,\n master_train_loss_meter.avg,\n master_train_acc_meter.avg,\n train_time)\n\n\ndef validate(dataloader,\n model,\n criterion,\n total_batch,\n debug_steps=100,\n local_logger=None,\n master_logger=None):\n \"\"\"Validation for whole dataset\n Args:\n dataloader: paddle.io.DataLoader, dataloader instance\n model: nn.Layer, a ViT model\n criterion: nn.criterion\n total_epoch: int, total num of epoch, for logging\n debug_steps: int, num of iters to log info, default: 100\n local_logger: logger for local process/gpu, default: None\n master_logger: logger for main process, default: None\n Returns:\n val_loss_meter.avg: float, average loss on current process/gpu\n val_acc1_meter.avg: float, average top1 accuracy on current process/gpu\n val_acc5_meter.avg: float, average top5 accuracy on current process/gpu\n master_val_loss_meter.avg: float, average loss on all processes/gpus\n master_val_acc1_meter.avg: float, average top1 accuracy on all processes/gpus\n master_val_acc5_meter.avg: float, average top5 accuracy on all processes/gpus\n val_time: float, validation time\n \"\"\"\n model.eval()\n val_loss_meter = AverageMeter()\n val_acc1_meter = AverageMeter()\n val_acc5_meter = AverageMeter()\n master_val_loss_meter = AverageMeter()\n master_val_acc1_meter = AverageMeter()\n master_val_acc5_meter = AverageMeter()\n time_st = time.time()\n\n with paddle.no_grad():\n for batch_id, data in enumerate(dataloader):\n image = data[0]\n label = data[1]\n\n output = model(image)\n loss = criterion(output, label)\n\n pred = F.softmax(output)\n acc1 = paddle.metric.accuracy(pred, label.unsqueeze(1))\n acc5 = paddle.metric.accuracy(pred, label.unsqueeze(1), k=5)\n\n batch_size = paddle.to_tensor(image.shape[0])\n\n master_loss = loss.clone()\n master_acc1 = acc1.clone()\n master_acc5 = acc5.clone()\n master_batch_size = batch_size.clone()\n\n dist.all_reduce(master_loss)\n dist.all_reduce(master_acc1)\n dist.all_reduce(master_acc5)\n dist.all_reduce(master_batch_size)\n master_loss = master_loss / dist.get_world_size()\n master_acc1 = master_acc1 / dist.get_world_size()\n master_acc5 = master_acc5 / dist.get_world_size()\n\n master_val_loss_meter.update(master_loss.numpy()[0], master_batch_size.numpy()[0])\n master_val_acc1_meter.update(master_acc1.numpy()[0], master_batch_size.numpy()[0])\n master_val_acc5_meter.update(master_acc5.numpy()[0], master_batch_size.numpy()[0])\n\n val_loss_meter.update(loss.numpy()[0], batch_size.numpy()[0])\n val_acc1_meter.update(acc1.numpy()[0], batch_size.numpy()[0])\n val_acc5_meter.update(acc5.numpy()[0], batch_size.numpy()[0])\n\n if batch_id % debug_steps == 0:\n if local_logger:\n local_logger.info(\n f\"Val Step[{batch_id:04d}/{total_batch:04d}], \" +\n f\"Avg Loss: {val_loss_meter.avg:.4f}, \" +\n f\"Avg Acc@1: {val_acc1_meter.avg:.4f}, \" +\n f\"Avg Acc@5: {val_acc5_meter.avg:.4f}\")\n if master_logger and dist.get_rank() == 0:\n master_logger.info(\n f\"Val Step[{batch_id:04d}/{total_batch:04d}], \" +\n f\"Avg Loss: {master_val_loss_meter.avg:.4f}, \" +\n f\"Avg Acc@1: {master_val_acc1_meter.avg:.4f}, \" +\n f\"Avg Acc@5: {master_val_acc5_meter.avg:.4f}\")\n val_time = time.time() - time_st\n return (val_loss_meter.avg,\n val_acc1_meter.avg,\n val_acc5_meter.avg,\n master_val_loss_meter.avg,\n master_val_acc1_meter.avg,\n master_val_acc5_meter.avg,\n val_time)\n\n\ndef main_worker(*args):\n # STEP 0: Preparation\n config = args[0]\n dist.init_parallel_env()\n last_epoch = config.TRAIN.LAST_EPOCH\n world_size = dist.get_world_size()\n local_rank = dist.get_rank()\n seed = config.SEED + local_rank\n paddle.seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n # logger for each process/gpu\n local_logger = get_logger(\n filename=os.path.join(config.SAVE, 'log_{}.txt'.format(local_rank)),\n logger_name='local_logger')\n # overall logger\n if local_rank == 0:\n master_logger = get_logger(\n filename=os.path.join(config.SAVE, 'log.txt'),\n logger_name='master_logger')\n master_logger.info(f'\\n{config}')\n else:\n master_logger = None\n local_logger.info(f'----- world_size = {world_size}, local_rank = {local_rank}')\n if local_rank == 0:\n master_logger.info(f'----- world_size = {world_size}, local_rank = {local_rank}')\n \n # STEP 1: Create model\n model = build_model(config)\n model = paddle.DataParallel(model)\n\n # STEP 2: Create train and val dataloader\n dataset_train, dataset_val = args[1], args[2]\n dataloader_train = get_dataloader(config, dataset_train, 'train', True)\n dataloader_val = get_dataloader(config, dataset_val, 'test', True)\n total_batch_train = len(dataloader_train)\n total_batch_val = len(dataloader_val)\n local_logger.info(f'----- Total # of train batch (single gpu): {total_batch_train}')\n local_logger.info(f'----- Total # of val batch (single gpu): {total_batch_val}')\n if local_rank == 0:\n master_logger.info(f'----- Total # of train batch (single gpu): {total_batch_train}')\n master_logger.info(f'----- Total # of val batch (single gpu): {total_batch_val}')\n\n # STEP 3: Define Mixup function\n mixup_fn = None\n if config.TRAIN.MIXUP_PROB > 0 or config.TRAIN.CUTMIX_ALPHA > 0 or config.TRAIN.CUTMIX_MINMAX is not None:\n mixup_fn = Mixup(mixup_alpha=config.TRAIN.MIXUP_ALPHA,\n cutmix_alpha=config.TRAIN.CUTMIX_ALPHA,\n cutmix_minmax=config.TRAIN.CUTMIX_MINMAX,\n prob=config.TRAIN.MIXUP_PROB,\n switch_prob=config.TRAIN.MIXUP_SWITCH_PROB,\n mode=config.TRAIN.MIXUP_MODE,\n label_smoothing=config.TRAIN.SMOOTHING,\n num_classes=config.MODEL.NUM_CLASSES)\n\n # STEP 4: Define criterion\n if config.TRAIN.MIXUP_PROB > 0.:\n criterion = SoftTargetCrossEntropyLoss()\n elif config.TRAIN.SMOOTHING:\n criterion = LabelSmoothingCrossEntropyLoss()\n else:\n criterion = nn.CrossEntropyLoss()\n # only use cross entropy for val\n criterion_val = nn.CrossEntropyLoss()\n\n # STEP 5: Define optimizer and lr_scheduler\n # set lr according to batch size and world size (hacked from Swin official code and modified for CSwin)\n if config.TRAIN.LINEAR_SCALED_LR is not None:\n linear_scaled_lr = (\n config.TRAIN.BASE_LR * config.DATA.BATCH_SIZE) / config.TRAIN.LINEAR_SCALED_LR\n linear_scaled_warmup_start_lr = (\n config.TRAIN.WARMUP_START_LR * config.DATA.BATCH_SIZE) / config.TRAIN.LINEAR_SCALED_LR\n linear_scaled_end_lr = (\n config.TRAIN.END_LR * config.DATA.BATCH_SIZE) / config.TRAIN.LINEAR_SCALED_LR\n \n if config.TRAIN.ACCUM_ITER > 1:\n linear_scaled_lr = linear_scaled_lr * config.TRAIN.ACCUM_ITER\n linear_scaled_warmup_start_lr = linear_scaled_warmup_start_lr * config.TRAIN.ACCUM_ITER\n linear_scaled_end_lr = linear_scaled_end_lr * config.TRAIN.ACCUM_ITER\n \n config.TRAIN.BASE_LR = linear_scaled_lr\n config.TRAIN.WARMUP_START_LR = linear_scaled_warmup_start_lr\n config.TRAIN.END_LR = linear_scaled_end_lr\n\n scheduler = None\n if config.TRAIN.LR_SCHEDULER.NAME == \"warmupcosine\":\n scheduler = WarmupCosineScheduler(learning_rate=config.TRAIN.BASE_LR,\n warmup_start_lr=config.TRAIN.WARMUP_START_LR,\n start_lr=config.TRAIN.BASE_LR,\n end_lr=config.TRAIN.END_LR,\n warmup_epochs=config.TRAIN.WARMUP_EPOCHS,\n total_epochs=config.TRAIN.NUM_EPOCHS,\n last_epoch=config.TRAIN.LAST_EPOCH,\n )\n elif config.TRAIN.LR_SCHEDULER.NAME == \"cosine\":\n scheduler = paddle.optimizer.lr.CosineAnnealingDecay(learning_rate=config.TRAIN.BASE_LR,\n T_max=config.TRAIN.NUM_EPOCHS,\n last_epoch=last_epoch)\n elif config.scheduler == \"multi-step\":\n milestones = [int(v.strip()) for v in config.TRAIN.LR_SCHEDULER.MILESTONES.split(\",\")]\n scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=config.TRAIN.BASE_LR,\n milestones=milestones,\n gamma=config.TRAIN.LR_SCHEDULER.DECAY_RATE,\n last_epoch=last_epoch)\n else:\n local_logger.fatal(f\"Unsupported Scheduler: {config.TRAIN.LR_SCHEDULER}.\")\n if local_rank == 0:\n master_logger.fatal(f\"Unsupported Scheduler: {config.TRAIN.LR_SCHEDULER}.\")\n raise NotImplementedError(f\"Unsupported Scheduler: {config.TRAIN.LR_SCHEDULER}.\")\n\n if config.TRAIN.OPTIMIZER.NAME == \"SGD\":\n if config.TRAIN.GRAD_CLIP:\n clip = paddle.nn.ClipGradByGlobalNorm(config.TRAIN.GRAD_CLIP)\n else:\n clip = None\n optimizer = paddle.optimizer.Momentum(\n parameters=model.parameters(),\n learning_rate=scheduler if scheduler is not None else config.TRAIN.BASE_LR,\n weight_decay=config.TRAIN.WEIGHT_DECAY,\n momentum=config.TRAIN.OPTIMIZER.MOMENTUM,\n grad_clip=clip)\n elif config.TRAIN.OPTIMIZER.NAME == \"AdamW\":\n if config.TRAIN.GRAD_CLIP:\n clip = paddle.nn.ClipGradByGlobalNorm(config.TRAIN.GRAD_CLIP)\n else:\n clip = None\n optimizer = paddle.optimizer.AdamW(\n parameters=model.parameters(),\n learning_rate=scheduler if scheduler is not None else config.TRAIN.BASE_LR,\n beta1=config.TRAIN.OPTIMIZER.BETAS[0],\n beta2=config.TRAIN.OPTIMIZER.BETAS[1],\n weight_decay=config.TRAIN.WEIGHT_DECAY,\n epsilon=config.TRAIN.OPTIMIZER.EPS,\n grad_clip=clip,\n apply_decay_param_fun=get_exclude_from_weight_decay_fn([\n 'absolute_pos_embed', 'relative_position_bias_table']),\n )\n else:\n local_logger.fatal(f\"Unsupported Optimizer: {config.TRAIN.OPTIMIZER.NAME}.\")\n if local_rank == 0:\n master_logger.fatal(f\"Unsupported Optimizer: {config.TRAIN.OPTIMIZER.NAME}.\")\n raise NotImplementedError(f\"Unsupported Optimizer: {config.TRAIN.OPTIMIZER.NAME}.\")\n\n # STEP 6: Load pretrained model / load resumt model and optimizer states\n if config.MODEL.PRETRAINED:\n if (config.MODEL.PRETRAINED).endswith('.pdparams'):\n raise ValueError(f'{config.MODEL.PRETRAINED} should not contain .pdparams')\n assert os.path.isfile(config.MODEL.PRETRAINED + '.pdparams') is True\n model_state = paddle.load(config.MODEL.PRETRAINED+'.pdparams')\n model.set_dict(model_state)\n local_logger.info(f\"----- Pretrained: Load model state from {config.MODEL.PRETRAINED}\")\n if local_rank == 0:\n master_logger.info(\n f\"----- Pretrained: Load model state from {config.MODEL.PRETRAINED}\")\n\n if config.MODEL.RESUME:\n assert os.path.isfile(config.MODEL.RESUME + '.pdparams') is True\n assert os.path.isfile(config.MODEL.RESUME + '.pdopt') is True\n model_state = paddle.load(config.MODEL.RESUME + '.pdparams')\n model.set_dict(model_state)\n opt_state = paddle.load(config.MODEL.RESUME+'.pdopt')\n optimizer.set_state_dict(opt_state)\n local_logger.info(\n f\"----- Resume Training: Load model and optmizer from {config.MODEL.RESUME}\")\n if local_rank == 0:\n master_logger.info(\n f\"----- Resume Training: Load model and optmizer from {config.MODEL.RESUME}\")\n \n # STEP 7: Validation (eval mode)\n if config.EVAL:\n local_logger.info('----- Start Validating')\n if local_rank == 0:\n master_logger.info('----- Start Validating')\n val_loss, val_acc1, val_acc5, avg_loss, avg_acc1, avg_acc5, val_time = validate(\n dataloader=dataloader_val,\n model=model,\n criterion=criterion_val,\n total_batch=total_batch_val,\n debug_steps=config.REPORT_FREQ,\n local_logger=local_logger,\n master_logger=master_logger)\n local_logger.info(f\"Validation Loss: {val_loss:.4f}, \" +\n f\"Validation Acc@1: {val_acc1:.4f}, \" +\n f\"Validation Acc@5: {val_acc5:.4f}, \" +\n f\"time: {val_time:.2f}\")\n if local_rank == 0:\n master_logger.info(f\"Validation Loss: {avg_loss:.4f}, \" +\n f\"Validation Acc@1: {avg_acc1:.4f}, \" +\n f\"Validation Acc@5: {avg_acc5:.4f}, \" +\n f\"time: {val_time:.2f}\")\n return\n\n # STEP 8: Start training and validation (train mode)\n local_logger.info(f\"Start training from epoch {last_epoch+1}.\")\n if local_rank == 0:\n master_logger.info(f\"Start training from epoch {last_epoch+1}.\")\n for epoch in range(last_epoch+1, config.TRAIN.NUM_EPOCHS+1):\n # train\n local_logger.info(f\"Now training epoch {epoch}. LR={optimizer.get_lr():.6f}\")\n if local_rank == 0:\n master_logger.info(f\"Now training epoch {epoch}. LR={optimizer.get_lr():.6f}\")\n train_loss, train_acc, avg_loss, avg_acc, train_time = train(\n dataloader=dataloader_train,\n model=model,\n criterion=criterion,\n optimizer=optimizer,\n epoch=epoch,\n total_epochs=config.TRAIN.NUM_EPOCHS,\n total_batch=total_batch_train,\n debug_steps=config.REPORT_FREQ,\n accum_iter=config.TRAIN.ACCUM_ITER,\n mixup_fn=mixup_fn,\n amp=config.AMP,\n local_logger=local_logger,\n master_logger=master_logger)\n\n scheduler.step()\n\n local_logger.info(f\"----- Epoch[{epoch:03d}/{config.TRAIN.NUM_EPOCHS:03d}], \" +\n f\"Train Loss: {train_loss:.4f}, \" +\n f\"Train Acc: {train_acc:.4f}, \" +\n f\"time: {train_time:.2f}\")\n if local_rank == 0:\n master_logger.info(f\"----- Epoch[{epoch:03d}/{config.TRAIN.NUM_EPOCHS:03d}], \" +\n f\"Train Loss: {avg_loss:.4f}, \" +\n f\"Train Acc: {avg_acc:.4f}, \" +\n f\"time: {train_time:.2f}\")\n\n # validation\n if epoch % config.VALIDATE_FREQ == 0 or epoch == config.TRAIN.NUM_EPOCHS:\n local_logger.info(f'----- Validation after Epoch: {epoch}')\n if local_rank == 0:\n master_logger.info(f'----- Validation after Epoch: {epoch}')\n val_loss, val_acc1, val_acc5, avg_loss, avg_acc1, avg_acc5, val_time = validate(\n dataloader=dataloader_val,\n model=model,\n criterion=criterion_val,\n total_batch=total_batch_val,\n debug_steps=config.REPORT_FREQ,\n local_logger=local_logger,\n master_logger=master_logger)\n local_logger.info(f\"----- Epoch[{epoch:03d}/{config.TRAIN.NUM_EPOCHS:03d}], \" +\n f\"Validation Loss: {val_loss:.4f}, \" +\n f\"Validation Acc@1: {val_acc1:.4f}, \" +\n f\"Validation Acc@5: {val_acc5:.4f}, \" +\n f\"time: {val_time:.2f}\")\n if local_rank == 0:\n master_logger.info(f\"----- Epoch[{epoch:03d}/{config.TRAIN.NUM_EPOCHS:03d}], \" +\n f\"Validation Loss: {avg_loss:.4f}, \" +\n f\"Validation Acc@1: {avg_acc1:.4f}, \" +\n f\"Validation Acc@5: {avg_acc5:.4f}, \" +\n f\"time: {val_time:.2f}\")\n # model save\n if local_rank == 0:\n if epoch % config.SAVE_FREQ == 0 or epoch == config.TRAIN.NUM_EPOCHS:\n model_path = os.path.join(\n config.SAVE, f\"{config.MODEL.TYPE}-Epoch-{epoch}-Loss-{train_loss}\")\n paddle.save(model.state_dict(), model_path + '.pdparams')\n paddle.save(optimizer.state_dict(), model_path + '.pdopt')\n master_logger.info(f\"----- Save model: {model_path}.pdparams\")\n master_logger.info(f\"----- Save optim: {model_path}.pdopt\")\n\n\ndef main():\n # config is updated by: (1) config.py, (2) yaml file, (3) arguments\n arguments = get_arguments()\n config = get_config()\n config = update_config(config, arguments)\n\n # set output folder\n if not config.EVAL:\n config.SAVE = '{}/train-{}'.format(config.SAVE, time.strftime('%Y%m%d-%H-%M-%S'))\n else:\n config.SAVE = '{}/eval-{}'.format(config.SAVE, time.strftime('%Y%m%d-%H-%M-%S'))\n\n if not os.path.exists(config.SAVE):\n os.makedirs(config.SAVE, exist_ok=True)\n\n # get dataset and start DDP\n dataset_train = get_dataset(config, mode='train')\n dataset_val = get_dataset(config, mode='val')\n config.NGPUS = len(paddle.static.cuda_places()) if config.NGPUS == -1 else config.NGPUS\n dist.spawn(main_worker, args=(config, dataset_train, dataset_val, ), nprocs=config.NGPUS)\n\n\nif __name__ == \"__main__\":\n main()\n",
"# Copyright (c) 2021 PPViT Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nimport numpy as np\nimport paddle\nimport paddle.nn as nn\nfrom mixup import *\n\n\nclass MixupTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n paddle.set_device('cpu')\n\n @classmethod\n def tearDown(cls):\n pass\n\n #@unittest.skip('skip for debug')\n def test_rand_bbox(self):\n image_shape = [4, 3, 224, 224] \n lam = 0.2\n cut_rate = np.sqrt(1. - lam)\n for i in range(20):\n x1, y1, x2, y2 = rand_bbox(image_shape, lam)\n #print(x1, y1, x2, y2)\n h = x2 - x1\n w = y2 - y1\n self.assertTrue(0 <= x1 <= 224)\n self.assertTrue(0 <= y1 <= 224)\n self.assertTrue(0 <= x2 <= 224)\n self.assertTrue(0 <= y2 <= 224)\n self.assertTrue(h <= int(cut_rate * 224))\n self.assertTrue(w <= int(cut_rate * 224))\n\n def test_rand_bbox_minmax(self):\n image_shape = [4, 3, 224, 224] \n minmax = [0.1, 0.3]\n for i in range(20):\n x1, y1, x2, y2 = rand_bbox_minmax(image_shape, minmax)\n h = x2 - x1\n w = y2 - y1\n self.assertTrue(0 <= x1 <= 224)\n self.assertTrue(0 <= y1 <= 224)\n self.assertTrue(0 <= x2 <= 224)\n self.assertTrue(0 <= y2 <= 224)\n self.assertTrue(h >= int(minmax[0]* 224))\n self.assertTrue(w >= int(minmax[0]* 224))\n self.assertTrue(h <= int(minmax[1]* 224))\n self.assertTrue(w <= int(minmax[1]* 224))\n\n #@unittest.skip('skip for debug')\n def test_cutmix_generate_bbox_adjust_lam_lam(self):\n image_shape = [4, 3, 224, 224] \n orig_lam = 0.2\n cut_rate = np.sqrt(1. - orig_lam)\n minmax = None\n (x1, y1, x2, y2), lam = cutmix_generate_bbox_adjust_lam(image_shape, orig_lam, minmax)\n h = x2 - x1\n w = y2 - y1\n self.assertTrue(0 <= x1 <= 224)\n self.assertTrue(0 <= y1 <= 224)\n self.assertTrue(0 <= x2 <= 224)\n self.assertTrue(0 <= y2 <= 224)\n self.assertTrue(h <= cut_rate * 224)\n self.assertTrue(w <=cut_rate * 224)\n self.assertNotEqual(orig_lam, lam)\n\n #@unittest.skip('skip for debug')\n def test_cutmix_generate_bbox_adjust_lam_minmax(self):\n image_shape = [4, 3, 224, 224] \n orig_lam = 0.2\n minmax = [0.1, 0.3]\n (x1, y1, x2, y2), lam = cutmix_generate_bbox_adjust_lam(image_shape, orig_lam, minmax)\n h = x2 - x1\n w = y2 - y1\n self.assertTrue(0 <= x1 <= 224)\n self.assertTrue(0 <= y1 <= 224)\n self.assertTrue(0 <= x2 <= 224)\n self.assertTrue(0 <= y2 <= 224)\n self.assertTrue(h >= minmax[0]* 224 - 1)\n self.assertTrue(w >= minmax[0]* 224 - 1)\n self.assertTrue(h <= minmax[1]* 224 - 1)\n self.assertTrue(w <= minmax[1]* 224 - 1)\n self.assertNotEqual(orig_lam, lam)\n\n #@unittest.skip('skip for debug')\n def test_one_hot(self):\n num_classes = 10\n x = paddle.randint(0, num_classes, [4])\n x_smoothed = one_hot(x, num_classes, on_value=0.8, off_value=0.2)\n for i in range(4):\n self.assertEqual(x_smoothed[i, x[i]], 0.8)\n for j in range(num_classes):\n if j != x[i]:\n self.assertEqual(x_smoothed[i, j], 0.2)\n\n #@unittest.skip('skip for debug')\n def test_mixup_one_hot(self):\n num_classes = 10\n x = paddle.randint(0, num_classes, [4])\n x_mixup = mixup_one_hot(x, num_classes, lam=0.8, smoothing=0.2)\n off_value = 0.2 / 10\n on_value = 1. - 0.2 + off_value\n for i in range(4):\n if x[i] != x[-(i+1)]:\n self.assertAlmostEqual(x_mixup[i, x[i]].numpy()[0], on_value*0.8 + off_value * 0.2, places=4)\n else:\n self.assertAlmostEqual(x_mixup[i, x[i]].numpy()[0], on_value*0.8 + on_value * 0.2, places=4)\n\n #@unittest.skip('skip for debug')\n def test_mixup(self):\n x = paddle.randn([4, 3, 224, 224])\n label = paddle.randint(0, 10, [4])\n mixup_fn = Mixup(num_classes=10, cutmix_alpha=1.0) \n x_new, label_new = mixup_fn(x, label)\n self.assertEqual(x_new.shape, x.shape)\n self.assertEqual(label_new.shape, [4, 10])\n\n mixup_fn = Mixup(num_classes=10, cutmix_alpha=0.2) \n x_new, label_new = mixup_fn(x, label)\n self.assertEqual(x_new.shape, x.shape)\n self.assertEqual(label_new.shape, [4, 10])\n",
"# Copyright (c) 2021 PPViT Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport numpy as np\nimport paddle\nimport torch\nfrom shuffle_transformer import *\nfrom shuffle_pth.shuffle_transformer_torch import ShuffleTransformer as ShuffleTransformerTorch\nfrom config import *\n\nconfig = get_config()\nparser = argparse.ArgumentParser('')\nparser.add_argument('-cfg', type=str, default='./configs/shuffle_vit_base_patch4_window7_224.yaml')\nparser.add_argument('-dataset', type=str, default=None)\nparser.add_argument('-batch_size', type=int, default=None)\nparser.add_argument('-image_size', type=int, default=None)\nparser.add_argument('-data_path', type=str, default=None)\nparser.add_argument('-ngpus', type=int, default=None)\nparser.add_argument('-eval', action=\"store_true\")\nparser.add_argument('-pretrained', type=str, default=None)\nparser.add_argument('-resume', type=str, default=None)\nparser.add_argument('-last_epoch', type=int, default=None)\nargs = parser.parse_args()\n\nconfig = get_config()\nconfig = update_config(config, args)\nprint(config)\n\n\ndef print_model_named_params(model):\n for name, param in model.named_parameters():\n print(name, param.shape)\n\n\ndef print_model_named_buffers(model):\n for name, buff in model.named_buffers():\n print(name, buff.shape)\n\n\ndef torch_to_paddle_mapping():\n # (torch_param_name, paddle_param_name)\n mapping = [\n ('to_token.conv1.0', 'patch_embedding.conv1.0'), # conv\n ('to_token.conv1.1', 'patch_embedding.conv1.1'), # bn\n ('to_token.conv2.0', 'patch_embedding.conv2.0'), # conv\n ('to_token.conv2.1', 'patch_embedding.conv2.1'), # bn\n ('to_token.conv3', 'patch_embedding.conv3'), # conv\n ]\n\n for stage_idx, num_layers in enumerate(config.MODEL.TRANS.DEPTHS):\n for idx in range(num_layers):\n th_layer_idx_0 = idx // 2\n th_layer_idx_1 = idx % 2\n th_prefix = f'stage{stage_idx+1}.layers.{th_layer_idx_0}.{th_layer_idx_1}'\n pp_prefix = f'stages.{stage_idx}.layers.{idx}'\n layer_mapping = [\n (f'{th_prefix}.norm1', f'{pp_prefix}.norm1'), #bn\n (f'{th_prefix}.attn.relative_position_bias_table', f'{pp_prefix}.attn.relative_position_bias_table'), # no transpose\n (f'{th_prefix}.attn.relative_position_index', f'{pp_prefix}.attn.relative_position_index'), # no transpose\n (f'{th_prefix}.attn.to_qkv', f'{pp_prefix}.attn.qkv'),\n (f'{th_prefix}.attn.proj', f'{pp_prefix}.attn.proj'),\n (f'{th_prefix}.local', f'{pp_prefix}.local'),\n (f'{th_prefix}.norm2', f'{pp_prefix}.norm2'), #bn\n (f'{th_prefix}.mlp.fc1', f'{pp_prefix}.mlp.fc1'), \n (f'{th_prefix}.mlp.fc2', f'{pp_prefix}.mlp.fc2'), \n (f'{th_prefix}.norm3', f'{pp_prefix}.norm3'), #bn\n ]\n mapping.extend(layer_mapping)\n\n if stage_idx > 0:\n layer_mapping = [\n (f'stage{stage_idx+1}.patch_partition.norm', f'stages.{stage_idx}.patch_partition.norm'), #bn\n (f'stage{stage_idx+1}.patch_partition.reduction', f'stages.{stage_idx}.patch_partition.reduction'),\n ]\n mapping.extend(layer_mapping)\n\n head_mapping = [\n ('head', 'head'),\n ]\n mapping.extend(head_mapping)\n\n return mapping\n\n\ndef convert(torch_model, paddle_model):\n def _set_value(th_name, pd_name, transpose=True):\n th_shape = th_params[th_name].shape\n pd_shape = tuple(pd_params[pd_name].shape) # paddle shape default type is list\n #assert th_shape == pd_shape, f'{th_shape} != {pd_shape}'\n print(f'set {th_name} {th_shape} to {pd_name} {pd_shape}')\n if isinstance(th_params[th_name], torch.nn.parameter.Parameter):\n value = th_params[th_name].data.numpy()\n else:\n value = th_params[th_name].numpy()\n if len(value.shape) == 2 and transpose:\n value = value.transpose((1, 0))\n pd_params[pd_name].set_value(value)\n\n # 1. get paddle and torch model parameters\n pd_params = {}\n th_params = {}\n for name, param in paddle_model.named_parameters():\n pd_params[name] = param\n for name, param in paddle_model.named_buffers():\n pd_params[name] = param\n\n for name, param in torch_model.named_parameters():\n th_params[name] = param\n for name, param in torch_model.named_buffers():\n th_params[name] = param\n\n # 2. get name mapping pairs\n mapping = torch_to_paddle_mapping()\n # 3. set torch param values to paddle params: may needs transpose on weights\n for th_name, pd_name in mapping:\n if th_name in th_params.keys(): # nn.Parameters\n if 'relative_position' in th_name:\n _set_value(th_name, pd_name, transpose=False)\n else:\n _set_value(th_name, pd_name)\n else: # weight & bias\n th_name_w = f'{th_name}.weight'\n pd_name_w = f'{pd_name}.weight'\n _set_value(th_name_w, pd_name_w)\n\n if f'{th_name}.bias' in th_params.keys():\n th_name_b = f'{th_name}.bias'\n pd_name_b = f'{pd_name}.bias'\n _set_value(th_name_b, pd_name_b)\n\n if f'{th_name}.running_mean' in th_params.keys():\n th_name_b = f'{th_name}.running_mean'\n pd_name_b = f'{pd_name}._mean'\n _set_value(th_name_b, pd_name_b)\n\n if f'{th_name}.running_var' in th_params.keys():\n th_name_b = f'{th_name}.running_var'\n pd_name_b = f'{pd_name}._variance'\n _set_value(th_name_b, pd_name_b)\n\n return paddle_model\n\n\ndef main():\n\n paddle.set_device('cpu')\n paddle_model = build_shuffle_transformer(config)\n paddle_model.eval()\n\n print_model_named_params(paddle_model)\n print('--------------')\n print_model_named_buffers(paddle_model)\n print('----------------------------------')\n\n device = torch.device('cpu')\n torch_model = ShuffleTransformerTorch(layers=[2, 2, 18, 2],\n num_heads=[4, 8, 16, 32],\n qkv_bias=True,\n embed_dim=128,\n )\n model_state_dict = torch.load('./shuffle_pth/shuffle_vit_base_patch4_window7_224_ep296.pth', map_location='cpu') \n torch_model.load_state_dict(model_state_dict['model'])\n torch_model = torch_model.to(device)\n torch_model.eval()\n\n print_model_named_params(torch_model)\n print('--------------')\n print_model_named_buffers(torch_model)\n print('----------------------------------')\n\n\n #return\n\n # convert weights\n paddle_model = convert(torch_model, paddle_model)\n\n # check correctness\n x = np.random.randn(2, 3, 224, 224).astype('float32')\n x_paddle = paddle.to_tensor(x)\n x_torch = torch.Tensor(x).to(device)\n\n out_torch = torch_model(x_torch)\n out_paddle = paddle_model(x_paddle)\n\n out_torch = out_torch.data.cpu().numpy()\n out_paddle = out_paddle.cpu().numpy()\n\n print(out_torch.shape, out_paddle.shape)\n print(out_torch[0, 0:100])\n print(out_paddle[0, 0:100])\n assert np.allclose(out_torch, out_paddle, atol = 1e-5)\n \n # save weights for paddle model\n model_path = os.path.join('./shuffle_vit_base_patch4_window7_224.pdparams')\n paddle.save(paddle_model.state_dict(), model_path)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.array"
],
[
"numpy.random.seed"
],
[
"numpy.sqrt"
],
[
"torch.device",
"numpy.random.randn",
"numpy.allclose",
"torch.load",
"torch.Tensor"
]
] |
drammock/expyfun
|
[
"b92bf5291318ee4cb1692e7bcb9757a422f48304"
] |
[
"examples/stimuli/stimulus_power.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\n=====================================\nExamine and manipulate stimulus power\n=====================================\n\nThis shows how to make stimuli that play at different SNRs and db SPL.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom expyfun.stimuli import window_edges, read_wav, rms\nfrom expyfun import fetch_data_file\n\nprint(__doc__)\n\n###############################################################################\n# Load data\n# ---------\n# Get 2 seconds of data\ndata_orig, fs = read_wav(fetch_data_file('audio/dream.wav'))\nstop = int(round(fs * 2))\ndata_orig = window_edges(data_orig[0, :stop], fs)\nt = np.arange(data_orig.size) / float(fs)\n\n# look at the waveform\nfig, ax = plt.subplots()\nax.plot(t, data_orig)\nax.set(xlabel='Time (sec)', ylabel='Amplitude', title='Original',\n xlim=t[[0, -1]])\nfig.tight_layout()\n\n###############################################################################\n# Normalize it\n# ------------\n# :class:`expyfun.ExperimentController` by default has ``stim_rms=0.01``. This\n# means that audio samples normalized to an RMS (root-mean-square) value of\n# 0.01 will play out at whatever ``stim_db`` value you supply (during class\n# initialization) when the experiment is deployed on properly calibrated\n# hardware, typically in an experimental booth. So let's normalize our clip:\n\nprint(rms(data_orig))\ntarget = data_orig / rms(data_orig)\ntarget *= 0.01\n# do manual calculation same as ``rms``, result should be 0.01\n# (to numerical precision)\nprint(np.sqrt(np.mean(target ** 2)))\n\n###############################################################################\n# One important thing to note about this stimulus is that its long-term RMS\n# (over the entire 2 seconds) is now 0.01. There will be quiet parts where the\n# RMS is effectively lower (close to zero) and louder parts where it's bigger.\n#\n# Add some noise\n# --------------\n# Now let's add some masker noise, say 6 dB down (6 dB target-to-masker ratio;\n# TMR) from that of the target.\n#\n# .. note::\n# White noise is used here just as an example. If you want continuous\n# white background noise in your experiment, consider using\n# :meth:`ec.start_noise() <expyfun.ExperimentController.start_noise>`\n# and/or\n# :meth:`ec.set_noise_db() <expyfun.ExperimentController.set_noise_db>`\n# which will automatically keep background noise continuously playing\n# during your experiment.\n\n# Good idea to use a seed for reproducibility!\nratio_dB = -6. # dB\nrng = np.random.RandomState(0)\nmasker = rng.randn(len(target))\nmasker /= rms(masker) # now has unit RMS\nmasker *= 0.01 # now has RMS=0.01, same as target\nratio_amplitude = 10 ** (ratio_dB / 20.) # conversion from dB to amplitude\nmasker *= ratio_amplitude\n\n###############################################################################\n# Looking at the overlaid traces, you can see that the resulting SNR varies as\n# a function of time.\n\ncolors = ['#4477AA', '#EE7733']\nfig, ax = plt.subplots()\nax.plot(t, target, label='target', alpha=0.5, color=colors[0], lw=0.5)\nax.plot(t, masker, label='masker', alpha=0.5, color=colors[1], lw=0.5)\nax.axhline(0.01, label='target RMS', color=colors[0], lw=1)\nax.axhline(0.01 * ratio_amplitude, label='masker RMS', color=colors[1], lw=1)\nax.set(xlabel='Time (sec)', ylabel='Amplitude', title='Calibrated',\n xlim=t[[0, -1]])\nax.legend()\nfig.tight_layout()\n\n###############################################################################\n# Examine spectra\n# ---------------\n# We can also look at the spectra of these stimuli to get a sense of how the\n# SNR varies as a function of frequency.\n\nfrom scipy.fft import rfft, rfftfreq # noqa\nf = rfftfreq(len(target), 1. / fs)\nT = np.abs(rfft(target)) / np.sqrt(len(target)) # normalize the FFT properly\nM = np.abs(rfft(masker)) / np.sqrt(len(target))\nfig, ax = plt.subplots()\nax.plot(f, T, label='target', alpha=0.5, color=colors[0], lw=0.5)\nax.plot(f, M, label='masker', alpha=0.5, color=colors[1], lw=0.5)\nT_rms = rms(T)\nM_rms = rms(M)\nprint('Parseval\\'s theorem: target RMS still %s' % (T_rms,))\nprint('dB TMR is still %s' % (20 * np.log10(T_rms / M_rms),))\nax.axhline(T_rms, label='target RMS', color=colors[0], lw=1)\nax.axhline(M_rms, label='masker RMS', color=colors[1], lw=1)\nax.set(xlabel='Freq (Hz)', ylabel='Amplitude', title='Spectrum',\n xlim=f[[0, -1]])\nax.legend()\nfig.tight_layout()\n"
] |
[
[
"numpy.random.RandomState",
"scipy.fft.rfft",
"numpy.mean",
"matplotlib.pyplot.subplots",
"numpy.arange",
"numpy.log10"
]
] |
gf91597/summer
|
[
"d3096fc66636a3247bc6d6dbfa5f4ca5414d57ff"
] |
[
"test/t2.py"
] |
[
"#!/usr/local/bin/python3\n\nfrom matplotlib import pyplot as plt\nimport mpl_finance as mpf\n#from matplotlib import finance as mpf\nfrom matplotlib.pylab import date2num\nimport pandas as pd\nimport datetime\n\nplt.bar([1, 3, 5, 7, 9], [5, 4, 8, 12, 7], label='graph 1')\n\nplt.bar([2, 4, 6, 8, 10], [4, 6, 8, 13, 15], label='graph 2')\n\n# params\n\n# x: 条形图x轴\n# y:条形图的高度\n# width:条形图的宽度 默认是0.8\n# bottom:条形底部的y坐标值 默认是0\n# align:center / edge 条形图是否以x轴坐标为中心点或者是以x轴坐标为边缘\n\nplt.legend()\n\nplt.xlabel('number')\nplt.ylabel('value')\n\nplt.title(u'测试例子——条形图')\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.bar"
]
] |
gonzzza007/Russian-gpt-2
|
[
"22bc186d6320b315cd0066bd21bff9c5c9457c77"
] |
[
"src/sample.py"
] |
[
"import tensorflow as tf\n\nimport model\n\ndef top_k_logits(logits, k):\n if k == 0:\n # no truncation\n return logits\n\n def _top_k():\n values, _ = tf.nn.top_k(logits, k=k)\n min_values = values[:, -1, tf.newaxis]\n return tf.where(\n logits < min_values,\n tf.ones_like(logits, dtype=logits.dtype) * -1e10,\n logits,\n )\n return tf.cond(\n tf.equal(k, 0),\n lambda: logits,\n lambda: _top_k(),\n )\n\n\ndef top_p_logits(logits, p):\n with tf.variable_scope('top_p_logits'):\n logits_sort = tf.sort(logits, direction='DESCENDING')\n probs_sort = tf.nn.softmax(logits_sort)\n probs_sums = tf.cumsum(probs_sort, axis=1, exclusive=True)\n logits_masked = tf.where(probs_sums < p, logits_sort, tf.ones_like(logits_sort)*1000) # [batchsize, vocab]\n min_logits = tf.reduce_min(logits_masked, axis=1, keepdims=True) # [batchsize, 1]\n return tf.where(\n logits < min_logits,\n tf.ones_like(logits, dtype=logits.dtype) * -1e10,\n logits,\n )\n\n\ndef sample_sequence(*, hparams, length, start_token=None, batch_size=None, context=None, temperature=1, top_k=0, top_p=0.0):\n if start_token is None:\n assert context is not None, 'Specify exactly one of start_token and context!'\n else:\n assert context is None, 'Specify exactly one of start_token and context!'\n context = tf.fill([batch_size, 1], start_token)\n\n def step(hparams, tokens, past=None):\n lm_output = model.model(hparams=hparams, X=tokens, past=past, reuse=tf.compat.v1.AUTO_REUSE)\n logits = lm_output['logits'][:, :, :hparams.n_vocab]\n presents = lm_output['present']\n presents.set_shape(model.past_shape(hparams=hparams, batch_size=batch_size))\n return {\n 'logits': logits,\n 'presents': presents,\n }\n\n with tf.name_scope('sample_sequence'):\n # Don't feed the last context token -- leave that to the loop below\n # TODO: Would be slightly faster if we called step on the entire context,\n # rather than leaving the last token transformer calculation to the while loop.\n context_output = step(hparams, context[:, :-1])\n\n def body(past, prev, output):\n next_outputs = step(hparams, prev[:, tf.newaxis], past=past)\n logits = next_outputs['logits'][:, -1, :] / tf.to_float(temperature)\n if top_p > 0.0:\n logits = top_p_logits(logits, p=top_p)\n else:\n logits = top_k_logits(logits, k=top_k)\n samples = tf.multinomial(logits, num_samples=1, output_dtype=tf.int32)\n return [\n tf.concat([past, next_outputs['presents']], axis=-2),\n tf.squeeze(samples, axis=[1]),\n tf.concat([output, samples], axis=1),\n ]\n\n def cond(*args):\n return True\n\n _, _, tokens = tf.while_loop(\n cond=cond, body=body,\n maximum_iterations=length,\n loop_vars=[\n context_output['presents'],\n context[:, -1],\n context,\n ],\n shape_invariants=[\n tf.TensorShape(model.past_shape(hparams=hparams, batch_size=batch_size)),\n tf.TensorShape([batch_size]),\n tf.TensorShape([batch_size, None]),\n ],\n back_prop=False,\n )\n\n return tokens\n"
] |
[
[
"tensorflow.reduce_min",
"tensorflow.cumsum",
"tensorflow.concat",
"tensorflow.multinomial",
"tensorflow.equal",
"tensorflow.fill",
"tensorflow.ones_like",
"tensorflow.TensorShape",
"tensorflow.variable_scope",
"tensorflow.sort",
"tensorflow.squeeze",
"tensorflow.name_scope",
"tensorflow.to_float",
"tensorflow.nn.top_k",
"tensorflow.nn.softmax"
]
] |
KabohaJeanMark/tensorflow
|
[
"c6156aaaa110ec7091648123bf8c04c52d832ddb",
"c6156aaaa110ec7091648123bf8c04c52d832ddb"
] |
[
"tensorflow/python/keras/engine/training.py",
"tensorflow/examples/speech_commands/train.py"
] |
[
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Training-related part of the Keras engine.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport json\nimport numpy as np\n\nfrom tensorflow.python import tf2\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.distribute import multi_worker_util\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import monitoring\nfrom tensorflow.python.framework import composite_tensor_utils\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import type_spec\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import losses\nfrom tensorflow.python.keras import metrics as metrics_module\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.keras.distribute import distributed_training_utils\nfrom tensorflow.python.keras.engine import data_adapter\nfrom tensorflow.python.keras.engine import network\nfrom tensorflow.python.keras.engine import training_arrays\nfrom tensorflow.python.keras.engine import training_distributed\nfrom tensorflow.python.keras.engine import training_eager\nfrom tensorflow.python.keras.engine import training_generator\nfrom tensorflow.python.keras.engine import training_utils\nfrom tensorflow.python.keras.engine import training_v2\nfrom tensorflow.python.keras.engine import training_v2_utils\nfrom tensorflow.python.keras.saving import saving_utils\nfrom tensorflow.python.keras.utils import data_utils\nfrom tensorflow.python.keras.utils import losses_utils\nfrom tensorflow.python.keras.utils.mode_keys import ModeKeys\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.losses import util as tf_losses_utils\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.training.tracking import layer_utils as trackable_layer_utils\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import serialization\nfrom tensorflow.python.util import tf_inspect\nfrom tensorflow.python.util.tf_export import keras_export\nfrom tensorflow.python.util.compat import collections_abc\n\ntry:\n from scipy.sparse import issparse # pylint: disable=g-import-not-at-top\nexcept ImportError:\n issparse = None\n\n_keras_api_gauge = monitoring.BoolGauge('/tensorflow/api/keras',\n 'keras api usage', 'method')\n\n\n@keras_export('keras.models.Model', 'keras.Model')\nclass Model(network.Network):\n \"\"\"`Model` groups layers into an object with training and inference features.\n\n There are two ways to instantiate a `Model`:\n\n 1 - With the \"functional API\", where you start from `Input`,\n you chain layer calls to specify the model's forward pass,\n and finally you create your model from inputs and outputs:\n\n ```python\n import tensorflow as tf\n\n inputs = tf.keras.Input(shape=(3,))\n x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)\n outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)\n model = tf.keras.Model(inputs=inputs, outputs=outputs)\n ```\n\n 2 - By subclassing the `Model` class: in that case, you should define your\n layers in `__init__` and you should implement the model's forward pass\n in `call`.\n\n ```python\n import tensorflow as tf\n\n class MyModel(tf.keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)\n\n def call(self, inputs):\n x = self.dense1(inputs)\n return self.dense2(x)\n\n model = MyModel()\n ```\n\n If you subclass `Model`, you can optionally have\n a `training` argument (boolean) in `call`, which you can use to specify\n a different behavior in training and inference:\n\n ```python\n import tensorflow as tf\n\n class MyModel(tf.keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)\n self.dropout = tf.keras.layers.Dropout(0.5)\n\n def call(self, inputs, training=False):\n x = self.dense1(inputs)\n if training:\n x = self.dropout(x, training=training)\n return self.dense2(x)\n\n model = MyModel()\n ```\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(Model, self).__init__(*args, **kwargs)\n _keras_api_gauge.get_cell('model').set(True)\n # initializing _distribution_strategy here since it is possible to call\n # predict on a model without compiling it.\n self._distribution_strategy = None\n self._compile_time_distribution_strategy = None\n\n # This flag is used to track if the user is using the deprecated path of\n # passing distribution strategy to compile rather than creating the model\n # under distribution strategy scope.\n self._compile_distribution = False\n\n self._run_eagerly = None\n self._experimental_run_tf_function = False\n\n def get_weights(self):\n \"\"\"Retrieves the weights of the model.\n\n Returns:\n A flat list of Numpy arrays.\n \"\"\"\n strategy = (self._distribution_strategy or\n self._compile_time_distribution_strategy)\n if strategy:\n with strategy.scope():\n return super(Model, self).get_weights()\n return super(Model, self).get_weights()\n\n def load_weights(self, filepath, by_name=False):\n \"\"\"Loads all layer weights, either from a TensorFlow or an HDF5 file.\"\"\"\n if distributed_training_utils.is_tpu_strategy(self._distribution_strategy):\n if (self._distribution_strategy.extended.steps_per_run > 1 and\n (not network._is_hdf5_filepath(filepath))): # pylint: disable=protected-access\n raise ValueError('Load weights is not yet supported with TPUStrategy '\n 'with steps_per_run greater than 1.')\n return super(Model, self).load_weights(filepath, by_name)\n\n @trackable.no_automatic_dependency_tracking\n def compile(self,\n optimizer='rmsprop',\n loss=None,\n metrics=None,\n loss_weights=None,\n sample_weight_mode=None,\n weighted_metrics=None,\n target_tensors=None,\n distribute=None,\n **kwargs):\n \"\"\"Configures the model for training.\n\n Arguments:\n optimizer: String (name of optimizer) or optimizer instance.\n See `tf.keras.optimizers`.\n loss: String (name of objective function), objective function or\n `tf.losses.Loss` instance. See `tf.losses`. If the model has\n multiple outputs, you can use a different loss on each output by\n passing a dictionary or a list of losses. The loss value that will\n be minimized by the model will then be the sum of all individual\n losses.\n metrics: List of metrics to be evaluated by the model during training\n and testing. Typically you will use `metrics=['accuracy']`.\n To specify different metrics for different outputs of a\n multi-output model, you could also pass a dictionary, such as\n `metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}`.\n You can also pass a list (len = len(outputs)) of lists of metrics\n such as `metrics=[['accuracy'], ['accuracy', 'mse']]` or\n `metrics=['accuracy', ['accuracy', 'mse']]`.\n loss_weights: Optional list or dictionary specifying scalar\n coefficients (Python floats) to weight the loss contributions\n of different model outputs.\n The loss value that will be minimized by the model\n will then be the *weighted sum* of all individual losses,\n weighted by the `loss_weights` coefficients.\n If a list, it is expected to have a 1:1 mapping\n to the model's outputs. If a tensor, it is expected to map\n output names (strings) to scalar coefficients.\n sample_weight_mode: If you need to do timestep-wise\n sample weighting (2D weights), set this to `\"temporal\"`.\n `None` defaults to sample-wise weights (1D).\n If the model has multiple outputs, you can use a different\n `sample_weight_mode` on each output by passing a\n dictionary or a list of modes.\n weighted_metrics: List of metrics to be evaluated and weighted\n by sample_weight or class_weight during training and testing.\n target_tensors: By default, Keras will create placeholders for the\n model's target, which will be fed with the target data during\n training. If instead you would like to use your own\n target tensors (in turn, Keras will not expect external\n Numpy data for these targets at training time), you\n can specify them via the `target_tensors` argument. It can be\n a single tensor (for a single-output model), a list of tensors,\n or a dict mapping output names to target tensors.\n distribute: NOT SUPPORTED IN TF 2.0, please create and compile the\n model under distribution strategy scope instead of passing it to\n compile.\n **kwargs: Any additional arguments.\n\n Raises:\n ValueError: In case of invalid arguments for\n `optimizer`, `loss`, `metrics` or `sample_weight_mode`.\n \"\"\"\n self._run_eagerly = kwargs.pop('run_eagerly', None)\n self._experimental_run_tf_function = kwargs.pop(\n 'experimental_run_tf_function', False)\n\n if isinstance(optimizer, (list, tuple)):\n self.optimizer = [optimizers.get(opt) for opt in optimizer]\n is_any_optimizer_v1 = any(\n isinstance(opt, optimizers.Optimizer) for opt in self.optimizer)\n else:\n self.optimizer = optimizers.get(optimizer)\n is_any_optimizer_v1 = isinstance(self.optimizer, optimizers.Optimizer)\n\n if ((sample_weight_mode is not None)\n or (target_tensors is not None)\n or (weighted_metrics is not None)\n or is_any_optimizer_v1\n or not context.executing_eagerly()):\n # Fallback out of things that aren't supported with v2 loops\n self._experimental_run_tf_function = False\n\n self._compile_time_distribution_strategy = (\n distribution_strategy_context.get_strategy())\n\n if distribute is not None:\n if tf2.enabled() or self._experimental_run_tf_function:\n raise ValueError(\n 'Distribute argument in compile is not available in TF 2.0 please '\n 'create the model under the distribution strategy scope.')\n logging.warning('Distribute argument in compile is deprecated please '\n 'create the model under the distribution strategy scope.')\n self._distribution_strategy = distribute\n self._compile_distribution = True\n else:\n if distribution_strategy_context.has_strategy():\n # When the user builds the model in the DS scope and cross replica\n # context we want distribution strategy to be set but when building the\n # replica copies of the models internally we should not be compiling\n # with distribution strategy and use the default compilation path.\n if distribution_strategy_context.in_cross_replica_context():\n self._distribution_strategy = (\n distribution_strategy_context.get_strategy())\n\n if not self._experimental_run_tf_function:\n self._validate_compile_param_for_distribution_strategy(self.run_eagerly,\n sample_weight_mode,\n target_tensors,\n weighted_metrics)\n # We've disabled automatic dependency tracking for this method, but do want\n # to add a checkpoint dependency on the optimizer if it's trackable.\n if isinstance(self.optimizer, trackable.Trackable):\n self._track_trackable(\n self.optimizer, name='optimizer', overwrite=True)\n self.loss = loss or {}\n self.loss_weights = loss_weights\n self.sample_weight_mode = sample_weight_mode\n self._compile_metrics = metrics or []\n self._compile_weighted_metrics = weighted_metrics\n if self.run_eagerly and target_tensors is not None:\n raise ValueError(\n 'target_tensors argument is not supported when '\n 'running a model eagerly.')\n\n # _training_endpoints contains a list of _TrainingEndpoint object, which has\n # all the model output/target/loss and related metadata.\n self._training_endpoints = []\n\n # Used to freeze the behavior of the Model once `compile` has been called.\n self._compiled_trainable_state = self._get_trainable_state()\n\n # Set tf.distribute.Strategy specific parameters.\n self._distributed_model_cache = {}\n self._distributed_function_cache = {}\n\n # Clear any `_eager_losses` that was added.\n self._clear_losses()\n\n if (not context.executing_eagerly() and\n self._distribution_strategy is not None):\n # Ensures a Session is created and configured correctly for Distribution\n # Strategy.\n K.configure_and_create_distributed_session(self._distribution_strategy)\n # Initialize model metric attributes.\n self._init_metric_attributes()\n if not self.built or not self.inputs or not self.outputs:\n # Model is not compilable because it does not know its number of inputs\n # and outputs, nor their shapes and names. We will compile after the first\n # time the model gets called on training data.\n return\n self._is_compiled = True\n _keras_api_gauge.get_cell('compile').set(True)\n\n # Prepare list of loss functions, same size of model outputs.\n self.loss_functions = training_utils.prepare_loss_functions(\n self.loss, self.output_names)\n\n target_tensors = self._process_target_tensor_for_compile(target_tensors)\n\n for o, n, l, t in zip(self.outputs, self.output_names,\n self.loss_functions, target_tensors):\n endpoint = _TrainingEndpoint(o, n, l)\n endpoint.create_training_target(t, run_eagerly=self.run_eagerly)\n self._training_endpoints.append(endpoint)\n\n # Prepare list loss weights, same size of model outputs.\n training_utils.prepare_loss_weights(self._training_endpoints, loss_weights)\n\n # Initialization for Eager mode execution.\n if self.run_eagerly:\n self._compile_eagerly(metrics, weighted_metrics, sample_weight_mode)\n return\n\n with K.get_graph().as_default():\n # Save all metric attributes per output of the model.\n self._cache_output_metric_attributes(metrics, weighted_metrics)\n\n # Set metric attributes on model.\n self._set_metric_attributes()\n\n # Invoke metric functions (unweighted) for all the outputs.\n self._handle_metrics(\n self.outputs,\n targets=self._targets,\n skip_target_masks=self._prepare_skip_target_masks(),\n masks=self._prepare_output_masks())\n\n # Prepare sample weight modes. List with the same length as model outputs.\n training_utils.prepare_sample_weight_modes(\n self._training_endpoints, sample_weight_mode)\n\n # Creates the model loss and weighted metrics sub-graphs.\n self._compile_weights_loss_and_weighted_metrics()\n\n # Functions for train, test and predict will\n # be compiled lazily when required.\n # This saves time when the user is not using all functions.\n self._function_kwargs = kwargs\n\n self.train_function = None\n self.test_function = None\n self.predict_function = None\n\n # Collected trainable weights, sorted in topological order.\n self._collected_trainable_weights = self._unique_trainable_weights\n\n # Validate all variables were correctly created in distribution scope.\n if self._distribution_strategy and not self._compile_distribution:\n for v in self.variables:\n strategy = self._distribution_strategy\n if not strategy.extended.variable_created_in_scope(v):\n raise ValueError(\n 'Variable (%s) was not created in the distribution strategy '\n 'scope of (%s). It is most likely due to not all layers or '\n 'the model or optimizer being created outside the distribution '\n 'strategy scope. Try to make sure your code looks similar '\n 'to the following.\\n'\n 'with strategy.scope():\\n'\n ' model=_create_model()\\n'\n ' model.compile(...)'% (v, strategy))\n\n @trackable.no_automatic_dependency_tracking\n def _init_distributed_function_cache_if_not_compiled(self):\n if not hasattr(self, '_distributed_function_cache'):\n self._distributed_function_cache = {}\n\n @property\n def metrics(self):\n \"\"\"Returns the model's metrics added using `compile`, `add_metric` APIs.\"\"\"\n metrics = []\n if self._is_compiled:\n metrics += self._compile_metric_functions\n metrics.extend(self._metrics)\n metrics.extend(_get_metrics_from_layers(self._layers))\n return metrics\n\n @property\n def metrics_names(self):\n \"\"\"Returns the model's display labels for all outputs.\"\"\"\n metrics_names = ['loss']\n if self._is_compiled:\n # Add output loss metric names to the metric names list.\n if len(self._training_endpoints) > 1:\n metrics_names.extend([\n e.loss_name()\n for e in self._training_endpoints\n if not e.should_skip_target()\n ])\n\n # Add compile metrics/weighted metrics' names to the metric names list.\n metrics_names.extend([m.name for m in self._compile_metric_functions])\n\n # Add metric names from layers.\n for layer in self.layers:\n metrics_names += [m.name for m in layer._metrics] # pylint: disable=protected-access\n metrics_names += [m.name for m in self._metrics]\n return metrics_names\n\n @property\n def run_eagerly(self):\n \"\"\"Settable attribute indicating whether the model should run eagerly.\n\n Running eagerly means that your model will be run step by step,\n like Python code. Your model might run slower, but it should become easier\n for you to debug it by stepping into individual layer calls.\n\n By default, we will attempt to compile your model to a static graph to\n deliver the best execution performance.\n\n Returns:\n Boolean, whether the model should run eagerly.\n \"\"\"\n if self._run_eagerly is True and not context.executing_eagerly():\n raise ValueError('You can only set `run_eagerly=True` if eager execution '\n 'is enabled.')\n if not self.dynamic:\n if self._run_eagerly is None:\n # Respect `tf.config.experimental_run_functions_eagerly` unless\n # `run_eagerly` was explicitly passed to `compile`.\n return def_function.RUN_FUNCTIONS_EAGERLY\n else:\n return self._run_eagerly\n else:\n if not context.executing_eagerly():\n raise ValueError('Your model contains layers that can only be '\n 'successfully run in eager execution (layers '\n 'constructed with `dynamic=True`). '\n 'You must enable eager execution with '\n '`tf.enable_eager_execution()`.')\n if self._run_eagerly is False:\n # TODO(fchollet): consider using py_func to enable this.\n raise ValueError('Your model contains layers that can only be '\n 'successfully run in eager execution (layers '\n 'constructed with `dynamic=True`). '\n 'You cannot set `run_eagerly=False`.')\n return context.executing_eagerly()\n\n @run_eagerly.setter\n def run_eagerly(self, value):\n self._run_eagerly = value\n\n def _select_training_loop(self, inputs, callbacks):\n \"\"\"Select training loop for fit/eval/predict based on the inputs.\"\"\"\n # TODO(kaftan) or TODO(scottzhu): This check should eventually be nicely\n # integrated into the data adapters in the v2 loop. We can't do this yet\n # because we currently have to fall back for unhandled data types.\n if isinstance(inputs, (iterator_ops.Iterator,\n iterator_ops.IteratorV2)):\n raise ValueError('For performance reasons Keras `fit`, `evaluate` and'\n '`predict` accept tf.data `Datasets` as input but not '\n 'iterators that have been manually generated from '\n 'Datasets by users. Please directly pass in the '\n 'original `Dataset` object instead of passing in '\n '`iter(dataset)`.')\n\n # Experiment training loop with default DS path.\n if (context.executing_eagerly()\n and self._experimental_run_tf_function\n and not distributed_training_utils.is_tpu_strategy(\n self._distribution_strategy)\n and not training_v2_utils.should_fallback_to_v1_for_callback(\n inputs, callbacks)):\n try:\n valid_adapter = data_adapter.select_data_adapter(inputs, None)\n except ValueError as data_failure_exception:\n valid_adapter = None\n logging.warning('Falling back from v2 loop because of error: '\n '%s' % data_failure_exception)\n if valid_adapter:\n if multi_worker_util.in_multi_worker_mode():\n return training_distributed.DistributionMultiWorkerTrainingLoop(\n training_v2.Loop())\n else:\n return training_v2.Loop()\n\n # Case 1: distribution strategy.\n if self._distribution_strategy:\n if multi_worker_util.in_multi_worker_mode():\n return training_distributed.DistributionMultiWorkerTrainingLoop(\n training_distributed.DistributionSingleWorkerTrainingLoop())\n else:\n return training_distributed.DistributionSingleWorkerTrainingLoop()\n\n # Case 2: generator-like. Input is Python generator, or Sequence object,\n # or a non-distributed Dataset or iterator in eager execution.\n if data_utils.is_generator_or_sequence(inputs):\n return training_generator.GeneratorOrSequenceTrainingLoop()\n if training_utils.is_eager_dataset_or_iterator(inputs):\n return training_generator.EagerDatasetOrIteratorTrainingLoop()\n\n # Case 3: Symbolic tensors or Numpy array-like.\n # This includes Datasets and iterators in graph mode (since they\n # generate symbolic tensors).\n if self.run_eagerly:\n return training_generator.GeneratorLikeTrainingLoop()\n else:\n return training_arrays.ArrayLikeTrainingLoop()\n\n def fit(self,\n x=None,\n y=None,\n batch_size=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_split=0.,\n validation_data=None,\n shuffle=True,\n class_weight=None,\n sample_weight=None,\n initial_epoch=0,\n steps_per_epoch=None,\n validation_steps=None,\n validation_freq=1,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n **kwargs):\n \"\"\"Trains the model for a fixed number of epochs (iterations on a dataset).\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset. Should return a tuple\n of either `(inputs, targets)` or\n `(inputs, targets, sample_weights)`.\n - A generator or `keras.utils.Sequence` returning `(inputs, targets)`\n or `(inputs, targets, sample weights)`.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely). If `x` is a dataset, generator,\n or `keras.utils.Sequence` instance, `y` should\n not be specified (since targets will be obtained from `x`).\n batch_size: Integer or `None`.\n Number of samples per gradient update.\n If unspecified, `batch_size` will default to 32.\n Do not specify the `batch_size` if your data is in the\n form of symbolic tensors, datasets,\n generators, or `keras.utils.Sequence` instances (since they generate\n batches).\n epochs: Integer. Number of epochs to train the model.\n An epoch is an iteration over the entire `x` and `y`\n data provided.\n Note that in conjunction with `initial_epoch`,\n `epochs` is to be understood as \"final epoch\".\n The model is not trained for a number of iterations\n given by `epochs`, but merely until the epoch\n of index `epochs` is reached.\n verbose: 0, 1, or 2. Verbosity mode.\n 0 = silent, 1 = progress bar, 2 = one line per epoch.\n Note that the progress bar is not particularly useful when\n logged to a file, so verbose=2 is recommended when not running\n interactively (eg, in a production environment).\n callbacks: List of `keras.callbacks.Callback` instances.\n List of callbacks to apply during training.\n See `tf.keras.callbacks`.\n validation_split: Float between 0 and 1.\n Fraction of the training data to be used as validation data.\n The model will set apart this fraction of the training data,\n will not train on it, and will evaluate\n the loss and any model metrics\n on this data at the end of each epoch.\n The validation data is selected from the last samples\n in the `x` and `y` data provided, before shuffling. This argument is\n not supported when `x` is a dataset, generator or\n `keras.utils.Sequence` instance.\n validation_data: Data on which to evaluate\n the loss and any model metrics at the end of each epoch.\n The model will not be trained on this data.\n `validation_data` will override `validation_split`.\n `validation_data` could be:\n - tuple `(x_val, y_val)` of Numpy arrays or tensors\n - tuple `(x_val, y_val, val_sample_weights)` of Numpy arrays\n - dataset\n For the first two cases, `batch_size` must be provided.\n For the last case, `validation_steps` must be provided.\n shuffle: Boolean (whether to shuffle the training data\n before each epoch) or str (for 'batch').\n 'batch' is a special option for dealing with the\n limitations of HDF5 data; it shuffles in batch-sized chunks.\n Has no effect when `steps_per_epoch` is not `None`.\n class_weight: Optional dictionary mapping class indices (integers)\n to a weight (float) value, used for weighting the loss function\n (during training only).\n This can be useful to tell the model to\n \"pay more attention\" to samples from\n an under-represented class.\n sample_weight: Optional Numpy array of weights for\n the training samples, used for weighting the loss function\n (during training only). You can either pass a flat (1D)\n Numpy array with the same length as the input samples\n (1:1 mapping between weights and samples),\n or in the case of temporal data,\n you can pass a 2D array with shape\n `(samples, sequence_length)`,\n to apply a different weight to every timestep of every sample.\n In this case you should make sure to specify\n `sample_weight_mode=\"temporal\"` in `compile()`. This argument is not\n supported when `x` is a dataset, generator, or\n `keras.utils.Sequence` instance, instead provide the sample_weights\n as the third element of `x`.\n initial_epoch: Integer.\n Epoch at which to start training\n (useful for resuming a previous training run).\n steps_per_epoch: Integer or `None`.\n Total number of steps (batches of samples)\n before declaring one epoch finished and starting the\n next epoch. When training with input tensors such as\n TensorFlow data tensors, the default `None` is equal to\n the number of samples in your dataset divided by\n the batch size, or 1 if that cannot be determined. If x is a\n `tf.data` dataset, and 'steps_per_epoch'\n is None, the epoch will run until the input dataset is exhausted.\n This argument is not supported with array inputs.\n validation_steps: Only relevant if `validation_data` is provided and\n is a `tf.data` dataset. Total number of steps (batches of\n samples) to draw before stopping when performing validation\n at the end of every epoch. If validation_data is a `tf.data` dataset\n and 'validation_steps' is None, validation\n will run until the `validation_data` dataset is exhausted.\n validation_freq: Only relevant if validation data is provided. Integer\n or `collections_abc.Container` instance (e.g. list, tuple, etc.).\n If an integer, specifies how many training epochs to run before a\n new validation run is performed, e.g. `validation_freq=2` runs\n validation every 2 epochs. If a Container, specifies the epochs on\n which to run validation, e.g. `validation_freq=[1, 2, 10]` runs\n validation at the end of the 1st, 2nd, and 10th epochs.\n max_queue_size: Integer. Used for generator or `keras.utils.Sequence`\n input only. Maximum size for the generator queue.\n If unspecified, `max_queue_size` will default to 10.\n workers: Integer. Used for generator or `keras.utils.Sequence` input\n only. Maximum number of processes to spin up\n when using process-based threading. If unspecified, `workers`\n will default to 1. If 0, will execute the generator on the main\n thread.\n use_multiprocessing: Boolean. Used for generator or\n `keras.utils.Sequence` input only. If `True`, use process-based\n threading. If unspecified, `use_multiprocessing` will default to\n `False`. Note that because this implementation relies on\n multiprocessing, you should not pass non-picklable arguments to\n the generator as they can't be passed easily to children processes.\n **kwargs: Used for backwards compatibility.\n\n Returns:\n A `History` object. Its `History.history` attribute is\n a record of training loss values and metrics values\n at successive epochs, as well as validation loss values\n and validation metrics values (if applicable).\n\n Raises:\n RuntimeError: If the model was never compiled.\n ValueError: In case of mismatch between the provided input data\n and what the model expects.\n \"\"\"\n _keras_api_gauge.get_cell('fit').set(True)\n # Legacy support\n if 'nb_epoch' in kwargs:\n logging.warning(\n 'The `nb_epoch` argument in `fit` has been renamed `epochs`.')\n epochs = kwargs.pop('nb_epoch')\n if kwargs:\n raise TypeError('Unrecognized keyword arguments: ' + str(kwargs))\n self._assert_compile_was_called()\n self._check_call_args('fit')\n\n func = self._select_training_loop(x, callbacks)\n return func.fit(\n self,\n x=x,\n y=y,\n batch_size=batch_size,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n validation_split=validation_split,\n validation_data=validation_data,\n shuffle=shuffle,\n class_weight=class_weight,\n sample_weight=sample_weight,\n initial_epoch=initial_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_steps=validation_steps,\n validation_freq=validation_freq,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing)\n\n def evaluate(self,\n x=None,\n y=None,\n batch_size=None,\n verbose=1,\n sample_weight=None,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False):\n \"\"\"Returns the loss value & metrics values for the model in test mode.\n\n Computation is done in batches.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset.\n - A generator or `keras.utils.Sequence` instance.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely).\n If `x` is a dataset, generator or\n `keras.utils.Sequence` instance, `y` should not be specified (since\n targets will be obtained from the iterator/dataset).\n batch_size: Integer or `None`.\n Number of samples per gradient update.\n If unspecified, `batch_size` will default to 32.\n Do not specify the `batch_size` is your data is in the\n form of symbolic tensors, dataset,\n generators, or `keras.utils.Sequence` instances (since they generate\n batches).\n verbose: 0 or 1. Verbosity mode.\n 0 = silent, 1 = progress bar.\n sample_weight: Optional Numpy array of weights for\n the test samples, used for weighting the loss function.\n You can either pass a flat (1D)\n Numpy array with the same length as the input samples\n (1:1 mapping between weights and samples),\n or in the case of temporal data,\n you can pass a 2D array with shape\n `(samples, sequence_length)`,\n to apply a different weight to every timestep of every sample.\n In this case you should make sure to specify\n `sample_weight_mode=\"temporal\"` in `compile()`. This argument is not\n supported when `x` is a dataset, instead pass\n sample weights as the third element of `x`.\n steps: Integer or `None`.\n Total number of steps (batches of samples)\n before declaring the evaluation round finished.\n Ignored with the default value of `None`.\n If x is a `tf.data` dataset and `steps` is\n None, 'evaluate' will run until the dataset is exhausted.\n This argument is not supported with array inputs.\n callbacks: List of `keras.callbacks.Callback` instances.\n List of callbacks to apply during evaluation.\n See [callbacks](/api_docs/python/tf/keras/callbacks).\n max_queue_size: Integer. Used for generator or `keras.utils.Sequence`\n input only. Maximum size for the generator queue.\n If unspecified, `max_queue_size` will default to 10.\n workers: Integer. Used for generator or `keras.utils.Sequence` input\n only. Maximum number of processes to spin up when using\n process-based threading. If unspecified, `workers` will default\n to 1. If 0, will execute the generator on the main thread.\n use_multiprocessing: Boolean. Used for generator or\n `keras.utils.Sequence` input only. If `True`, use process-based\n threading. If unspecified, `use_multiprocessing` will default to\n `False`. Note that because this implementation relies on\n multiprocessing, you should not pass non-picklable arguments to\n the generator as they can't be passed easily to children processes.\n\n Returns:\n Scalar test loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: in case of invalid arguments.\n \"\"\"\n _keras_api_gauge.get_cell('evaluate').set(True)\n self._assert_compile_was_called()\n self._check_call_args('evaluate')\n\n func = self._select_training_loop(x, callbacks)\n return func.evaluate(\n self,\n x=x,\n y=y,\n batch_size=batch_size,\n verbose=verbose,\n sample_weight=sample_weight,\n steps=steps,\n callbacks=callbacks,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing)\n\n def predict(self,\n x,\n batch_size=None,\n verbose=0,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False):\n \"\"\"Generates output predictions for the input samples.\n\n Computation is done in batches.\n\n Arguments:\n x: Input samples. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A `tf.data` dataset.\n - A generator or `keras.utils.Sequence` instance.\n batch_size: Integer or `None`.\n Number of samples per gradient update.\n If unspecified, `batch_size` will default to 32.\n Do not specify the `batch_size` is your data is in the\n form of symbolic tensors, dataset,\n generators, or `keras.utils.Sequence` instances (since they generate\n batches).\n verbose: Verbosity mode, 0 or 1.\n steps: Total number of steps (batches of samples)\n before declaring the prediction round finished.\n Ignored with the default value of `None`. If x is a `tf.data`\n dataset and `steps` is None, `predict` will\n run until the input dataset is exhausted.\n callbacks: List of `keras.callbacks.Callback` instances.\n List of callbacks to apply during prediction.\n See [callbacks](/api_docs/python/tf/keras/callbacks).\n max_queue_size: Integer. Used for generator or `keras.utils.Sequence`\n input only. Maximum size for the generator queue.\n If unspecified, `max_queue_size` will default to 10.\n workers: Integer. Used for generator or `keras.utils.Sequence` input\n only. Maximum number of processes to spin up when using\n process-based threading. If unspecified, `workers` will default\n to 1. If 0, will execute the generator on the main thread.\n use_multiprocessing: Boolean. Used for generator or\n `keras.utils.Sequence` input only. If `True`, use process-based\n threading. If unspecified, `use_multiprocessing` will default to\n `False`. Note that because this implementation relies on\n multiprocessing, you should not pass non-picklable arguments to\n the generator as they can't be passed easily to children processes.\n\n\n Returns:\n Numpy array(s) of predictions.\n\n Raises:\n ValueError: In case of mismatch between the provided\n input data and the model's expectations,\n or in case a stateful model receives a number of samples\n that is not a multiple of the batch size.\n \"\"\"\n _keras_api_gauge.get_cell('predict').set(True)\n self._check_call_args('predict')\n\n func = self._select_training_loop(x, callbacks)\n return func.predict(\n self,\n x=x,\n batch_size=batch_size,\n verbose=verbose,\n steps=steps,\n callbacks=callbacks,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing)\n\n def reset_metrics(self):\n \"\"\"Resets the state of metrics.\"\"\"\n metrics = self._get_training_eval_metrics()\n for m in metrics:\n m.reset_states()\n\n # Reset metrics on all the distributed (cloned) models.\n if self._distribution_strategy:\n distributed_training_utils._reset_metrics(self) # pylint: disable=protected-access\n\n def train_on_batch(self,\n x,\n y=None,\n sample_weight=None,\n class_weight=None,\n reset_metrics=True):\n \"\"\"Runs a single gradient update on a single batch of data.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset.\n y: Target data. Like the input data `x`, it could be either Numpy\n array(s) or TensorFlow tensor(s). It should be consistent with `x`\n (you cannot have Numpy inputs and tensor targets, or inversely). If\n `x` is a dataset, `y` should not be specified\n (since targets will be obtained from the iterator).\n sample_weight: Optional array of the same length as x, containing\n weights to apply to the model's loss for each sample. In the case of\n temporal data, you can pass a 2D array with shape (samples,\n sequence_length), to apply a different weight to every timestep of\n every sample. In this case you should make sure to specify\n sample_weight_mode=\"temporal\" in compile(). This argument is not\n supported when `x` is a dataset.\n class_weight: Optional dictionary mapping class indices (integers) to a\n weight (float) to apply to the model's loss for the samples from this\n class during training. This can be useful to tell the model to \"pay\n more attention\" to samples from an under-represented class.\n reset_metrics: If `True`, the metrics returned will be only for this\n batch. If `False`, the metrics will be statefully accumulated across\n batches.\n\n Returns:\n Scalar training loss\n (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: In case of invalid user-provided arguments.\n \"\"\"\n self._assert_compile_was_called()\n self._check_call_args('train_on_batch')\n if self._experimental_run_tf_function:\n outputs = training_v2_utils.train_on_batch(\n self, x, y=y, sample_weight=sample_weight,\n class_weight=class_weight, reset_metrics=reset_metrics)\n outputs = [\n training_v2_utils._non_none_constant_value(v) for v in outputs] # pylint: disable=protected-access\n if len(outputs) == 1:\n outputs = outputs[0]\n return outputs\n\n # If at this point we are in the replica context, then it is okay to execute\n # the Eager code path. The expected way to get here is to call `fit` that\n # calls `train_on_batch` on each replica.\n if (self._distribution_strategy and\n distribution_strategy_context.in_cross_replica_context()):\n raise NotImplementedError('`train_on_batch` is not supported for models '\n 'distributed with tf.distribute.Strategy.')\n # Validate and standardize user data.\n x, y, sample_weights = self._standardize_user_data(\n x, y, sample_weight=sample_weight, class_weight=class_weight,\n extract_tensors_from_dataset=True)\n\n # If `self._distribution_strategy` is True, then we are in a replica context\n # at this point because of the check above. `train_on_batch` is being run\n # for each replica by `self._distribution_strategy` and the same code path\n # as Eager is expected to be taken.\n if self.run_eagerly or self._distribution_strategy:\n outputs = training_eager.train_on_batch(\n self,\n x,\n y,\n sample_weights=sample_weights,\n output_loss_metrics=self._output_loss_metrics)\n outputs = [\n training_v2_utils._non_none_constant_value(v) for v in outputs] # pylint: disable=protected-access\n else:\n x = training_utils.ModelInputs(x).as_list()\n ins = x + (y or []) + (sample_weights or [])\n\n if not isinstance(K.symbolic_learning_phase(), int):\n ins += [True] # Add learning phase value.\n\n self._update_sample_weight_modes(sample_weights=sample_weights)\n self._make_train_function()\n outputs = self.train_function(ins) # pylint: disable=not-callable\n\n if reset_metrics:\n self.reset_metrics()\n\n if len(outputs) == 1:\n return outputs[0]\n return outputs\n\n def test_on_batch(self, x, y=None, sample_weight=None, reset_metrics=True):\n \"\"\"Test the model on a single batch of samples.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely). If `x` is a dataset `y` should\n not be specified (since targets will be obtained from the iterator).\n sample_weight: Optional array of the same length as x, containing\n weights to apply to the model's loss for each sample.\n In the case of temporal data, you can pass a 2D array\n with shape (samples, sequence_length),\n to apply a different weight to every timestep of every sample.\n In this case you should make sure to specify\n sample_weight_mode=\"temporal\" in compile(). This argument is not\n supported when `x` is a dataset.\n reset_metrics: If `True`, the metrics returned will be only for this\n batch. If `False`, the metrics will be statefully accumulated across\n batches.\n\n Returns:\n Scalar test loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: In case of invalid user-provided arguments.\n \"\"\"\n self._assert_compile_was_called()\n self._check_call_args('test_on_batch')\n if self._experimental_run_tf_function:\n outputs = training_v2_utils.test_on_batch(\n self, x, y=y, sample_weight=sample_weight,\n reset_metrics=reset_metrics)\n outputs = [\n training_v2_utils._non_none_constant_value(v) for v in outputs] # pylint: disable=protected-access\n if len(outputs) == 1:\n outputs = outputs[0]\n return outputs\n\n if (self._distribution_strategy and\n distribution_strategy_context.in_cross_replica_context()):\n raise NotImplementedError('`test_on_batch` is not supported for models '\n 'distributed with tf.distribute.Strategy.')\n # Validate and standardize user data.\n x, y, sample_weights = self._standardize_user_data(\n x, y, sample_weight=sample_weight, extract_tensors_from_dataset=True)\n\n # If `self._distribution_strategy` is True, then we are in a replica context\n # at this point.\n if self.run_eagerly or self._distribution_strategy:\n outputs = training_eager.test_on_batch(\n self,\n x,\n y,\n sample_weights=sample_weights,\n output_loss_metrics=self._output_loss_metrics)\n outputs = [\n training_v2_utils._non_none_constant_value(v) for v in outputs] # pylint: disable=protected-access\n else:\n x = training_utils.ModelInputs(x).as_list()\n inputs = x + (y or []) + (sample_weights or [])\n\n self._update_sample_weight_modes(sample_weights=sample_weights)\n self._make_test_function()\n outputs = self.test_function(inputs) # pylint: disable=not-callable\n\n if reset_metrics:\n self.reset_metrics()\n\n if len(outputs) == 1:\n return outputs[0]\n return outputs\n\n def predict_on_batch(self, x):\n \"\"\"Returns predictions for a single batch of samples.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A `tf.data` dataset.\n\n Returns:\n Numpy array(s) of predictions.\n\n Raises:\n ValueError: In case of mismatch between given number of inputs and\n expectations of the model.\n \"\"\"\n self._check_call_args('predict_on_batch')\n if self._experimental_run_tf_function:\n return training_v2_utils.predict_on_batch(self, x)\n\n if (self._distribution_strategy and\n distribution_strategy_context.in_cross_replica_context()):\n raise NotImplementedError(\n '`predict_on_batch` is not supported for models distributed with'\n ' tf.distribute.Strategy.')\n # Validate and standardize user data.\n inputs, _, _ = self._standardize_user_data(\n x, extract_tensors_from_dataset=True)\n # If `self._distribution_strategy` is True, then we are in a replica context\n # at this point.\n if self.run_eagerly or self._distribution_strategy:\n inputs = training_utils.cast_if_floating_dtype(inputs)\n if isinstance(inputs, collections_abc.Sequence):\n # Unwrap lists with only one input, as we do when training on batch\n if len(inputs) == 1:\n inputs = inputs[0]\n\n return self(inputs) # pylint: disable=not-callable\n\n self._make_predict_function()\n outputs = self.predict_function(inputs)\n\n if len(outputs) == 1:\n return outputs[0]\n return outputs\n\n def fit_generator(self,\n generator,\n steps_per_epoch=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_data=None,\n validation_steps=None,\n validation_freq=1,\n class_weight=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n shuffle=True,\n initial_epoch=0):\n \"\"\"Fits the model on data yielded batch-by-batch by a Python generator.\n\n The generator is run in parallel to the model, for efficiency.\n For instance, this allows you to do real-time data augmentation\n on images on CPU in parallel to training your model on GPU.\n\n The use of `keras.utils.Sequence` guarantees the ordering\n and guarantees the single use of every input per epoch when\n using `use_multiprocessing=True`.\n\n Arguments:\n generator: A generator or an instance of `Sequence`\n (`keras.utils.Sequence`)\n object in order to avoid duplicate data\n when using multiprocessing.\n The output of the generator must be either\n - a tuple `(inputs, targets)`\n - a tuple `(inputs, targets, sample_weights)`.\n This tuple (a single output of the generator) makes a single batch.\n Therefore, all arrays in this tuple must have the same length (equal\n to the size of this batch). Different batches may have different\n sizes.\n For example, the last batch of the epoch is commonly smaller than\n the\n others, if the size of the dataset is not divisible by the batch\n size.\n The generator is expected to loop over its data\n indefinitely. An epoch finishes when `steps_per_epoch`\n batches have been seen by the model.\n steps_per_epoch: Total number of steps (batches of samples)\n to yield from `generator` before declaring one epoch\n finished and starting the next epoch. It should typically\n be equal to the number of samples of your dataset\n divided by the batch size.\n Optional for `Sequence`: if unspecified, will use\n the `len(generator)` as a number of steps.\n epochs: Integer, total number of iterations on the data.\n verbose: Verbosity mode, 0, 1, or 2.\n callbacks: List of callbacks to be called during training.\n validation_data: This can be either\n - a generator for the validation data\n - a tuple (inputs, targets)\n - a tuple (inputs, targets, sample_weights).\n validation_steps: Only relevant if `validation_data`\n is a generator. Total number of steps (batches of samples)\n to yield from `generator` before stopping.\n Optional for `Sequence`: if unspecified, will use\n the `len(validation_data)` as a number of steps.\n validation_freq: Only relevant if validation data is provided. Integer\n or `collections_abc.Container` instance (e.g. list, tuple, etc.).\n If an integer, specifies how many training epochs to run before a\n new validation run is performed, e.g. `validation_freq=2` runs\n validation every 2 epochs. If a Container, specifies the epochs on\n which to run validation, e.g. `validation_freq=[1, 2, 10]` runs\n validation at the end of the 1st, 2nd, and 10th epochs.\n class_weight: Dictionary mapping class indices to a weight\n for the class.\n max_queue_size: Integer. Maximum size for the generator queue.\n If unspecified, `max_queue_size` will default to 10.\n workers: Integer. Maximum number of processes to spin up\n when using process-based threading.\n If unspecified, `workers` will default to 1. If 0, will\n execute the generator on the main thread.\n use_multiprocessing: Boolean.\n If `True`, use process-based threading.\n If unspecified, `use_multiprocessing` will default to `False`.\n Note that because this implementation relies on multiprocessing,\n you should not pass non-picklable arguments to the generator\n as they can't be passed easily to children processes.\n shuffle: Boolean. Whether to shuffle the order of the batches at\n the beginning of each epoch. Only used with instances\n of `Sequence` (`keras.utils.Sequence`).\n Has no effect when `steps_per_epoch` is not `None`.\n initial_epoch: Epoch at which to start training\n (useful for resuming a previous training run)\n\n Returns:\n A `History` object.\n\n Example:\n\n ```python\n def generate_arrays_from_file(path):\n while 1:\n f = open(path)\n for line in f:\n # create numpy arrays of input data\n # and labels, from each line in the file\n x1, x2, y = process_line(line)\n yield ({'input_1': x1, 'input_2': x2}, {'output': y})\n f.close()\n\n model.fit_generator(generate_arrays_from_file('/my_file.txt'),\n steps_per_epoch=10000, epochs=10)\n ```\n Raises:\n ValueError: In case the generator yields data in an invalid format.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`fit_generator` is not supported for '\n 'models compiled with tf.distribute.Strategy.')\n _keras_api_gauge.get_cell('fit_generator').set(True)\n self._check_call_args('fit_generator')\n return training_generator.fit_generator(\n self,\n generator,\n steps_per_epoch=steps_per_epoch,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n validation_data=validation_data,\n validation_steps=validation_steps,\n validation_freq=validation_freq,\n class_weight=class_weight,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n shuffle=shuffle,\n initial_epoch=initial_epoch,\n steps_name='steps_per_epoch')\n\n def evaluate_generator(self,\n generator,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n verbose=0):\n \"\"\"Evaluates the model on a data generator.\n\n The generator should return the same kind of data\n as accepted by `test_on_batch`.\n\n Arguments:\n generator: Generator yielding tuples (inputs, targets)\n or (inputs, targets, sample_weights)\n or an instance of `keras.utils.Sequence`\n object in order to avoid duplicate data\n when using multiprocessing.\n steps: Total number of steps (batches of samples)\n to yield from `generator` before stopping.\n Optional for `Sequence`: if unspecified, will use\n the `len(generator)` as a number of steps.\n callbacks: List of `keras.callbacks.Callback` instances.\n List of callbacks to apply during evaluation.\n See [callbacks](/api_docs/python/tf/keras/callbacks).\n max_queue_size: maximum size for the generator queue\n workers: Integer. Maximum number of processes to spin up\n when using process-based threading.\n If unspecified, `workers` will default to 1. If 0, will\n execute the generator on the main thread.\n use_multiprocessing: Boolean.\n If `True`, use process-based threading.\n If unspecified, `use_multiprocessing` will default to `False`.\n Note that because this implementation relies on multiprocessing,\n you should not pass non-picklable arguments to the generator\n as they can't be passed easily to children processes.\n verbose: Verbosity mode, 0 or 1.\n\n Returns:\n Scalar test loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: in case of invalid arguments.\n\n Raises:\n ValueError: In case the generator yields data in an invalid format.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`evaluate_generator` is not supported for '\n 'models compiled with tf.distribute.Strategy.')\n _keras_api_gauge.get_cell('evaluate_generator').set(True)\n self._check_call_args('evaluate_generator')\n\n return training_generator.evaluate_generator(\n self,\n generator,\n steps=steps,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n verbose=verbose,\n callbacks=callbacks)\n\n def predict_generator(self,\n generator,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n verbose=0):\n \"\"\"Generates predictions for the input samples from a data generator.\n\n The generator should return the same kind of data as accepted by\n `predict_on_batch`.\n\n Arguments:\n generator: Generator yielding batches of input samples\n or an instance of `keras.utils.Sequence` object in order to\n avoid duplicate data when using multiprocessing.\n steps: Total number of steps (batches of samples)\n to yield from `generator` before stopping.\n Optional for `Sequence`: if unspecified, will use\n the `len(generator)` as a number of steps.\n callbacks: List of `keras.callbacks.Callback` instances.\n List of callbacks to apply during prediction.\n See [callbacks](/api_docs/python/tf/keras/callbacks).\n max_queue_size: Maximum size for the generator queue.\n workers: Integer. Maximum number of processes to spin up\n when using process-based threading.\n If unspecified, `workers` will default to 1. If 0, will\n execute the generator on the main thread.\n use_multiprocessing: Boolean.\n If `True`, use process-based threading.\n If unspecified, `use_multiprocessing` will default to `False`.\n Note that because this implementation relies on multiprocessing,\n you should not pass non-picklable arguments to the generator\n as they can't be passed easily to children processes.\n verbose: verbosity mode, 0 or 1.\n\n Returns:\n Numpy array(s) of predictions.\n\n Raises:\n ValueError: In case the generator yields data in an invalid format.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`predict_generator` is not supported for '\n 'models compiled with tf.distribute.Strategy.')\n _keras_api_gauge.get_cell('predict_generator').set(True)\n return training_generator.predict_generator(\n self,\n generator,\n steps=steps,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n verbose=verbose,\n callbacks=callbacks)\n\n def _check_call_args(self, method_name):\n \"\"\"Check that `call` has only one positional arg.\"\"\"\n # Always allow first arg, regardless of arg name.\n fullargspec = tf_inspect.getfullargspec(self.call)\n if fullargspec.defaults:\n positional_args = fullargspec.args[:-len(fullargspec.defaults)]\n else:\n positional_args = fullargspec.args\n if 'training' in positional_args:\n positional_args.remove('training')\n\n # self and first arg can be positional.\n if len(positional_args) > 2:\n extra_args = positional_args[2:]\n raise ValueError(\n 'Models passed to `' + method_name + '` can only have `training` '\n 'and the first argument in `call` as positional arguments, '\n 'found: ' + str(extra_args) + '.')\n\n def _prepare_validation_data(self, validation_data, batch_size,\n validation_steps):\n \"\"\"Unpack and check the validation data.\"\"\"\n val_x, val_y, val_sample_weights = training_utils.unpack_validation_data(\n validation_data)\n return self._standardize_user_data(\n val_x,\n val_y,\n sample_weight=val_sample_weights,\n batch_size=batch_size,\n steps=validation_steps,\n steps_name='validation_steps')\n\n def _validate_compile_param_for_distribution_strategy(\n self, run_eagerly, sample_weight_mode, target_tensors, weighted_metrics):\n # Validate that arguments passed by the user to `compile` are supported by\n # tf.distribute.Strategy.\n if self._distribution_strategy:\n if sample_weight_mode:\n raise NotImplementedError('sample_weight_mode is not supported with '\n 'tf.distribute.Strategy.')\n if weighted_metrics:\n raise NotImplementedError('weighted_metrics is not supported with '\n 'tf.distribute.Strategy.')\n if target_tensors:\n raise ValueError('target_tensors is not supported with '\n 'tf.distribute.Strategy.')\n\n if run_eagerly:\n raise ValueError(\n 'We currently do not support enabling `run_eagerly` with '\n 'distribution strategy.')\n\n if (distributed_training_utils.is_distributing_by_cloning(self) and\n (not self.built or not self.inputs or not self.outputs)):\n raise ValueError(\n 'We currently do not support distribution strategy with a '\n '`Sequential` model that is created without `input_shape`/'\n '`input_dim` set in its first layer or a subclassed model.')\n\n def _process_target_tensor_for_compile(self, target_tensors):\n if self.run_eagerly:\n # target tensor is not supported with run_eagerly. Create a list with None\n # as placeholder for each output.\n return [None for _ in self.output_names]\n\n if target_tensors not in (None, []):\n if isinstance(target_tensors, list):\n if len(target_tensors) != len(self.outputs):\n raise ValueError(\n 'When passing a list as `target_tensors`, '\n 'it should have one entry per model output. '\n 'The model has %s outputs, but you passed target_tensors=%s' %\n (len(self.outputs), target_tensors))\n elif isinstance(target_tensors, dict):\n unexpected_target_tensor_names = set(target_tensors.keys()).difference(\n self.output_names)\n if unexpected_target_tensor_names:\n raise ValueError(\n 'Unknown entry in `target_tensors` dictionary: \"{name}\". '\n 'Only expected the following keys: {keys}'.format(\n name=unexpected_target_tensor_names,\n keys=str(self.output_names)))\n tmp_target_tensors = []\n for name in self.output_names:\n tmp_target_tensors.append(target_tensors.get(name, None))\n target_tensors = tmp_target_tensors\n elif tensor_util.is_tensor(target_tensors):\n target_tensors = [target_tensors]\n else:\n raise TypeError('Expected `target_tensors` to be a list or tuple or '\n 'dict or a single tensor, but got:', target_tensors)\n else:\n # In case target tensor is empty or None, create a list with Nones\n # that has same length as self.output_names. With that, the None check of\n # target tensor can be skipped downstream.\n target_tensors = [None for _ in self.output_names]\n return target_tensors\n\n def _compile_eagerly(self, metrics, weighted_metrics, sample_weight_mode):\n # Prepare sample weight modes. List with the same length as model outputs.\n training_utils.prepare_sample_weight_modes(\n self._training_endpoints, sample_weight_mode)\n # Prepare sample weights.\n self._prepare_sample_weights()\n # Save all metric attributes per output of the model.\n self._cache_output_metric_attributes(metrics, weighted_metrics)\n self.total_loss = None\n # Set metric attributes on model.\n self._set_metric_attributes()\n\n self._collected_trainable_weights = self._unique_trainable_weights\n\n def _update_sample_weight_modes(self, sample_weights=None):\n \"\"\"Updates sample weight modes based on training/eval inputs.\n\n Sample weight placeholders will be created for all or no outputs\n based on whether sample_weight is provided for any output.\n\n If model contains `_sample_weight_modes` we check if the input\n `sample_weights` corresponds to the sample weight modes.\n 1. Set sample weight mode to be 'temporal' for output i, if `compile`\n sample_weight_mode was set to `temporal` and sample weight inputs\n are given for one or more outputs.\n 2. Set sample weight mode to be 'samplewise' for output i, if `compile`\n sample_weight_mode was not set and sample weight inputs are given for\n one or more outputs.\n 3. Reset sample weight mode to None for output i if sample weight mode\n was set but there is no sample weight input.\n\n Args:\n sample_weights: List of sample weights of the same length as model outputs\n or None.\n \"\"\"\n if not self._is_compiled:\n return\n if sample_weights and any([s is not None for s in sample_weights]):\n for endpoint in self._training_endpoints:\n endpoint.sample_weight_mode = (\n endpoint.sample_weight_mode or 'samplewise')\n else:\n for endpoint in self._training_endpoints:\n endpoint.sample_weight_mode = None\n\n def _recompile_weights_loss_and_weighted_metrics(self):\n if not self._is_compiled:\n return False\n recompile = any([e.sample_weights_mismatch()\n for e in self._training_endpoints])\n\n if recompile:\n self._compile_weights_loss_and_weighted_metrics()\n return recompile\n\n @trackable.no_automatic_dependency_tracking\n def _compile_weights_loss_and_weighted_metrics(self, sample_weights=None):\n \"\"\"Compiles the model loss and weighted metric sub-graphs.\n\n This may be used to set graph tensors as sample weights (instead of creating\n placeholders). This functionality is necessary for\n `tf.keras.estimator.model_to_estimator`, which calls Keras models in a v1\n graph, and creates iterator tensors for inputs, targets, and sample weights.\n\n Args:\n sample_weights: List of tensors to use as the sample weights. Must be the\n same length as the number of outputs. If left as `None`, placeholders\n are used instead.\n \"\"\"\n with K.get_graph().as_default():\n if sample_weights is not None:\n self._update_sample_weight_modes(sample_weights)\n self._prepare_sample_weights(sample_weights)\n\n masks = self._prepare_output_masks()\n\n # Compute weighted metrics.\n self._handle_metrics(\n self.outputs,\n targets=self._targets,\n skip_target_masks=self._prepare_skip_target_masks(),\n sample_weights=self.sample_weights,\n masks=masks,\n return_weighted_metrics=True)\n\n # Compute total loss.\n # Used to keep track of the total loss value (stateless).\n # eg., total_loss = loss_weight_1 * output_1_loss_fn(...) +\n # loss_weight_2 * output_2_loss_fn(...) +\n # layer losses.\n self.total_loss = self._prepare_total_loss(masks)\n\n def _prepare_skip_target_masks(self):\n \"\"\"Boolean mask for whether the target in the output list should be skipped.\n\n If the loss function corresponding to a model output is None, then this\n output will be skipped during total loss calculation and feed targets\n preparation.\n\n Returns:\n A boolean list for whether the corresponding target in the output list\n should be skipped during loss calculation.\n \"\"\"\n return [l is None for l in self.loss_functions]\n\n def _prepare_output_masks(self):\n \"\"\"Returns masks corresponding to model outputs.\"\"\"\n return [getattr(x, '_keras_mask', None) for x in self.outputs]\n\n def _prepare_total_loss(self, masks):\n \"\"\"Computes total loss from loss functions.\n\n Arguments:\n masks: List of mask values corresponding to each model output.\n\n Returns:\n A list of loss weights of python floats.\n\n Raises:\n TypeError: If model run_eagerly is True.\n \"\"\"\n if self.run_eagerly:\n raise TypeError('total loss can not be computed when compiled with '\n 'run_eagerly = True.')\n total_loss = None\n with K.name_scope('loss'):\n for endpoint, mask in zip(self._training_endpoints, masks):\n if endpoint.should_skip_target():\n continue\n y_true = endpoint.training_target.target\n y_pred = endpoint.output\n loss_fn = endpoint.loss_fn\n loss_weight = endpoint.loss_weight\n loss_name = endpoint.loss_name()\n sample_weight = endpoint.sample_weight\n\n with K.name_scope(loss_name):\n if mask is not None:\n mask = math_ops.cast(mask, y_pred.dtype)\n # Update weights with mask.\n if sample_weight is None:\n sample_weight = mask\n else:\n # Update dimensions of weights to match with mask if possible.\n mask, _, sample_weight = (\n tf_losses_utils.squeeze_or_expand_dimensions(\n mask, sample_weight=sample_weight))\n sample_weight *= mask\n\n if hasattr(loss_fn, 'reduction'):\n per_sample_losses = loss_fn.call(y_true, y_pred)\n weighted_losses = losses_utils.compute_weighted_loss(\n per_sample_losses,\n sample_weight=sample_weight,\n reduction=losses_utils.ReductionV2.NONE)\n loss_reduction = loss_fn.reduction\n\n # `AUTO` loss reduction defaults to `SUM_OVER_BATCH_SIZE` for all\n # compile use cases.\n if loss_reduction == losses_utils.ReductionV2.AUTO:\n loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE\n\n # Compute the stateless loss value.\n output_loss = losses_utils.reduce_weighted_loss(\n weighted_losses, reduction=loss_reduction)\n else:\n # Compute the stateless loss value for a custom loss class.\n # Here we assume that the class takes care of loss reduction\n # because if this class returns a vector value we cannot\n # differentiate between use case where a custom optimizer\n # expects a vector loss value vs unreduced per-sample loss value.\n output_loss = loss_fn(y_true, y_pred, sample_weight=sample_weight)\n loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE\n\n if len(self.outputs) > 1:\n # Keep track of stateful result tensor for the loss.\n endpoint.output_loss_metric(output_loss)\n\n # Scale output loss for distribution. For custom losses we assume\n # reduction was mean.\n if loss_reduction == losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE:\n output_loss = losses_utils.scale_loss_for_distribution(output_loss)\n\n if total_loss is None:\n total_loss = loss_weight * output_loss\n else:\n total_loss += loss_weight * output_loss\n if total_loss is None:\n if not self.losses:\n raise ValueError('The model cannot be compiled '\n 'because it has no loss to optimize.')\n else:\n total_loss = 0.\n\n # Add regularization penalties and other layer-specific losses.\n custom_losses = self.get_losses_for(None) + self.get_losses_for(\n self.inputs)\n if custom_losses:\n total_loss += losses_utils.scale_loss_for_distribution(\n math_ops.add_n(custom_losses))\n return total_loss\n\n def _get_callback_model(self):\n \"\"\"Returns the Callback Model for this Model.\"\"\"\n\n if hasattr(self, '_replicated_model') and self._replicated_model:\n # When using training_distributed, we set the callback model\n # to an instance of the `DistributedModel` that we create in\n # the `compile` call. The `DistributedModel` is initialized\n # with the first replicated model. We need to set the callback\n # model to a DistributedModel to allow us to override saving\n # and loading weights when we checkpoint the model during training.\n return self._replicated_model\n if hasattr(self, 'callback_model') and self.callback_model:\n return self.callback_model\n return self\n\n def _make_callback_model(self, grouped_model):\n first_replicated_model = self._distribution_strategy.unwrap(\n grouped_model)[0]\n # We initialize the callback model with the first replicated model.\n self._replicated_model = DistributedCallbackModel(first_replicated_model)\n self._replicated_model.set_original_model(self)\n\n def _validate_or_infer_batch_size(self, batch_size, steps, x):\n \"\"\"Validates that the `batch_size` provided is consistent with InputLayer.\n\n It's possible that the user specified a static batch size in their\n InputLayer. If so, this method checks the provided `batch_size` and `x`\n arguments are consistent with this static batch size. Also, if\n `batch_size` is `None`, this method will attempt to infer the batch size\n from the static batch size of the InputLayer. Lastly, ValueError will be\n raised if `x` is a tf.data.Dataset and `batch_size` is specified as we\n expect users to provide batched datasets.\n\n Arguments:\n batch_size: The batch_size provided as an argument to\n fit/evaluate/predict.\n steps: The steps provided as an argument to fit/evaluate/predict.\n x: The data passed as `x` to fit/evaluate/predict.\n\n Returns:\n The validated batch_size, auto-inferred from the first layer if not\n provided.\n \"\"\"\n if batch_size is not None and isinstance(x, dataset_ops.DatasetV2):\n raise ValueError('The `batch_size` argument must not be specified when'\n ' using dataset as an input.')\n\n layers = super(Model, self).layers # Avoids the override in Sequential.\n if layers:\n first_layer = layers[0]\n static_batch_size = training_utils.get_static_batch_size(first_layer)\n if static_batch_size is not None:\n split_batch_size = self._distribution_strategy and \\\n distributed_training_utils.global_batch_size_supported(\n self._distribution_strategy)\n if split_batch_size:\n num_replicas = self._distribution_strategy.num_replicas_in_sync\n\n # Check `batch_size` argument is consistent with InputLayer.\n if batch_size is not None:\n if split_batch_size:\n if batch_size % num_replicas != 0:\n raise ValueError('The `batch_size` argument value {} cannot be '\n 'divisible by number of replicas {}'.format(\n batch_size, num_replicas))\n per_replica_batch_size = batch_size // num_replicas\n else:\n per_replica_batch_size = batch_size\n\n if per_replica_batch_size != static_batch_size:\n raise ValueError('The `batch_size` argument value {} is '\n 'incompatible with the specified batch size of '\n 'your Input Layer: {}'.format(\n per_replica_batch_size, static_batch_size))\n\n # Check Dataset/Iterator batch size is consistent with InputLayer.\n if isinstance(x, (dataset_ops.DatasetV2, iterator_ops.Iterator,\n iterator_ops.IteratorV2)):\n ds_batch_size = tensor_shape.as_dimension(\n nest.flatten(dataset_ops.get_legacy_output_shapes(x))[0][0]).value\n if ds_batch_size is not None:\n if split_batch_size:\n if ds_batch_size % num_replicas != 0:\n raise ValueError(\n 'The batch output shape of your `Dataset` {} '\n 'cannot be divisible by number of replicas {}'.format(\n ds_batch_size, num_replicas))\n ds_batch_size = ds_batch_size // num_replicas\n\n if ds_batch_size != static_batch_size:\n raise ValueError('The batch output shape of your `Dataset` is '\n '{}, which is incompatible with the specified '\n 'batch size of your Input Layer: {}'.format(\n ds_batch_size, static_batch_size))\n\n # Set inferred batch size from the InputLayer.\n if steps is None:\n batch_size = static_batch_size\n\n if (batch_size is None\n and steps is None\n and not isinstance(x, (dataset_ops.DatasetV2,\n iterator_ops.Iterator,\n iterator_ops.IteratorV2,\n data_utils.Sequence))\n and not tf_inspect.isgenerator(x)):\n # Backwards compatibility\n batch_size = 32\n return batch_size\n\n def _prepare_sample_weights(self, sample_weights=None):\n \"\"\"Sets sample weight attribute on the model.\"\"\"\n # List with the same length as model outputs.\n if sample_weights is not None:\n if len(sample_weights) != len(self._training_endpoints):\n raise ValueError('Provided sample weights must have same length as the '\n 'number of outputs. Expected: {}, got: {}.'.format(\n len(self._training_endpoints),\n len(sample_weights)))\n else:\n sample_weights = [None] * len(self._training_endpoints)\n for endpoint, weight in zip(self._training_endpoints, sample_weights):\n endpoint.populate_sample_weight(weight, endpoint.sample_weight_mode)\n\n def _cache_output_metric_attributes(self, metrics, weighted_metrics):\n \"\"\"Caches metric name and function attributes for every model output.\"\"\"\n output_shapes = []\n for output in self.outputs:\n if output is None or output.shape.rank is None:\n output_shapes.append(None)\n else:\n output_shapes.append(output.shape.as_list())\n self._per_output_metrics = training_utils.collect_per_output_metric_info(\n metrics, self.output_names, output_shapes, self.loss_functions)\n self._per_output_weighted_metrics = (\n training_utils.collect_per_output_metric_info(\n weighted_metrics,\n self.output_names,\n output_shapes,\n self.loss_functions,\n is_weighted=True))\n\n def _add_unique_metric_name(self, metric_name, output_index):\n \"\"\"Makes the metric name unique and adds it to the model's metric name list.\n\n If there are multiple outputs for which the metrics are calculated, the\n metric names have to be made unique by appending an integer.\n\n Arguments:\n metric_name: Metric name that corresponds to the metric specified by the\n user. For example: 'acc'.\n output_index: The index of the model output for which the metric name is\n being added.\n\n Returns:\n string, name of the model's unique metric name\n \"\"\"\n if len(self.output_names) > 1:\n metric_name = '%s_%s' % (self.output_names[output_index], metric_name)\n j = 1\n base_metric_name = metric_name\n while metric_name in self.metrics_names:\n metric_name = '%s_%d' % (base_metric_name, j)\n j += 1\n\n return metric_name\n\n def _init_metric_attributes(self):\n \"\"\"Initialized model metric attributes.\"\"\"\n # List of stateful metric functions. Used for resetting metric state during\n # training/eval.\n self._compile_metric_functions = []\n\n def _set_per_output_metric_attributes(self, metrics_dict, output_index):\n \"\"\"Sets the metric attributes on the model for the given output.\n\n Arguments:\n metrics_dict: A dict with metric names as keys and metric fns as values.\n output_index: The index of the model output for which the metric\n attributes are added.\n\n Returns:\n Metrics dict updated with unique metric names as keys.\n \"\"\"\n updated_metrics_dict = collections.OrderedDict()\n for metric_name, metric_fn in metrics_dict.items():\n metric_name = self._add_unique_metric_name(metric_name, output_index)\n\n # Update the name on the metric class to be the unique generated name.\n metric_fn._name = metric_name # pylint: disable=protected-access\n updated_metrics_dict[metric_name] = metric_fn\n # Keep track of metric name and function.\n self._compile_metric_functions.append(metric_fn)\n return updated_metrics_dict\n\n def _set_metric_attributes(self):\n \"\"\"Sets the metric attributes on the model for all the model outputs.\"\"\"\n updated_per_output_metrics = []\n updated_per_output_weighted_metrics = []\n for i, endpoint in enumerate(self._training_endpoints):\n if endpoint.should_skip_target():\n updated_per_output_metrics.append(self._per_output_metrics[i])\n updated_per_output_weighted_metrics.append(\n self._per_output_weighted_metrics[i])\n continue\n updated_per_output_metrics.append(\n self._set_per_output_metric_attributes(self._per_output_metrics[i],\n i))\n updated_per_output_weighted_metrics.append(\n self._set_per_output_metric_attributes(\n self._per_output_weighted_metrics[i], i))\n\n # Create a metric wrapper for each output loss. This computes mean of an\n # output loss across mini-batches (irrespective of how we reduce within a\n # batch).\n if len(self._training_endpoints) > 1:\n for endpoint in self._training_endpoints:\n if not endpoint.should_skip_target():\n endpoint.output_loss_metric = metrics_module.Mean(\n name=endpoint.loss_name())\n\n self._per_output_metrics = updated_per_output_metrics\n self._per_output_weighted_metrics = updated_per_output_weighted_metrics\n\n def _handle_per_output_metrics(self,\n metrics_dict,\n y_true,\n y_pred,\n mask,\n weights=None):\n \"\"\"Calls metric functions for a single output.\n\n Arguments:\n metrics_dict: A dict with metric names as keys and metric fns as values.\n y_true: Target output.\n y_pred: Predicted output.\n mask: Computed mask value for the current output.\n weights: Weights to be applied on the current output.\n\n Returns:\n A list of metric result tensors.\n \"\"\"\n metric_results = []\n for metric_name, metric_fn in metrics_dict.items():\n with K.name_scope(metric_name):\n metric_result = training_utils.call_metric_function(\n metric_fn, y_true, y_pred, weights=weights, mask=mask)\n metric_results.append(metric_result)\n return metric_results\n\n def _handle_metrics(self,\n outputs,\n targets=None,\n skip_target_masks=None,\n sample_weights=None,\n masks=None,\n return_weighted_metrics=False,\n return_weighted_and_unweighted_metrics=False):\n \"\"\"Handles calling metric functions.\n\n Arguments:\n outputs: List of outputs (predictions).\n targets: List of targets.\n skip_target_masks: Optional. List of boolean for whether the corresponding\n target should be ignored or not.\n sample_weights: Optional list of sample weight arrays.\n masks: List of computed output mask values.\n return_weighted_metrics: Flag that indicates whether weighted metrics\n should be computed instead of unweighted metrics. This flag is ignored\n when `return_weighted_and_unweighted_metrics` is enabled.\n return_weighted_and_unweighted_metrics: Flag that is used to indicate\n whether both weighted and unweighted metrics should be computed. When\n this is not enabled, we use `return_weighted_metrics` param to indicate\n whether weighted or unweighted metrics should be returned.\n\n Returns:\n A list of metric result tensors.\n \"\"\"\n # TODO(scottzhu): Update this to use the new training_endpoints. Currently\n # the eager and graph logic is bit different.\n skip_target_masks = skip_target_masks or [False] * len(outputs)\n metric_results = []\n with K.name_scope('metrics'):\n # Invoke all metrics added using `compile`.\n for i in range(len(outputs)):\n if skip_target_masks[i]:\n continue\n output = outputs[i] if outputs else None\n target = targets[i] if targets else None\n output_mask = masks[i] if masks else None\n\n if (return_weighted_and_unweighted_metrics or\n not return_weighted_metrics):\n metric_results.extend(\n self._handle_per_output_metrics(self._per_output_metrics[i],\n target, output, output_mask))\n if return_weighted_and_unweighted_metrics or return_weighted_metrics:\n metric_results.extend(\n self._handle_per_output_metrics(\n self._per_output_weighted_metrics[i],\n target,\n output,\n output_mask,\n weights=sample_weights[i] if sample_weights else None))\n return metric_results\n\n def _check_trainable_weights_consistency(self):\n \"\"\"Check trainable weights count consistency.\n\n This will raise a warning if `trainable_weights` and\n `_collected_trainable_weights` are inconsistent (i.e. have different\n number of parameters).\n Inconsistency will typically arise when one modifies `model.trainable`\n without calling `model.compile` again.\n \"\"\"\n if not hasattr(self, '_collected_trainable_weights'):\n return\n\n if (len(self._unique_trainable_weights) !=\n len(self._collected_trainable_weights)):\n logging.log_first_n(\n logging.WARN, 'Discrepancy between trainable weights and collected'\n ' trainable weights, did you set `model.trainable`'\n ' without calling `model.compile` after ?', 1)\n\n def _make_train_function(self):\n has_recompiled = self._recompile_weights_loss_and_weighted_metrics()\n self._check_trainable_weights_consistency()\n if isinstance(self.optimizer, list):\n raise ValueError('The `optimizer` in `compile` should be a single '\n 'optimizer.')\n # If we have re-compiled the loss/weighted metric sub-graphs then create\n # train function even if one exists already. This is because\n # `_feed_sample_weights` list has been updated on re-copmpile.\n if getattr(self, 'train_function', None) is None or has_recompiled:\n # Restore the compiled trainable state.\n current_trainable_state = self._get_trainable_state()\n self._set_trainable_state(self._compiled_trainable_state)\n\n inputs = (self._feed_inputs +\n self._feed_targets +\n self._feed_sample_weights)\n if not isinstance(K.symbolic_learning_phase(), int):\n inputs += [K.symbolic_learning_phase()]\n\n with K.get_graph().as_default():\n with K.name_scope('training'):\n # Training updates\n updates = self.optimizer.get_updates(\n params=self._collected_trainable_weights, loss=self.total_loss)\n # Unconditional updates\n updates += self.get_updates_for(None)\n # Conditional updates relevant to this model\n updates += self.get_updates_for(self.inputs)\n\n metrics = self._get_training_eval_metrics()\n metrics_tensors = [\n m._call_result for m in metrics if hasattr(m, '_call_result') # pylint: disable=protected-access\n ]\n\n with K.name_scope('training'):\n # Gets loss and metrics. Updates weights at each call.\n fn = K.function(\n inputs, [self.total_loss] + metrics_tensors,\n updates=updates,\n name='train_function',\n **self._function_kwargs)\n setattr(self, 'train_function', fn)\n\n # Restore the current trainable state\n self._set_trainable_state(current_trainable_state)\n\n def _make_test_function(self):\n has_recompiled = self._recompile_weights_loss_and_weighted_metrics()\n # If we have re-compiled the loss/weighted metric sub-graphs then create\n # test function even if one exists already. This is because\n # `_feed_sample_weights` list has been updated on re-copmpile.\n if getattr(self, 'test_function', None) is None or has_recompiled:\n inputs = (self._feed_inputs +\n self._feed_targets +\n self._feed_sample_weights)\n\n with K.get_graph().as_default():\n metrics = self._get_training_eval_metrics()\n metrics_tensors = [\n m._call_result for m in metrics if hasattr(m, '_call_result') # pylint: disable=protected-access\n ]\n\n with K.name_scope('evaluation'):\n updates = self.state_updates\n # Return loss and metrics, no gradient updates.\n # Does update the network states.\n fn = K.function(\n inputs, [self.total_loss] + metrics_tensors,\n updates=updates,\n name='test_function',\n **self._function_kwargs)\n setattr(self, 'test_function', fn)\n\n def _make_predict_function(self):\n if not hasattr(self, 'predict_function'):\n self.predict_function = None\n if self.predict_function is None:\n inputs = self._feed_inputs\n # Gets network outputs. Does not update weights.\n # Does update the network states.\n kwargs = getattr(self, '_function_kwargs', {})\n with K.name_scope(ModeKeys.PREDICT):\n self.predict_function = K.function(\n inputs,\n self.outputs,\n updates=self.state_updates,\n name='predict_function',\n **kwargs)\n\n def _make_execution_function(self, mode):\n if mode == ModeKeys.TRAIN:\n self._make_train_function()\n return self.train_function\n if mode == ModeKeys.TEST:\n self._make_test_function()\n return self.test_function\n if mode == ModeKeys.PREDICT:\n self._make_predict_function()\n return self.predict_function\n\n def _distribution_standardize_user_data(self,\n x,\n y=None,\n sample_weight=None,\n class_weight=None,\n batch_size=None,\n validation_split=0,\n shuffle=False,\n epochs=1,\n allow_partial_batch=False):\n \"\"\"Runs validation checks on input and target data passed by the user.\n\n This is called when using tf.distribute.Strategy to train, evaluate or serve\n the model.\n\n Args:\n x: Input data. A numpy array or `tf.data` dataset.\n y: Target data. A numpy array or None if x is a `tf.data` dataset.\n sample_weight: An optional sample-weight array passed by the user to\n weight the importance of each sample in `x`.\n class_weight: An optional class-weight array by the user to\n weight the importance of samples in `x` based on the class they belong\n to, as conveyed by `y`.\n batch_size: Integer batch size. If provided, it is used to run additional\n validation checks on stateful models.\n validation_split: Float between 0 and 1.\n Fraction of the training data to be used as validation data.\n shuffle: Boolean whether to shuffle the training data before each epoch.\n epochs: Integer epochs. If > 1, repeat the numpy training data epochs\n times when converting to training dataset.\n allow_partial_batch: Boolean whether to enforce that all batches have the\n same size.\n\n Returns:\n Dataset instance.\n\n Raises:\n ValueError: In case of invalid user-provided data.\n RuntimeError: If the model was never compiled.\n \"\"\"\n if class_weight:\n raise NotImplementedError('`class_weight` is currently not supported '\n 'when using tf.distribute.Strategy.')\n\n if (sample_weight is not None and sample_weight.all() and\n distributed_training_utils.is_tpu_strategy(\n self._distribution_strategy)):\n raise NotImplementedError('`sample_weight` is currently not supported '\n 'when using TPUStrategy.')\n\n if (self.stateful and distributed_training_utils.is_tpu_strategy(\n self._distribution_strategy) and self._distribution_strategy.\n num_replicas_in_sync != 1):\n raise ValueError('Single core must be used for computation on '\n 'stateful models. Consider adding `device_assignment` '\n 'parameter to TPUStrategy using\\n'\n 'topology = tf.contrib.distribute.'\n 'initialize_tpu_system()\\n'\n 'device_assignment = tf.contrib.tpu.DeviceAssignment('\n 'topology, core_assignment=tf.contrib.tpu.'\n 'SINGLE_CORE_ASSIGNMENT)\\n'\n 'tpu_strategy = tf.contrib.distribute.TPUStrategy('\n 'device_assignment=device_assignment)')\n\n # Validates `steps` and `shuffle` arguments right at the beginning\n # since we use it to construct the dataset object.\n # TODO(anjalisridhar): Remove this check once we refactor the\n # _standardize_user_data code path. This check is already present elsewhere\n # in the codebase.\n if isinstance(x, dataset_ops.DatasetV2):\n if shuffle:\n training_utils.verify_dataset_shuffled(x)\n\n strategy = self._distribution_strategy\n with strategy.scope():\n # We should be sure to call get_session() inside the strategy.scope()\n # so the strategy can affect the session options.\n if ops.executing_eagerly_outside_functions():\n session = None\n else:\n session = K.get_session()\n\n first_x_value = nest.flatten(x)[0]\n if isinstance(first_x_value, np.ndarray):\n x = training_utils.list_to_tuple(x)\n if y is not None:\n y = training_utils.list_to_tuple(y)\n if sample_weight is not None:\n sample_weight = training_utils.list_to_tuple(sample_weight)\n in_tuple = (x, y, sample_weight)\n else:\n in_tuple = (x, y)\n else:\n in_tuple = x\n\n ds = strategy.extended.experimental_make_numpy_dataset(in_tuple,\n session=session)\n if shuffle:\n # We want a buffer size that is larger than the batch size provided by\n # the user and provides sufficient randomness. Note that larger\n # numbers introduce more memory usage based on the size of each\n # sample.\n ds = ds.shuffle(max(1024, batch_size * 8))\n if epochs > 1:\n ds = ds.repeat(epochs)\n\n # We need to use the drop_remainder argument to get a known static\n # input shape which is required for TPUs.\n drop_remainder = (not allow_partial_batch and\n strategy.extended.experimental_require_static_shapes)\n\n # TODO(b/131720208): We still drop remainder here if number of examples\n # is divisible by batch size, as sometimes dynamic padder will time out\n # with keras.metrics.CategoricalAccuracy() metric.\n if distributed_training_utils.is_tpu_strategy(\n strategy) and not drop_remainder:\n dataset_size = first_x_value.shape[0]\n if dataset_size % batch_size == 0:\n drop_remainder = True\n\n x = ds.batch(batch_size, drop_remainder=drop_remainder)\n else:\n assert isinstance(x, dataset_ops.DatasetV2)\n training_utils.validate_dataset_input(x, y, sample_weight,\n validation_split)\n return x\n\n def _standardize_user_data(self,\n x,\n y=None,\n sample_weight=None,\n class_weight=None,\n batch_size=None,\n check_steps=False,\n steps_name='steps',\n steps=None,\n validation_split=0,\n shuffle=False,\n extract_tensors_from_dataset=False):\n \"\"\"Runs validation checks on input and target data passed by the user.\n\n Also standardizes the data to lists of arrays, in order.\n\n Also builds and compiles the model on the fly if it is a subclassed model\n that has never been called before (and thus has no inputs/outputs).\n\n This is a purely internal method, subject to refactoring at any time.\n\n Args:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely). If `x` is a dataset, `y` should not be\n specified (since targets will be obtained from the iterator).\n sample_weight: An optional sample-weight array passed by the user to\n weight the importance of each sample in `x`.\n class_weight: An optional class-weight array by the user to\n weight the importance of samples in `x` based on the class they belong\n to, as conveyed by `y`. If both `sample_weight` and `class_weight` are\n provided, the weights are multiplied.\n batch_size: Integer batch size. If provided, it is used to run additional\n validation checks on stateful models.\n check_steps: boolean, True if we want to check for validity of `steps` and\n False, otherwise. For example, when we are standardizing one batch of\n data for train_on_batch/predict_on_batch/test_on_batch APIs, `steps`\n value is not required and we should not check for its validity in these\n cases.\n steps_name: The public API's parameter name for `steps`.\n steps: Integer or `None`. Total number of steps (batches of samples) to\n execute.\n validation_split: Float between 0 and 1.\n Fraction of the training data to be used as validation data.\n shuffle: Boolean whether to shuffle the training data before each epoch.\n extract_tensors_from_dataset: Boolean. When `x` is a dataset instance,\n this indicates whether to extract actual tensors from the dataset or\n instead output the dataset instance itself.\n Set to True when calling from `train_on_batch`/etc.\n\n Returns:\n A tuple of 3: inputs (arrays or dicts, depending on whether `x` was a dict\n or not), target arrays, sample-weight arrays.\n If the model's input and targets are symbolic, these lists are empty\n (since the model takes no user-provided data, instead the data comes\n from the symbolic inputs/targets).\n\n Raises:\n ValueError: In case of invalid user-provided data.\n RuntimeError: If the model was never compiled.\n \"\"\"\n if isinstance(x, (dataset_ops.DatasetV1, dataset_ops.DatasetV2)):\n # Graph mode dataset. We'll pass the dataset as-is (unless\n # `extract_tensors_from_dataset` is True, in which case we extract\n # the tensors from the dataset and we output them.\n training_utils.validate_dataset_input(x, y, sample_weight,\n validation_split)\n if shuffle:\n training_utils.verify_dataset_shuffled(x)\n\n is_dataset = True\n if extract_tensors_from_dataset:\n # We do this for `train_on_batch`/etc.\n x, y, sample_weight = training_utils.extract_tensors_from_dataset(x)\n elif isinstance(x, iterator_ops.Iterator):\n # Graph mode iterator. We extract the symbolic tensors.\n training_utils.validate_dataset_input(x, y, sample_weight,\n validation_split)\n iterator = x\n x, y, sample_weight = training_utils.unpack_iterator_input(iterator)\n is_dataset = True\n else:\n is_dataset = False\n\n # Validates `steps` argument based on x's type.\n if check_steps:\n training_utils.check_steps_argument(x, steps, steps_name)\n\n # First, we build the model on the fly if necessary.\n if not self.inputs:\n all_inputs, y_input, dict_inputs = self._build_model_with_inputs(x, y)\n is_build_called = True\n else:\n all_inputs = []\n # Whether this is a subclassed model that expects dictionary inputs\n # rather than list inputs (e.g. FeatureColumn-based models).\n dict_inputs = isinstance(self.inputs, dict)\n is_build_called = False\n y_input = y\n\n # Second, we compile the model on the fly if necessary, mostly for subclass\n # models.\n is_compile_called = False\n if not self._is_compiled and self.optimizer:\n self._compile_from_inputs(all_inputs, y_input, x, y)\n is_compile_called = True\n\n # In graph mode, if we had just set inputs and targets as symbolic tensors\n # by invoking build and compile on the model respectively, we do not have to\n # feed anything to the model. Model already has input and target data as\n # part of the graph.\n # Note: in this case, `any` and `all` are equivalent since we disallow\n # mixed symbolic/value inputs.\n if (not self.run_eagerly and is_build_called and is_compile_called and\n not is_dataset and any(_is_symbolic_tensor(v) for v in all_inputs)):\n return [], [], None\n\n # What follows is input validation and standardization to list format,\n # in the case where all inputs are value arrays.\n\n if self.run_eagerly:\n # In eager mode, do not do shape validation\n # since the network has no input nodes (placeholders) to be fed.\n feed_input_names = self.input_names\n feed_input_shapes = None\n elif not self._is_graph_network:\n # Case: symbolic-mode subclassed network. Do not do shape validation.\n feed_input_names = self._feed_input_names\n feed_input_shapes = None\n else:\n # Case: symbolic-mode graph network.\n # In this case, we run extensive shape validation checks.\n feed_input_names = self._feed_input_names\n feed_input_shapes = self._feed_input_shapes\n\n # Standardize the inputs.\n if not isinstance(x, (dataset_ops.DatasetV1, dataset_ops.DatasetV2)):\n # TODO(fchollet): run static checks with dataset output shape(s).\n x = training_utils.standardize_input_data(\n x,\n feed_input_names,\n feed_input_shapes,\n check_batch_axis=False, # Don't enforce the batch size.\n exception_prefix='input')\n\n # Get typespecs for the input data and sanitize it if necessary.\n # TODO(momernick): This should be capable of doing full input validation\n # at all times - validate that this is so and refactor the standardization\n # code.\n if isinstance(x, dataset_ops.DatasetV2):\n x_shapes = dataset_ops.get_structure(x)\n if isinstance(x_shapes, tuple):\n # If the output of a Dataset is a tuple, we assume it's either of the\n # form (x_data, y_data) or (x_data, y_data, sample_weights). In either\n # case, we only care about x_data here.\n x_shapes = x_shapes[0]\n else:\n flat_inputs = nest.flatten(x, expand_composites=False)\n flat_expected_inputs = nest.flatten(self.inputs, expand_composites=False)\n converted_x = []\n for (a, b) in zip(flat_inputs, flat_expected_inputs):\n converted_x.append(_convert_scipy_sparse_tensor(a, b))\n x = nest.pack_sequence_as(x, converted_x, expand_composites=False)\n x_shapes = nest.map_structure(type_spec.type_spec_from_value, x)\n\n flat_inputs = nest.flatten(x_shapes, expand_composites=False)\n flat_expected_inputs = nest.flatten(self.inputs, expand_composites=False)\n for (a, b) in zip(flat_inputs, flat_expected_inputs):\n nest.assert_same_structure(a, b, expand_composites=True)\n\n if y is not None:\n # Prepare self._sample_weight_modes. List with the same length as\n # model outputs.\n training_utils.prepare_sample_weight_modes(self._training_endpoints,\n self.sample_weight_mode)\n feed_output_names = self._feed_output_names\n feed_sample_weight_modes = self._sample_weight_modes\n if not self._is_graph_network:\n feed_output_shapes = None\n else:\n feed_output_shapes = self._feed_output_shapes\n\n # Standardize the outputs.\n y = training_utils.standardize_input_data(\n y,\n feed_output_names,\n # Don't enforce target shapes to match output shapes.\n # Precise checks will be run in `check_loss_and_target_compatibility`.\n shapes=None,\n check_batch_axis=False, # Don't enforce the batch size.\n exception_prefix='target')\n\n # Generate sample-wise weight values given the `sample_weight` and\n # `class_weight` arguments.\n sample_weights = training_utils.standardize_sample_weights(\n sample_weight, feed_output_names)\n class_weights = training_utils.standardize_class_weights(\n class_weight, feed_output_names)\n sample_weights = [\n training_utils.standardize_weights(ref, sw, cw, mode)\n for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights,\n feed_sample_weight_modes)\n ]\n # Check that all arrays have the same length.\n if not self._distribution_strategy:\n training_utils.check_array_lengths(x, y, sample_weights)\n if self._is_graph_network and not self.run_eagerly:\n # Additional checks to avoid users mistakenly using improper loss fns.\n training_utils.check_loss_and_target_compatibility(\n y, self._feed_loss_fns, feed_output_shapes)\n\n # If sample weight mode has not been set and weights are None for all the\n # model outputs, return None (we do not create placeholders for\n # sample weights) so we do not want to feed any value.\n is_sample_weight_mode_set = any(\n s is not None for s in feed_sample_weight_modes)\n if (not is_sample_weight_mode_set and\n all(s is None for s in sample_weights)):\n sample_weights = None # If the list contains only None, return None\n else:\n y = []\n sample_weights = None\n\n if self.stateful and batch_size and not is_dataset:\n # Check that for stateful networks, number of samples is a multiple\n # of the static batch size.\n if x[0].shape[0] % batch_size != 0:\n raise ValueError('In a stateful network, '\n 'you should only pass inputs with '\n 'a number of samples that can be '\n 'divided by the batch size. Found: ' +\n str(x[0].shape[0]) + ' samples')\n\n # If dictionary inputs were provided, we return a dictionary as well.\n if dict_inputs and not isinstance(x, (dataset_ops.DatasetV1,\n dataset_ops.DatasetV2)):\n x = dict(zip(feed_input_names, x))\n return x, y, sample_weights\n\n def _build_model_with_inputs(self, inputs, targets):\n \"\"\"Build the model (set model inputs/outputs), mainly for subclass model.\"\"\"\n processed_inputs = []\n is_dict_inputs = False\n orig_inputs = inputs\n # We need to use `inputs` to set the model inputs.\n # If input data is a dataset iterator in graph mode or if it is an eager\n # iterator and only one batch of samples is required, we fetch the data\n # tensors from the iterator and then standardize them.\n if isinstance(inputs, (dataset_ops.DatasetV1, dataset_ops.DatasetV2)):\n inputs, targets, _ = training_utils.extract_tensors_from_dataset(inputs)\n # We type-check that `inputs` and `targets` are either single arrays\n # or lists of arrays, and extract a flat list of inputs from the passed\n # structure.\n training_utils.validate_input_types(inputs, orig_inputs)\n\n if isinstance(inputs, (list, tuple)):\n processed_inputs += list(inputs)\n elif isinstance(inputs, dict):\n is_dict_inputs = True\n keys = sorted(inputs.keys())\n processed_inputs = [inputs[k] for k in keys]\n else:\n processed_inputs.append(inputs)\n # Now that we have a flat set of inputs, we make sure that none of them\n # are CompositeTensors or CompositeTensorValues of any type (or scipy\n # sparse arrays, which we treat as SparseTensor values). We cannot safely\n # infer input data from an arbitrary composite tensor, so we don't try -\n # users should explicitly add composite tensor inputs to their subclassed\n # models.\n for input_tensor in processed_inputs:\n if composite_tensor_utils.is_composite_or_composite_value(input_tensor):\n # TODO(b/132691975): Document subclass-model CT input handling.\n raise ValueError(\n 'All SparseTensor and RaggedTensor inputs must be explicitly '\n 'declared using a keras.Input() with sparse=True or ragged=True. '\n 'We found an undeclared input %s. For Sequential models, please '\n 'add a keras.Input() as your first Layer. For subclassed models, '\n 'please call self._add_inputs() on your input set, which you can '\n 'create using keras.Input() for each input to your model.' %\n (input_tensor,))\n # Build the model using the retrieved inputs (value or symbolic).\n # If values are generated from a dataset, then in symbolic-mode\n # placeholders will be created to match the value shapes.\n if isinstance(orig_inputs, (dataset_ops.DatasetV1, dataset_ops.DatasetV2,\n iterator_ops.Iterator)):\n def create_tensor_spec(t):\n return tensor_spec.TensorSpec(t.shape, t.dtype)\n\n cast_inputs = nest.map_structure(create_tensor_spec, inputs)\n elif training_utils.has_tensors(inputs):\n cast_inputs = training_utils.cast_if_floating_dtype(inputs)\n else:\n cast_inputs = inputs\n self._set_inputs(cast_inputs)\n return processed_inputs, targets, is_dict_inputs\n\n def _compile_from_inputs(self, all_inputs, target, orig_inputs, orig_target):\n if target is not None:\n # We need to use `y` to set the model targets.\n if training_utils.has_tensors(target):\n target = training_utils.cast_if_floating_dtype(target)\n training_utils.validate_input_types(target, orig_target,\n allow_dict=False, field_name='target')\n if isinstance(target, (list, tuple)):\n all_inputs += list(target)\n else:\n all_inputs.append(target)\n # Type check that all inputs are *either* value *or* symbolic.\n # TODO(fchollet): this check could be removed in Eager mode?\n if any(tensor_util.is_tensor(v) for v in all_inputs):\n if not all(tensor_util.is_tensor(v) for v in all_inputs):\n raise ValueError('Do not pass inputs that mix Numpy arrays and '\n 'TensorFlow tensors. '\n 'You passed: x=' + str(orig_inputs) +\n '; y=' + str(orig_target))\n is_dataset = isinstance(orig_inputs, (dataset_ops.DatasetV1,\n dataset_ops.DatasetV2,\n iterator_ops.Iterator))\n if is_dataset or context.executing_eagerly():\n target_tensors = None\n else:\n # Handle target tensors if any passed.\n if target is not None:\n if not isinstance(target, (list, tuple)):\n target = [target]\n target_tensors = [v for v in target if _is_symbolic_tensor(v)]\n else:\n target_tensors = None\n\n self.compile(\n optimizer=self.optimizer,\n loss=self.loss,\n metrics=self._compile_metrics,\n weighted_metrics=self._compile_weighted_metrics,\n loss_weights=self.loss_weights,\n target_tensors=target_tensors,\n sample_weight_mode=self.sample_weight_mode,\n run_eagerly=self.run_eagerly,\n experimental_run_tf_function=self._experimental_run_tf_function)\n\n # TODO(omalleyt): Consider changing to a more descriptive function name.\n def _set_inputs(self, inputs, outputs=None, training=None):\n \"\"\"Set model's input and output specs based on the input data received.\n\n This is to be used for Model subclasses, which do not know at instantiation\n time what their inputs look like.\n\n Args:\n inputs: Single array, or list of arrays. The arrays could be placeholders,\n Numpy arrays, data tensors, or TensorSpecs.\n - if placeholders: the model is built on top of these placeholders,\n and we expect Numpy data to be fed for them when calling `fit`/etc.\n - if Numpy data or TensorShapes: we create placeholders matching the\n TensorShapes or shapes of the Numpy arrays. We expect Numpy data to be\n fed for these placeholders when calling `fit`/etc.\n - if data tensors: the model is built on top of these tensors.\n We do not expect any Numpy data to be provided when calling `fit`/etc.\n outputs: None, a data tensor, or a list of tensors. If None, the\n outputs will be determined by invoking `self.call()`, otherwise the\n provided value will be used.\n training: Boolean or None. Only relevant in symbolic mode. Specifies\n whether to build the model's graph in inference mode (False), training\n mode (True), or using the Keras learning phase (None).\n Raises:\n ValueError: If dict inputs are passed to a Sequential Model where the\n first layer isn't FeatureLayer.\n \"\"\"\n inputs = self._set_input_attrs(inputs)\n\n if outputs is None:\n kwargs = {}\n if self._expects_training_arg:\n # In V2 mode, feeding `training=None` is not allowed because any value\n # explicitly passed by the user is respected, even `None`.`\n if training is None and not ops.executing_eagerly_outside_functions():\n training = K.learning_phase()\n if training is not None:\n kwargs['training'] = training\n try:\n outputs = self(inputs, **kwargs)\n except NotImplementedError:\n # This Model or a submodel is dynamic and hasn't overridden\n # `compute_output_shape`.\n outputs = None\n\n self._set_output_attrs(outputs)\n\n @trackable.no_automatic_dependency_tracking\n def _set_input_attrs(self, inputs):\n \"\"\"Sets attributes related to the inputs of the Model.\"\"\"\n if self.inputs:\n raise ValueError('Model inputs are already set.')\n\n if self.__class__.__name__ == 'Sequential' and not self.built:\n if tensor_util.is_tensor(inputs):\n input_shape = (None,) + tuple(inputs.shape.as_list()[1:])\n elif isinstance(inputs, tensor_shape.TensorShape):\n input_shape = (None,) + tuple(inputs.as_list()[1:])\n elif isinstance(inputs, dict):\n # We assert that the first layer is a FeatureLayer.\n if not training_utils.is_feature_layer(self.layers[0]):\n raise ValueError('Passing a dictionary input to a Sequential Model '\n 'which doesn\\'t have FeatureLayer as the first layer'\n ' is an error.')\n input_shape = (None,)\n else:\n input_shape = (None,) + tuple(inputs.shape[1:])\n self._build_input_shape = input_shape\n\n # On-the-fly setting of symbolic model inputs (either by using the tensor\n # provided, or by creating a placeholder if Numpy data was provided).\n model_inputs = training_utils.ModelInputs(inputs)\n inputs = model_inputs.get_symbolic_inputs()\n self.inputs = model_inputs.get_symbolic_inputs(return_single_as_list=True)\n self.input_names = model_inputs.get_input_names()\n\n self._feed_inputs = []\n self._feed_input_names = []\n self._feed_input_shapes = []\n\n for k, v in model_inputs.as_dict():\n if K.is_placeholder(v):\n self._feed_input_names.append(k)\n self._feed_inputs.append(v)\n self._feed_input_shapes.append(K.int_shape(v))\n\n return inputs\n\n @trackable.no_automatic_dependency_tracking\n def _set_output_attrs(self, outputs):\n \"\"\"Sets attributes related to the outputs of the Model.\"\"\"\n outputs = nest.flatten(outputs)\n self.outputs = outputs\n self.output_names = training_utils.generic_output_names(outputs)\n # TODO(scottzhu): Should we cleanup the self._training_endpoints here?\n self.built = True\n\n @property\n def _targets(self):\n \"\"\"The output target tensors for the model.\"\"\"\n return [\n e.training_target.target\n for e in self._training_endpoints\n if e.has_training_target()\n ]\n\n @property\n def _feed_targets(self):\n return [\n e.training_target.target\n for e in self._training_endpoints\n if e.has_feedable_training_target()\n ]\n\n @property\n def _feed_output_names(self):\n return [\n e.output_name\n for e in self._training_endpoints\n if e.has_feedable_training_target()\n ]\n\n @property\n def _feed_output_shapes(self):\n return [\n e.feed_output_shape\n for e in self._training_endpoints\n if e.has_feedable_training_target()\n ]\n\n @property\n def _feed_loss_fns(self):\n return [\n e.loss_fn\n for e in self._training_endpoints\n if e.has_feedable_training_target()\n ]\n\n @property\n def _loss_weights_list(self):\n return [e.loss_weight for e in self._training_endpoints]\n\n @property\n def _output_loss_metrics(self):\n if hasattr(self, '_training_endpoints'):\n return [\n e.output_loss_metric\n for e in self._training_endpoints\n if e.output_loss_metric is not None\n ]\n return None\n\n @property\n def sample_weights(self):\n return [e.sample_weight for e in self._training_endpoints]\n\n @property\n def _sample_weight_modes(self):\n return [e.sample_weight_mode for e in self._training_endpoints]\n\n @property\n def _feed_sample_weights(self):\n return [e.sample_weight for e in self._training_endpoints\n if e.sample_weight is not None]\n\n def _maybe_load_initial_epoch_from_ckpt(self, initial_epoch, mode):\n \"\"\"Maybe load initial epoch from ckpt considering possible worker recovery.\n\n Refer to tensorflow/python/keras/distribute/multi_worker_training_state.py\n for more information.\n\n Arguments:\n initial_epoch: The original initial_epoch user passes in in `fit()`.\n mode: The mode for running `model.fit()`.\n\n Returns:\n If the training is recovering from previous failure under multi-worker\n training setting, return the epoch the training is supposed to continue\n at. Otherwise, return the `initial_epoch` the user passes in.\n \"\"\"\n if hasattr(self, '_training_state'):\n return self._training_state.maybe_load_initial_epoch_from_ckpt(\n initial_epoch, mode)\n return initial_epoch\n\n def _get_training_eval_metrics(self):\n \"\"\"Returns all the metrics that are to be reported.\n\n This includes the output loss metrics, compile metrics/weighted metrics,\n add_metric metrics.\n \"\"\"\n metrics = []\n if getattr(self, '_output_loss_metrics', None) is not None:\n metrics.extend(self._output_loss_metrics)\n if hasattr(self, 'metrics'):\n metrics.extend(self.metrics)\n return metrics\n\n @property\n def _object_identifier(self):\n return '_tf_keras_model'\n\n @property\n def _tracking_metadata(self):\n metadata = json.loads(super(Model, self)._tracking_metadata)\n metadata.update(saving_utils.model_metadata(\n self, include_optimizer=True, require_config=False))\n return json.dumps(metadata, default=serialization.get_json_type)\n\n def _assert_compile_was_called(self):\n # Checks whether `compile` has been called. If it has been called,\n # then the optimizer is set. This is different from whether the\n # model is compiled\n # (i.e. whether the model is built and its inputs/outputs are set).\n if not self.optimizer:\n raise RuntimeError('You must compile your model before '\n 'training/testing. '\n 'Use `model.compile(optimizer, loss)`.')\n\n\nclass DistributedCallbackModel(Model):\n \"\"\"Model that is used for callbacks with tf.distribute.Strategy.\"\"\"\n\n def __init__(self, model):\n super(DistributedCallbackModel, self).__init__()\n self.optimizer = model.optimizer\n\n def set_original_model(self, orig_model):\n self._original_model = orig_model\n\n def save_weights(self, filepath, overwrite=True, save_format=None):\n self._replicated_model.save_weights(filepath, overwrite=overwrite,\n save_format=save_format)\n\n def save(self, filepath, overwrite=True, include_optimizer=True):\n # save weights from the distributed model to the original model\n distributed_model_weights = self.get_weights()\n self._original_model.set_weights(distributed_model_weights)\n # TODO(anjalisridhar): Do we need to save the original model here?\n # Saving the first replicated model works as well.\n self._original_model.save(filepath, overwrite=True, include_optimizer=False)\n\n def load_weights(self, filepath, by_name=False):\n self._original_model.load_weights(filepath, by_name=False)\n # Copy the weights from the original model to each of the replicated models.\n orig_model_weights = self._original_model.get_weights()\n distributed_training_utils.set_weights(\n self._original_model._distribution_strategy, self, # pylint: disable=protected-access\n orig_model_weights)\n\n def __getattr__(self, item):\n # Whitelisted atttributes of the model that can be accessed by the user\n # during a callback.\n if item not in ('_setattr_tracking', '_layers'):\n logging.warning('You are accessing attribute ' + item + ' of the '\n 'DistributedCallbackModel that may not have been set '\n 'correctly.')\n return super(DistributedCallbackModel, self).__getattr__(item)\n\n\nclass _TrainingEndpoint(object):\n \"\"\"A container for the training output/target and related entities.\n\n In the case of model with multiple outputs, there is a one-to-one mapping\n between model output (y_pred), model target (y_true), loss, metrics etc.\n By unifying these entities into one class, different entity can access\n information between each other, rather than currently access different list of\n attributes of the model.\n \"\"\"\n\n def __init__(self,\n output,\n output_name,\n loss_fn,\n loss_weight=None,\n training_target=None,\n output_loss_metric=None,\n sample_weight=None,\n sample_weight_mode=None):\n \"\"\"Initialize the _TrainingEndpoint.\n\n Note that the output and output_name should be stable as long as the model\n structure doesn't change. The training_target suppose to be mutable since\n the information is provided via `compile()`\n\n Args:\n output: the output tensor of the model.\n output_name: the unique name of the output tensor.\n loss_fn: the loss function for the output tensor.\n loss_weight: float, the weights for the loss.\n training_target: the _TrainingTarget for the model.\n output_loss_metric: the metric object for the loss function.\n sample_weight: the weights for how a sample is weighted during metric and\n loss calculation. Could be None.\n sample_weight_mode: string, 'temporal', 'samplewise' or None. The mode for\n how the sample_weight is populated.\n \"\"\"\n self._output = output\n self._output_name = output_name\n self._loss_fn = loss_fn\n self._loss_weight = loss_weight\n self._training_target = training_target\n self._output_loss_metric = output_loss_metric\n self._sample_weight = sample_weight\n self._sample_weight_mode = sample_weight_mode\n\n @property\n def output(self):\n return self._output\n\n @property\n def output_name(self):\n return self._output_name\n\n @property\n def shape(self):\n return K.int_shape(self.output)\n\n @property\n def loss_fn(self):\n return self._loss_fn\n\n @property\n def loss_weight(self):\n return self._loss_weight\n\n @loss_weight.setter\n def loss_weight(self, value):\n self._loss_weight = value\n\n @property\n def training_target(self):\n return self._training_target\n\n @training_target.setter\n def training_target(self, value):\n self._training_target = value\n\n def create_training_target(self, target, run_eagerly=False):\n \"\"\"Create training_target instance and update the self.training_target.\n\n Note that the input target should just be a tensor or None, and\n corresponding training target will be created based on the output and\n loss_fn.\n\n Args:\n target: the target tensor for the current output. Could be None.\n run_eagerly: boolean, whether the model is in run_eagerly mode.\n\n Raises:\n ValueError if the training_target field for the current instance has\n already been populated.\n \"\"\"\n if self.has_training_target():\n raise ValueError('The training_target field for the _TrainingEndpoint '\n 'instance has already been populated')\n if run_eagerly:\n # When run_eagerly, the target tensor is ignored, and the None placeholder\n # is created instead.\n self.training_target = _TrainingTarget(\n None, feedable=True, skip_target_weights=False)\n return\n\n if self.should_skip_target():\n self.training_target = _TrainingTarget(None)\n else:\n if target is not None and not K.is_placeholder(target):\n feedable = False\n skip_target_weights = True\n else:\n feedable = True\n skip_target_weights = False\n\n if target is None:\n target_dtype = losses.LABEL_DTYPES_FOR_LOSSES.get(\n self.loss_fn, K.dtype(self.output))\n\n target = K.placeholder(\n ndim=len(self.shape),\n name=self.output_name + '_target',\n sparse=K.is_sparse(self.output),\n dtype=target_dtype)\n\n self.training_target = _TrainingTarget(\n target,\n feedable=feedable,\n skip_target_weights=skip_target_weights)\n\n @property\n def output_loss_metric(self):\n return self._output_loss_metric\n\n @output_loss_metric.setter\n def output_loss_metric(self, value):\n self._output_loss_metric = value\n\n @property\n def sample_weight(self):\n return self._sample_weight\n\n @sample_weight.setter\n def sample_weight(self, value):\n self._sample_weight = value\n\n @property\n def sample_weight_mode(self):\n return self._sample_weight_mode\n\n @sample_weight_mode.setter\n def sample_weight_mode(self, value):\n self._sample_weight_mode = value\n\n def should_skip_target(self):\n return self._loss_fn is None\n\n def should_skip_target_weights(self):\n return (self.should_skip_target() or self.training_target is None or\n self.training_target.skip_target_weights)\n\n def has_training_target(self):\n return self.training_target is not None\n\n def has_feedable_training_target(self):\n return (not self.should_skip_target() and\n self.training_target is not None and self.training_target.feedable)\n\n def loss_name(self):\n if self._loss_fn is not None:\n return self._output_name + '_loss'\n return None\n\n @property\n def feed_output_shape(self):\n \"\"\"The output shape for the feedable target.\"\"\"\n if not self.has_feedable_training_target():\n return None\n\n if ((isinstance(self.loss_fn, losses.LossFunctionWrapper) and\n self.loss_fn.fn == losses.sparse_categorical_crossentropy)) or (\n isinstance(self.loss_fn, losses.SparseCategoricalCrossentropy)):\n if K.image_data_format() == 'channels_first':\n return (self.shape[0], 1) + self.shape[2:]\n else:\n return self.shape[:-1] + (1,)\n elif (not isinstance(self.loss_fn, losses.Loss) or\n (isinstance(self.loss_fn, losses.LossFunctionWrapper) and\n (getattr(losses, self.loss_fn.fn.__name__, None) is None))):\n # If the given loss is not an instance of the `Loss` class (custom\n # class) or if the loss function that is wrapped is not in the\n # `losses` module, then it is a user-defined loss and we make no\n # assumptions about it.\n return None\n else:\n return self.shape\n\n def sample_weights_mismatch(self):\n \"\"\"Check if the sample weight and the mode match or not.\"\"\"\n # If there is a mismatch between sample weight mode and the placeholders\n # created, then recompile the sub-graphs that depend on sample weights.\n return (\n (self.sample_weight_mode is not None and self.sample_weight is None) or\n (self.sample_weight_mode is None and self.sample_weight is not None))\n\n def populate_sample_weight(self, sample_weight, sample_weight_mode):\n \"\"\"Populate the sample weight and based on the sample weight mode.\"\"\"\n if (sample_weight is None and\n (self.should_skip_target_weights() or sample_weight_mode is None or\n context.executing_eagerly())):\n self._sample_weight = None\n return\n\n assert sample_weight_mode in ['temporal', 'samplewise']\n if sample_weight_mode == 'temporal':\n default_value = [[1.]]\n shape = [None, None]\n else:\n # sample_weight_mode == 'samplewise'\n default_value = [1.]\n shape = [None]\n\n if sample_weight is not None:\n if not sample_weight.shape.is_compatible_with(shape):\n raise ValueError('Received sample weight with shape {}. Expected shape '\n '{}.'.format(sample_weight.shape, shape))\n self._sample_weight = sample_weight\n else:\n self._sample_weight = array_ops.placeholder_with_default(\n constant_op.constant(default_value, dtype=K.floatx()),\n shape=shape,\n name=self.output_name + '_sample_weights')\n\n\nclass _TrainingTarget(object):\n \"\"\"Container for a target tensor (y_true) and its metadata (shape, loss...).\n\n Arguments:\n target: A target tensor for the model. It may be `None` if the\n output is excluded from loss computation. It is still kept as None\n since each output of the model should have a corresponding target. If\n the target is None, the rest of the attributes will be None as well.\n feedable: Boolean, whether the target is feedable (requires data to be\n passed in `fit` or `train_on_batch`), or not (model compiled with\n `target_tensors` argument).\n skip_target_weights: Boolean, whether the target should be skipped during\n weights calculation.\n \"\"\"\n\n def __init__(self, target, feedable=False, skip_target_weights=True):\n self._target = target\n self._feedable = feedable\n self._skip_target_weights = skip_target_weights\n\n @property\n def target(self):\n return self._target\n\n @property\n def feedable(self):\n return self._feedable\n\n @property\n def skip_target_weights(self):\n return self._skip_target_weights\n\n\ndef _is_symbolic_tensor(x):\n return tensor_util.is_tensor(x) and not isinstance(x, ops.EagerTensor)\n\n\ndef _convert_scipy_sparse_tensor(value, expected_input):\n \"\"\"Handle scipy sparse tensor conversions.\n\n This method takes a value 'value' and returns the proper conversion. If\n value is a scipy sparse tensor and the expected input is a dense tensor,\n we densify 'value'. If value is a scipy sparse tensor and the expected input\n is a TF SparseTensor, we convert 'value' to a SparseTensor. If 'value' is\n not a scipy sparse tensor, or scipy is not imported, we pass it through\n unchanged.\n\n Arguments:\n value: An object that may be a scipy sparse tensor\n expected_input: The expected input placeholder.\n\n Returns:\n The possibly-converted 'value'.\n \"\"\"\n if issparse is not None and issparse(value):\n if ops.is_dense_tensor_like(expected_input):\n return value.toarray()\n else:\n sparse_coo = value.tocoo()\n row, col = sparse_coo.row, sparse_coo.col\n data, shape = sparse_coo.data, sparse_coo.shape\n indices = np.concatenate((np.expand_dims(row, 1), np.expand_dims(col, 1)),\n 1)\n return sparse_tensor.SparseTensor(indices, data, shape)\n else:\n return value\n\n\ndef _get_metrics_from_layers(layers):\n \"\"\"Returns list of metrics from the given layers.\n\n This will not include the `compile` metrics of a model layer.\n\n Arguments:\n layers: List of layers.\n\n Returns:\n List of metrics.\n \"\"\"\n metrics = []\n layers = trackable_layer_utils.filter_empty_layer_containers(layers)\n for layer in layers:\n if isinstance(layer, Model):\n # We cannot call 'metrics' on the model because we do not want to\n # include the metrics that were added in compile API of a nested model.\n metrics.extend(layer._metrics) # pylint: disable=protected-access\n metrics.extend(_get_metrics_from_layers(layer.layers))\n else:\n metrics.extend(layer.metrics)\n return metrics\n",
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nr\"\"\"Simple speech recognition to spot a limited number of keywords.\n\nThis is a self-contained example script that will train a very basic audio\nrecognition model in TensorFlow. It downloads the necessary training data and\nruns with reasonable defaults to train within a few hours even only using a CPU.\nFor more information, please see\nhttps://www.tensorflow.org/tutorials/audio_recognition.\n\nIt is intended as an introduction to using neural networks for audio\nrecognition, and is not a full speech recognition system. For more advanced\nspeech systems, I recommend looking into Kaldi. This network uses a keyword\ndetection style to spot discrete words from a small vocabulary, consisting of\n\"yes\", \"no\", \"up\", \"down\", \"left\", \"right\", \"on\", \"off\", \"stop\", and \"go\".\n\nTo run the training process, use:\n\nbazel run tensorflow/examples/speech_commands:train\n\nThis will write out checkpoints to /tmp/speech_commands_train/, and will\ndownload over 1GB of open source training data, so you'll need enough free space\nand a good internet connection. The default data is a collection of thousands of\none-second .wav files, each containing one spoken word. This data set is\ncollected from https://aiyprojects.withgoogle.com/open_speech_recording, please\nconsider contributing to help improve this and other models!\n\nAs training progresses, it will print out its accuracy metrics, which should\nrise above 90% by the end. Once it's complete, you can run the freeze script to\nget a binary GraphDef that you can easily deploy on mobile applications.\n\nIf you want to train on your own data, you'll need to create .wavs with your\nrecordings, all at a consistent length, and then arrange them into subfolders\norganized by label. For example, here's a possible file structure:\n\nmy_wavs >\n up >\n audio_0.wav\n audio_1.wav\n down >\n audio_2.wav\n audio_3.wav\n other>\n audio_4.wav\n audio_5.wav\n\nYou'll also need to tell the script what labels to look for, using the\n`--wanted_words` argument. In this case, 'up,down' might be what you want, and\nthe audio in the 'other' folder would be used to train an 'unknown' category.\n\nTo pull this all together, you'd run:\n\nbazel run tensorflow/examples/speech_commands:train -- \\\n--data_dir=my_wavs --wanted_words=up,down\n\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os.path\nimport sys\n\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nimport input_data\nimport models\nfrom tensorflow.python.platform import gfile\n\nFLAGS = None\n\n\ndef main(_):\n # We want to see all the logging messages for this tutorial.\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)\n\n # Start a new TensorFlow session.\n sess = tf.compat.v1.InteractiveSession()\n\n # Begin by making sure we have the training data we need. If you already have\n # training data of your own, use `--data_url= ` on the command line to avoid\n # downloading.\n model_settings = models.prepare_model_settings(\n len(input_data.prepare_words_list(FLAGS.wanted_words.split(','))),\n FLAGS.sample_rate, FLAGS.clip_duration_ms, FLAGS.window_size_ms,\n FLAGS.window_stride_ms, FLAGS.feature_bin_count, FLAGS.preprocess)\n audio_processor = input_data.AudioProcessor(\n FLAGS.data_url, FLAGS.data_dir,\n FLAGS.silence_percentage, FLAGS.unknown_percentage,\n FLAGS.wanted_words.split(','), FLAGS.validation_percentage,\n FLAGS.testing_percentage, model_settings, FLAGS.summaries_dir)\n fingerprint_size = model_settings['fingerprint_size']\n label_count = model_settings['label_count']\n time_shift_samples = int((FLAGS.time_shift_ms * FLAGS.sample_rate) / 1000)\n # Figure out the learning rates for each training phase. Since it's often\n # effective to have high learning rates at the start of training, followed by\n # lower levels towards the end, the number of steps and learning rates can be\n # specified as comma-separated lists to define the rate at each stage. For\n # example --how_many_training_steps=10000,3000 --learning_rate=0.001,0.0001\n # will run 13,000 training loops in total, with a rate of 0.001 for the first\n # 10,000, and 0.0001 for the final 3,000.\n training_steps_list = list(map(int, FLAGS.how_many_training_steps.split(',')))\n learning_rates_list = list(map(float, FLAGS.learning_rate.split(',')))\n if len(training_steps_list) != len(learning_rates_list):\n raise Exception(\n '--how_many_training_steps and --learning_rate must be equal length '\n 'lists, but are %d and %d long instead' % (len(training_steps_list),\n len(learning_rates_list)))\n\n input_placeholder = tf.compat.v1.placeholder(\n tf.float32, [None, fingerprint_size], name='fingerprint_input')\n if FLAGS.quantize:\n fingerprint_min, fingerprint_max = input_data.get_features_range(\n model_settings)\n fingerprint_input = tf.quantization.fake_quant_with_min_max_args(\n input_placeholder, fingerprint_min, fingerprint_max)\n else:\n fingerprint_input = input_placeholder\n\n logits, dropout_prob = models.create_model(\n fingerprint_input,\n model_settings,\n FLAGS.model_architecture,\n is_training=True)\n\n # Define loss and optimizer\n ground_truth_input = tf.compat.v1.placeholder(\n tf.int64, [None], name='groundtruth_input')\n\n # Optionally we can add runtime checks to spot when NaNs or other symptoms of\n # numerical errors start occurring during training.\n control_dependencies = []\n if FLAGS.check_nans:\n checks = tf.compat.v1.add_check_numerics_ops()\n control_dependencies = [checks]\n\n # Create the back propagation and training evaluation machinery in the graph.\n with tf.compat.v1.name_scope('cross_entropy'):\n cross_entropy_mean = tf.compat.v1.losses.sparse_softmax_cross_entropy(\n labels=ground_truth_input, logits=logits)\n if FLAGS.quantize:\n tf.contrib.quantize.create_training_graph(quant_delay=0)\n with tf.compat.v1.name_scope('train'), tf.control_dependencies(\n control_dependencies):\n learning_rate_input = tf.compat.v1.placeholder(\n tf.float32, [], name='learning_rate_input')\n train_step = tf.compat.v1.train.GradientDescentOptimizer(\n learning_rate_input).minimize(cross_entropy_mean)\n predicted_indices = tf.argmax(input=logits, axis=1)\n correct_prediction = tf.equal(predicted_indices, ground_truth_input)\n confusion_matrix = tf.math.confusion_matrix(labels=ground_truth_input,\n predictions=predicted_indices,\n num_classes=label_count)\n evaluation_step = tf.reduce_mean(input_tensor=tf.cast(correct_prediction,\n tf.float32))\n with tf.compat.v1.get_default_graph().name_scope('eval'):\n tf.compat.v1.summary.scalar('cross_entropy', cross_entropy_mean)\n tf.compat.v1.summary.scalar('accuracy', evaluation_step)\n\n global_step = tf.compat.v1.train.get_or_create_global_step()\n increment_global_step = tf.compat.v1.assign(global_step, global_step + 1)\n\n saver = tf.compat.v1.train.Saver(tf.compat.v1.global_variables())\n\n # Merge all the summaries and write them out to /tmp/retrain_logs (by default)\n merged_summaries = tf.compat.v1.summary.merge_all(scope='eval')\n train_writer = tf.compat.v1.summary.FileWriter(FLAGS.summaries_dir + '/train',\n sess.graph)\n validation_writer = tf.compat.v1.summary.FileWriter(\n FLAGS.summaries_dir + '/validation')\n\n tf.compat.v1.global_variables_initializer().run()\n\n start_step = 1\n\n if FLAGS.start_checkpoint:\n models.load_variables_from_checkpoint(sess, FLAGS.start_checkpoint)\n start_step = global_step.eval(session=sess)\n\n tf.compat.v1.logging.info('Training from step: %d ', start_step)\n\n # Save graph.pbtxt.\n tf.io.write_graph(sess.graph_def, FLAGS.train_dir,\n FLAGS.model_architecture + '.pbtxt')\n\n # Save list of words.\n with gfile.GFile(\n os.path.join(FLAGS.train_dir, FLAGS.model_architecture + '_labels.txt'),\n 'w') as f:\n f.write('\\n'.join(audio_processor.words_list))\n\n # Training loop.\n training_steps_max = np.sum(training_steps_list)\n for training_step in xrange(start_step, training_steps_max + 1):\n # Figure out what the current learning rate is.\n training_steps_sum = 0\n for i in range(len(training_steps_list)):\n training_steps_sum += training_steps_list[i]\n if training_step <= training_steps_sum:\n learning_rate_value = learning_rates_list[i]\n break\n # Pull the audio samples we'll use for training.\n train_fingerprints, train_ground_truth = audio_processor.get_data(\n FLAGS.batch_size, 0, model_settings, FLAGS.background_frequency,\n FLAGS.background_volume, time_shift_samples, 'training', sess)\n # Run the graph with this batch of training data.\n train_summary, train_accuracy, cross_entropy_value, _, _ = sess.run(\n [\n merged_summaries,\n evaluation_step,\n cross_entropy_mean,\n train_step,\n increment_global_step,\n ],\n feed_dict={\n fingerprint_input: train_fingerprints,\n ground_truth_input: train_ground_truth,\n learning_rate_input: learning_rate_value,\n dropout_prob: 0.5\n })\n train_writer.add_summary(train_summary, training_step)\n tf.compat.v1.logging.info(\n 'Step #%d: rate %f, accuracy %.1f%%, cross entropy %f' %\n (training_step, learning_rate_value, train_accuracy * 100,\n cross_entropy_value))\n is_last_step = (training_step == training_steps_max)\n if (training_step % FLAGS.eval_step_interval) == 0 or is_last_step:\n set_size = audio_processor.set_size('validation')\n total_accuracy = 0\n total_conf_matrix = None\n for i in xrange(0, set_size, FLAGS.batch_size):\n validation_fingerprints, validation_ground_truth = (\n audio_processor.get_data(FLAGS.batch_size, i, model_settings, 0.0,\n 0.0, 0, 'validation', sess))\n # Run a validation step and capture training summaries for TensorBoard\n # with the `merged` op.\n validation_summary, validation_accuracy, conf_matrix = sess.run(\n [merged_summaries, evaluation_step, confusion_matrix],\n feed_dict={\n fingerprint_input: validation_fingerprints,\n ground_truth_input: validation_ground_truth,\n dropout_prob: 1.0\n })\n validation_writer.add_summary(validation_summary, training_step)\n batch_size = min(FLAGS.batch_size, set_size - i)\n total_accuracy += (validation_accuracy * batch_size) / set_size\n if total_conf_matrix is None:\n total_conf_matrix = conf_matrix\n else:\n total_conf_matrix += conf_matrix\n tf.compat.v1.logging.info('Confusion Matrix:\\n %s' % (total_conf_matrix))\n tf.compat.v1.logging.info('Step %d: Validation accuracy = %.1f%% (N=%d)' %\n (training_step, total_accuracy * 100, set_size))\n\n # Save the model checkpoint periodically.\n if (training_step % FLAGS.save_step_interval == 0 or\n training_step == training_steps_max):\n checkpoint_path = os.path.join(FLAGS.train_dir,\n FLAGS.model_architecture + '.ckpt')\n tf.compat.v1.logging.info('Saving to \"%s-%d\"', checkpoint_path,\n training_step)\n saver.save(sess, checkpoint_path, global_step=training_step)\n\n set_size = audio_processor.set_size('testing')\n tf.compat.v1.logging.info('set_size=%d', set_size)\n total_accuracy = 0\n total_conf_matrix = None\n for i in xrange(0, set_size, FLAGS.batch_size):\n test_fingerprints, test_ground_truth = audio_processor.get_data(\n FLAGS.batch_size, i, model_settings, 0.0, 0.0, 0, 'testing', sess)\n test_accuracy, conf_matrix = sess.run(\n [evaluation_step, confusion_matrix],\n feed_dict={\n fingerprint_input: test_fingerprints,\n ground_truth_input: test_ground_truth,\n dropout_prob: 1.0\n })\n batch_size = min(FLAGS.batch_size, set_size - i)\n total_accuracy += (test_accuracy * batch_size) / set_size\n if total_conf_matrix is None:\n total_conf_matrix = conf_matrix\n else:\n total_conf_matrix += conf_matrix\n tf.compat.v1.logging.info('Confusion Matrix:\\n %s' % (total_conf_matrix))\n tf.compat.v1.logging.info('Final test accuracy = %.1f%% (N=%d)' %\n (total_accuracy * 100, set_size))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--data_url',\n type=str,\n # pylint: disable=line-too-long\n default='https://storage.googleapis.com/download.tensorflow.org/data/speech_commands_v0.02.tar.gz',\n # pylint: enable=line-too-long\n help='Location of speech training data archive on the web.')\n parser.add_argument(\n '--data_dir',\n type=str,\n default='/tmp/speech_dataset/',\n help=\"\"\"\\\n Where to download the speech training data to.\n \"\"\")\n parser.add_argument(\n '--background_volume',\n type=float,\n default=0.1,\n help=\"\"\"\\\n How loud the background noise should be, between 0 and 1.\n \"\"\")\n parser.add_argument(\n '--background_frequency',\n type=float,\n default=0.8,\n help=\"\"\"\\\n How many of the training samples have background noise mixed in.\n \"\"\")\n parser.add_argument(\n '--silence_percentage',\n type=float,\n default=10.0,\n help=\"\"\"\\\n How much of the training data should be silence.\n \"\"\")\n parser.add_argument(\n '--unknown_percentage',\n type=float,\n default=10.0,\n help=\"\"\"\\\n How much of the training data should be unknown words.\n \"\"\")\n parser.add_argument(\n '--time_shift_ms',\n type=float,\n default=100.0,\n help=\"\"\"\\\n Range to randomly shift the training audio by in time.\n \"\"\")\n parser.add_argument(\n '--testing_percentage',\n type=int,\n default=10,\n help='What percentage of wavs to use as a test set.')\n parser.add_argument(\n '--validation_percentage',\n type=int,\n default=10,\n help='What percentage of wavs to use as a validation set.')\n parser.add_argument(\n '--sample_rate',\n type=int,\n default=16000,\n help='Expected sample rate of the wavs',)\n parser.add_argument(\n '--clip_duration_ms',\n type=int,\n default=1000,\n help='Expected duration in milliseconds of the wavs',)\n parser.add_argument(\n '--window_size_ms',\n type=float,\n default=30.0,\n help='How long each spectrogram timeslice is.',)\n parser.add_argument(\n '--window_stride_ms',\n type=float,\n default=10.0,\n help='How far to move in time between spectogram timeslices.',)\n parser.add_argument(\n '--feature_bin_count',\n type=int,\n default=40,\n help='How many bins to use for the MFCC fingerprint',\n )\n parser.add_argument(\n '--how_many_training_steps',\n type=str,\n default='15000,3000',\n help='How many training loops to run',)\n parser.add_argument(\n '--eval_step_interval',\n type=int,\n default=400,\n help='How often to evaluate the training results.')\n parser.add_argument(\n '--learning_rate',\n type=str,\n default='0.001,0.0001',\n help='How large a learning rate to use when training.')\n parser.add_argument(\n '--batch_size',\n type=int,\n default=100,\n help='How many items to train with at once',)\n parser.add_argument(\n '--summaries_dir',\n type=str,\n default='/tmp/retrain_logs',\n help='Where to save summary logs for TensorBoard.')\n parser.add_argument(\n '--wanted_words',\n type=str,\n default='yes,no,up,down,left,right,on,off,stop,go',\n help='Words to use (others will be added to an unknown label)',)\n parser.add_argument(\n '--train_dir',\n type=str,\n default='/tmp/speech_commands_train',\n help='Directory to write event logs and checkpoint.')\n parser.add_argument(\n '--save_step_interval',\n type=int,\n default=100,\n help='Save model checkpoint every save_steps.')\n parser.add_argument(\n '--start_checkpoint',\n type=str,\n default='',\n help='If specified, restore this pretrained model before any training.')\n parser.add_argument(\n '--model_architecture',\n type=str,\n default='conv',\n help='What model architecture to use')\n parser.add_argument(\n '--check_nans',\n type=bool,\n default=False,\n help='Whether to check for invalid numbers during processing')\n parser.add_argument(\n '--quantize',\n type=bool,\n default=False,\n help='Whether to train the model for eight-bit deployment')\n parser.add_argument(\n '--preprocess',\n type=str,\n default='mfcc',\n help='Spectrogram processing mode. Can be \"mfcc\", \"average\", or \"micro\"')\n\n FLAGS, unparsed = parser.parse_known_args()\n tf.compat.v1.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n"
] |
[
[
"tensorflow.python.keras.utils.losses_utils.reduce_weighted_loss",
"tensorflow.python.keras.backend.symbolic_learning_phase",
"tensorflow.python.keras.backend.is_placeholder",
"tensorflow.python.keras.engine.training_v2.Loop",
"tensorflow.python.distribute.distribution_strategy_context.get_strategy",
"tensorflow.python.tf2.enabled",
"tensorflow.python.keras.engine.training_utils.extract_tensors_from_dataset",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.keras.engine.training_generator.evaluate_generator",
"tensorflow.python.training.tracking.layer_utils.filter_empty_layer_containers",
"tensorflow.python.keras.engine.network._is_hdf5_filepath",
"tensorflow.python.util.nest.assert_same_structure",
"tensorflow.python.framework.ops.executing_eagerly_outside_functions",
"numpy.expand_dims",
"tensorflow.python.util.tf_inspect.isgenerator",
"tensorflow.python.util.nest.pack_sequence_as",
"tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes",
"tensorflow.python.keras.engine.training_eager.test_on_batch",
"tensorflow.python.keras.distribute.distributed_training_utils.is_tpu_strategy",
"tensorflow.python.keras.backend.image_data_format",
"tensorflow.python.keras.engine.training_utils.unpack_validation_data",
"tensorflow.python.keras.engine.data_adapter.select_data_adapter",
"tensorflow.python.keras.engine.training_v2_utils.train_on_batch",
"tensorflow.python.keras.backend.floatx",
"tensorflow.python.keras.engine.training_eager.train_on_batch",
"tensorflow.python.keras.engine.training_utils.validate_dataset_input",
"tensorflow.python.keras.engine.training_utils.is_eager_dataset_or_iterator",
"tensorflow.python.keras.distribute.distributed_training_utils.is_distributing_by_cloning",
"tensorflow.python.keras.engine.training_generator.fit_generator",
"tensorflow.python.keras.backend.dtype",
"tensorflow.python.keras.engine.training_utils.cast_if_floating_dtype",
"tensorflow.python.keras.engine.training_utils.verify_dataset_shuffled",
"tensorflow.python.distribute.distribution_strategy_context.in_cross_replica_context",
"tensorflow.python.platform.tf_logging.log_first_n",
"tensorflow.python.keras.engine.training_utils.standardize_sample_weights",
"tensorflow.python.keras.engine.training_distributed.DistributionSingleWorkerTrainingLoop",
"tensorflow.python.keras.engine.training_utils.prepare_loss_functions",
"tensorflow.python.keras.engine.training_utils.check_steps_argument",
"tensorflow.python.keras.engine.training_utils.has_tensors",
"tensorflow.python.keras.engine.training_utils.standardize_class_weights",
"tensorflow.python.keras.engine.training_v2_utils._non_none_constant_value",
"tensorflow.python.keras.engine.training_generator.GeneratorLikeTrainingLoop",
"tensorflow.python.keras.backend.configure_and_create_distributed_session",
"tensorflow.python.data.ops.dataset_ops.get_structure",
"tensorflow.python.ops.losses.util.squeeze_or_expand_dimensions",
"tensorflow.python.keras.engine.training_utils.prepare_sample_weight_modes",
"tensorflow.python.ops.math_ops.add_n",
"tensorflow.python.keras.optimizers.get",
"tensorflow.python.keras.engine.training_generator.GeneratorOrSequenceTrainingLoop",
"tensorflow.python.util.tf_inspect.getfullargspec",
"tensorflow.python.keras.backend.function",
"tensorflow.python.keras.utils.data_utils.is_generator_or_sequence",
"tensorflow.python.keras.backend.learning_phase",
"tensorflow.python.keras.engine.training_utils.is_feature_layer",
"tensorflow.python.distribute.multi_worker_util.in_multi_worker_mode",
"tensorflow.python.keras.engine.training_utils.call_metric_function",
"tensorflow.python.keras.engine.training_generator.EagerDatasetOrIteratorTrainingLoop",
"tensorflow.python.keras.engine.training_utils.unpack_iterator_input",
"tensorflow.python.keras.backend.is_sparse",
"tensorflow.python.keras.backend.name_scope",
"tensorflow.python.keras.utils.losses_utils.scale_loss_for_distribution",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.keras.engine.training_utils.generic_output_names",
"tensorflow.python.eager.monitoring.BoolGauge",
"tensorflow.python.keras.engine.training_utils.prepare_loss_weights",
"scipy.sparse.issparse",
"tensorflow.python.keras.engine.training_utils.ModelInputs",
"tensorflow.python.framework.tensor_spec.TensorSpec",
"tensorflow.python.keras.utils.losses_utils.compute_weighted_loss",
"tensorflow.python.keras.engine.training_utils.get_static_batch_size",
"tensorflow.python.keras.engine.training_utils.list_to_tuple",
"tensorflow.python.keras.engine.training_utils.collect_per_output_metric_info",
"tensorflow.python.keras.engine.training_utils.validate_input_types",
"tensorflow.python.keras.backend.get_graph",
"tensorflow.python.keras.saving.saving_utils.model_metadata",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.keras.distribute.distributed_training_utils._reset_metrics",
"tensorflow.python.keras.backend.int_shape",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.framework.ops.is_dense_tensor_like",
"tensorflow.python.keras.distribute.distributed_training_utils.global_batch_size_supported",
"tensorflow.python.keras.engine.training_utils.check_loss_and_target_compatibility",
"tensorflow.python.keras.engine.training_v2_utils.test_on_batch",
"tensorflow.python.keras.backend.get_session",
"tensorflow.python.keras.distribute.distributed_training_utils.set_weights",
"tensorflow.python.framework.sparse_tensor.SparseTensor",
"tensorflow.python.keras.engine.training_arrays.ArrayLikeTrainingLoop",
"tensorflow.python.keras.engine.training_v2_utils.should_fallback_to_v1_for_callback",
"tensorflow.python.keras.engine.training_utils.standardize_input_data",
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.keras.engine.training_generator.predict_generator",
"tensorflow.python.keras.engine.training_v2_utils.predict_on_batch",
"tensorflow.python.framework.composite_tensor_utils.is_composite_or_composite_value",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.keras.engine.training_utils.standardize_weights",
"tensorflow.python.keras.engine.training_utils.check_array_lengths",
"tensorflow.python.distribute.distribution_strategy_context.has_strategy",
"tensorflow.python.framework.tensor_util.is_tensor"
],
[
"tensorflow.compat.v1.assign",
"tensorflow.compat.v1.logging.info",
"tensorflow.compat.v1.get_default_graph",
"tensorflow.compat.v1.global_variables",
"tensorflow.compat.v1.add_check_numerics_ops",
"tensorflow.control_dependencies",
"tensorflow.quantization.fake_quant_with_min_max_args",
"tensorflow.cast",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.summary.FileWriter",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.name_scope",
"tensorflow.argmax",
"tensorflow.compat.v1.train.get_or_create_global_step",
"tensorflow.compat.v1.losses.sparse_softmax_cross_entropy",
"tensorflow.math.confusion_matrix",
"tensorflow.compat.v1.app.run",
"tensorflow.compat.v1.summary.merge_all",
"tensorflow.compat.v1.InteractiveSession",
"tensorflow.compat.v1.summary.scalar",
"tensorflow.contrib.quantize.create_training_graph",
"numpy.sum",
"tensorflow.compat.v1.train.GradientDescentOptimizer",
"tensorflow.equal",
"tensorflow.compat.v1.logging.set_verbosity",
"tensorflow.io.write_graph"
]
] |
Pad0y/imagepy
|
[
"23f41b64ade02f94b566b0d23a4b6459c1a1578d",
"23f41b64ade02f94b566b0d23a4b6459c1a1578d"
] |
[
"sciwx/__init__.py",
"imagepy/menus/Image/Adjust/brightcons_plg.py"
] |
[
"from sciapp import Manager\nimport numpy as np\n\nColorManager = Manager()\nimport matplotlib.pyplot as plt\n\nfor i in plt.colormaps()[::-1]:\n cm = plt.get_cmap(i)\n if i[-2:] == \"_r\":\n continue\n vs = np.linspace(0, cm.N, 256, endpoint=False)\n lut = cm(vs.astype(np.int), bytes=True)[:, :3]\n ColorManager.add(i, lut)\ndel plt\ngraylut = ColorManager.get(\"gray\")\nColorManager.add(\"Grays\", graylut)\nColorManager.remove(\"gray\")\n",
"\"\"\"\nCreated on Sun Nov 27 00:56:00 2016\n@author: yxl\n\"\"\"\nimport numpy as np\nfrom sciapp.action import Filter\n\n# from imagepy.ui.widgets import HistCanvas\n\n\nclass Plugin(Filter):\n title = \"Bright And Constract\"\n note = [\"all\", \"auto_msk\", \"auto_snap\", \"not_channel\", \"preview\"]\n\n def load(self, ips):\n hist = ips.histogram(chans=\"all\", step=512)\n if ips.dtype == np.uint8:\n self.para = {\"b_c\": (0, 45)}\n self.view = [(\"hist\", \"b_c\", \"bc\", hist, (-255, 255), 0)]\n else:\n self.rrange = minv, maxv = ips.img.min(), ips.img.max()\n self.para = {\n \"bright\": np.mean(ips.range) - np.mean(self.range),\n \"contrast\": round(\n np.arctan((maxv - minv) / (ips.range[1] - ips.range[0]))\n / np.pi\n * 180\n ),\n }\n self.view = [\n (\"hist\", \"b_c\", \"bc\", hist, (-(maxv - minv) / 2, (maxv - minv) / 2), 10)\n ]\n self.lut = ips.lut\n return True\n\n # process\n def run(self, ips, snap, img, para=None):\n bright, contrast = para[\"b_c\"]\n if not ips.dtype == np.uint8:\n mid = (self.arange[0] + self.arange[1]) / 2 - bright\n length = (self.arange[1] - self.arange[0]) / np.tan(\n contrast / 180.0 * np.pi\n )\n ips.range = (mid - length / 2, mid + length / 2)\n return\n if para == None:\n para = self.para\n mid = 128 - bright\n length = 255 / np.tan(contrast / 180.0 * np.pi)\n img[:] = snap\n if mid - length / 2 > 0:\n np.subtract(img, mid - length / 2, out=img, casting=\"unsafe\")\n np.multiply(img, 255.0 / length, out=img, casting=\"unsafe\")\n else:\n np.multiply(img, 255.0 / length, out=img, casting=\"unsafe\")\n np.subtract(\n img, (mid - length / 2) / length * 255, out=img, casting=\"unsafe\"\n )\n img[snap < mid - length / 2] = 0\n img[snap > mid + length / 2] = 255\n"
] |
[
[
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.colormaps",
"numpy.linspace"
],
[
"numpy.tan",
"numpy.mean",
"numpy.multiply",
"numpy.arctan",
"numpy.subtract"
]
] |
vigsterkr/FlowKet
|
[
"61238afd3fe1488d35c57d280675f544c559bd01"
] |
[
"examples/rbm_heisenberg_1d_sr.py"
] |
[
"from tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\n\nimport numpy\n\nfrom flowket.callbacks.monte_carlo import TensorBoardWithGeneratorValidationData, \\\n default_wave_function_stats_callbacks_factory, MCMCStats\nfrom flowket.machines import RBMSym\nfrom flowket.operators import Heisenberg\nfrom flowket.optimizers import ComplexValuesStochasticReconfiguration\nfrom flowket.optimization import VariationalMonteCarlo, loss_for_energy_minimization\nfrom flowket.samplers import MetropolisHastingsHamiltonian\n\nhilbert_state_shape = (20, 1)\ninputs = Input(shape=hilbert_state_shape, dtype='int8')\nrbm = RBMSym(inputs, stddev=0.01, use_float64_ops=True)\npredictions = rbm.predictions\nmodel = Model(inputs=inputs, outputs=predictions)\n\nbatch_size = 1000\nsteps_per_epoch = 300\n\noptimizer = ComplexValuesStochasticReconfiguration(model, rbm.predictions_jacobian, lr=0.05, diag_shift=0.1,\n iterative_solver=False)\nmodel.compile(optimizer=optimizer, loss=loss_for_energy_minimization, metrics=optimizer.metrics)\nmodel.summary()\noperator = Heisenberg(hilbert_state_shape=hilbert_state_shape, pbc=True)\nsampler = MetropolisHastingsHamiltonian(model, batch_size, operator, num_of_chains=20, unused_sampels=numpy.prod(hilbert_state_shape))\nvariational_monte_carlo = VariationalMonteCarlo(model, operator, sampler)\n\ntensorboard = TensorBoardWithGeneratorValidationData(log_dir='tensorboard_logs/rbm_with_sr_run_6',\n generator=variational_monte_carlo, update_freq=1,\n histogram_freq=1, batch_size=batch_size, write_output=False)\ncallbacks = default_wave_function_stats_callbacks_factory(variational_monte_carlo,\n true_ground_state_energy=-35.6175461195) + [MCMCStats(variational_monte_carlo), tensorboard]\nmodel.fit_generator(variational_monte_carlo.to_generator(), steps_per_epoch=steps_per_epoch, epochs=1,\n callbacks=callbacks,max_queue_size=0, workers=0)\nmodel.save_weights('final_1d_heisenberg.h5')\n"
] |
[
[
"numpy.prod",
"tensorflow.keras.layers.Input",
"tensorflow.keras.models.Model"
]
] |
yeqingli/ml-testing-accelerators
|
[
"d33a18e1782875dfe647c149553d54cc0c5e88cd",
"d33a18e1782875dfe647c149553d54cc0c5e88cd"
] |
[
"metrics_v2/handler/collectors/tensorboard_collector_test.py",
"metrics_v2/handler/collectors/base.py"
] |
[
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport contextlib\nimport os\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\n\nimport base\nimport tensorboard_collector\nfrom handler import utils\nimport metrics_pb2\n\nclass TensorBoardCollectorTest(parameterized.TestCase):\n def setUp(self):\n self.temp_dir = self.create_tempdir().full_path\n summary_writer = tf.summary.create_file_writer(self.temp_dir)\n with summary_writer.as_default(), contextlib.closing(summary_writer):\n tf.summary.scalar(\"foo\", 1, 0)\n tf.summary.scalar(\"foo\", 2, 100)\n\n train_summary_writer = tf.summary.create_file_writer(\n os.path.join(self.temp_dir, 'train'))\n with train_summary_writer.as_default(), contextlib.closing(train_summary_writer):\n tf.summary.scalar(\"bar\", 10, 0)\n tf.summary.scalar(\"bar\", 100, 200)\n tf.summary.scalar(\"bar\", 100, 100)\n\n eval_summary_writer = tf.summary.create_file_writer(\n os.path.join(self.temp_dir, 'eval'))\n with eval_summary_writer.as_default(), contextlib.closing(eval_summary_writer):\n tf.summary.scalar(\"accuracy\", .125, 0)\n tf.summary.scalar(\"accuracy\", .5, 100)\n tf.summary.scalar(\"accuracy\", .25, 200)\n\n def test_aggregate_metrics_include_all_strategies(self):\n metric_source = metrics_pb2.MetricSource(\n tensorboard=metrics_pb2.TensorBoardSource(\n include_tags=[\n metrics_pb2.TensorBoardSource.TagStrategy(\n tag_pattern=\"*\",\n strategies=[\n metrics_pb2.TensorBoardSource.FINAL,\n metrics_pb2.TensorBoardSource.MAX,\n metrics_pb2.TensorBoardSource.MIN,\n metrics_pb2.TensorBoardSource.AVERAGE,\n metrics_pb2.TensorBoardSource.MEDIAN,\n ]\n )\n ]\n )\n )\n event = metrics_pb2.TestCompletedEvent(\n benchmark_id=\"test_benchmark\",\n output_path=self.temp_dir,\n metric_collection_config=metrics_pb2.MetricCollectionConfig(\n sources=[metric_source]\n )\n )\n collector = tensorboard_collector.TensorBoardCollector(event=event, raw_source=metric_source)\n points = list(collector.metric_points())\n\n metric_to_value = {\n key: value\n for key, value, _ in points\n }\n\n self.assertDictEqual(\n metric_to_value,\n {\n 'foo_final': 2,\n 'foo_min': 1,\n 'foo_max': 2,\n 'foo_average': 1.5,\n 'foo_median': 1.5,\n 'eval/accuracy_final': .25,\n 'eval/accuracy_min': .125,\n 'eval/accuracy_max': .5,\n 'eval/accuracy_average': np.mean([.125, .25, .5]),\n 'eval/accuracy_median': np.median([.125, .25, .5]),\n 'train/bar_final': 100,\n 'train/bar_min': 10,\n 'train/bar_max': 100,\n 'train/bar_average': np.mean([10, 100, 100]),\n 'train/bar_median': np.median([10, 100, 100]),\n }\n )\n\n for _, _, bounds in points:\n self.assertEqual(bounds, utils.NO_BOUNDS)\n\n\n def test_aggregate_metrics_with_assertion(self):\n metric_source = metrics_pb2.MetricSource(\n tensorboard=metrics_pb2.TensorBoardSource(\n include_tags=[\n metrics_pb2.TensorBoardSource.TagStrategy(\n tag_pattern=\"eval/*\",\n strategies=[\n metrics_pb2.TensorBoardSource.FINAL,\n metrics_pb2.TensorBoardSource.MAX,\n metrics_pb2.TensorBoardSource.MIN,\n ]\n )\n ],\n aggregate_assertions=[\n metrics_pb2.TensorBoardSource.AggregateAssertion(\n tag='eval/accuracy',\n strategy=metrics_pb2.TensorBoardSource.MAX,\n assertion=metrics_pb2.Assertion(\n within_bounds=metrics_pb2.Assertion.WithinBounds(\n lower_bound=.4,\n upper_bound=1.0,\n ),\n inclusive_bounds=True,\n )\n )\n ]\n )\n )\n event = metrics_pb2.TestCompletedEvent(\n benchmark_id=\"test_benchmark\",\n output_path=self.temp_dir,\n metric_collection_config=metrics_pb2.MetricCollectionConfig(\n sources=[metric_source]\n )\n )\n collector = tensorboard_collector.TensorBoardCollector(event=event, raw_source=metric_source)\n points = list(collector.metric_points())\n\n self.assertCountEqual(\n points,\n [\n utils.MetricPoint('eval/accuracy_max', .5, utils.Bounds(.4, 1.0, True)),\n utils.MetricPoint('eval/accuracy_min', .125, utils.NO_BOUNDS),\n utils.MetricPoint('eval/accuracy_final', .25, utils.NO_BOUNDS),\n ],\n )\n\n def test_include_and_exclude(self):\n metric_source = metrics_pb2.MetricSource(\n tensorboard=metrics_pb2.TensorBoardSource(\n include_tags=[\n metrics_pb2.TensorBoardSource.TagStrategy(\n tag_pattern=\"*\",\n strategies=[\n metrics_pb2.TensorBoardSource.FINAL,\n ]\n )\n ],\n exclude_tags=[\n 'foo',\n 'train/*',\n ],\n aggregate_assertions=[\n metrics_pb2.TensorBoardSource.AggregateAssertion(\n tag='foo',\n strategy=metrics_pb2.TensorBoardSource.MIN,\n assertion=metrics_pb2.Assertion(\n within_bounds=metrics_pb2.Assertion.WithinBounds(\n lower_bound=0.,\n upper_bound=2.,\n )\n )\n )\n ]\n )\n )\n event = metrics_pb2.TestCompletedEvent(\n benchmark_id=\"test_benchmark\",\n output_path=self.temp_dir,\n metric_collection_config=metrics_pb2.MetricCollectionConfig(\n sources=[metric_source]\n )\n )\n collector = tensorboard_collector.TensorBoardCollector(event=event, raw_source=metric_source)\n points = list(collector.metric_points())\n\n self.assertCountEqual(\n points,\n [\n utils.MetricPoint('eval/accuracy_final', .25, utils.NO_BOUNDS),\n utils.MetricPoint('foo_min', 1, utils.Bounds(0., 2., False)),\n ],\n )\n\nif __name__ == '__main__':\n absltest.main()\n",
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\nimport math\nimport typing\n\nfrom absl import logging\nimport numpy as np\nfrom google.protobuf import duration_pb2\nfrom google.protobuf import timestamp_pb2\n\nfrom handler import utils\nimport metrics_pb2\n\n\nclass BaseCollector:\n \"\"\"\n Base class for Collector implementations.\n \"\"\"\n def __init__(self, event, raw_source: metrics_pb2.MetricSource, metric_store=None):\n self._event = event\n if raw_source:\n self._source = getattr(raw_source, raw_source.WhichOneof('source_type'))\n self._metric_store = metric_store\n\n @property\n def output_path(self):\n \"\"\"Output path from test event.\"\"\"\n return self._event.output_path\n\n def read_metrics_and_assertions(self) -> (\n typing.Iterable[typing.Tuple[str, float, metrics_pb2.Assertion]]):\n \"\"\"Yields unique metric keys, values, and the corresponding assertions.\"\"\"\n raise NotImplementedError\n\n def get_metric_history(\n self,\n metric_key: str,\n time_window: duration_pb2.Duration,\n min_timestamp: timestamp_pb2.Timestamp\n ) -> typing.List[float]:\n \"\"\"Returns the historical values of a given metric.\n \n Args:\n metric_key: Unique string identifying the name of the metric.\n time_window: Time limit for metric history, relative to the test start\n time. Data points older than the time window will not be returned.\n min_timestamp: Absolute time limit for metric history. Data points older\n than this timestamp will not be returned.\n\n Returns:\n A list of the historical values of the given metric as floats.\n \"\"\"\n if not self._metric_store:\n raise ValueError('Metric history requested for {}, but no metric store '\n 'was provided to Collector.'.format(metric_key))\n\n if time_window.ToTimedelta():\n min_time = max(\n min_timestamp.ToDatetime(),\n self._event.start_time.ToDatetime() - time_window.ToTimedelta())\n else:\n min_time = min_timestamp.ToDatetime()\n\n history_rows = self._metric_store.get_metric_history(\n benchmark_id=(\n self._event.metric_collection_config.compare_to_benchmark_id or\n self._event.benchmark_id),\n metric_key=metric_key,\n min_time=min_time,\n )\n \n return [row.metric_value for row in history_rows]\n\n def compute_bounds(\n self,\n metric_key: str,\n assertion: metrics_pb2.Assertion\n ) -> utils.Bounds:\n \"\"\"Returns the bounds for a given metric, based on the given assertion.\n\n This method may result in database calls to gather historical data for some\n types of assertions.\n\n Args:\n metric_key: Unique string identifying the name of the metric.\n assertion: The assertion that will be used to define the bounds.\n\n Returns:\n An instance of utils.Bounds representing the metric bounds.\n \"\"\"\n if assertion is None:\n return utils.NO_BOUNDS\n\n lower_bound = -math.inf\n upper_bound = math.inf\n inclusive = assertion.inclusive_bounds\n\n assertion_type = assertion.WhichOneof('assertion_type')\n if assertion_type == 'fixed_value':\n c = assertion.fixed_value.comparison\n if c == metrics_pb2.Assertion.LESS:\n upper_bound = assertion.fixed_value.value\n elif c == metrics_pb2.Assertion.GREATER:\n lower_bound = assertion.fixed_value.value\n elif c == metrics_pb2.Assertion.EQUAL:\n lower_bound = assertion.fixed_value.value\n upper_bound = assertion.fixed_value.value\n inclusive = True\n elif assertion_type == 'within_bounds':\n lower_bound = assertion.within_bounds.lower_bound\n upper_bound = assertion.within_bounds.upper_bound\n elif assertion_type == 'std_devs_from_mean':\n values = self.get_metric_history(\n metric_key,\n assertion.time_window,\n assertion.min_timestamp)\n \n # Standard deviation not defined for n < 2\n min_num_points = max(assertion.wait_for_n_data_points, 2)\n if len(values) < min_num_points:\n logging.info('Not enough data points to compute bounds for %s. '\n 'Need %d points, have %d.',\n metric_key, min_num_points, len(values))\n return utils.NO_BOUNDS\n\n mean = np.mean(values)\n stddev = np.std(values)\n c = assertion.std_devs_from_mean.comparison\n if c in (metrics_pb2.Assertion.LESS, metrics_pb2.Assertion.WITHIN):\n upper_bound = mean + (stddev * assertion.std_devs_from_mean.std_devs)\n if c in (metrics_pb2.Assertion.GREATER, metrics_pb2.Assertion.WITHIN):\n lower_bound = mean - (stddev * assertion.std_devs_from_mean.std_devs)\n\n if upper_bound == math.inf and lower_bound == -math.inf:\n logging.error(\n '%s: comparison %s is not implemented for assertion type `%s`',\n metric_key, metrics_pb2.Assertion.Comparison.Name(c), assertion_type)\n return utils.NO_BOUNDS\n elif assertion_type == 'percent_difference':\n target_type = assertion.percent_difference.WhichOneof('target_type')\n if target_type == 'use_historical_mean':\n values = self.get_metric_history(\n metric_key,\n assertion.time_window,\n assertion.min_timestamp)\n\n # Mean not defined for n < 1.\n min_num_points = max(assertion.wait_for_n_data_points, 1)\n if len(values) < min_num_points:\n logging.info('Not enough data points to compute bounds for %s. '\n 'Need %d points, have %d.',\n metric_key, len(values), min_num_points)\n return utils.NO_BOUNDS\n target = np.mean(values)\n elif target_type == 'value':\n target = assertion.percent_difference.value\n else:\n logging.error('%s: No `target_type` defined for assertion type `%s`.',\n metric_key, assertion_type)\n return utils.NO_BOUNDS\n\n c = assertion.percent_difference.comparison\n if c in (metrics_pb2.Assertion.LESS, metrics_pb2.Assertion.WITHIN):\n upper_bound = target + (assertion.percent_difference.percent * target)\n if c in (metrics_pb2.Assertion.GREATER, metrics_pb2.Assertion.WITHIN):\n lower_bound = target - (assertion.percent_difference.percent * target)\n\n if upper_bound == math.inf and lower_bound == -math.inf:\n logging.error(\n '%s: comparison %s is not implemented for assertion type `%s`',\n metric_key, metrics_pb2.Assertion.Comparison.Name(c), assertion_type)\n return utils.NO_BOUNDS\n\n return utils.Bounds(lower_bound, upper_bound, inclusive)\n\n def metric_points(self) -> typing.Iterable[utils.MetricPoint]:\n \"\"\"Returns a list of metric points collected from the test output.\"\"\"\n return [\n utils.MetricPoint(key, value, self.compute_bounds(key, assertion))\n for key, value, assertion in self.read_metrics_and_assertions()]\n"
] |
[
[
"numpy.median",
"tensorflow.summary.create_file_writer",
"numpy.mean",
"tensorflow.summary.scalar"
],
[
"numpy.std",
"numpy.mean"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.